diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 93c2254a1..65d8418b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,11 @@ jobs: # targets this repository ships for. - name: vet run: go vet ./... + # The page-facing packages keep reflection and untyped containers out of + # their exported API; the layout, input, scene and render paths depend on + # it, and a symbol that needs one usually needs a typed one instead. + - name: API discipline + run: go run ./tools/apicheck ./ui ./components ./app ./gfx # Every target Viva ships for must at least type-check, tests included. The # targets do not depend on each other, so they run at the same time on one diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 53228c65a..93a201319 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -4,12 +4,20 @@ on: push: paths: - 'app/**' + - 'internal/iconshape/**' + - 'internal/dbus/**' - 'internal/platform/**' + - 'internal/ibus/**' + - 'internal/render/**' - '.github/workflows/text-input.yml' pull_request: paths: - 'app/**' + - 'internal/iconshape/**' + - 'internal/dbus/**' - 'internal/platform/**' + - 'internal/ibus/**' + - 'internal/render/**' - '.github/workflows/text-input.yml' workflow_dispatch: @@ -42,6 +50,35 @@ jobs: cache: true - name: Application input lifecycle run: go test ./app -count=1 + - name: GTK native probe dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libgtk-3-0t64 xvfb xauth dbus-x11 + dpkg-query -W libgtk-3-0t64 xvfb xauth dbus-x11 + - name: GTK native composition lifecycle + if: runner.os == 'Linux' + run: dbus-run-session -- xvfb-run -a env VIVA_GTK_IME_NATIVE=1 GTK_IM_MODULE=gtk-im-context-simple GDK_BACKEND=x11 NO_AT_BRIDGE=1 G_DEBUG=fatal-criticals go test -tags vivagtk ./internal/platform/linux -run '^TestGTKNativeComposition$' -count=1 -v -timeout=90s + - name: Linux IME protocol lifecycle + if: runner.os == 'Linux' + run: go test ./internal/ibus ./internal/platform/linux -run 'Test(IME|Preedit|CommitAndPreedit|MalformedPreedit)' -count=1 -timeout=90s + - name: Install Linux input service test dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libgtk-3-0t64 xvfb xauth dbus-x11 ibus ibus-libpinyin ibus-hangul python3-gi gir1.2-ibus-1.0 gir1.2-gtk-3.0 libglib2.0-bin dconf-cli + dpkg-query -W libgtk-3-0t64 xvfb xauth dbus-x11 ibus ibus-libpinyin ibus-hangul python3-gi gir1.2-ibus-1.0 gir1.2-gtk-3.0 libglib2.0-bin dconf-cli + - name: IBus native engine lifecycle + if: runner.os == 'Linux' + run: | + go test -c -o "$RUNNER_TEMP/viva-ibus-native.test" ./internal/ibus + xvfb-run -a env VIVA_IBUS_TEST_BINARY="$RUNNER_TEMP/viva-ibus-native.test" VIVA_IBUS_REFERENCE=1 sh internal/ibus/testdata/native-service.sh libpinyin hangul + - name: Linux text callback ordering + if: runner.os == 'Linux' + run: go test -race ./internal/platform/linux -run '^TestLinuxTextCallback' -count=1 -timeout=90s + - name: GTK text callback ordering + if: runner.os == 'Linux' + 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 @@ -51,6 +88,12 @@ jobs: - name: Linux aligned text input if: runner.os == 'Linux' run: go test ./internal/platform/linux -run '^TestLinux(TextInputAlignmentMatchesGlyphCaretUnderlineAndPointer|RightToLeftAlignmentUsesLineWidthNotLogicalEndCaret|CandidateWindowFollowsAlignmentWhenNativeOverlaysAreHidden)$' -count=1 + - name: GTK input method teardown ordering + if: runner.os == 'Linux' + run: go test -tags vivagtk ./internal/platform/linux -run '^TestGTKDestroyDetachesInputMethodBeforeNativeWidget$' -count=1 -v + - name: Linux clipboard, compositing and icon contracts + if: runner.os == 'Linux' + run: go test -tags vivagtk ./internal/platform/linux -run '^Test(AClipboardHTML|SetClipboardHTML|GTKClipboardHTML|CompositingLayers|NetWMIcon)' -count=1 -v # A terminal input is a preedit surface with a cursor of its own: the native # editor must draw no caret or selection over it, and blink none. - name: Windows terminal preedit draws no native caret diff --git a/README.md b/README.md index 4cf42a9b2..e5396d884 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Viva reaches Cocoa and Metal through cgo; on Linux, X11 with the system XCB and Vulkan loaders; on Windows, Win32 with Direct3D 11 and DirectWrite. Viva loads the system libraries at runtime and bundles none of them. -The current release is `v0.6.3`; name it explicitly (`@v0.6.3`) to pin it. Guides, +The current release is `v0.6.4`; name it explicitly (`@v0.6.4`) to pin it. Guides, the API reference, and a component catalog with live previews live in [`website/`](website/); run it with `npm run dev` there, or read them on [vivaui.dev](https://vivaui.dev/en/), which is also available in @@ -115,6 +115,21 @@ WebView and no bundled rendering runtime. corner of the application's Dock tile, and an empty label removes it. - `app.StoreSecret`/`LoadSecret`/`DeleteSecret` keep a small secret in the system's own store (Keychain, Credential Manager, Secret Service). +- `app.PreventSleep` keeps the machine out of idle sleep while a transfer or a + remote session runs, naming the work in the system's own power diagnostics + (`pmset`, `powercfg`, `systemd-inhibit`). It holds no timer or goroutine, and + releasing it ends the request. +- `Application.SetMenuBar` puts the application's own File, Edit and View menus + between the system's application menu and Window menu on macOS, with key + equivalents, enablement, check marks, submenus and loop-thread callbacks; the + other desktop targets build their menus in the window with `components.Menubar`. +- `Application.Post` hands work a background goroutine finished to the window + thread: accepted functions run there in order, with no goroutine, timer or + blocking wait added, and no "call the loop and wait" form that could deadlock. +- `app/proxy.SystemProxy` reports the proxy the desktop selects for an HTTP URL: + CFNetwork on macOS, WinHTTP's automatic proxy on Windows (PAC, WPAD and the + static settings), and the environment on Linux. A policy the platform cannot + evaluate is an error, never a silent direct connection. - `gfx.MonoFamily` draws fixed-pitch text in any installed family and `app.MonospaceFamilies` lists them. - `Config.OnFileDrop` receives files dragged from the file manager, with the hit diff --git a/README.zh-CN.md b/README.zh-CN.md index c3237e9c0..c643f4e78 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -34,7 +34,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st 环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal;Linux 上需要带系统 XCB 和 Vulkan 加载库的 X11;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 -当前版本是 `v0.6.3`;要固定版本就写明(`@v0.6.3`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 +当前版本是 `v0.6.4`;要固定版本就写明(`@v0.6.4`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 下面的一切描述的都是这个仓库:它的测量、它自己的程序,以及如何开发框架本身,而不是如何用框架。 diff --git a/app/app.go b/app/app.go index 6b1beb0ec..25e04c9fd 100644 --- a/app/app.go +++ b/app/app.go @@ -96,6 +96,15 @@ type Config struct { // supplied it. Without one the panel is centered on the screen. Anchor StatusAnchor ClearColor Color + // WindowBorderColor is read at every paint and names the color of the + // border Windows 11 draws around a custom-titlebar window. The system + // composites that border against what is behind the window rather than + // against the window's own pixels, so the desktop shows through it as a + // seam about a pixel wide at 100% scale and proportionally wider at higher + // scale. Return the color the window's own edge is painted with to make it + // continuous. Nil uses ClearColor; a transparent color leaves the system's + // border. Other platforms ignore it. + WindowBorderColor func() Color // WindowBackdrop is read on the window thread after each paint. Windows // 11 22H2+ supports all materials; Windows 10 1809 through 11 21H2 supports // Acrylic through an undocumented accent policy. Other cases use ClearColor. diff --git a/app/application.go b/app/application.go index df70dc9e7..0bdac102f 100644 --- a/app/application.go +++ b/app/application.go @@ -47,6 +47,29 @@ type Host interface { // Quit closes every window, close requests notwithstanding, and ends the // loop. It is safe to call from any goroutine. Quit() + // Post runs fn on the application's event-loop thread. It is safe from any + // goroutine and never blocks. + Post(fn func()) +} + +// Post runs fn on the application's event-loop thread. Use it to hand work a +// background goroutine finished to the thread that owns the windows, the pages +// and the retained scene. It is safe from any goroutine, never blocks, and the +// functions it accepts run in the order Post accepted them; a function posted +// after the loop has ended may not run. +// +// A posted function runs on the loop thread and must not wait for the loop: it +// is the same thread that would have to run the work it waits on. Viva provides +// no "call the loop and wait" form for that reason; a result is published where +// the next Window wake or Paint reads it, as Config.OnWake and +// Invalidator.Invalidate already arrange. +// +// It starts no goroutine: the adapter wakes the loop it already has. +func (application *Application) Post(fn func()) { + if application == nil || application.host == nil || fn == nil { + return + } + application.host.Post(fn) } // Window is one independently retained native window. Close is idempotent and diff --git a/app/application_native.go b/app/application_native.go index e9c651706..7ba7ccb78 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -3,6 +3,7 @@ package app import ( + "fmt" "runtime" "github.com/vivaui/viva/gfx" @@ -128,8 +129,22 @@ func (host nativeHost) SetDockBadge(text string) { host.native.SetDockBadge(text func (host nativeHost) SetProgress(fraction float32) { host.native.SetProgress(fraction) } +// SetMenuBar installs the application's own menus where the adapter has an +// application menu bar; the adapters without one report ErrUnsupported. +func (host nativeHost) SetMenuBar(menus []Menu) error { + setter, ok := host.native.(interface { + SetMenuBar([]platform.MenuBarMenu) error + }) + if !ok { + return fmt.Errorf("%w: the application menu bar", ErrUnsupported) + } + return setter.SetMenuBar(platformMenuBar(menus)) +} + func (host nativeHost) Quit() { host.native.Quit() } +func (host nativeHost) Post(fn func()) { host.native.Post(fn) } + type nativeStatusItem struct{ item platform.StatusItem } func (item nativeStatusItem) SetIcon(icon StatusIcon) error { diff --git a/app/application_test.go b/app/application_test.go index 95468fdb7..42edfa644 100644 --- a/app/application_test.go +++ b/app/application_test.go @@ -75,6 +75,12 @@ func (host *fakeHost) SetDockBadge(text string) { host.badge = text } func (host *fakeHost) SetProgress(fraction float32) { host.progress = fraction } +func (host *fakeHost) Post(fn func()) { + if fn != nil { + fn() + } +} + func (host *fakeHost) Quit() { host.quits++ } func useHost(t *testing.T, host *fakeHost) { @@ -513,3 +519,18 @@ func TestCaptureSystemShortcutsReachesThePlatformThatCanTakeThem(t *testing.T) { t.Fatal("a closed window was still asked") } } + +// Post hands the work to the host's event loop: the Application does not run it +// on the caller's goroutine itself. +func TestPostDelegatesToTheHost(t *testing.T) { + host := &fakeHost{} + application := &Application{host: host} + ran := false + application.Post(func() { ran = true }) + if !ran { + t.Fatal("the host did not run the posted work") + } + application.Post(nil) // harmless + var nilApplication *Application + nilApplication.Post(func() { t.Fatal("a nil application ran work") }) +} diff --git a/app/capabilities.go b/app/capabilities.go index 56761c77d..12b6c3012 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -36,6 +36,13 @@ const ( CapabilityReduceMotion CapabilitySecretStoreAsync CapabilityFontRegistrationAsync + // CapabilityPreventSleep means PreventSleep can hold the system out of + // idle sleep. It does not promise a Linux session has logind to ask. + CapabilityPreventSleep + // CapabilitySystemProxy means app/proxy.SystemProxy can read the desktop's + // proxy settings. Linux reads the environment only, and macOS reports a + // PAC policy as an error. + CapabilitySystemProxy ) // Capabilities is a set of platform integrations. diff --git a/app/capabilities_native.go b/app/capabilities_native.go index 5cb9a2890..31281cb49 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -30,7 +30,9 @@ func nativeCapabilities() Capabilities { CapabilityFullscreen | CapabilityWindowFrame | CapabilityWindowMinimize | - CapabilityReduceMotion + CapabilityReduceMotion | + CapabilityPreventSleep | + CapabilitySystemProxy if runtime.GOOS == "darwin" { capabilities |= CapabilityNativeAppearance } else { diff --git a/app/composition_dispatch_reentry_test.go b/app/composition_dispatch_reentry_test.go new file mode 100644 index 000000000..942c65b37 --- /dev/null +++ b/app/composition_dispatch_reentry_test.go @@ -0,0 +1,115 @@ +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +func TestPainterReentrantTextEventKeepsLatestAcknowledgment(t *testing.T) { + for _, mode := range []string{"nested edit", "ignored newline"} { + t.Run(mode, func(t *testing.T) { + editor := text.NewEditor("a") + editor.MoveTo(1, false) + owner := &painter{nativeText: platform.TextInput{Multiline: mode == "nested edit"}} + owner.nativeText.State = platform.EditorState(editor) + owner.activeText = &TextInput{State: TextStateOf(editor)} + owner.activeText.OnEvent = func(event TextEvent) (TextState, error) { + event.Apply(editor) + ack := TextStateOf(editor) + if event.Text == "r" { + nested := platform.TextEvent{Kind: platform.TextInsert, Text: "z"} + if mode == "ignored newline" { + nested = platform.TextEvent{Kind: platform.TextCommandEvent, Command: platform.TextInsertNewline} + } + if _, err := owner.applyTextEvent(nested); err != nil { + t.Fatal(err) + } + } + return ack, nil + } + ack, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "r"}) + want := TextStateOf(editor) + wantValue := "arz" + if mode == "ignored newline" { + wantValue = "ar" + } + if err != nil || want.Value != wantValue || owner.activeText.State != want || + owner.nativeText.State != platform.EditorState(editor) || ack.WithoutRedraw() != platform.EditorState(editor) { + t.Fatalf("nested text acknowledgment: editor=%+v active=%+v native=%+v ack=%+v err=%v", want, owner.activeText.State, owner.nativeText.State, ack, err) + } + }) + } +} + +func TestPainterTextCallbackSyncPreservesInputOwnership(t *testing.T) { + for _, mode := range []string{"same owner fresh provider", "same owner geometry", "replacement owner", "identical direct replacement", "removed owner"} { + t.Run(mode, func(t *testing.T) { + first, second := text.NewEditor("a"), text.NewEditor("other") + first.MoveTo(1, false) + if mode == "identical direct replacement" { + second = text.NewEditor("a") + second.MoveTo(1, false) + } + current := first + extraWidth := float32(0) + var canvas gfx.Canvas + config := Config{Title: "reentrant provider", Width: 200, Height: 80} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(11), gfx.Rect{Width: 120, Height: 24}, "Name", gfx.HitOptions{Role: gfx.RoleTextField}) + } + var owner *painter + config.TextInput = func(context TextInputContext) *TextInput { + if current == nil { + return nil + } + editor := current + bounds := context.Bounds + bounds.Width += extraWidth + if mode == "identical direct replacement" && editor == second { + return &TextInput{Bounds: bounds, FontSize: 13, Editor: editor} + } + return &TextInput{Bounds: bounds, FontSize: 13, State: TextStateOf(editor), OnEvent: func(event TextEvent) (TextState, error) { + if mode == "replacement owner" || mode == "identical direct replacement" || mode == "removed owner" { + event.Apply(editor) + current = second + if mode == "removed owner" { + current = nil + } + owner.syncTextInput() + } else { + if mode == "same owner geometry" { + extraWidth = 10 + } + owner.syncTextInput() + event.Apply(editor) + } + ack := TextStateOf(editor) + ack.Redraw = true + return ack, nil + }} + } + owner = newTestPainter(t, &canvas, config) + for _, kind := range []platform.PointerEventKind{platform.PointerMove, platform.PointerDown, platform.PointerUp} { + if _, err := owner.pointerEvent(platform.PointerEvent{Kind: kind, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + } + ack, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "r"}) + if mode == "removed owner" { + if err != nil || first.String() != "ar" || owner.activeText != nil || owner.textEnabled || + ack.WithoutRedraw() != (platform.TextState{}) || !ack.Redraw { + t.Fatalf("removed provider acknowledgment: active=%+v enabled=%t ack=%+v error=%v", owner.activeText, owner.textEnabled, ack, err) + } + return + } + want := TextStateOf(current) + if err != nil || first.String() != "ar" || owner.activeText.State != want || + owner.nativeText.State != platform.EditorState(current) || ack.WithoutRedraw() != platform.EditorState(current) || !ack.Redraw { + t.Fatalf("provider acknowledgment: editor=%+v active=%+v native=%+v ack=%+v err=%v", want, owner.activeText.State, owner.nativeText.State, ack, err) + } + }) + } +} diff --git a/app/composition_dispatch_test.go b/app/composition_dispatch_test.go new file mode 100644 index 000000000..7e3cb2570 --- /dev/null +++ b/app/composition_dispatch_test.go @@ -0,0 +1,544 @@ +package app + +import ( + "runtime" + "testing" + "time" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +func TestTextEventApplyForwardsCompositionFields(t *testing.T) { + editor := text.NewEditor("abcd") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + TextEvent{ + Kind: TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "\u00e9\U0001d11e", + MarkedSelection: TextRange{Start: 2, End: 2}, + }.Apply(editor) + TextEvent{ + Kind: TextInsert, CompositionPhase: text.CompositionResult, Text: "r", + HasReplacement: true, Replacement: TextRange{Start: 0, End: 1}, + HasReplacementUTF16: true, ReplacementUTF16: text.UTF16Range{Start: 5, Length: 1}, + }.Apply(editor) + if got := editor.String(); got != "acdr" { + t.Fatalf("app Apply raw result = %q, want acdr", got) + } +} + +func TestNativeTextEventAdapterPreservesTaggedFields(t *testing.T) { + event := platform.TextEvent{ + Kind: platform.TextInsert, Text: "native", Command: platform.TextUndo, + Selection: text.Range{Start: 1, End: 2}, MarkedSelection: text.Range{Start: 3, End: 4}, + Replacement: text.Range{Start: 5, End: 6}, HasReplacement: true, + CompositionPhase: text.CompositionResult, + ReplacementUTF16: text.UTF16Range{Start: 7, Length: 8}, HasReplacementUTF16: true, + } + want := TextEvent{ + Kind: TextInsert, Text: "native", Command: TextUndo, + Selection: TextRange{Start: 1, End: 2}, MarkedSelection: TextRange{Start: 3, End: 4}, + Replacement: TextRange{Start: 5, End: 6}, HasReplacement: true, + CompositionPhase: text.CompositionResult, + ReplacementUTF16: text.UTF16Range{Start: 7, Length: 8}, HasReplacementUTF16: true, + } + if got := appTextEvent(event); got != want { + t.Fatalf("native event adaptation = %+v, want %+v", got, want) + } +} + +func TestTextStateOfTentativeCompositionSnapshot(t *testing.T) { + editor := text.NewEditor("abc") + if TextStateOf(editor).TentativeComposition { + t.Fatal("default editor reported the opt-in capability") + } + if !editor.EnableTentativeComposition() || !TextStateOf(editor).TentativeComposition { + t.Fatal("app snapshot did not follow opt-in") + } + identity := editor.TentativeCompositionIdentity() + TextEvent{Kind: TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "x"}.Apply(editor) + if state := TextStateOf(editor); !state.Composing || !state.TentativeComposition || platformTextState(state).CompositionIdentity != identity { + t.Fatalf("live app state = %+v", state) + } + TextEvent{Kind: TextInsert, CompositionPhase: text.CompositionCommit}.Apply(editor) + if state := TextStateOf(editor); state.Composing || !state.TentativeComposition { + t.Fatalf("idle app state = %+v", state) + } + if !editor.DisableTentativeComposition() { + t.Fatal("disable refused") + } + if state := TextStateOf(editor); state.Composing || state.TentativeComposition || platformTextState(state).CompositionIdentity != (text.CompositionIdentity{}) { + t.Fatalf("passive disabled app state = %+v", state) + } +} + +func TestPainterApplyTextEventCopiesTaggedFieldsAndCapability(t *testing.T) { + editor := text.NewEditor("abcd") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + owner := &painter{activeText: &TextInput{Editor: editor}, nativeText: platform.TextInput{Multiline: true}} + state, err := owner.applyTextEvent(platform.TextEvent{ + Kind: platform.TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "\u00e9\U0001d11e", + MarkedSelection: text.Range{Start: 2, End: 2}, + }) + if err != nil || !state.TentativeComposition || !state.Composing || + !owner.activeText.State.TentativeComposition || !owner.nativeText.State.TentativeComposition { + t.Fatalf("direct Update adaptation lost capability: %+v, %v", state, err) + } + state, err = owner.applyTextEvent(platform.TextEvent{ + Kind: platform.TextInsert, CompositionPhase: text.CompositionResult, Text: "r", + HasReplacementUTF16: true, ReplacementUTF16: text.UTF16Range{Start: 5, Length: 1}, + }) + if err != nil || state.Value != "acdr" || state.Composing || !state.TentativeComposition || owner.nativeText.State != state { + t.Fatalf("direct Result adaptation lost raw replacement/state: %+v, %v", state, err) + } + var received TextEvent + owner.activeText = &TextInput{OnEvent: func(event TextEvent) (TextState, error) { + received = event + return TextState{Value: "handled", TentativeComposition: true, Redraw: true}, nil + }} + event := platform.TextEvent{ + Kind: platform.TextInsert, CompositionPhase: text.CompositionResult, Text: "native", + Selection: text.Range{Start: 7, End: 8}, MarkedSelection: text.Range{Start: 2, End: 3}, + HasReplacement: true, Replacement: text.Range{Start: 4, End: 5}, + HasReplacementUTF16: true, ReplacementUTF16: text.UTF16Range{Start: 9, Length: 11}, + } + state, err = owner.applyTextEvent(event) + if err != nil || received.CompositionPhase != event.CompositionPhase || received.Text != event.Text || + received.ReplacementUTF16 != event.ReplacementUTF16 || !received.HasReplacementUTF16 || + received.Selection != (TextRange{Start: 7, End: 8}) || received.MarkedSelection != (TextRange{Start: 2, End: 3}) || + !received.HasReplacement || received.Replacement != (TextRange{Start: 4, End: 5}) { + t.Fatalf("custom handler adaptation lost fields: %+v, %v", received, err) + } + if !state.TentativeComposition || !state.Redraw || !owner.nativeText.State.TentativeComposition || owner.nativeText.State.Redraw { + t.Fatal("returned/mirrored capability or one-shot redraw changed") + } +} + +func TestPainterTaggedCompositionKeepsSingleLineSanitation(t *testing.T) { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 1}) + owner := &painter{activeText: &TextInput{Editor: editor}, nativeText: platform.TextInput{}} + if _, err := owner.applyTextEvent(platform.TextEvent{ + Kind: platform.TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "p", + }); err != nil { + t.Fatal(err) + } + state, err := owner.applyTextEvent(platform.TextEvent{ + Kind: platform.TextInsert, CompositionPhase: text.CompositionResult, Text: "x\ny", + }) + if err != nil || editor.String() != "ax ybc" || state.Value != "ax ybc" { + t.Fatalf("tagged single-line result = %q (state %q), error=%v", editor.String(), state.Value, err) + } +} + +func TestPainterTaggedTerminalSurvivesEmptySingleLineSanitation(t *testing.T) { + for _, scenario := range []struct { + name string + phase text.CompositionPhase + want string + }{ + {name: "result", phase: text.CompositionResult, want: "ac"}, + {name: "cancel", phase: text.CompositionCancel, want: "ac"}, + {name: "commit", phase: text.CompositionCommit, want: "apc"}, + {name: "empty commit", phase: text.CompositionEmptyCommit, want: "ac"}, + } { + for _, custom := range []bool{false, true} { + name := scenario.name + "/editor" + if custom { + name = scenario.name + "/handler" + } + t.Run(name, func(t *testing.T) { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + owner := &painter{activeText: &TextInput{Editor: editor}} + if custom { + owner.activeText = &TextInput{State: TextStateOf(editor), OnEvent: func(event TextEvent) (TextState, error) { + event.Apply(editor) + return TextStateOf(editor), nil + }} + } + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "p"}); err != nil { + t.Fatal(err) + } + ack, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextInsert, CompositionPhase: scenario.phase, Text: "\n"}) + if err != nil || editor.String() != scenario.want || editor.CompositionActive() || + owner.activeText.State != TextStateOf(editor) || owner.nativeText.State != platform.EditorState(editor) || ack.WithoutRedraw() != platform.EditorState(editor) { + t.Fatalf("sanitized terminal: editor=%+v active=%+v native=%+v ack=%+v err=%v", TextStateOf(editor), owner.activeText.State, owner.nativeText.State, ack, err) + } + }) + } + } +} + +func TestPainterSecureTentativeCompositionRetainsOnlyLiveRollback(t *testing.T) { + for _, scenario := range []struct { + name string + phase text.CompositionPhase + want string + }{ + {name: "result", phase: text.CompositionResult, want: "arc"}, + {name: "cancel", phase: text.CompositionCancel, want: "ac"}, + {name: "commit", phase: text.CompositionCommit, want: "apc"}, + {name: "empty commit", phase: text.CompositionEmptyCommit, want: "ac"}, + {name: "empty update", phase: text.CompositionUpdate, want: "ac"}, + } { + t.Run(scenario.name, func(t *testing.T) { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + owner := &painter{activeText: &TextInput{Editor: editor}, nativeText: platform.TextInput{Secure: true}} + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "p"}); err != nil { + t.Fatal(err) + } + if !editor.CanUndo() { + t.Error("secure Update discarded the live rollback units") + } + for _, command := range []platform.TextCommand{platform.TextUndo, platform.TextRedo} { + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextCommandEvent, Command: command}); err != nil { + t.Fatal(err) + } + if editor.String() != "apc" || !editor.CompositionActive() || !editor.CanUndo() { + t.Error("secure no-op Undo/Redo changed or discarded live rollback") + } + } + ending := platform.TextEvent{Kind: platform.TextInsert, CompositionPhase: scenario.phase} + if scenario.phase == text.CompositionResult { + ending.Text = "r" + } + ack, err := owner.applyTextEvent(ending) + if err != nil || editor.String() != scenario.want || editor.CompositionActive() || editor.CanUndo() || editor.CanRedo() || + owner.activeText.State != TextStateOf(editor) || owner.nativeText.State != platform.EditorState(editor) || ack.WithoutRedraw() != platform.EditorState(editor) { + t.Fatalf("secure settlement: editor=%+v active=%+v native=%+v ack=%+v undo=%t redo=%t err=%v", TextStateOf(editor), owner.activeText.State, owner.nativeText.State, ack, editor.CanUndo(), editor.CanRedo(), err) + } + }) + } +} + +func TestPainterTaggedTerminalSurvivesSingleLineCommandFilter(t *testing.T) { + for _, custom := range []bool{false, true} { + for _, command := range []platform.TextCommand{platform.TextInsertNewline, platform.TextInsertLineBreak} { + for _, phase := range []text.CompositionPhase{text.CompositionResult, text.CompositionCommit, text.CompositionCancel, text.CompositionEmptyCommit} { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + owner := &painter{activeText: &TextInput{Editor: editor}} + calls := 0 + if custom { + owner.activeText = &TextInput{State: TextStateOf(editor), OnEvent: func(event TextEvent) (TextState, error) { + calls++ + event.Apply(editor) + return TextStateOf(editor), nil + }} + } + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "p"}); err != nil { + t.Fatal(err) + } + ack, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextCommandEvent, Command: command, CompositionPhase: phase}) + want := "ac" + if phase == text.CompositionCommit { + want = "apc" + } + if err != nil || editor.String() != want || editor.CompositionActive() || + owner.activeText.State != TextStateOf(editor) || owner.nativeText.State != platform.EditorState(editor) || ack.WithoutRedraw() != platform.EditorState(editor) || custom && calls != 2 { + t.Errorf("tagged command suppressed: custom=%t command=%v phase=%v state=%+v calls=%d ack=%+v err=%v", custom, command, phase, TextStateOf(editor), calls, ack, err) + } + } + } + } +} + +func TestPainterSecureRejectedTaggedEventPreservesHistory(t *testing.T) { + for _, active := range []bool{false, true} { + name := "idle" + if active { + name = "active" + } + t.Run(name, func(t *testing.T) { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + cursor, _, ok := editor.TrackHistory() + if !ok { + t.Fatal("history setup refused") + } + editor.Type("x") + editor.SetSavePoint() + if active && !editor.ApplyComposition(text.CompositionEvent{Phase: text.CompositionUpdate, Text: "p"}) { + t.Fatal("active setup refused") + } + _, cursor, ok = editor.HistorySince(cursor) + if !ok { + t.Fatal("history prefix unavailable before refusal") + } + before, undo, redo, saved := TextStateOf(editor), editor.CanUndo(), editor.CanRedo(), editor.AtSavePoint() + owner := &painter{activeText: &TextInput{Editor: editor}, nativeText: platform.TextInput{Secure: true}} + ack, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextInsert, CompositionPhase: text.CompositionPhase(255), Text: "refused"}) + if err != nil || TextStateOf(editor) != before || editor.CanUndo() != undo || editor.CanRedo() != redo || editor.AtSavePoint() != saved || ack.WithoutRedraw() != platform.EditorState(editor) { + t.Errorf("refused secure event changed source/save/undo: state=%+v undo=%t redo=%t saved=%t err=%v", TextStateOf(editor), editor.CanUndo(), editor.CanRedo(), editor.AtSavePoint(), err) + } + if frames, latest, ok := editor.HistorySince(cursor); !ok || len(frames) != 0 || latest != cursor { + t.Error("refused secure event cleared producer metadata") + } + }) + } +} + +func TestPainterSecureLegacyCompositionStillClearsHistory(t *testing.T) { + for _, mode := range []string{"disabled legacy", "enabled legacy", "explicit escape"} { + t.Run(mode, func(t *testing.T) { + editor := text.NewEditor("abc") + if mode != "disabled legacy" && !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + owner := &painter{activeText: &TextInput{Editor: editor}, nativeText: platform.TextInput{Secure: true}} + if mode == "explicit escape" { + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "p"}); err != nil { + t.Fatal(err) + } + } + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextSetMarked, Text: "q"}); err != nil { + t.Fatal(err) + } + if editor.String() != "aqc" || !editor.CompositionActive() || editor.CanUndo() || editor.CanRedo() { + t.Fatalf("legacy marking retained password history: state=%+v undo=%t redo=%t", TextStateOf(editor), editor.CanUndo(), editor.CanRedo()) + } + ack, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "r"}) + if err != nil || editor.String() != "arc" || editor.CompositionActive() || editor.CanUndo() || editor.CanRedo() || ack.WithoutRedraw() != platform.EditorState(editor) { + t.Fatalf("legacy result changed secure behavior: state=%+v undo=%t redo=%t err=%v", TextStateOf(editor), editor.CanUndo(), editor.CanRedo(), err) + } + }) + } +} + +func TestPainterSingleLineLegacyControlTextStaysIgnored(t *testing.T) { + for _, enabled := range []bool{false, true} { + for _, phase := range []text.CompositionPhase{text.CompositionNone, text.CompositionResult} { + if enabled && phase != text.CompositionNone { + continue + } + editor := text.NewEditor("abc") + if enabled && !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + calls := 0 + owner := &painter{activeText: &TextInput{State: TextStateOf(editor), OnEvent: func(event TextEvent) (TextState, error) { + calls++ + return TextStateOf(editor), nil + }}} + for _, event := range []platform.TextEvent{ + {Kind: platform.TextInsert, Text: "\n"}, + {Kind: platform.TextCommandEvent, Command: platform.TextInsertNewline}, + {Kind: platform.TextCommandEvent, Command: platform.TextInsertLineBreak}, + } { + event.CompositionPhase = phase + if _, err := owner.applyTextEvent(event); err != nil || calls != 0 { + t.Fatalf("legacy control-only input reached the handler: enabled=%t phase=%v calls=%d err=%v", enabled, phase, calls, err) + } + } + } + } +} + +func TestPainterFocusedStateCarriesTentativeCapability(t *testing.T) { + editor := text.NewEditor("Go") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + var canvas gfx.Canvas + config := Config{Title: "capability snapshot", Width: 200, Height: 80} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(11), gfx.Rect{Width: 120, Height: 24}, "Name", gfx.HitOptions{Role: gfx.RoleTextField}) + } + config.TextInput = func(context TextInputContext) *TextInput { + return &TextInput{Bounds: context.Bounds, FontSize: 13, Editor: editor} + } + owner := newTestPainter(t, &canvas, config) + for _, kind := range []platform.PointerEventKind{platform.PointerMove, platform.PointerDown, platform.PointerUp} { + if _, err := owner.pointerEvent(platform.PointerEvent{Kind: kind, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + } + owner.syncTextInput() + if !owner.nativeText.State.TentativeComposition || owner.nativeText.State.CompositionIdentity != editor.TentativeCompositionIdentity() { + t.Fatal("focused native state lost capability ownership") + } + if !editor.DisableTentativeComposition() { + t.Fatal("disable refused") + } + owner.syncTextInput() + if owner.nativeText.State.TentativeComposition || TextStateOf(editor).TentativeComposition { + t.Fatal("passive disabled owner leaked an enabled snapshot") + } +} + +func TestPainterDistinguishesIdenticalTentativeEditorOwners(t *testing.T) { + for _, custom := range []bool{false, true} { + name := "editor" + if custom { + name = "custom handler" + } + t.Run(name, func(t *testing.T) { + first, second := text.NewEditor("same"), text.NewEditor("same") + if !first.EnableTentativeComposition() || !second.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + current := first + var canvas gfx.Canvas + config := Config{Title: "composition ownership", Width: 200, Height: 80} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(11), gfx.Rect{Width: 120, Height: 24}, "Name", gfx.HitOptions{Role: gfx.RoleTextField}) + } + config.TextInput = func(context TextInputContext) *TextInput { + owner := current + input := &TextInput{Bounds: context.Bounds, FontSize: 13, Editor: owner} + if custom { + input.Editor = nil + input.State = TextStateOf(owner) + input.OnEvent = func(event TextEvent) (TextState, error) { + event.Apply(owner) + return TextStateOf(owner), nil + } + } + return input + } + owner := newTestPainter(t, &canvas, config) + for _, kind := range []platform.PointerEventKind{platform.PointerMove, platform.PointerDown, platform.PointerUp} { + if _, err := owner.pointerEvent(platform.PointerEvent{Kind: kind, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + } + if update := owner.syncTextInput(); update.Changed { + t.Fatal("the same owner's identical snapshot forced input replacement") + } + if !first.DisableTentativeComposition() || !first.EnableTentativeComposition() { + t.Fatal("capability restart refused") + } + if update := owner.syncTextInput(); !update.Changed || update.Input == nil || + update.Input.State.CompositionIdentity != first.TentativeCompositionIdentity() { + t.Fatal("re-enabled ownership was not published for the identical target and editor") + } + current = second + if update := owner.syncTextInput(); !update.Changed || update.Input == nil { + t.Fatal("a different tentative owner with identical state was not replaced") + } + }) + } +} + +func TestTentativeStateSnapshotDoesNotRetainTheEditor(t *testing.T) { + released := make(chan struct{}) + makeSnapshot := func() TextState { + editor := text.NewEditor("snapshot remains readable") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + runtime.AddCleanup(editor, func(done chan struct{}) { close(done) }, released) + return TextStateOf(editor) + } + snapshot := makeSnapshot() + deadline := time.Now().Add(5 * time.Second) + for { + runtime.GC() + select { + case <-released: + if snapshot.Value != "snapshot remains readable" { + t.Fatal("reclaiming the Editor invalidated its value snapshot") + } + runtime.KeepAlive(snapshot) + return + default: + } + if time.Now().After(deadline) { + t.Fatal("a retained value snapshot kept the Editor and history alive") + } + runtime.Gosched() + } +} + +var nativeStateBenchmarkSink TextState + +func BenchmarkPainterTextAcknowledgment(b *testing.B) { + editor := text.NewEditor("a") + owner := &painter{activeText: &TextInput{Editor: editor}, nativeText: platform.TextInput{Multiline: true}} + b.ReportAllocs() + b.ResetTimer() + index := 0 + for b.Loop() { + index ^= 1 + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextSetSelection, Selection: text.Range{Start: index, End: index}}); err != nil { + b.Fatal(err) + } + } + b.ReportMetric(float64(unsafe.Sizeof(painter{})), "painter-B") +} + +func BenchmarkNativeStateSnapshot(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("state snapshot") + if enabled && !editor.EnableTentativeComposition() { + b.Fatal("capability setup refused") + } + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + nativeStateBenchmarkSink = TextStateOf(editor) + } + b.ReportMetric(float64(unsafe.Sizeof(TextState{})), "app-state-B") + b.ReportMetric(float64(unsafe.Sizeof(platform.TextState{})), "native-state-B") + runtime.KeepAlive(editor) + }) + } +} + +func BenchmarkNativeStateFirstSnapshot(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + editor := text.NewEditor("first snapshot") + if !editor.EnableTentativeComposition() { + b.Fatal("capability setup refused") + } + nativeStateBenchmarkSink = TextStateOf(editor) + } +} + +func BenchmarkNativeStateDefaultConstruction(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + editor := text.NewEditor("first snapshot") + nativeStateBenchmarkSink = TextStateOf(editor) + } +} + +func TestDefaultStateSnapshotPreservesConstructionAllocations(t *testing.T) { + allocations := testing.AllocsPerRun(100, func() { + editor := text.NewEditor("first snapshot") + nativeStateBenchmarkSink = TextStateOf(editor) + }) + if allocations > 2 { + t.Fatalf("default state snapshot construction allocated %.0f times, want at most 2", allocations) + } +} diff --git a/app/driver_system.go b/app/driver_system.go index c6174578c..163b0f834 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -6,6 +6,7 @@ import ( "fmt" "path/filepath" "runtime" + "sort" "sync" "sync/atomic" @@ -30,6 +31,8 @@ type driverSystem struct { clipboardHTML string // the rich flavour SetClipboardHTML last wrote beside the plain one primary string // the primary selection (Linux only), private like the clipboard schemes []string // the URL schemes SetSchemeHandlers declared as registered + sleepMu sync.Mutex + sleep map[string]int // sleep-prevention reasons this run holds, with their counts } type driverSaveFileResponse struct { @@ -188,6 +191,46 @@ func driverDeleteSecret(service, account string) (error, bool) { return nil, true } +// driverPreventSleep answers PreventSleep in a driver-backed run: it records the +// request instead of asking the real system, so a headless test neither needs +// nor disturbs the machine's power state. +func driverPreventSleep(reason string) (func(), error, bool) { + system := activeDriverSystem.Load() + if system == nil { + return nil, nil, false + } + system.sleepMu.Lock() + if system.sleep == nil { + system.sleep = make(map[string]int) + } + system.sleep[reason]++ + system.sleepMu.Unlock() + var once sync.Once + return func() { + once.Do(func() { + system.sleepMu.Lock() + system.sleep[reason]-- + if system.sleep[reason] <= 0 { + delete(system.sleep, reason) + } + system.sleepMu.Unlock() + }) + }, nil, true +} + +// AwakeReasons returns the sleep-prevention reasons a driver-backed run holds, +// sorted, so a test can see what the application asked to keep awake. +func (driver *Driver) AwakeReasons() []string { + driver.system.sleepMu.Lock() + defer driver.system.sleepMu.Unlock() + reasons := make([]string, 0, len(driver.system.sleep)) + for reason := range driver.system.sleep { + reasons = append(reasons, reason) + } + sort.Strings(reasons) + return reasons +} + func driverSendNotification(notification Notification) (error, bool) { system := activeDriverSystem.Load() if system == nil { diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index d8d6376f1..809e936d4 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -51,3 +51,5 @@ func driverStoreSecret(string, string, []byte) (error, bool) { return nil, false func driverLoadSecret(string, string) ([]byte, error, bool) { return nil, nil, false } func driverDeleteSecret(string, string) (error, bool) { return nil, false } + +func driverPreventSleep(string) (func(), error, bool) { return nil, nil, false } diff --git a/app/file_icon_darwin_test.go b/app/file_icon_darwin_test.go index e0eeb439d..6dea0bc2b 100644 --- a/app/file_icon_darwin_test.go +++ b/app/file_icon_darwin_test.go @@ -4,6 +4,8 @@ package app import ( "bytes" + "os" + "path/filepath" "sync" "testing" ) @@ -67,6 +69,30 @@ func TestFileIconAnswersFromAnyGoroutineAndForAMissingPath(t *testing.T) { } } +func TestFileIconAnswersAMissingPathWithItsExtensionIcon(t *testing.T) { + // FileIcon documents that a path need not exist: its icon is the one for + // its extension. The reference is a real empty file of that type, which the + // system already answers correctly, so the comparison holds whatever the + // system associates the type with. + const pixels = 32 + dir := t.TempDir() + real := filepath.Join(dir, "document.txt") + if err := os.WriteFile(real, nil, 0o644); err != nil { + t.Fatal(err) + } + existing, err := FileIcon(real, pixels) + if err != nil { + t.Fatal(err) + } + missing, err := FileIcon(filepath.Join(dir, "never-created", "document.txt"), pixels) + if err != nil { + t.Fatalf("a missing path has the icon of its extension, got %v", err) + } + if !bytes.Equal(existing.Pix, missing.Pix) { + t.Fatal("a missing path got a different icon from the same type's real file") + } +} + func BenchmarkFileIcon(b *testing.B) { b.ReportAllocs() for b.Loop() { diff --git a/app/keepawake.go b/app/keepawake.go new file mode 100644 index 000000000..f433d191d --- /dev/null +++ b/app/keepawake.go @@ -0,0 +1,54 @@ +package app + +import ( + "errors" + "fmt" + "strings" + "unicode/utf8" +) + +// ErrSleepPreventionUnavailable reports that this system cannot be asked to +// stay awake: it has no power service to hold a request for this process, or +// the one it has refused. The Web target has none, and a Linux session without +// logind has none. +var ErrSleepPreventionUnavailable = errors.New("app: preventing system sleep is unavailable") + +// maxSleepReasonLength bounds the reason a platform shows in its power UI. +const maxSleepReasonLength = 256 + +// PreventSleep asks the operating system to keep the machine out of idle sleep +// while the returned release function has not been called. Use it for work +// whose interruption costs more than the sleep would: a file transfer, a long +// command, a remote desktop session. It does not keep the display on, and it +// does not prevent the user from sleeping the machine deliberately through the +// system's own controls. +// +// reason names the work and is what the system's power diagnostics show: pmset +// -g assertions on macOS, powercfg /requests on Windows, systemd-inhibit --list +// on Linux. It is required, at most 256 characters, and has no control +// characters. +// +// Every call is a separate request. Release each one exactly once; releasing +// twice is harmless, and the request also ends with the process. The call is +// safe from any goroutine, is bounded, and starts no goroutine, timer or +// polling loop. +// +// Where the system has no such service the call returns an error wrapping +// ErrSleepPreventionUnavailable: the Web target, and a Linux session without +// logind. Supports(CapabilityPreventSleep) reports the build target's answer +// before the first call. +func PreventSleep(reason string) (release func(), err error) { + if strings.TrimSpace(reason) == "" { + return nil, errors.New("app: a sleep-prevention reason is required") + } + if utf8.RuneCountInString(reason) > maxSleepReasonLength { + return nil, fmt.Errorf("app: a sleep-prevention reason is at most %d characters", maxSleepReasonLength) + } + if strings.ContainsAny(reason, "\x00\r\n") { + return nil, errors.New("app: a sleep-prevention reason has no control characters") + } + if release, err, handled := driverPreventSleep(reason); handled { + return release, err + } + return nativePreventSleep(reason) +} diff --git a/app/keepawake_darwin.go b/app/keepawake_darwin.go new file mode 100644 index 000000000..5e1c3c8c8 --- /dev/null +++ b/app/keepawake_darwin.go @@ -0,0 +1,18 @@ +//go:build darwin + +package app + +import ( + "errors" + "fmt" + + darwinplatform "github.com/vivaui/viva/internal/platform/darwin" +) + +func nativePreventSleep(reason string) (func(), error) { + release, err := darwinplatform.PreventSleep(reason) + if errors.Is(err, darwinplatform.ErrSleepUnavailable) { + return nil, fmt.Errorf("%w: %v", ErrSleepPreventionUnavailable, err) + } + return release, err +} diff --git a/app/keepawake_driver_test.go b/app/keepawake_driver_test.go new file mode 100644 index 000000000..e95dc2fb0 --- /dev/null +++ b/app/keepawake_driver_test.go @@ -0,0 +1,39 @@ +//go:build darwin || windows || linux + +package app + +import ( + "testing" +) + +func TestDriverInterceptsPreventSleep(t *testing.T) { + driver, err := NewDriver(Config{}, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + + release, err := PreventSleep("Motty: transferring files") + if err != nil { + t.Fatal(err) + } + if reasons := driver.AwakeReasons(); len(reasons) != 1 || reasons[0] != "Motty: transferring files" { + t.Fatalf("AwakeReasons = %v", reasons) + } + second, err := PreventSleep("Motty: remote desktop") + if err != nil { + t.Fatal(err) + } + if reasons := driver.AwakeReasons(); len(reasons) != 2 { + t.Fatalf("AwakeReasons = %v", reasons) + } + release() + release() // releasing twice does not end the other request + if reasons := driver.AwakeReasons(); len(reasons) != 1 || reasons[0] != "Motty: remote desktop" { + t.Fatalf("AwakeReasons = %v after one release", reasons) + } + second() + if reasons := driver.AwakeReasons(); len(reasons) != 0 { + t.Fatalf("AwakeReasons = %v after both releases", reasons) + } +} diff --git a/app/keepawake_js.go b/app/keepawake_js.go new file mode 100644 index 000000000..5e18866ff --- /dev/null +++ b/app/keepawake_js.go @@ -0,0 +1,7 @@ +//go:build js && wasm + +package app + +// nativePreventSleep has no page API to ask: a page cannot keep the machine +// awake. +func nativePreventSleep(string) (func(), error) { return nil, ErrSleepPreventionUnavailable } diff --git a/app/keepawake_linux.go b/app/keepawake_linux.go new file mode 100644 index 000000000..5a9f30883 --- /dev/null +++ b/app/keepawake_linux.go @@ -0,0 +1,18 @@ +//go:build linux + +package app + +import ( + "errors" + "fmt" + + linuxplatform "github.com/vivaui/viva/internal/platform/linux" +) + +func nativePreventSleep(reason string) (func(), error) { + release, err := linuxplatform.PreventSleep(reason) + if errors.Is(err, linuxplatform.ErrSleepUnavailable) { + return nil, fmt.Errorf("%w: %v", ErrSleepPreventionUnavailable, err) + } + return release, err +} diff --git a/app/keepawake_test.go b/app/keepawake_test.go new file mode 100644 index 000000000..921fdfa0d --- /dev/null +++ b/app/keepawake_test.go @@ -0,0 +1,14 @@ +package app + +import ( + "strings" + "testing" +) + +func TestPreventSleepValidatesItsReason(t *testing.T) { + for _, reason := range []string{"", " ", "\t", "a\x00b", "a\nb", "a\rb", strings.Repeat("x", maxSleepReasonLength+1)} { + if _, err := PreventSleep(reason); err == nil { + t.Fatalf("PreventSleep(%q) was accepted", reason) + } + } +} diff --git a/app/keepawake_unsupported.go b/app/keepawake_unsupported.go new file mode 100644 index 000000000..d4550fa02 --- /dev/null +++ b/app/keepawake_unsupported.go @@ -0,0 +1,5 @@ +//go:build !darwin && !windows && !linux && !(js && wasm) + +package app + +func nativePreventSleep(string) (func(), error) { return nil, ErrSleepPreventionUnavailable } diff --git a/app/keepawake_windows.go b/app/keepawake_windows.go new file mode 100644 index 000000000..abdaf154b --- /dev/null +++ b/app/keepawake_windows.go @@ -0,0 +1,18 @@ +//go:build windows + +package app + +import ( + "errors" + "fmt" + + windowsplatform "github.com/vivaui/viva/internal/platform/windows" +) + +func nativePreventSleep(reason string) (func(), error) { + release, err := windowsplatform.PreventSleep(reason) + if errors.Is(err, windowsplatform.ErrSleepUnavailable) { + return nil, fmt.Errorf("%w: %v", ErrSleepPreventionUnavailable, err) + } + return release, err +} diff --git a/app/menu_bar.go b/app/menu_bar.go new file mode 100644 index 000000000..e8ca146ac --- /dev/null +++ b/app/menu_bar.go @@ -0,0 +1,102 @@ +package app + +import ( + "errors" + "fmt" + "strings" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/keymap" +) + +// Menu is one top-level menu of the application's own menu bar entries, shown +// between the application menu and the Window menu macOS supplies. Windows and +// Linux do not have an application menu bar in this API yet: SetMenuBar returns +// ErrUnsupported there, and an application uses the in-window components.Menubar. +type Menu struct { + Title string + Items []MenuBarItem +} + +// MenuBarItem is one entry of a Menu. +type MenuBarItem struct { + Title string + // Separator makes the entry a dividing line; its other fields are ignored. + Separator bool + // Disabled shows the entry dimmed and not selectable. + Disabled bool + // Checked puts a check mark beside the entry. Set it when the menu is built; + // call SetMenuBar again to show a new state. + Checked bool + // Shortcut is the key the system offers for the entry. Only a character key + // is represented in a menu; a chord with a named key shows no shortcut, and + // the application still receives that key through its own handler. + Shortcut keymap.Chord + // Submenu, when not empty, makes the entry open a menu of these. + Submenu []MenuBarItem + // OnSelect runs on the event-loop thread when the user chooses the entry. + OnSelect func() +} + +// SetMenuBar replaces the application's own menus. It is macOS-only today and +// returns an error wrapping ErrUnsupported elsewhere. Call it on the +// event-loop thread; the menus are built now, so an application that shows +// changing state (a check mark) calls it again with the new value. +// +// The standard application and Window menus stay where the system puts them; +// these menus are inserted between them. +func (application *Application) SetMenuBar(menus []Menu) error { + if application == nil || application.host == nil { + return errors.New("app: the application is not running") + } + setter, ok := application.host.(interface{ SetMenuBar([]Menu) error }) + if !ok { + return fmt.Errorf("%w: the application menu bar", ErrUnsupported) + } + return setter.SetMenuBar(menus) +} + +// platform menus carry a key as a character and a modifier mask, so the +// platform layer does not depend on keymap. +func platformMenuBar(menus []Menu) []platform.MenuBarMenu { + out := make([]platform.MenuBarMenu, len(menus)) + for index, menu := range menus { + out[index] = platform.MenuBarMenu{Title: menu.Title, Items: platformMenuItems(menu.Items)} + } + return out +} + +func platformMenuItems(items []MenuBarItem) []platform.MenuBarItem { + out := make([]platform.MenuBarItem, len(items)) + for index, item := range items { + key := "" + var modifiers uint32 + if item.Shortcut.Char != 0 { + key = strings.ToLower(string(item.Shortcut.Char)) + modifiers = menuModifiers(item.Shortcut.Modifiers) + } + out[index] = platform.MenuBarItem{ + Title: item.Title, Separator: item.Separator, Disabled: item.Disabled, Checked: item.Checked, + Key: key, Modifiers: modifiers, OnSelect: item.OnSelect, Items: platformMenuItems(item.Submenu), + } + } + return out +} + +func menuModifiers(modifiers gfx.Modifiers) uint32 { + var out uint32 + if modifiers&gfx.ModifierMeta != 0 { + out |= 1 << 20 // NSEventModifierFlagCommand + } + if modifiers&gfx.ModifierShift != 0 { + out |= 1 << 17 // NSEventModifierFlagShift + } + if modifiers&gfx.ModifierAlt != 0 { + out |= 1 << 19 // NSEventModifierFlagOption + } + if modifiers&gfx.ModifierControl != 0 { + out |= 1 << 18 // NSEventModifierFlagControl + } + return out +} diff --git a/app/menu_bar_test.go b/app/menu_bar_test.go new file mode 100644 index 000000000..6d7c61aec --- /dev/null +++ b/app/menu_bar_test.go @@ -0,0 +1,42 @@ +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" +) + +func TestMenuBarItemsCarryCharacterShortcuts(t *testing.T) { + menus := platformMenuBar([]Menu{{ + Title: "File", + Items: []MenuBarItem{ + {Title: "New", Shortcut: keymap.Chord{Char: 'N', Modifiers: gfx.ModifierMeta}}, + {Title: "Disabled", Disabled: true}, + {Title: "More", Shortcut: keymap.Chord{}, Submenu: []MenuBarItem{{Title: "Inside", Shortcut: keymap.Chord{Char: 'i', Modifiers: gfx.ModifierAlt}}}}, + }, + }}) + if len(menus) != 1 || menus[0].Title != "File" || len(menus[0].Items) != 3 { + t.Fatalf("menus = %+v", menus) + } + newItem := menus[0].Items[0] + if newItem.Key != "n" || newItem.Modifiers != 1<<20 { + t.Fatalf("New = %+v, want key n with Command", newItem) + } + if menus[0].Items[1].Disabled != true { + t.Fatalf("Disabled = %+v", menus[0].Items[1]) + } + nested := menus[0].Items[2] + if len(nested.Items) != 1 || nested.Items[0].Key != "i" || nested.Items[0].Modifiers != 1<<19 { + t.Fatalf("nested = %+v", nested) + } +} + +func TestANamedKeyShowsNoMenuShortcut(t *testing.T) { + menus := platformMenuBar([]Menu{{Title: "Edit", Items: []MenuBarItem{ + {Title: "Delete", Shortcut: keymap.Chord{Key: gfx.KeyDelete, Modifiers: gfx.ModifierMeta}}, + }}}) + if menus[0].Items[0].Key != "" || menus[0].Items[0].Modifiers != 0 { + t.Fatalf("a named key became a menu shortcut: %+v", menus[0].Items[0]) + } +} diff --git a/app/painter.go b/app/painter.go index b3b70a99c..b1a92b481 100644 --- a/app/painter.go +++ b/app/painter.go @@ -7,6 +7,7 @@ import ( "math" "slices" "time" + "unicode" "unicode/utf8" "unsafe" @@ -42,11 +43,16 @@ type painter struct { textInput TextInputProvider activeText *TextInput 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. - placing bool - placeAnchor int - nativeText platform.TextInput + // (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 + // selection it covered, which a drag then extends by the same unit. + placing bool + placeAnchor int + placeUnit int + placeUnitRange text.Range + nativeText platform.TextInput // keys follows the keys of a terminal that asked for releases (see // TextInput.KeyReleases). keys interaction.Keys @@ -422,10 +428,35 @@ func (painter *painter) placeCaret(event platform.PointerEvent) bool { } value := input.State.Value index := utf8.RuneCountInString(value[:max(0, min(offset, len(value)))]) - if event.Kind == platform.PointerDown { + selection := TextEvent{Kind: TextSetSelection, Selection: TextRange{Start: painter.placeAnchor, End: index}} + switch event.Kind { + case platform.PointerDown: painter.placing, painter.placeAnchor = true, index + painter.placeUnit, painter.placeUnitRange = 0, text.Range{} + switch { + case event.ClickCount >= 3: + painter.placeUnit, painter.placeUnitRange = 3, text.LineRange(value, index) + case event.ClickCount == 2: + painter.placeUnit, painter.placeUnitRange = 2, text.WordRange(value, index) + } + if painter.placeUnit == 2 && rangeIsSpace(value, painter.placeUnitRange) { + // A double click on whitespace has no word to take: leave the caret + // where the press landed instead of selecting the newlines that the + // next keystroke would use to join two lines. + painter.placeUnit = 0 + } + if painter.placeUnit != 0 { + painter.placeAnchor = painter.placeUnitRange.Start + selection.Selection = TextRange{Start: painter.placeUnitRange.Start, End: painter.placeUnitRange.End} + } + default: + if painter.placeUnit != 0 { + selection.Selection = placeUnitSelection(value, index, painter.placeUnit, painter.placeUnitRange) + } + if event.Kind == platform.PointerUp { + painter.placeUnit, painter.placeUnitRange = 0, text.Range{} + } } - selection := TextEvent{Kind: TextSetSelection, Selection: TextRange{Start: painter.placeAnchor, End: index}} if input.Editor != nil { selection.Apply(input.Editor) input.State = TextStateOf(input.Editor) @@ -442,6 +473,35 @@ func (painter *painter) placeCaret(event platform.PointerEvent) bool { return true } +// placeUnitSelection extends the unit a multi-click press took to the unit +// under the dragging pointer, keeping the pressed unit whole. +func placeUnitSelection(value string, index, unit int, anchor text.Range) TextRange { + target := text.WordRange(value, index) + if unit == 3 { + target = text.LineRange(value, index) + } + switch { + case index >= anchor.Start && index <= anchor.End: + return TextRange{Start: anchor.Start, End: anchor.End} + case index > anchor.End: + return TextRange{Start: anchor.Start, End: target.End} + default: + return TextRange{Start: target.Start, End: anchor.End} + } +} + +// rangeIsSpace reports whether a range of value holds only whitespace. +func rangeIsSpace(value string, r text.Range) bool { + runes := []rune(value) + start, end := max(0, min(r.Start, len(runes))), max(0, min(r.End, len(runes))) + for _, r := range runes[start:end] { + if !unicode.IsSpace(r) { + return false + } + } + return true +} + // isWindowControl reports whether id is one of the window buttons Viva draws. func (painter *painter) isWindowControl(id gfx.ID) bool { if painter.controls == nil || painter.fullscreen { @@ -1216,6 +1276,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { if !painter.textEnabled { return platform.TextInputUpdate{} } + painter.textEpoch++ painter.textEnabled = false return platform.TextInputUpdate{Changed: true} } @@ -1254,6 +1315,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { if !painter.textEnabled { return platform.TextInputUpdate{} } + painter.textEpoch++ painter.textEnabled = false return platform.TextInputUpdate{Changed: true} } @@ -1284,13 +1346,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { Red: float64(tint.Red), Green: float64(tint.Green), Blue: float64(tint.Blue), Alpha: float64(tint.Alpha), }, - State: platform.TextState{ - Value: input.State.Value, - Selection: platformTextRange(input.State.Selection), - SelectionReversed: input.State.SelectionReversed, - Composition: platformTextRange(input.State.Composition), - Composing: input.State.Composing, - }, + State: platformTextState(input.State).WithoutRedraw(), OnEvent: painter.onTextEvent, } if placement != nil { @@ -1303,6 +1359,12 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { } } painter.activeText = input + 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 || + painter.nativeText.DisableIME != native.DisableIME || painter.nativeText.State != native.State { + painter.textEpoch++ + } if painter.textEnabled && samePlatformTextInput(painter.nativeText, native) { return platform.TextInputUpdate{} } @@ -1317,21 +1379,24 @@ func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextS if active == nil || active.Editor == nil && active.OnEvent == nil { return platform.TextState{}, fmt.Errorf("app: native text event without an active handler") } - appEvent := TextEvent{ - Kind: TextEventKind(event.Kind), Text: event.Text, - Selection: appTextRange(event.Selection), - MarkedSelection: appTextRange(event.MarkedSelection), - Replacement: appTextRange(event.Replacement), HasReplacement: event.HasReplacement, - Command: TextCommand(event.Command), + epoch := painter.textEpoch + appEvent := appTextEvent(event) + explicit := event.CompositionPhase != text.CompositionNone + if explicit { + if active.Editor != nil { + explicit = active.Editor.TentativeCompositionEnabled() + } else { + explicit = active.State.TentativeComposition + } } if !painter.nativeText.Multiline && !painter.nativeText.Terminal && (event.Kind == platform.TextPaste || event.Kind == platform.TextInsert) && event.Text != "" { appEvent.Text = text.SingleLine(event.Text) - if appEvent.Text == "" { + if appEvent.Text == "" && !explicit { return painter.nativeText.State, nil } } - if !painter.nativeText.Multiline && !painter.nativeText.Terminal && + if !explicit && !painter.nativeText.Multiline && !painter.nativeText.Terminal && event.Kind == platform.TextCommandEvent && (event.Command == platform.TextInsertNewline || event.Command == platform.TextInsertLineBreak) { // A single-line field holds no line break. While an input method is @@ -1341,8 +1406,8 @@ func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextS } var next TextState if active.Editor != nil { - appEvent.Apply(active.Editor) - if painter.nativeText.Secure { + accepted := appEvent.apply(active.Editor) + if painter.nativeText.Secure && accepted && !active.Editor.TentativeCompositionActive() { active.Editor.ClearHistory() } next = TextStateOf(active.Editor) @@ -1352,15 +1417,18 @@ func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextS return platform.TextState{}, err } } - painter.activeText.State = next - native := platform.TextState{ - Value: next.Value, - Selection: platformTextRange(next.Selection), - SelectionReversed: next.SelectionReversed, - Composition: platformTextRange(next.Composition), - Composing: next.Composing, - Redraw: next.Redraw, + if painter.textEpoch != epoch { + // Nested input or provider replacement has already installed newer state. + if painter.activeText == nil { + return platform.TextState{Redraw: true}, nil + } + native := painter.nativeText.State + native.Redraw = true + return native, nil } + painter.textEpoch++ + painter.activeText.State = next + native := platformTextState(next) // What the platform mirrors back never carries the one-shot request. painter.nativeText.State = native.WithoutRedraw() painter.activeText.State.Redraw = false diff --git a/app/place_unit_test.go b/app/place_unit_test.go new file mode 100644 index 000000000..a21bb95c5 --- /dev/null +++ b/app/place_unit_test.go @@ -0,0 +1,47 @@ +package app + +import ( + "testing" + + "github.com/vivaui/viva/text" +) + +func TestPlaceUnitSelectionKeepsWholeWordsAndLines(t *testing.T) { + const value = "alpha beta gamma" + word := text.WordRange(value, 7) // beta + if word != (text.Range{Start: 6, End: 10}) { + t.Fatalf("word = %+v", word) + } + if got := placeUnitSelection(value, 12, 2, word); got != (TextRange{Start: 6, End: 16}) { + t.Fatalf("drag right = %+v", got) + } + if got := placeUnitSelection(value, 1, 2, word); got != (TextRange{Start: 0, End: 10}) { + t.Fatalf("drag left = %+v", got) + } + if got := placeUnitSelection(value, 8, 2, word); got != (TextRange{Start: 6, End: 10}) { + t.Fatalf("drag inside the word = %+v", got) + } + + const lines = "one\ntwo\nthree" + line := text.LineRange(lines, 5) // two, with its newline + if line != (text.Range{Start: 4, End: 8}) { + t.Fatalf("line = %+v", line) + } + if got := placeUnitSelection(lines, 10, 3, line); got != (TextRange{Start: 4, End: 13}) { + t.Fatalf("line drag down = %+v", got) + } + if got := placeUnitSelection(lines, 1, 3, line); got != (TextRange{Start: 0, End: 8}) { + t.Fatalf("line drag up = %+v", got) + } +} + +func TestRangeIsSpaceFindsBlankRuns(t *testing.T) { + const value = "alpha\n\ngamma" + blank := text.WordRange(value, 6) // the two newlines of the empty line + if !rangeIsSpace(value, blank) { + t.Fatalf("blank run %+v is not whitespace", blank) + } + if rangeIsSpace(value, text.Range{Start: 0, End: 5}) { + t.Fatal("a word was taken for whitespace") + } +} diff --git a/app/proxy/native_darwin.go b/app/proxy/native_darwin.go new file mode 100644 index 000000000..b88aa6eea --- /dev/null +++ b/app/proxy/native_darwin.go @@ -0,0 +1,19 @@ +//go:build darwin + +package proxy + +import ( + "errors" + "fmt" + "net/url" + + darwinplatform "github.com/vivaui/viva/internal/platform/darwin" +) + +func nativeSystemProxy(target *url.URL) (*url.URL, error) { + proxy, err := darwinplatform.SystemProxy(target.String()) + if errors.Is(err, darwinplatform.ErrProxyUnavailable) { + return nil, fmt.Errorf("%w: %v", errSystemProxyUnavailable, err) + } + return proxy, err +} diff --git a/app/proxy/native_js.go b/app/proxy/native_js.go new file mode 100644 index 000000000..3b5c6f503 --- /dev/null +++ b/app/proxy/native_js.go @@ -0,0 +1,7 @@ +//go:build js && wasm + +package proxy + +import "net/url" + +func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrUnavailable } diff --git a/app/proxy/native_linux.go b/app/proxy/native_linux.go new file mode 100644 index 000000000..f4b0a3e86 --- /dev/null +++ b/app/proxy/native_linux.go @@ -0,0 +1,11 @@ +//go:build linux + +package proxy + +import "net/url" + +// nativeSystemProxy is the environment, which SystemProxy has already read: +// Linux desktops that keep a proxy in GSettings do not export it, and asking +// them would mean starting a session-bus or GIO connection for a setting most +// programs do not read. A system proxy configured there is not reported. +func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, nil } diff --git a/app/proxy/native_unsupported.go b/app/proxy/native_unsupported.go new file mode 100644 index 000000000..5488aa63a --- /dev/null +++ b/app/proxy/native_unsupported.go @@ -0,0 +1,7 @@ +//go:build !darwin && !windows && !linux && !(js && wasm) + +package proxy + +import "net/url" + +func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrUnavailable } diff --git a/app/proxy/native_windows.go b/app/proxy/native_windows.go new file mode 100644 index 000000000..ead6795bc --- /dev/null +++ b/app/proxy/native_windows.go @@ -0,0 +1,19 @@ +//go:build windows + +package proxy + +import ( + "errors" + "fmt" + "net/url" + + windowsplatform "github.com/vivaui/viva/internal/platform/windows" +) + +func nativeSystemProxy(target *url.URL) (*url.URL, error) { + proxy, err := windowsplatform.SystemProxy(target.String()) + if errors.Is(err, windowsplatform.ErrProxyUnavailable) { + return nil, fmt.Errorf("%w: %v", errSystemProxyUnavailable, err) + } + return proxy, err +} diff --git a/app/proxy/proxy.go b/app/proxy/proxy.go new file mode 100644 index 000000000..6cef6ffcc --- /dev/null +++ b/app/proxy/proxy.go @@ -0,0 +1,70 @@ +// Package proxy reads the desktop's proxy settings. It is a package of its own +// rather than part of app so that an application which never asks for a proxy +// does not link net/http and its TLS stack: SystemProxy is the only entry, and +// the environment answer is net/http's own. +package proxy + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "os" +) + +// ErrUnavailable reports that the desktop's proxy settings could not +// be read: a macOS system that routes through a PAC script, or a Windows +// WinHTTP session that refused the request. An application that gets it either +// goes direct or keeps its own resolver; Viva never reports a proxy it did not +// read. +var ErrUnavailable = errors.New("app: the system proxy settings cannot be read") + +// SystemProxy reports the proxy the desktop's settings select for target, nil +// when the request goes direct. It is for HTTP clients: the update downloader, +// a WebView-less API call, an MCP bridge. +// +// An explicit proxy in the environment (HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and +// their lowercase forms, with NO_PROXY) wins, as it does for net/http. Without +// one, macOS asks CFNetwork, Windows asks WinHTTP's automatic proxy (PAC, WPAD +// and the static per-user settings), and Linux reads the environment only: +// desktops that keep their proxy in GSettings do not export it, and this +// package does not start a D-Bus or GIO session to find it. +// +// A macOS system whose policy is a PAC script returns +// ErrUnavailable: evaluating the script is asynchronous and needs a +// run loop, and silently going direct would bypass the user's policy. +// +// The call may block while the system evaluates its policy. It starts no +// goroutine and keeps nothing after it returns. +func SystemProxy(target *url.URL) (*url.URL, error) { + if target == nil || (target.Scheme != "http" && target.Scheme != "https") { + return nil, errors.New("app: SystemProxy needs an http or https URL") + } + if environmentProxyConfigured() { + request := &http.Request{URL: target} + return http.ProxyFromEnvironment(request) + } + proxy, err := nativeSystemProxy(target) + if errors.Is(err, errSystemProxyUnavailable) { + return nil, fmt.Errorf("%w: %v", ErrUnavailable, err) + } + return proxy, err +} + +// errSystemProxyUnavailable is what a platform reports for a policy it cannot +// evaluate; SystemProxy turns it into ErrUnavailable. +var errSystemProxyUnavailable = errors.New("app: the system proxy settings cannot be read") + +// environmentProxyConfigured reports whether any proxy variable is set at all. +// Without one, a nil answer from net/http means "direct", and the system is +// asked instead; with one, NO_PROXY's answer is the last word. +func environmentProxyConfigured() bool { + for _, name := range []string{ + "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy", + } { + if os.Getenv(name) != "" { + return true + } + } + return false +} diff --git a/app/proxy/proxy_test.go b/app/proxy/proxy_test.go new file mode 100644 index 000000000..5d37a1cdf --- /dev/null +++ b/app/proxy/proxy_test.go @@ -0,0 +1,67 @@ +package proxy + +import ( + "net/url" + "os" + "os/exec" + "runtime" + "strings" + "testing" +) + +func TestSystemProxyNeedsAnHTTPURL(t *testing.T) { + for _, raw := range []string{"ftp://example.com", "file:///tmp/x", "example.com"} { + target, err := url.Parse(raw) + if err != nil { + continue + } + if _, err := SystemProxy(target); err == nil { + t.Errorf("SystemProxy(%q) was accepted", raw) + } + } + if _, err := SystemProxy(nil); err == nil { + t.Fatal("SystemProxy(nil) was accepted") + } +} + +// TestSystemProxyReadsTheEnvironmentInAFreshProcess runs the assertion in a +// child: net/http caches the environment the first time it is asked, so a +// table of t.Setenv calls would test the cache, not the proxy. +func TestSystemProxyReadsTheEnvironmentInAFreshProcess(t *testing.T) { + if runtime.GOOS == "js" { + t.Skip("a wasm test cannot start a child process") + } + if os.Getenv("VIVA_PROXY_CHILD") == "1" { + target, err := url.Parse("http://example.com/path") + if err != nil { + t.Fatal(err) + } + proxy, err := SystemProxy(target) + if err != nil { + t.Fatal(err) + } + if proxy == nil || proxy.Host != "127.0.0.1:3128" { + t.Fatalf("proxy = %+v, want the environment's", proxy) + } + return + } + var environment []string + for _, entry := range os.Environ() { + name, _, _ := strings.Cut(entry, "=") + switch strings.ToLower(name) { + case "http_proxy", "https_proxy", "all_proxy", "no_proxy": + continue + } + environment = append(environment, entry) + } + environment = append(environment, + "VIVA_PROXY_CHILD=1", + "HTTP_PROXY=http://127.0.0.1:3128", + "NO_PROXY=", + ) + command := exec.Command(os.Args[0], "-test.run=TestSystemProxyReadsTheEnvironmentInAFreshProcess") + command.Env = environment + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("%v\n%s", err, output) + } +} diff --git a/app/run.go b/app/run.go index 93a1b3d08..e568aa86a 100644 --- a/app/run.go +++ b/app/run.go @@ -38,5 +38,6 @@ func Run(config Config) error { Blue: normalized.ClearColor.Blue, Alpha: normalized.ClearColor.Alpha, }, + WindowBorderColor: borderColorHandler(normalized.WindowBorderColor), }) } diff --git a/app/run_canvas.go b/app/run_canvas.go index 8e5831f1b..69dd5f9c1 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -70,6 +70,18 @@ func minimizeHandler(callback func(bool)) platform.MinimizeHandler { return platform.MinimizeHandler(callback) } +// borderColorHandler adapts the application's window border color callback to +// the platform's. It runs on the window thread with every frame. +func borderColorHandler(callback func() Color) func() platform.Color { + if callback == nil { + return nil + } + return func() platform.Color { + color := callback() + return platform.Color{Red: color.Red, Green: color.Green, Blue: color.Blue, Alpha: color.Alpha} + } +} + // maximizeHandler adapts the application's maximize callback to the platform's. // OpenWindow always installs one, so the runtime's own state stays current. func maximizeHandler(callback func(bool)) platform.MaximizeHandler { @@ -146,7 +158,7 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, if normalized.OnCloseRequest != nil { closeHandler = platform.CloseRequestHandler(normalized.OnCloseRequest) } - return platform.Config{ + config := platform.Config{ Actions: painter.windowActions(), TextInput: painter.initialTextInput(), Title: normalized.Title, Class: normalized.Class, Icon: normalized.Icon.platform(), Width: normalized.Width, Height: normalized.Height, @@ -190,7 +202,9 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, OnCloseRequest: closeHandler, OnClosed: normalized.OnClosed, DynamicTextInput: normalized.TextInput != nil, - }, frames + } + config.WindowBorderColor = borderColorHandler(normalized.WindowBorderColor) + return config, frames } // prepareNativeWindow builds the native window for one application window. It diff --git a/app/run_canvas_js_test.go b/app/run_canvas_js_test.go index e05d70093..f5b0578f9 100644 --- a/app/run_canvas_js_test.go +++ b/app/run_canvas_js_test.go @@ -103,6 +103,52 @@ func TestWebTextInputConnectsAnEditorToTheBrowser(t *testing.T) { } } +func TestWebTextInputPreservesTaggedCompositionAndOwnership(t *testing.T) { + for _, custom := range []bool{false, true} { + name := "editor" + if custom { + name = "handler" + } + t.Run(name, func(t *testing.T) { + editor := text.NewEditor("abcd") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + var received TextEvent + provider := webTextInput(func(TextInputContext) *TextInput { + if custom { + return &TextInput{State: TextStateOf(editor), OnEvent: func(event TextEvent) (TextState, error) { + received = event + event.Apply(editor) + return TextStateOf(editor), nil + }} + } + return &TextInput{Editor: editor} + }) + input := provider(web.TextInputContext{ID: gfx.Item(7), Multiline: true}) + if !input.State.TentativeComposition || input.State.CompositionIdentity != editor.TentativeCompositionIdentity() { + t.Fatal("Web state dropped capability ownership") + } + for _, event := range []platform.TextEvent{ + {Kind: platform.TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "\u00e9\U0001d11e", MarkedSelection: text.Range{Start: 2, End: 2}}, + {Kind: platform.TextInsert, CompositionPhase: text.CompositionResult, Text: "r", HasReplacementUTF16: true, ReplacementUTF16: text.UTF16Range{Start: 5, Length: 1}}, + } { + state, err := input.OnEvent(event) + if err != nil || state != platform.EditorState(editor) { + t.Fatalf("Web acknowledgment = %+v, err=%v", state, err) + } + if custom && received != appTextEvent(event) { + t.Fatalf("Web handler lost tagged fields: %+v", received) + } + } + if editor.String() != "acdr" || editor.CompositionActive() { + t.Fatalf("Web tagged result = %+v", TextStateOf(editor)) + } + }) + } +} + func TestWebTextInputPreservesAlignment(t *testing.T) { for _, testcase := range []struct { name string diff --git a/app/text_input.go b/app/text_input.go index 61ac88f63..0c3d79cd3 100644 --- a/app/text_input.go +++ b/app/text_input.go @@ -28,11 +28,16 @@ type TextState struct { Selection TextRange Composition TextRange Composing bool + // TentativeComposition snapshots the editor's explicit opt-in capability, + // independently of whether it currently has visible marked text. + TentativeComposition bool // Redraw asks for a frame after the event although the editor looks the same, // because the application changed something else in response. A terminal // uses it when typed text appears ahead of the server's echo; ordinary // terminal input leaves it false and costs no frame. Redraw bool + // Numeric ownership keeps editor/history references out of value snapshots. + compositionIdentity text.CompositionIdentity } // TextEventKind identifies one native text-system mutation. @@ -111,6 +116,11 @@ type TextEvent struct { Replacement TextRange HasReplacement bool Command TextCommand + // CompositionPhase is forwarded unchanged; the target editor's capability + // selects the explicit route. Zero preserves the legacy event contract. + CompositionPhase text.CompositionPhase + ReplacementUTF16 text.UTF16Range + HasReplacementUTF16 bool } // TextInputContext describes the focused Canvas text-field hit. @@ -202,7 +212,8 @@ type TextInput struct { // it composes with the input method over there. Text events still arrive // if a method commits anyway, so a paste keeps working. Combine it with // KeyReleases for a surface that shows another machine's desktop. - // Implemented on Windows. + // Implemented on macOS and Windows; the Linux backend does not consult it + // yet. DisableIME bool // NavigationKeys asks Up, Down, PageUp and PageDown to reach the // application as raw gfx.KeyEvents while the field is focused, instead @@ -232,11 +243,44 @@ func TextStateOf(editor *text.Editor) TextState { selection := editor.Selection() composition, composing := editor.Composition() return TextState{ - Value: editor.String(), - Selection: appTextRange(selection), - SelectionReversed: selection.Start != selection.End && editor.Caret() == selection.Start, - Composition: appTextRange(composition), - Composing: composing, + Value: editor.String(), + Selection: appTextRange(selection), + SelectionReversed: selection.Start != selection.End && editor.Caret() == selection.Start, + Composition: appTextRange(composition), + Composing: composing, + TentativeComposition: editor.TentativeCompositionEnabled(), + compositionIdentity: editor.TentativeCompositionIdentity(), + } +} + +func platformTextState(state TextState) platform.TextState { + identity := state.compositionIdentity + if !state.TentativeComposition { + identity = text.CompositionIdentity{} + } + return platform.TextState{ + Value: state.Value, + Selection: platformTextRange(state.Selection), + SelectionReversed: state.SelectionReversed, + Composition: platformTextRange(state.Composition), + Composing: state.Composing, + TentativeComposition: state.TentativeComposition, + Redraw: state.Redraw, + CompositionIdentity: identity, + } +} + +func appTextEvent(event platform.TextEvent) TextEvent { + return TextEvent{ + Kind: TextEventKind(event.Kind), Text: event.Text, + Selection: appTextRange(event.Selection), + MarkedSelection: appTextRange(event.MarkedSelection), + Replacement: appTextRange(event.Replacement), + HasReplacement: event.HasReplacement, + Command: TextCommand(event.Command), + CompositionPhase: event.CompositionPhase, + ReplacementUTF16: event.ReplacementUTF16, + HasReplacementUTF16: event.HasReplacementUTF16, } } @@ -244,14 +288,21 @@ func TextStateOf(editor *text.Editor) TextState { // the platform's, value for value, so the one switch that maps them lives in // internal/platform rather than in a second copy here. func (event TextEvent) Apply(editor *text.Editor) { - platform.TextEvent{ - Kind: platform.TextEventKind(event.Kind), - Text: event.Text, - Selection: platformTextRange(event.Selection), - MarkedSelection: platformTextRange(event.MarkedSelection), - Replacement: platformTextRange(event.Replacement), - HasReplacement: event.HasReplacement, - Command: platform.TextCommand(event.Command), + event.apply(editor) +} + +func (event TextEvent) apply(editor *text.Editor) bool { + return platform.TextEvent{ + Kind: platform.TextEventKind(event.Kind), + Text: event.Text, + Selection: platformTextRange(event.Selection), + MarkedSelection: platformTextRange(event.MarkedSelection), + Replacement: platformTextRange(event.Replacement), + HasReplacement: event.HasReplacement, + Command: platform.TextCommand(event.Command), + CompositionPhase: event.CompositionPhase, + ReplacementUTF16: event.ReplacementUTF16, + HasReplacementUTF16: event.HasReplacementUTF16, }.Apply(editor) } diff --git a/app/text_input_js.go b/app/text_input_js.go index 3c889e00a..dbf193c33 100644 --- a/app/text_input_js.go +++ b/app/text_input_js.go @@ -78,24 +78,3 @@ func webTextInput(provider TextInputProvider) web.TextInputProvider { return &native } } - -func platformTextState(state TextState) platform.TextState { - return platform.TextState{ - Value: state.Value, - Selection: platformTextRange(state.Selection), - SelectionReversed: state.SelectionReversed, - Composition: platformTextRange(state.Composition), - Composing: state.Composing, - Redraw: state.Redraw, - } -} - -func appTextEvent(event platform.TextEvent) TextEvent { - return TextEvent{ - Kind: TextEventKind(event.Kind), Text: event.Text, - Selection: appTextRange(event.Selection), - MarkedSelection: appTextRange(event.MarkedSelection), - Replacement: appTextRange(event.Replacement), HasReplacement: event.HasReplacement, - Command: TextCommand(event.Command), - } -} diff --git a/cmd/viva-conformance/main.go b/cmd/viva-conformance/main.go index 38d4fc2b1..711bfdf7a 100644 --- a/cmd/viva-conformance/main.go +++ b/cmd/viva-conformance/main.go @@ -312,15 +312,21 @@ func (r *runner) scenarios(results *report) { } time.Sleep(300 * time.Millisecond) before, floodFor := p.wakes.Load(), 600*time.Millisecond + var calls atomic.Int64 for end := time.Now().Add(floodFor); time.Now().Before(end); { p.inv.Invalidate() + calls.Add(1) } time.Sleep(quiet) - got := p.wakes.Load() - before - // The frame grid is 120 Hz; a few more allow for the first wake, which goes out at - // once, and a window thread that runs late. - if limit := int64(floodFor/(time.Second/120)) + 8; got < 1 || got > limit { - return fmt.Errorf("%d wakes in %v of constant Invalidate, want between 1 and %d", got, floodFor, limit) + got, sent := p.wakes.Load()-before, calls.Load() + // What must hold is coalescing, not a display rate: a window whose present + // blocks is paced by its display, and one presenting to a software surface + // (a virtual machine, a CPU fallback) legitimately runs faster than a + // monitor. At least one wake must happen, and the flood must collapse into + // far fewer wakes than the calls that asked for them. The absolute ceiling + // catches a wake per call on a machine that spins very fast. + if got < 1 || (sent > 0 && got > sent/10) || got > 1024 { + return fmt.Errorf("%d wakes for %d Invalidate calls in %v; want at least 1 and fewer than a tenth, at most 1024", got, sent, floodFor) } return nil }) diff --git a/cmd/viva/feed.go b/cmd/viva/feed.go index 33ee0cd41..f104d5d30 100644 --- a/cmd/viva/feed.go +++ b/cmd/viva/feed.go @@ -43,7 +43,16 @@ func runFeed(arguments []string, output, _ io.Writer) error { flags.StringVar(¬es, "notes", "", "HTTPS page describing the release") var validFor time.Duration var patchFroms []patchFrom - flags.Func("patch-from", "make a delta update from this earlier release: os/arch=version=archive (repeatable; darwin and linux)", func(value string) error { + var patchExcludes []string + flags.Func("patch-exclude", "a path left out of every patch, relative to the payload (repeatable; for example a portable copy's data folder)", func(value string) error { + value = strings.TrimSpace(value) + if value == "" { + return errors.New("--patch-exclude needs a path") + } + patchExcludes = append(patchExcludes, value) + return nil + }) + flags.Func("patch-from", "make a delta update from this earlier release: os/arch=version=archive (repeatable; darwin, linux and windows)", func(value string) error { parsed, err := parsePatchFrom(value) if err != nil { return err @@ -106,7 +115,7 @@ func runFeed(arguments []string, output, _ io.Writer) error { return err } if len(patchFroms) > 0 { - if err := addPatches(assets, patchFroms, artifactsDir, baseURL, version, app, loaded.ExecutableName()); err != nil { + if err := addPatches(assets, patchFroms, patchExcludes, artifactsDir, baseURL, version, app, loaded.ExecutableName()); err != nil { return err } } @@ -431,8 +440,8 @@ func parsePatchFrom(value string) (patchFrom, error) { } target, version, archive := parts[0], parts[1], parts[2] goos, goarch, ok := strings.Cut(target, "/") - if !ok || (goos != "darwin" && goos != "linux") { - return patchFrom{}, fmt.Errorf("--patch-from %q: patches are made for darwin and linux", target) + if !ok || (goos != "darwin" && goos != "linux" && goos != "windows") { + return patchFrom{}, fmt.Errorf("--patch-from %q: patches are made for darwin, linux and windows", target) } if goarch != "amd64" && goarch != "arm64" { return patchFrom{}, fmt.Errorf("--patch-from %q: architecture must be amd64 or arm64", target) @@ -443,7 +452,7 @@ func parsePatchFrom(value string) (patchFrom, error) { // addPatches writes a patch for every --patch-from that names a listed asset // and adds it to the asset. Every argument must match an asset, so a typo in // the platform cannot publish a feed that silently lacks its delta. -func addPatches(assets []update.Asset, froms []patchFrom, dir, baseURL, version, app, executable string) error { +func addPatches(assets []update.Asset, froms []patchFrom, excludes []string, dir, baseURL, version, app, executable string) error { base := strings.TrimRight(baseURL, "/") byTarget := make(map[string][]patchFrom, len(froms)) for _, from := range froms { @@ -471,6 +480,14 @@ func addPatches(assets []update.Asset, froms []patchFrom, dir, baseURL, version, if len(froms) == 0 { continue } + switch { + case asset.OS == "windows" && asset.Format != update.FormatZIP: + continue // an NSIS setup is an installer; the portable zip carries the payload + case asset.OS == "darwin" && asset.Format != update.FormatZIP: + continue + case asset.OS == "linux" && asset.Format != update.FormatTarGz: + continue + } name, err := url.PathUnescape(strings.TrimPrefix(asset.URL, base+"/")) if err != nil { return fmt.Errorf("feed: %s: %w", asset.URL, err) @@ -482,8 +499,8 @@ func addPatches(assets []update.Asset, froms []patchFrom, dir, baseURL, version, App: app, FromVersion: from.version, ToVersion: version, OS: asset.OS, Arch: asset.Arch, OldArchive: from.archive, NewArchive: newArchive, - Executable: executable, - Output: &encoded, + Executable: executable, Exclude: excludes, + Output: &encoded, }); err != nil { return fmt.Errorf("feed: patch %s from %s: %w", key, from.version, err) } diff --git a/cmd/viva/feed_test.go b/cmd/viva/feed_test.go index a29b0f2b1..cb5ccc533 100644 --- a/cmd/viva/feed_test.go +++ b/cmd/viva/feed_test.go @@ -1,6 +1,7 @@ package main import ( + "archive/zip" "bytes" "crypto/ed25519" "crypto/rand" @@ -624,3 +625,101 @@ func TestFeedRejectsBadPatchFrom(t *testing.T) { } } } + +func writeFeedZip(t *testing.T, path string, files map[string][]byte) { + t.Helper() + var encoded bytes.Buffer + writer := zip.NewWriter(&encoded) + for name, data := range files { + entry, err := writer.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := entry.Write(data); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, encoded.Bytes(), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestFeedAddsAWindowsPortablePatch(t *testing.T) { + t.Setenv("VIVA_UPDATE_KEY", "") + dir := t.TempDir() + writeFeedFile(t, filepath.Join(dir, "viva.toml"), feedTestBasicTOML) + dist := filepath.Join(dir, "dist") + writeFeedZip(t, filepath.Join(dist, "fixture-notes-2.0.1-windows-amd64.zip"), map[string][]byte{ + "fixture-notes.exe": []byte("the new program"), + "conpty/x64/conpty.dll": []byte("dll"), + "motty-data/README.txt": []byte("user data"), + }) + if err := os.WriteFile(filepath.Join(dist, "fixture-notes-2.0.1-windows-amd64-setup.exe"), []byte("installer"), 0o644); err != nil { + t.Fatal(err) + } + oldArchive := filepath.Join(dir, "fixture-notes-2.0.0-windows-amd64.zip") + writeFeedZip(t, oldArchive, map[string][]byte{ + "fixture-notes.exe": []byte("the old program"), + "conpty/x64/conpty.dll": []byte("dll"), + "motty-data/README.txt": []byte("user data"), + }) + key, _ := feedTestKey(t, dir) + feedPath := filepath.Join(dist, "latest.json") + var output bytes.Buffer + err := runCLI([]string{ + "feed", "-C", dir, "-dir", dist, "-base-url", "https://example.com/app", + "-key", key, "-out", feedPath, + "--patch-from", "windows/amd64=2.0.0=" + oldArchive, + "--patch-exclude", "motty-data", + }, &output, io.Discard) + if err != nil { + t.Fatalf("%v\n%s", err, output.String()) + } + data, err := os.ReadFile(feedPath) + if err != nil { + t.Fatal(err) + } + var feed update.Feed + if err := json.Unmarshal(data, &feed); err != nil { + t.Fatal(err) + } + if len(feed.Latest.Assets) != 2 { + t.Fatalf("feed = %s", data) + } + var zipAsset, setupAsset *update.Asset + for index := range feed.Latest.Assets { + switch feed.Latest.Assets[index].Format { + case update.FormatZIP: + zipAsset = &feed.Latest.Assets[index] + case update.FormatNSIS: + setupAsset = &feed.Latest.Assets[index] + } + } + if zipAsset == nil || len(zipAsset.Patches) != 1 { + t.Fatalf("the portable zip has no patch: %s", data) + } + if setupAsset != nil && len(setupAsset.Patches) != 0 { + t.Fatalf("the NSIS setup was given a patch: %s", data) + } + patchPath := filepath.Join(dist, "fixture-notes-2.0.1-windows-amd64.zip.2.0.0.patch") + reader, err := update.ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + defer reader.Close() + manifest := reader.Manifest() + if manifest.OS != "windows" || manifest.Payload != "dir" { + t.Fatalf("manifest = %+v", manifest) + } + for _, file := range manifest.Files { + if strings.Contains(file.Path, "motty-data") { + t.Fatalf("the excluded data folder is in the patch: %+v", manifest.Files) + } + } +} diff --git a/cmd/viva/help.go b/cmd/viva/help.go index db2f215ee..c6f6e4045 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -50,7 +50,7 @@ func commands() []command { detail: "Builds the program and packages it, all from viva.toml. --target darwin makes .app (--format\n" + "app, zip, dmg), --target windows an NSIS installer or a zip (nsis, zip; the installer needs makensis,\n" + "and the Homebrew build on Apple Silicon crashes, so build it on Linux or Windows), --target linux a\n" + - "tar.gz with an install script or a .deb (tar.gz, deb). --program packages an executable you built\n" + + "tar.gz with an install script, a .deb (deb), or an .rpm (rpm; opt-in, not in the default format). --program packages an executable you built\n" + "(or signed) yourself instead of building one. [app] url_schemes and [[app.file_types]] (name, extensions,\n" + "optional mime and macOS uti) register the links and documents the program opens with every format; on Windows and\n" + "Linux they arrive as arguments of a new process (app/singleinstance hands them to the running copy).\n" + @@ -78,7 +78,7 @@ func commands() []command { "as -notes must be when given. The signing key is -key, or $VIVA_UPDATE_KEY: the base64 64-byte\n" + "private key 'viva update-keygen' writes. App, version and archive directory default to viva.toml.\n" + "--patch-from os/arch=version=archive (repeatable) writes a delta update from that earlier\n" + - "release beside the archives and lists it on the asset; it works for darwin and linux.", + "release beside the archives and lists it on the asset; it works for darwin, linux and windows.", run: func(arguments []string, output, errorOutput io.Writer) error { return runFeed(arguments, output, errorOutput) }}, diff --git a/cmd/viva/package.go b/cmd/viva/package.go index a75ce5f70..d01e39fc2 100644 --- a/cmd/viva/package.go +++ b/cmd/viva/package.go @@ -18,7 +18,7 @@ import ( var packageFormats = map[string][]string{ "darwin": {"app", "zip", "dmg"}, "windows": {"nsis", "zip"}, - "linux": {"tar.gz", "deb", "pkgbuild"}, + "linux": {"tar.gz", "deb", "pkgbuild", "rpm"}, } // packageRequest is what one target's packager is given. @@ -66,7 +66,7 @@ func runPackage(arguments []string, output, errorOutput io.Writer) error { var pkgbuildURL string flags.StringVar(&requested, "o", "", "where to write: the .app for darwin, the output directory otherwise; default is [build] out") flags.StringVar(&requested, "out", "", "same as -o") - flags.StringVar(&formatList, "format", "", "comma-separated formats: darwin app, zip, dmg; windows nsis, zip; linux tar.gz, deb, pkgbuild") + flags.StringVar(&formatList, "format", "", "comma-separated formats: darwin app, zip, dmg; windows nsis, zip; linux tar.gz, deb, pkgbuild, rpm") flags.StringVar(&program, "program", "", "package this already built executable instead of building one (it must be for --target and --arch)") flags.StringVar(&pkgbuildURL, "pkgbuild-url", "", "linux pkgbuild: where makepkg downloads the tar.gz from (default: beside the PKGBUILD)") flags.BoolVar(&makeZip, "zip", false, "same as adding zip to --format") diff --git a/cmd/viva/package_tarball.go b/cmd/viva/package_tarball.go index 02ec2ad5e..decd280b6 100644 --- a/cmd/viva/package_tarball.go +++ b/cmd/viva/package_tarball.go @@ -13,6 +13,7 @@ import ( "github.com/vivaui/viva/tools/linuxicon" "github.com/vivaui/viva/tools/manifest" "github.com/vivaui/viva/tools/pkgbuild" + "github.com/vivaui/viva/tools/rpmpkg" "github.com/vivaui/viva/tools/tarball" ) @@ -24,6 +25,27 @@ 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"} + +// linuxApplication describes the application for the Debian and RPM packages: +// both install the same files, so they share one description. +func linuxApplication(plan buildPlan, program []byte, category string, icons []linuxicon.Rendition) debpkg.Package { + loaded := plan.manifest + maintainer := loaded.Linux.Maintainer + if maintainer == "" { + maintainer = loaded.App.Name + } + return debpkg.Package{ + Executable: plan.executable, ID: loaded.App.ID, Name: loaded.App.Name, Version: loaded.App.Version, Arch: plan.arch, + Maintainer: maintainer, Homepage: loaded.Linux.Homepage, Comment: loaded.Linux.Comment, Category: category, + Keywords: loaded.Linux.Keywords, URLSchemes: loaded.App.URLSchemes, FileTypes: linuxFileTypes(loaded.App.FileTypes), + Program: program, Icons: icons, + } +} + // packageLinux builds the program and writes the Linux packages asked for: a // .tar.gz with an install script, a .deb, and a PKGBUILD with its .SRCINFO for // an Arch binary package. Each is written beside its final name and renamed @@ -130,15 +152,8 @@ func packageLinux(request packageRequest) error { } } if request.wants("deb") { - maintainer := loaded.Linux.Maintainer - if maintainer == "" { - maintainer = loaded.App.Name - } - spec := debpkg.Package{ - Executable: plan.executable, ID: loaded.App.ID, Name: loaded.App.Name, Version: loaded.App.Version, Arch: plan.arch, - Maintainer: maintainer, Homepage: loaded.Linux.Homepage, Comment: loaded.Linux.Comment, Category: category, - Keywords: loaded.Linux.Keywords, URLSchemes: loaded.App.URLSchemes, FileTypes: linuxFileTypes(loaded.App.FileTypes), Depends: debDepends(loaded.Linux.Depends), Program: program, Icons: icons, - } + spec := linuxApplication(plan, program, category, icons) + spec.Depends = debDepends(loaded.Linux.Depends) if debName, err = spec.FileName(); err != nil { return err } @@ -146,6 +161,16 @@ func packageLinux(request packageRequest) error { return err } } + if request.wants("rpm") { + spec := rpmpkg.Package{App: linuxApplication(plan, program, category, icons), Requires: linuxRPMRuntimeDepends} + rpmName, err := spec.FileName() + if err != nil { + return err + } + if _, err := write("rpm", rpmName, spec.Write); err != nil { + return err + } + } if request.wants("pkgbuild") { maintainer := loaded.Linux.Maintainer if maintainer == "" { diff --git a/cmd/viva/package_tarball_test.go b/cmd/viva/package_tarball_test.go index c542b474b..409dbf37f 100644 --- a/cmd/viva/package_tarball_test.go +++ b/cmd/viva/package_tarball_test.go @@ -257,6 +257,24 @@ func TestPackageLinuxWarnsAboutASmallIcon(t *testing.T) { } } +func TestPackageLinuxMakesAnRPM(t *testing.T) { + dir := packageLinuxFixture(t, linuxTOML, 256) + if _, err := runLinuxPackage(t, dir, "--format", "rpm"); err != nil { + t.Fatal(err) + } + entries, err := os.ReadDir(filepath.Join(dir, "build")) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != "fixture-notes-2.0.1-1.x86_64.rpm" { + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + t.Fatalf("--format rpm wrote %v, want only fixture-notes-2.0.1-1.x86_64.rpm", names) + } +} + func TestPackageLinuxFailures(t *testing.T) { for _, test := range []struct { name, toml string @@ -264,7 +282,7 @@ func TestPackageLinuxFailures(t *testing.T) { arguments []string want string }{ - {"unknown format", linuxTOML, 256, []string{"--format", "rpm"}, `cannot be made as "rpm"`}, + {"unknown format", linuxTOML, 256, []string{"--format", "appimage"}, `cannot be made as "appimage"`}, {"msi", linuxTOML, 256, []string{"--format", "nsis"}, `cannot be made as "nsis"`}, {"zip flag", linuxTOML, 256, []string{"--zip"}, "--zip does not apply"}, {"small icon", linuxTOML, 64, nil, "at least 128 px"}, diff --git a/cmd/viva/templates/button.go.txt b/cmd/viva/templates/button.go.txt index 445e1dcf0..ce15f6417 100644 --- a/cmd/viva/templates/button.go.txt +++ b/cmd/viva/templates/button.go.txt @@ -60,6 +60,10 @@ type Button struct { height float32 fontSize float32 disabled bool + // recipe, when set, replaces ButtonRecipe for this button: a page whose + // application has a look of its own hands one down instead of painting + // every button from a Base. + recipe func(gfx.Theme, ButtonVariant, gfx.State) ButtonLook } // BeginButton starts a button declaration. Hit ID zero paints a static preview @@ -74,6 +78,16 @@ func BeginButton(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect return Button{canvas: canvas, theme: theme, id: id, bounds: bounds, state: state} } +// Recipe replaces the theme's button recipe for this button: the fill, label, +// border, corners, shadow and ring come from recipe instead of ButtonRecipe. +// The metrics (height, padding, text size) still come from the size and the +// theme, so a recipe changes the look without changing what the button +// measures. A nil recipe keeps the theme's. +func (button Button) Recipe(recipe func(gfx.Theme, ButtonVariant, gfx.State) ButtonLook) Button { + button.recipe = recipe + return button +} + // WithState pins a visual state, overriding canvas-derived interaction state. func (button Button) WithState(state ButtonState) Button { button.state = state @@ -359,6 +373,12 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { Hovered: button.state.Hovered, Pressed: button.state.Pressed, FocusVisible: button.state.Focused, Invalid: button.state.Invalid, Disabled: button.disabled, }) + if button.recipe != nil { + look = button.recipe(button.theme, variant, gfx.State{ + Hovered: button.state.Hovered, Pressed: button.state.Pressed, FocusVisible: button.state.Focused, + Invalid: button.state.Invalid, Disabled: button.disabled, + }) + } radius := look.Radius if look.Shadow != gfx.ShadowNone { button.canvas.Elevate(button.bounds, radius, look.Shadow) // shadow-xs diff --git a/cmd/viva/templates/checkbox.go.txt b/cmd/viva/templates/checkbox.go.txt index d5434d3ed..ec8cef8cf 100644 --- a/cmd/viva/templates/checkbox.go.txt +++ b/cmd/viva/templates/checkbox.go.txt @@ -18,6 +18,8 @@ type Checkbox struct { focused bool invalid bool disabled bool + // recipe, when set, replaces CheckboxRecipe; see Button.Recipe. + recipe func(gfx.Theme, gfx.State) CheckboxLook } // BeginCheckbox starts a checkbox declaration. Bounds provide only the visual @@ -34,6 +36,13 @@ func BeginCheckbox(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Re } } +// Recipe replaces the theme's checkbox recipe for this checkbox. A nil recipe +// keeps the theme's. +func (checkbox Checkbox) Recipe(recipe func(gfx.Theme, gfx.State) CheckboxLook) Checkbox { + checkbox.recipe = recipe + return checkbox +} + // Label sets the accessible name without changing visual geometry. func (checkbox Checkbox) Label(label string) Checkbox { checkbox.label = label @@ -115,6 +124,9 @@ func (checkbox Checkbox) Paint() CheckboxResult { Invalid: checkbox.invalid, Disabled: checkbox.disabled, } look := checkboxRecipe(&checkbox.theme, state) + if checkbox.recipe != nil { + look = checkbox.recipe(checkbox.theme, state) + } checkbox.canvas.Elevate(checkbox.bounds, look.Radius, look.Shadow) // shadow-xs if look.RingWidth > 0 { checkbox.canvas.Rounded(expand(checkbox.bounds, look.RingWidth), look.RingRadius, look.Ring) diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index b574f35ea..50e2117c1 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -8,12 +8,14 @@ import ( "github.com/vivaui/viva/text" ) -// CodeEditorRun colors one byte range of a line without changing its text -// geometry. Runs are ordered and non-overlapping; invalid and overlapping spans -// are ignored. +// CodeEditorRun colors and slants one byte range of a line without changing its +// text geometry: Italic draws the range in the italic face of the line's +// fixed-pitch font, as a comment is drawn in an editor. Runs are ordered and +// non-overlapping; invalid and overlapping spans are ignored. type CodeEditorRun struct { Start, End int Color gfx.Color + Italic bool } // CodeEditorMarkLayer paints colored byte ranges behind the text. Spans are diff --git a/cmd/viva/templates/code_editor_layout.go.txt b/cmd/viva/templates/code_editor_layout.go.txt index fd1907293..7b57ad48d 100644 --- a/cmd/viva/templates/code_editor_layout.go.txt +++ b/cmd/viva/templates/code_editor_layout.go.txt @@ -810,6 +810,7 @@ func gridRuns(dst []gfx.TextRun, line string, spec *gridRunSpec) (runs []gfx.Tex from = -1 included, ascii := true, false var last gfx.Color + var lastItalic bool for at := 0; at < len(line); { r, size := decodeAt(line, at) representation, represented := representationOf(spec.representations, r) @@ -839,6 +840,7 @@ func gridRuns(dst []gfx.TextRun, line string, spec *gridRunSpec) (runs []gfx.Tex next++ } color := spec.foreground + italic := false if represented && spec.representationColor.Alpha != 0 { color = spec.representationColor if spec.disabled { @@ -847,6 +849,7 @@ func gridRuns(dst []gfx.TextRun, line string, spec *gridRunSpec) (runs []gfx.Tex } if next < len(spec.highlight) && spec.highlight[next].Start <= relative { color = spec.highlight[next].Color + italic = spec.highlight[next].Italic if spec.disabled { color.Alpha *= 0.5 } @@ -877,13 +880,13 @@ func gridRuns(dst []gfx.TextRun, line string, spec *gridRunSpec) (runs []gfx.Tex case width == 0 && len(dst) > 0: dst[len(dst)-1].Bytes += int32(bytes) ascii = false - case plain && ascii && color == last: + case plain && ascii && color == last && italic == lastItalic: tail := &dst[len(dst)-1] tail.Bytes += int32(bytes) tail.Cells += int32(width) default: - dst = append(dst, gfx.TextRun{Column: int32(column - startColumn), Bytes: int32(bytes), Cells: int32(width), Color: color}) - ascii, last = plain, color + dst = append(dst, gfx.TextRun{Column: int32(column - startColumn), Bytes: int32(bytes), Cells: int32(width), Color: color, Italic: italic}) + ascii, last, lastItalic = plain, color, italic } to = offset + bytes endColumn = column + width @@ -908,7 +911,7 @@ func cleanHighlight(line string, runs []CodeEditorRun) []CodeEditorRun { if last <= first || first < previous || run.Color.Alpha == 0 { continue } - kept = append(kept, CodeEditorRun{Start: first, End: last, Color: run.Color}) + kept = append(kept, CodeEditorRun{Start: first, End: last, Color: run.Color, Italic: run.Italic}) previous = last } return kept diff --git a/cmd/viva/templates/context_menu.go.txt b/cmd/viva/templates/context_menu.go.txt index 2ae972f61..8aa65ab90 100644 --- a/cmd/viva/templates/context_menu.go.txt +++ b/cmd/viva/templates/context_menu.go.txt @@ -68,10 +68,16 @@ type ContextMenuOptions struct { // Submenu makes this the content of a submenu, which has a smaller minimum // width (128) than a context menu (144). Submenu bool - // RowHeight is the height of an item row. Zero is the standard 32px; a menu - // with many items can ask for a denser one (24, say). Group labels, separators - // and everything else keep their size. An icon never grows past the row. + // RowHeight is the height of an item row. Zero is the theme's control height + // (32 at the default density, 26 at the compact one); a menu with many items + // can ask for a denser one (24, say). Group labels, separators and everything + // else keep their size. An icon never grows past the row. RowHeight float32 + // Unpainted, PaintPanel and PaintItem are DropdownMenuOptions' and mean the + // same: the menu keeps its behavior and the caller draws its surface and rows. + Unpainted bool + PaintPanel func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) + PaintItem func(MenuItemPaint) } // ContextMenuItem describes one stable menu action. @@ -121,7 +127,7 @@ func ContextMenuItemWidth(canvas *gfx.Canvas, theme gfx.Theme, item ContextMenuI } // ContextMenuItemHeight is the height AddItem reserves for item. rowHeight is -// ContextMenuOptions.RowHeight (zero selects the standard 32px label row). +// ContextMenuOptions.RowHeight (zero selects the theme's control height). func ContextMenuItemHeight(theme gfx.Theme, item ContextMenuItem, rowHeight float32) float32 { return menuItemHeight(theme, item.common(), rowHeight) } @@ -145,6 +151,7 @@ func BeginContextMenu(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, opti layer: options.Layer, scope: options.Scope, dismissID: options.DismissID, viewport: options.Viewport, scroll: options.Scroll, key: overlayKey(options.ID, options.DismissID, options.Scope), side: options.Side, submenu: options.Submenu, instant: true, labelMuted: true, rowHeight: options.RowHeight, + unpainted: options.Unpainted, paintPanel: options.PaintPanel, paintItem: options.PaintItem, })} } diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index 973533a97..b0b17bb21 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -152,6 +152,14 @@ type DropdownMenuOptions struct { // Submenu makes this the content of a submenu, which has a smaller minimum // width (96) than a menu opened by a trigger (128). Submenu bool + // Unpainted declares the menu's behavior, size and rows but paints none of + // it: PaintPanel draws the surface and PaintItem draws each row, both inside + // the menu's layer, clipping and focus scope. Hits, focus, the keyboard and + // submenu expansion stay the menu's, so a menu of the application's own + // cannot behave differently. + Unpainted bool + PaintPanel func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) + PaintItem func(MenuItemPaint) } // DropdownMenuItem describes one stable menu action. @@ -231,14 +239,15 @@ func BeginDropdownMenu(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, opt layer: options.Layer, scope: options.Scope, dismissID: options.DismissID, viewport: options.Viewport, scroll: options.Scroll, key: overlayKey(options.ID, options.DismissID, options.Scope), side: options.Side, submenu: options.Submenu, labelMuted: true, tabCloses: true, + unpainted: options.Unpainted, paintPanel: options.PaintPanel, paintItem: options.PaintItem, })} } // Bounds returns the normalized overlay geometry. func (menu DropdownMenu) Bounds() gfx.Rect { return menu.surface.bounds } -// NextItemBounds returns the next 32px keyboard-navigation row without -// advancing the declaration cursor. +// NextItemBounds returns the next keyboard-navigation row, as tall as the +// theme's control height, without advancing the declaration cursor. func (menu DropdownMenu) NextItemBounds() gfx.Rect { return menu.surface.rowBounds(menu.surface.itemHeight()) } @@ -606,6 +615,8 @@ func (scroll *MenuScroll) follow(canvas *gfx.Canvas) { } const ( + // menuRowHeight is the height of an item row in a theme without a control + // height; a theme with one sizes its rows by it (menuThemeRowHeight). menuRowHeight = float32(32) menuLabelHeight = float32(28) menuSeparatorHeight = float32(9) @@ -654,6 +665,29 @@ type menuItem struct { Icon gfx.Icon } +// MenuItemPaint is one row of a menu declared Unpainted: the caller draws it, +// and the menu keeps the row's hit, focus and keyboard behavior. Separator and +// GroupLabel say the row is not an action. Active is the row the pointer or +// the keyboard is on, and Foreground is the color the menu's own row would +// give its label. +type MenuItemPaint struct { + Canvas *gfx.Canvas + Theme gfx.Theme + Bounds gfx.Rect + Label string + Description string + Shortcut string + Checked bool + Selected bool + Expanded bool + Disabled bool + Active bool + Destructive bool + Separator bool + GroupLabel bool + Foreground gfx.Color +} + type menuSurfaceOptions struct { layer uint16 scope gfx.ID @@ -675,8 +709,14 @@ type menuSurfaceOptions struct { indicatorLeft bool // tabCloses is MenuScroll.TabCloses for this surface. tabCloses bool - // rowHeight is the height of an item row; zero is menuRowHeight. + // rowHeight is the height of an item row; zero is the theme's + // (menuThemeRowHeight). rowHeight float32 + // unpainted leaves the surface and rows to paintPanel and paintItem; see + // DropdownMenuOptions.Unpainted. + unpainted bool + paintPanel func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) + paintItem func(MenuItemPaint) } // menuSurface is what the dropdown menu, the context menu and the menubar's popup @@ -703,6 +743,12 @@ type menuSurface struct { // hitInset is how much shorter than their paint the rows' hits are, to leave // the scrollbar's own. hitInset float32 + // viewport, when it has an area, is the region the rows and the scrollbar are + // painted and hit-tested in place of the clips around the caller: a surface + // declared inside a scroll area is not cut by it, as Canvas.PushOverlayClip + // suspends them for the duration of each row. The control's owner sets it; the + // menus leave it empty and keep their ancestor clips. + viewport gfx.Rect } // pointerRow remembers which option row the pointer is over so a list can move @@ -764,7 +810,13 @@ func beginMenuSurface(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, minW if options.submenu { level = gfx.ShadowLG } - paintPopupSurface(canvas, &theme, bounds, level) + if options.unpainted { + if options.paintPanel != nil { + options.paintPanel(canvas, bounds, theme) + } + } else { + paintPopupSurface(canvas, &theme, bounds, level) + } menu.popOverlay() return menu } @@ -813,9 +865,27 @@ func (menu *menuSurface) take(row gfx.Rect) bool { return !menu.hidden && row.Height > 0 && row.Y < menu.bottom && row.Y+row.Height > menu.top } +// pushClip suspends the clips around the surface for a viewport-anchored one, so a +// row is not cut by an ancestor scroll area, as Select sets one for its popup. A +// surface without a viewport keeps its ancestor clips, as the menus do. +func (menu *menuSurface) pushClip() { + if menu.viewport.Width > 0 && menu.viewport.Height > 0 { + menu.canvas.PushOverlayClip(menu.viewport) + } +} + +// popClip closes the clip pushClip opened. +func (menu *menuSurface) popClip() { + if menu.viewport.Width > 0 && menu.viewport.Height > 0 { + menu.canvas.PopOverlayClip() + } +} + // paintRow runs paint for a row on the menu's layer and scope, clipped to the // visible part of the surface when the row is cut by an edge. func (menu *menuSurface) paintRow(row gfx.Rect, paint func()) { + menu.pushClip() + defer menu.popClip() menu.pushOverlay() cut := row.Y < menu.top || row.Y+row.Height > menu.bottom if cut { @@ -833,6 +903,17 @@ func (menu *menuSurface) itemHeight() float32 { if menu.options.rowHeight > 0 { return menu.options.rowHeight } + return menuThemeRowHeight(menu.theme) +} + +// menuThemeRowHeight is the height of an item row in theme: its control +// height, so a compact theme packs its menus as densely as its buttons and +// inputs (32 at the default density, 26 at the compact one), and menuRowHeight +// for a theme without one. +func menuThemeRowHeight(theme gfx.Theme) float32 { + if height := theme.Metrics.ControlHeight; height > 0 { + return height + } return menuRowHeight } @@ -850,6 +931,14 @@ func (menu *menuSurface) addLabel(label string, inset bool) gfx.Rect { if inset { left = 32 } + if menu.options.unpainted { + menu.paintRow(row, func() { + if paint := menu.options.paintItem; paint != nil { + paint(MenuItemPaint{Canvas: menu.canvas, Theme: menu.theme, Bounds: row, Label: label, GroupLabel: true, Foreground: color}) + } + }) + return row + } menu.paintRow(row, func() { menu.canvas.Label(label, gfx.Rect{X: row.X + left, Y: row.Y, Width: max(0, row.Width-left-8), Height: row.Height}, gfx.TextStyle{ Size: size, Weight: weight, Color: color, @@ -863,6 +952,14 @@ func (menu *menuSurface) addSeparator() gfx.Rect { if !menu.take(row) { return gfx.Rect{} } + if menu.options.unpainted { + menu.paintRow(row, func() { + if paint := menu.options.paintItem; paint != nil { + paint(MenuItemPaint{Canvas: menu.canvas, Theme: menu.theme, Bounds: row, Separator: true, Foreground: menu.theme.Border}) + } + }) + return row + } menu.paintRow(row, func() { menu.canvas.Fill(gfx.Rect{X: row.X, Y: row.Y + 4, Width: row.Width, Height: 1}, menu.theme.Border) }) @@ -932,7 +1029,7 @@ func menuLineHeight(size float32) float32 { return size + 7 } func menuItemHeight(theme gfx.Theme, item menuItem, rowHeight float32) float32 { if rowHeight <= 0 { - rowHeight = menuRowHeight + rowHeight = menuThemeRowHeight(theme) } if item.Description != "" { lines := menuLineHeight(theme.Metrics.FontSizeM) + menuDescriptionGap + menuLineHeight(theme.Metrics.FontSizeS) @@ -941,13 +1038,13 @@ func menuItemHeight(theme gfx.Theme, item menuItem, rowHeight float32) float32 { return rowHeight } -func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { +// itemState is what a row does before it is painted: the pointer moves the +// menu's current row the way Radix does, entering a row focuses it, and the +// returned colors are the menu's own for the label. Both the painted and the +// unpainted row use it, so a menu of the application's own behaves the same. +func (menu *menuSurface) itemState(item menuItem) (active bool, foreground gfx.Color) { canvas, theme := menu.canvas, menu.theme enabled := !item.ID.IsZero() && !item.Disabled - // The pointer moves the menu's current row the way Radix does: entering a - // row focuses it, so the tint and Enter name one row instead of two. A - // pointer that rests in place never moves the row back, so the arrow keys - // keep working under it. hovered := canvas.Hovered() claim := canvas.HoverCrossed() && !hovered.IsZero() // While the pointer is over caller content inside the menu (a colour row, a @@ -965,27 +1062,64 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { } // Focused, not FocusVisible: a menu row the pointer focused is the current // row even though no key press made its focus ring visible. - active := enabled && !inContent && (claim && hovered == item.ID || !claim && canvas.Focused() == item.ID) + active = enabled && !inContent && (claim && hovered == item.ID || !claim && canvas.Focused() == item.ID) if item.Kind == menuSubmenu && item.Expanded { active = true } - foreground := theme.PopoverForeground + foreground = theme.PopoverForeground if item.Destructive { foreground = theme.Danger + } else if active { + foreground = theme.AccentForeground + } + if item.Disabled { + foreground.Alpha *= 0.50 + } + return active, foreground +} + +// declareItemHit gives a row the pointer, keyboard and assistive-technology +// behavior each path needs, painted or not. +func (menu *menuSurface) declareItemHit(bounds gfx.Rect, item menuItem) { + if item.ID.IsZero() { + return + } + hit := bounds + hit.Width -= menu.hitInset + menu.canvas.HitWithOptions(item.ID, hit, item.Label, gfx.HitOptions{ + Role: gfx.RoleMenuItem, Value: item.Value, Hint: item.Hint, Description: item.Description, + Disabled: item.Disabled, Checked: item.Kind == menuCheckbox && item.Checked, + Selected: item.Kind == menuRadio && item.Selected, + Expanded: item.Kind == menuSubmenu && item.Expanded, Expandable: item.Kind == menuSubmenu, + }) +} + +func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { + canvas, theme := menu.canvas, menu.theme + active, foreground := menu.itemState(item) + if menu.options.unpainted { + if paint := menu.options.paintItem; paint != nil { + paint(MenuItemPaint{ + Canvas: canvas, Theme: theme, Bounds: bounds, + Label: item.Label, Description: item.Description, Shortcut: item.Shortcut, + Checked: item.Kind == menuCheckbox && item.Checked, + Selected: item.Kind == menuRadio && item.Selected, + Expanded: item.Kind == menuSubmenu && item.Expanded, + Disabled: item.Disabled, Active: active, Destructive: item.Destructive, + Foreground: foreground, + }) + } + menu.declareItemHit(bounds, item) + return } if active { fill := theme.Accent if item.Destructive { fill = theme.Danger fill.Alpha = 0.10 - } else { - foreground = theme.AccentForeground } canvas.Rounded(bounds, theme.Metrics.RadiusItem(), fill) } - if item.Disabled { - foreground.Alpha *= 0.50 - } // A row with a description is two lines of type, not a taller one-line row: // the title keeps the system line height, the description follows one small // gap below it, and the pair is centered in the row. The indicator, icon and @@ -1057,16 +1191,7 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { Size: theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: color, }) } - if !item.ID.IsZero() { - hit := bounds - hit.Width -= menu.hitInset - canvas.HitWithOptions(item.ID, hit, item.Label, gfx.HitOptions{ - Role: gfx.RoleMenuItem, Value: item.Value, Hint: item.Hint, Description: item.Description, - Disabled: item.Disabled, Checked: item.Kind == menuCheckbox && item.Checked, - Selected: item.Kind == menuRadio && item.Selected, - Expanded: item.Kind == menuSubmenu && item.Expanded, Expandable: item.Kind == menuSubmenu, - }) - } + menu.declareItemHit(bounds, item) } // end paints a thin scrollbar thumb on the right edge when rows are scrolled out, @@ -1080,13 +1205,17 @@ func (menu *menuSurface) end() { thumb := max(view*view/(view+scroll.max), 18) at := menu.top + (view-thumb)*scroll.Offset/scroll.max scroll.barTop, scroll.thumb = menu.top, thumb + menu.pushClip() menu.pushOverlay() - menu.canvas.Rounded(gfx.Rect{X: menu.bounds.X + menu.bounds.Width - 6, Y: at, Width: 4, Height: thumb}, 2, menu.theme.Border) + if !menu.options.unpainted { + menu.canvas.Rounded(gfx.Rect{X: menu.bounds.X + menu.bounds.Width - 6, Y: at, Width: 4, Height: thumb}, 2, menu.theme.Border) + } if !scroll.BarID.IsZero() { menu.canvas.HitWithOptions(scroll.BarID, gfx.Rect{X: menu.bounds.X + menu.bounds.Width - 2 - menuBarWidth, Y: menu.top, Width: menuBarWidth, Height: view}, "Scroll", gfx.HitOptions{Role: gfx.RoleSlider, SkipFocus: true}) } menu.popOverlay() + menu.popClip() } if menu.animated { menu.canvas.EndPresence() diff --git a/cmd/viva/templates/input.go.txt b/cmd/viva/templates/input.go.txt index 6b638afef..14f5461d9 100644 --- a/cmd/viva/templates/input.go.txt +++ b/cmd/viva/templates/input.go.txt @@ -4,6 +4,7 @@ import ( "unicode/utf8" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" ) // InputSnapshot is one caller-owned single-line editor presentation. Value is @@ -36,12 +37,19 @@ type InputSnapshot struct { // can put the line a fraction of a pixel away from the canvas line; with the text // painted here it cannot move when the field opens. A fixed-pitch field does this // always (see InputTextStyle.Mono). - HideEditorText bool - NavigationKeys bool - ShowCaret bool - Caret int - SelectionStart int - SelectionEnd int + HideEditorText bool + NavigationKeys bool + ShowCaret bool + Caret int + SelectionStart int + SelectionEnd int + // SelectionRanges, when nonempty, replaces the single selection for + // painting: the selections of a multi-selection editor (see + // text.Editor.SelectionSpansInto). They are byte offsets into Value, in + // order, non-overlapping, and may sit anywhere on the line. Collapsed ones + // paint nothing. The caret is still Caret, so only the primary selection has + // one. + SelectionRanges []text.Span CompositionStart int CompositionEnd int // Text styles the text of the field: its size, weight and color. The zero value is the @@ -198,6 +206,9 @@ func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snaps snapshot.Caret = inputMaskOffset(snapshot.Value, snapshot.Caret) snapshot.SelectionStart = inputMaskOffset(snapshot.Value, snapshot.SelectionStart) snapshot.SelectionEnd = inputMaskOffset(snapshot.Value, snapshot.SelectionEnd) + // The offsets of a range would index the mask, not the value, and a + // password field has no multi-selection to paint. + snapshot.SelectionRanges = nil snapshot.CompositionStart = inputMaskOffset(snapshot.Value, snapshot.CompositionStart) snapshot.CompositionEnd = inputMaskOffset(snapshot.Value, snapshot.CompositionEnd) } @@ -229,15 +240,20 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, var ranges [4]gfx.Rect selectionStart, selectionEnd := inputRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) var selections []gfx.Rect - if selectionEnd > selectionStart && !placeholderShown { - selections = inputTextRanges(canvas, ranges[:0], bounds, bandTop, bandHeight, origin, value, textStyle, selectionStart, selectionEnd) - selectionColor, _ := selectionColors(theme) - if snapshot.Disabled { - selectionColor.Alpha *= 0.50 - } - for _, selection := range selections { - canvas.Fill(selection, selectionColor) + if len(snapshot.SelectionRanges) > 0 { + // A multi-selection editor: every range is painted, so two selections on + // the one line show as two bands. The primary's Caret is the only caret. + selections = ranges[:0] + for _, span := range snapshot.SelectionRanges { + start, end := inputRange(value, span.Start, span.End) + if end > start && !placeholderShown { + selections = inputTextRanges(canvas, selections, bounds, bandTop, bandHeight, origin, value, textStyle, start, end) + } } + selections = fillInputSelections(canvas, theme, snapshot, selections) + } else if selectionEnd > selectionStart && !placeholderShown { + selections = inputTextRanges(canvas, ranges[:0], bounds, bandTop, bandHeight, origin, value, textStyle, selectionStart, selectionEnd) + selections = fillInputSelections(canvas, theme, snapshot, selections) } compositionStart, compositionEnd := inputRange(value, snapshot.CompositionStart, snapshot.CompositionEnd) if compositionEnd > compositionStart && !placeholderShown { @@ -280,6 +296,23 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, canvas.Unclip() } +// fillInputSelections paints the bands of the field's selections and returns +// them, so the selected glyphs can be repainted in the selection foreground +// afterwards. +func fillInputSelections(canvas *gfx.Canvas, theme gfx.Theme, snapshot InputSnapshot, selections []gfx.Rect) []gfx.Rect { + if len(selections) == 0 { + return selections + } + selectionColor, _ := selectionColors(theme) + if snapshot.Disabled { + selectionColor.Alpha *= 0.50 + } + for _, selection := range selections { + canvas.Fill(selection, selectionColor) + } + return selections +} + // inputTextRanges appends the rectangles of the bytes [start, end) of value, a line drawn // from x = origin in bounds, clamped to bounds: one for left-to-right text, more where the // range crosses a change of direction. They fill the band of the line (inputLineBand), top diff --git a/cmd/viva/templates/popover.go.txt b/cmd/viva/templates/popover.go.txt index 6c3766b56..c68e7cbe7 100644 --- a/cmd/viva/templates/popover.go.txt +++ b/cmd/viva/templates/popover.go.txt @@ -325,6 +325,14 @@ func PlaceOverlay(anchor gfx.Rect, size gfx.Size, viewport gfx.Rect, placement O return overlayClamp(bounds, viewport, placement.Margin), side } +// ClampOverlay keeps an overlay opened at point inside viewport, except for its +// margin. Unlike PlaceOverlay, a context menu that fits above the pointer but +// would clamp below it stays at the pointer's y; that is how a native context +// menu opens at the mouse rather than choosing a side. +func ClampOverlay(point gfx.Point, size gfx.Size, viewport gfx.Rect, margin float32) gfx.Rect { + return overlayClamp(gfx.Rect{X: point.X, Y: point.Y, Width: size.Width, Height: size.Height}, viewport, margin) +} + // overlayClamp shrinks bounds to fit viewport less margin and shifts them back // inside it. func overlayClamp(bounds, viewport gfx.Rect, margin float32) gfx.Rect { diff --git a/cmd/viva/templates/select.go.txt b/cmd/viva/templates/select.go.txt index c24042d7e..af3f1c3a7 100644 --- a/cmd/viva/templates/select.go.txt +++ b/cmd/viva/templates/select.go.txt @@ -41,6 +41,11 @@ type SelectOptions struct { // whole window behind its surface, so pressing anywhere outside it, // including the trigger, reports DismissID (Escape reports it too). Leave // it empty to dismiss only on Escape and handle outside presses yourself. + // + // It also floats the open list: the popup is painted and hit-tested against + // the viewport instead of the clips around the select, so a list declared + // inside a scroll area is not cut by it. Leave it empty to keep the list + // inside the ancestor clips, as a component called without one always has. Viewport gfx.Rect // Scroll is the scroll position of a popup whose items do not all fit its // Content (see MenuScroll); without one such a popup shows only the items at @@ -146,12 +151,19 @@ func BeginSelect(canvas *gfx.Canvas, theme gfx.Theme, triggerBounds gfx.Rect, op options: menuSurfaceOptions{layer: options.Layer, scope: options.Scope, scroll: options.Scroll}, top: content.Y + menuPadding, bottom: content.Y + content.Height - menuPadding, viewHeight: max(content.Height-2*menuPadding, 0), + // An open list floats over the page: a select at the bottom of a scroll + // area shows its list whole instead of through the area's clip. The list + // stays inside the viewport when the caller gives one. + viewport: options.Viewport, } selectControl.rows.beginScroll() if options.Scroll != nil { options.Scroll.TabCloses = true } selectControl.pushOverlay() + // The popup and its backdrop float over the page: an ancestor scroll area's + // clip does not cut them, and the viewport bounds what shows. + selectControl.rows.pushClip() // Claim after pushing the popup's scope, so a select inside a dialog owns // the trap and Escape while it is open. if !options.Scope.IsZero() { @@ -173,6 +185,9 @@ func BeginSelect(canvas *gfx.Canvas, theme gfx.Theme, triggerBounds gfx.Rect, op if !options.Unpainted { paintPopupSurface(canvas, &theme, content, gfx.ShadowMD) // shadow-md } + // The surface is painted: the rows start their own overlay clip, so the two + // need not nest. Keep the popup's viewport open only through the surface. + selectControl.rows.popClip() selectControl.popOverlay() return selectControl } diff --git a/cmd/viva/templates/switch.go.txt b/cmd/viva/templates/switch.go.txt index 6df3bcf56..6bf73558e 100644 --- a/cmd/viva/templates/switch.go.txt +++ b/cmd/viva/templates/switch.go.txt @@ -28,6 +28,8 @@ type Switch struct { invalid bool size SwitchSize disabled bool + // recipe, when set, replaces SwitchRecipe; see Button.Recipe. + recipe func(gfx.Theme, gfx.State, float32) SwitchLook } // BeginSwitch starts a switch declaration. Zero-sized bounds select official @@ -43,6 +45,14 @@ func BeginSwitch(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect } } +// Recipe replaces the theme's switch recipe for this switch, progress being +// how far the thumb has travelled from off to on. A nil recipe keeps the +// theme's. +func (switchControl Switch) Recipe(recipe func(gfx.Theme, gfx.State, float32) SwitchLook) Switch { + switchControl.recipe = recipe + return switchControl +} + // Small selects the official compact switch size. func (switchControl Switch) Small() Switch { switchControl.size = SwitchSizeSmall @@ -134,6 +144,11 @@ func (switchControl Switch) Paint() SwitchResult { look := switchRecipe(&switchControl.theme, gfx.State{ FocusVisible: switchControl.focused, Invalid: switchControl.invalid, Disabled: switchControl.disabled, }, progress) + if switchControl.recipe != nil { + look = switchControl.recipe(switchControl.theme, gfx.State{ + FocusVisible: switchControl.focused, Invalid: switchControl.invalid, Disabled: switchControl.disabled, + }, progress) + } switchControl.canvas.Elevate(switchControl.bounds, switchControl.bounds.Height/2, look.Shadow) // shadow-xs if look.Bordered { switchControl.canvas.Rounded(expand(switchControl.bounds, look.RingWidth), switchControl.bounds.Height/2+look.RingWidth, look.Ring) diff --git a/cmd/viva/templates/textarea.go.txt b/cmd/viva/templates/textarea.go.txt index 3303cc24c..80e291a52 100644 --- a/cmd/viva/templates/textarea.go.txt +++ b/cmd/viva/templates/textarea.go.txt @@ -4,6 +4,7 @@ import ( "sort" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" ) // TextareaCommand is a request for the caller-owned editor. The component @@ -76,10 +77,15 @@ type TextareaSnapshot struct { // paints from its first row, which suits a box that shows what is in it. // With it, DisplayValue must be empty or the text of Value, whose byte // offsets Layout reports. - Layout *TextareaLayout - Caret int - SelectionStart int - SelectionEnd int + Layout *TextareaLayout + Caret int + SelectionStart int + SelectionEnd int + // SelectionRanges, when nonempty, replaces the single selection for + // painting: the selections of a multi-selection editor (see + // text.Editor.SelectionSpansInto), as byte offsets into Value in order and + // non-overlapping. Collapsed ones paint nothing; only the primary has Caret. + SelectionRanges []text.Span CompositionStart int CompositionEnd int } @@ -302,7 +308,17 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val holdsCaret = false } if !placeholderShown { - selections = textareaLineRanges(canvas, ranges[:0], labelBounds, origin, line, fontSize, row.Start, lineEnd, selectionStart, selectionEnd) + if len(snapshot.SelectionRanges) > 0 { + // A multi-selection editor paints every selection; two on one row + // show as two bands, and every row a range crosses gets its part. + selections = ranges[:0] + for _, span := range snapshot.SelectionRanges { + start, end := textareaRange(value, span.Start, span.End) + selections = textareaLineRanges(canvas, selections, labelBounds, origin, line, fontSize, row.Start, lineEnd, start, end) + } + } else { + selections = textareaLineRanges(canvas, ranges[:0], labelBounds, origin, line, fontSize, row.Start, lineEnd, selectionStart, selectionEnd) + } selectionColor, _ := selectionColors(theme) if snapshot.Disabled { selectionColor.Alpha *= 0.50 @@ -553,6 +569,26 @@ func (layout *TextareaLayout) ScrollBy(dy float32) { layout.scroll = layout.clampScroll(layout.scroll + dy) } +// Wheel scrolls the box by a wheel event over the text it last painted, as ScrollBy does, and +// reports whether the box moved. A wheel the box cannot move with (it is at the end the wheel +// points to, or it shows all its rows) reports false, so the page scrolls instead. +func (layout *TextareaLayout) Wheel(event gfx.ScrollEvent) bool { + content := layout.content + if !layout.painted || event.X < content.X || event.X >= content.X+content.Width || + event.Y < content.Y || event.Y >= content.Y+content.Height { + return false + } + dy := event.DeltaY + if !event.Precise && dy > 0 && dy < 24 { + dy = 24 + } else if !event.Precise && dy < 0 && dy > -24 { + dy = -24 + } + before := layout.scroll + layout.ScrollBy(dy) + return layout.scroll != before +} + // RowCount is how many rows text takes in a box of outer width width: one for // each line that fits and as many as a longer one wraps to, and an empty one // after a final newline. The rows it wraps are the ones the next paint at that diff --git a/components/button.go b/components/button.go index 607771626..c82b6e592 100644 --- a/components/button.go +++ b/components/button.go @@ -60,6 +60,10 @@ type Button struct { height float32 fontSize float32 disabled bool + // recipe, when set, replaces ButtonRecipe for this button: a page whose + // application has a look of its own hands one down instead of painting + // every button from a Base. + recipe func(gfx.Theme, ButtonVariant, gfx.State) ButtonLook } // BeginButton starts a button declaration. Hit ID zero paints a static preview @@ -74,6 +78,16 @@ func BeginButton(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect return Button{canvas: canvas, theme: theme, id: id, bounds: bounds, state: state} } +// Recipe replaces the theme's button recipe for this button: the fill, label, +// border, corners, shadow and ring come from recipe instead of ButtonRecipe. +// The metrics (height, padding, text size) still come from the size and the +// theme, so a recipe changes the look without changing what the button +// measures. A nil recipe keeps the theme's. +func (button Button) Recipe(recipe func(gfx.Theme, ButtonVariant, gfx.State) ButtonLook) Button { + button.recipe = recipe + return button +} + // WithState pins a visual state, overriding canvas-derived interaction state. func (button Button) WithState(state ButtonState) Button { button.state = state @@ -359,6 +373,12 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { Hovered: button.state.Hovered, Pressed: button.state.Pressed, FocusVisible: button.state.Focused, Invalid: button.state.Invalid, Disabled: button.disabled, }) + if button.recipe != nil { + look = button.recipe(button.theme, variant, gfx.State{ + Hovered: button.state.Hovered, Pressed: button.state.Pressed, FocusVisible: button.state.Focused, + Invalid: button.state.Invalid, Disabled: button.disabled, + }) + } radius := look.Radius if look.Shadow != gfx.ShadowNone { button.canvas.Elevate(button.bounds, radius, look.Shadow) // shadow-xs diff --git a/components/checkbox.go b/components/checkbox.go index 99a0466ad..bfc4e8532 100644 --- a/components/checkbox.go +++ b/components/checkbox.go @@ -18,6 +18,8 @@ type Checkbox struct { focused bool invalid bool disabled bool + // recipe, when set, replaces CheckboxRecipe; see Button.Recipe. + recipe func(gfx.Theme, gfx.State) CheckboxLook } // BeginCheckbox starts a checkbox declaration. Bounds provide only the visual @@ -34,6 +36,13 @@ func BeginCheckbox(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Re } } +// Recipe replaces the theme's checkbox recipe for this checkbox. A nil recipe +// keeps the theme's. +func (checkbox Checkbox) Recipe(recipe func(gfx.Theme, gfx.State) CheckboxLook) Checkbox { + checkbox.recipe = recipe + return checkbox +} + // Label sets the accessible name without changing visual geometry. func (checkbox Checkbox) Label(label string) Checkbox { checkbox.label = label @@ -115,6 +124,9 @@ func (checkbox Checkbox) Paint() CheckboxResult { Invalid: checkbox.invalid, Disabled: checkbox.disabled, } look := checkboxRecipe(&checkbox.theme, state) + if checkbox.recipe != nil { + look = checkbox.recipe(checkbox.theme, state) + } checkbox.canvas.Elevate(checkbox.bounds, look.Radius, look.Shadow) // shadow-xs if look.RingWidth > 0 { checkbox.canvas.Rounded(expand(checkbox.bounds, look.RingWidth), look.RingRadius, look.Ring) diff --git a/components/code_editor.go b/components/code_editor.go index 7819088cb..b86a53d89 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -8,12 +8,14 @@ import ( "github.com/vivaui/viva/text" ) -// CodeEditorRun colors one byte range of a line without changing its text -// geometry. Runs are ordered and non-overlapping; invalid and overlapping spans -// are ignored. +// CodeEditorRun colors and slants one byte range of a line without changing its +// text geometry: Italic draws the range in the italic face of the line's +// fixed-pitch font, as a comment is drawn in an editor. Runs are ordered and +// non-overlapping; invalid and overlapping spans are ignored. type CodeEditorRun struct { Start, End int Color gfx.Color + Italic bool } // CodeEditorMarkLayer paints colored byte ranges behind the text. Spans are diff --git a/components/code_editor_editor_multiselection_test.go b/components/code_editor_editor_multiselection_test.go new file mode 100644 index 000000000..90028be93 --- /dev/null +++ b/components/code_editor_editor_multiselection_test.go @@ -0,0 +1,67 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/text" +) + +// A code editor driven from a text.Editor's selections paints every one of +// them: SelectionSpansInto is what the snapshot's SelectionRanges is for. +func TestCodeEditorPaintsAnEditorsEverySelection(t *testing.T) { + editor := text.NewEditor("abc\ndef\nghi") + editor.SetSelections([]text.Range{{Start: 1, End: 2}, {Start: 5, End: 6}, {Start: 9, End: 10}}, 1) + fixture := newCodeFixture(editor.String()) + fixture.snapshot.SelectionRanges = editor.SelectionSpans() + fixture.snapshot.Caret = editor.ByteOffset(editor.Caret()) + fixture.paint() + fills := fixture.fills(fixture.theme.Selection) + if len(fills) != 3 { + t.Fatalf("selection fills = %+v, want one per selection", fills) + } + _, _, rowHeight := fixture.cell() + cell, _, _ := fixture.cell() + for index, fill := range fills { + if !near(fill.X, fixture.editor.content.X+cell) || !near(fill.Y, fixture.editor.content.Y+float32(index)*rowHeight) || !near(fill.Width, cell) { + t.Fatalf("selection row %d = %+v", index, fill) + } + } + // The primary is the middle range, and only it has a caret. + if bounds, ok := fixture.editor.CaretBounds(); !ok || !near(bounds.Y, fixture.editor.content.Y+rowHeight) { + t.Fatalf("caret = %+v, %v", bounds, ok) + } +} + +// Two selections on one line paint as two bands, and the caret sits on the +// primary one. +func TestCodeEditorPaintsTwoEditorSelectionsOnOneLine(t *testing.T) { + editor := text.NewEditor("abcdef") + editor.SetSelections([]text.Range{{Start: 0, End: 1}, {Start: 3, End: 5}}, 1) + fixture := newCodeFixture(editor.String()) + fixture.snapshot.SelectionRanges = editor.SelectionSpans() + fixture.snapshot.Caret = editor.ByteOffset(editor.Caret()) + fixture.paint() + cell, _, _ := fixture.cell() + fills := fixture.fills(fixture.theme.Selection) + if len(fills) != 2 || !near(fills[0].Width, cell) || !near(fills[1].X, fixture.editor.content.X+3*cell) || !near(fills[1].Width, 2*cell) { + t.Fatalf("two selections = %+v", fills) + } + if bounds, ok := fixture.editor.CaretBounds(); !ok || !near(bounds.X, fixture.editor.content.X+5*cell) { + t.Fatalf("caret = %+v, %v, want the primary's end", bounds, ok) + } +} + +// SelectionSpans and Selections describe the same set, so a view that converts +// through the editor and one that converts rune indices agree. +func TestSelectionSpansMatchSelections(t *testing.T) { + editor := text.NewEditor("a中b") + editor.SetSelections([]text.Range{{Start: 0, End: 1}, {Start: 2, End: 3}}, 0) + spans := editor.SelectionSpans() + if len(spans) != 2 || spans[0] != (text.Span{Start: 0, End: 1}) || spans[1] != (text.Span{Start: 4, End: 5}) { + t.Fatalf("spans = %+v", spans) + } + dst := make([]text.Span, 0, 2) + if allocations := testing.AllocsPerRun(100, func() { dst = editor.SelectionSpansInto(dst) }); allocations != 0 { + t.Fatalf("SelectionSpansInto allocated %v times with a reused scratch", allocations) + } +} diff --git a/components/code_editor_layout.go b/components/code_editor_layout.go index a872d6c8f..3060ee089 100644 --- a/components/code_editor_layout.go +++ b/components/code_editor_layout.go @@ -810,6 +810,7 @@ func gridRuns(dst []gfx.TextRun, line string, spec *gridRunSpec) (runs []gfx.Tex from = -1 included, ascii := true, false var last gfx.Color + var lastItalic bool for at := 0; at < len(line); { r, size := decodeAt(line, at) representation, represented := representationOf(spec.representations, r) @@ -839,6 +840,7 @@ func gridRuns(dst []gfx.TextRun, line string, spec *gridRunSpec) (runs []gfx.Tex next++ } color := spec.foreground + italic := false if represented && spec.representationColor.Alpha != 0 { color = spec.representationColor if spec.disabled { @@ -847,6 +849,7 @@ func gridRuns(dst []gfx.TextRun, line string, spec *gridRunSpec) (runs []gfx.Tex } if next < len(spec.highlight) && spec.highlight[next].Start <= relative { color = spec.highlight[next].Color + italic = spec.highlight[next].Italic if spec.disabled { color.Alpha *= 0.5 } @@ -877,13 +880,13 @@ func gridRuns(dst []gfx.TextRun, line string, spec *gridRunSpec) (runs []gfx.Tex case width == 0 && len(dst) > 0: dst[len(dst)-1].Bytes += int32(bytes) ascii = false - case plain && ascii && color == last: + case plain && ascii && color == last && italic == lastItalic: tail := &dst[len(dst)-1] tail.Bytes += int32(bytes) tail.Cells += int32(width) default: - dst = append(dst, gfx.TextRun{Column: int32(column - startColumn), Bytes: int32(bytes), Cells: int32(width), Color: color}) - ascii, last = plain, color + dst = append(dst, gfx.TextRun{Column: int32(column - startColumn), Bytes: int32(bytes), Cells: int32(width), Color: color, Italic: italic}) + ascii, last, lastItalic = plain, color, italic } to = offset + bytes endColumn = column + width @@ -908,7 +911,7 @@ func cleanHighlight(line string, runs []CodeEditorRun) []CodeEditorRun { if last <= first || first < previous || run.Color.Alpha == 0 { continue } - kept = append(kept, CodeEditorRun{Start: first, End: last, Color: run.Color}) + kept = append(kept, CodeEditorRun{Start: first, End: last, Color: run.Color, Italic: run.Italic}) previous = last } return kept diff --git a/components/code_editor_test.go b/components/code_editor_test.go index 54883009a..6f92db26c 100644 --- a/components/code_editor_test.go +++ b/components/code_editor_test.go @@ -534,6 +534,116 @@ func TestCodeEditorPaintsOneLabelPerRowWhateverTheHighlight(t *testing.T) { } } +// A highlighted range may be drawn italic, the way an editor draws a comment. The +// slant reaches the grid runs of the painted label without moving their columns, +// and a range of the same color but another slant keeps its own run. +func TestCodeEditorItalicHighlightReachesTheGridRuns(t *testing.T) { + const value = "x := 1 // note\ny := 2\n" + f := newCodeFixture(value) + comment, plain := gfx.RGB(110, 130, 118), gfx.RGB(20, 20, 20) + commentStart := strings.Index(value, "//") + f.snapshot.HighlightLine = func(_ string, lineIndex int, line string, dst []CodeEditorRun) []CodeEditorRun { + if lineIndex == 0 { + return append(dst, + CodeEditorRun{Start: 0, End: 1, Color: plain}, + CodeEditorRun{Start: commentStart, End: len(line), Color: comment, Italic: true}, + ) + } + return append(dst, CodeEditorRun{Start: 0, End: len(line), Color: plain}) + } + f.paint() + + var first, second gfx.Text + for _, text := range f.canvas.Texts() { + switch text.Value { + case "x := 1 // note": + first = text + case "y := 2": + second = text + } + } + if first.Value == "" || second.Value == "" { + t.Fatalf("rows not painted: %+v", f.canvas.Texts()) + } + var italicRun *gfx.TextRun + covered, column := 0, int32(0) + for index := range f.canvas.TextRuns(first) { + run := f.canvas.TextRuns(first)[index] + if run.Column != column { + t.Fatalf("run starts at column %d, want %d", run.Column, column) + } + if run.Italic { + italicRun = &run + } + covered += int(run.Bytes) + column += run.Cells + } + if covered != len(first.Value) { + t.Fatalf("runs cover %d of %d bytes", covered, len(first.Value)) + } + if italicRun == nil { + t.Fatalf("no italic run: %+v", f.canvas.TextRuns(first)) + } + if italicRun.Color != comment || italicRun.Column != int32(commentStart) || italicRun.Cells != int32(len("// note")) { + t.Fatalf("italic run = %+v, want the comment from column %d", *italicRun, commentStart) + } + // The first run's slant is its own: the plain range of another color before it + // is not italic, and the italic range did not extend back over it. + head := f.canvas.TextRuns(first)[0] + if head.Italic || head.Column != 0 { + t.Fatalf("first run = %+v, want the plain start", head) + } + for _, run := range f.canvas.TextRuns(second) { + if run.Italic { + t.Fatalf("an unhighlighted row inherited a slant: %+v", run) + } + } +} + +// Two adjacent ranges of one color that differ only in slant are separate runs: +// merging them would italicize the upright one. +func TestCodeEditorItalicRunIsNotMergedWithAnUprightNeighbor(t *testing.T) { + f := newCodeFixture("abcd") + fg := gfx.RGB(40, 40, 40) + f.snapshot.Highlight = func(_, _ string, dst []CodeEditorRun) []CodeEditorRun { + return append(dst, + CodeEditorRun{Start: 0, End: 2, Color: fg}, + CodeEditorRun{Start: 2, End: 4, Color: fg, Italic: true}, + ) + } + f.paint() + var text gfx.Text + for _, drawn := range f.canvas.Texts() { + if drawn.Value == "abcd" { + text = drawn + } + } + if text.Value == "" { + t.Fatal("row not painted") + } + runs := f.canvas.TextRuns(text) + if len(runs) != 2 || runs[0].Italic || !runs[1].Italic || runs[1].Column != 2 { + t.Fatalf("runs = %+v, want an upright run of 2 and an italic run of 2", runs) + } + if runs[0].Bytes != 2 || runs[1].Bytes != 2 { + t.Fatalf("bytes = %d/%d, want 2/2", runs[0].Bytes, runs[1].Bytes) + } +} + +func TestCodeEditorItalicHighlightSteadyPaintAllocatesNothing(t *testing.T) { + f := newCodeFixture(strings.Repeat("key: value # comment\n", 40)) + f.snapshot.Highlight = func(_, line string, dst []CodeEditorRun) []CodeEditorRun { + if at := strings.IndexByte(line, '#'); at >= 0 { + return append(dst, CodeEditorRun{Start: at, End: len(line), Color: gfx.RGB(110, 130, 118), Italic: true}) + } + return dst + } + f.paint() + if allocations := testing.AllocsPerRun(100, f.paint); allocations != 0 { + t.Fatalf("steady italic paint allocated %g times", allocations) + } +} + func TestCodeEditorHighlightLineReceivesLogicalIndexAfterScrolling(t *testing.T) { value := "same\n" + strings.Repeat("padding\n", 25) + "same" fixture := newCodeFixture(value) diff --git a/components/context_menu.go b/components/context_menu.go index 17b2baf7c..ced040f27 100644 --- a/components/context_menu.go +++ b/components/context_menu.go @@ -68,10 +68,16 @@ type ContextMenuOptions struct { // Submenu makes this the content of a submenu, which has a smaller minimum // width (128) than a context menu (144). Submenu bool - // RowHeight is the height of an item row. Zero is the standard 32px; a menu - // with many items can ask for a denser one (24, say). Group labels, separators - // and everything else keep their size. An icon never grows past the row. + // RowHeight is the height of an item row. Zero is the theme's control height + // (32 at the default density, 26 at the compact one); a menu with many items + // can ask for a denser one (24, say). Group labels, separators and everything + // else keep their size. An icon never grows past the row. RowHeight float32 + // Unpainted, PaintPanel and PaintItem are DropdownMenuOptions' and mean the + // same: the menu keeps its behavior and the caller draws its surface and rows. + Unpainted bool + PaintPanel func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) + PaintItem func(MenuItemPaint) } // ContextMenuItem describes one stable menu action. @@ -121,7 +127,7 @@ func ContextMenuItemWidth(canvas *gfx.Canvas, theme gfx.Theme, item ContextMenuI } // ContextMenuItemHeight is the height AddItem reserves for item. rowHeight is -// ContextMenuOptions.RowHeight (zero selects the standard 32px label row). +// ContextMenuOptions.RowHeight (zero selects the theme's control height). func ContextMenuItemHeight(theme gfx.Theme, item ContextMenuItem, rowHeight float32) float32 { return menuItemHeight(theme, item.common(), rowHeight) } @@ -145,6 +151,7 @@ func BeginContextMenu(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, opti layer: options.Layer, scope: options.Scope, dismissID: options.DismissID, viewport: options.Viewport, scroll: options.Scroll, key: overlayKey(options.ID, options.DismissID, options.Scope), side: options.Side, submenu: options.Submenu, instant: true, labelMuted: true, rowHeight: options.RowHeight, + unpainted: options.Unpainted, paintPanel: options.PaintPanel, paintItem: options.PaintItem, })} } diff --git a/components/context_menu_test.go b/components/context_menu_test.go index 6b203148b..e299fe567 100644 --- a/components/context_menu_test.go +++ b/components/context_menu_test.go @@ -179,6 +179,49 @@ func TestContextMenuRowHeightOptionPacksItemsDenser(t *testing.T) { } } +func TestMenuRowsFollowTheThemeControlHeight(t *testing.T) { + compact := gfx.LightTheme() + compact.Metrics = compact.Metrics.WithDensity(gfx.DensityCompact) + unsized := gfx.LightTheme() + unsized.Metrics.ControlHeight = 0 + for _, test := range []struct { + name string + theme gfx.Theme + rowHeight float32 + want float32 + }{ + {"default density", gfx.LightTheme(), 0, 32}, + {"compact density", compact, 0, 26}, + {"RowHeight wins over the theme", compact, 24, 24}, + {"theme without a control height", unsized, 0, menuRowHeight}, + } { + t.Run(test.name, func(t *testing.T) { + var canvas gfx.Canvas + menu := BeginContextMenu(&canvas, test.theme, gfx.Rect{X: 10, Y: 20, Width: 160, Height: 400}, ContextMenuOptions{Layer: 1, Scope: gfx.Item(2), DismissID: gfx.Item(3), RowHeight: test.rowHeight}) + item := ContextMenuItem{ID: gfx.Item(11), Label: "Copy Path"} + first := menu.AddItem(item) + label := menu.AddLabel("Group", false) + second := menu.AddItem(ContextMenuItem{ID: gfx.Item(12), Label: "Delete…"}) + if first.Height != test.want || second.Height != test.want || menu.NextItemBounds().Height != test.want { + t.Fatalf("rows = %+v %+v next %+v, want %v high", first, second, menu.NextItemBounds(), test.want) + } + if label.Height != menuLabelHeight { + t.Fatalf("label = %+v, want %v high whatever the rows", label, menuLabelHeight) + } + if got := ContextMenuItemHeight(test.theme, item, test.rowHeight); got != test.want { + t.Fatalf("ContextMenuItemHeight = %v, want %v", got, test.want) + } + }) + } + + var canvas gfx.Canvas + dropdown := BeginDropdownMenu(&canvas, compact, gfx.Rect{X: 10, Y: 20, Width: 160, Height: 400}, DropdownMenuOptions{Layer: 1, Scope: gfx.Item(4), DismissID: gfx.Item(5)}) + row := DropdownMenuItem{ID: gfx.Item(21), Label: "Hide"} + if bounds := dropdown.AddItem(row); bounds.Height != 26 || DropdownMenuItemHeight(compact, row) != 26 { + t.Fatalf("compact dropdown row = %+v, reserved %v, want 26", bounds, DropdownMenuItemHeight(compact, row)) + } +} + func TestContextMenuItemWidthKeepsTheLabelWhole(t *testing.T) { var canvas gfx.Canvas theme := gfx.LightTheme() diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index 4fd14679b..9d36d9b20 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -152,6 +152,14 @@ type DropdownMenuOptions struct { // Submenu makes this the content of a submenu, which has a smaller minimum // width (96) than a menu opened by a trigger (128). Submenu bool + // Unpainted declares the menu's behavior, size and rows but paints none of + // it: PaintPanel draws the surface and PaintItem draws each row, both inside + // the menu's layer, clipping and focus scope. Hits, focus, the keyboard and + // submenu expansion stay the menu's, so a menu of the application's own + // cannot behave differently. + Unpainted bool + PaintPanel func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) + PaintItem func(MenuItemPaint) } // DropdownMenuItem describes one stable menu action. @@ -231,14 +239,15 @@ func BeginDropdownMenu(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, opt layer: options.Layer, scope: options.Scope, dismissID: options.DismissID, viewport: options.Viewport, scroll: options.Scroll, key: overlayKey(options.ID, options.DismissID, options.Scope), side: options.Side, submenu: options.Submenu, labelMuted: true, tabCloses: true, + unpainted: options.Unpainted, paintPanel: options.PaintPanel, paintItem: options.PaintItem, })} } // Bounds returns the normalized overlay geometry. func (menu DropdownMenu) Bounds() gfx.Rect { return menu.surface.bounds } -// NextItemBounds returns the next 32px keyboard-navigation row without -// advancing the declaration cursor. +// NextItemBounds returns the next keyboard-navigation row, as tall as the +// theme's control height, without advancing the declaration cursor. func (menu DropdownMenu) NextItemBounds() gfx.Rect { return menu.surface.rowBounds(menu.surface.itemHeight()) } @@ -606,6 +615,8 @@ func (scroll *MenuScroll) follow(canvas *gfx.Canvas) { } const ( + // menuRowHeight is the height of an item row in a theme without a control + // height; a theme with one sizes its rows by it (menuThemeRowHeight). menuRowHeight = float32(32) menuLabelHeight = float32(28) menuSeparatorHeight = float32(9) @@ -654,6 +665,29 @@ type menuItem struct { Icon gfx.Icon } +// MenuItemPaint is one row of a menu declared Unpainted: the caller draws it, +// and the menu keeps the row's hit, focus and keyboard behavior. Separator and +// GroupLabel say the row is not an action. Active is the row the pointer or +// the keyboard is on, and Foreground is the color the menu's own row would +// give its label. +type MenuItemPaint struct { + Canvas *gfx.Canvas + Theme gfx.Theme + Bounds gfx.Rect + Label string + Description string + Shortcut string + Checked bool + Selected bool + Expanded bool + Disabled bool + Active bool + Destructive bool + Separator bool + GroupLabel bool + Foreground gfx.Color +} + type menuSurfaceOptions struct { layer uint16 scope gfx.ID @@ -675,8 +709,14 @@ type menuSurfaceOptions struct { indicatorLeft bool // tabCloses is MenuScroll.TabCloses for this surface. tabCloses bool - // rowHeight is the height of an item row; zero is menuRowHeight. + // rowHeight is the height of an item row; zero is the theme's + // (menuThemeRowHeight). rowHeight float32 + // unpainted leaves the surface and rows to paintPanel and paintItem; see + // DropdownMenuOptions.Unpainted. + unpainted bool + paintPanel func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) + paintItem func(MenuItemPaint) } // menuSurface is what the dropdown menu, the context menu and the menubar's popup @@ -703,6 +743,12 @@ type menuSurface struct { // hitInset is how much shorter than their paint the rows' hits are, to leave // the scrollbar's own. hitInset float32 + // viewport, when it has an area, is the region the rows and the scrollbar are + // painted and hit-tested in place of the clips around the caller: a surface + // declared inside a scroll area is not cut by it, as Canvas.PushOverlayClip + // suspends them for the duration of each row. The control's owner sets it; the + // menus leave it empty and keep their ancestor clips. + viewport gfx.Rect } // pointerRow remembers which option row the pointer is over so a list can move @@ -764,7 +810,13 @@ func beginMenuSurface(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, minW if options.submenu { level = gfx.ShadowLG } - paintPopupSurface(canvas, &theme, bounds, level) + if options.unpainted { + if options.paintPanel != nil { + options.paintPanel(canvas, bounds, theme) + } + } else { + paintPopupSurface(canvas, &theme, bounds, level) + } menu.popOverlay() return menu } @@ -813,9 +865,27 @@ func (menu *menuSurface) take(row gfx.Rect) bool { return !menu.hidden && row.Height > 0 && row.Y < menu.bottom && row.Y+row.Height > menu.top } +// pushClip suspends the clips around the surface for a viewport-anchored one, so a +// row is not cut by an ancestor scroll area, as Select sets one for its popup. A +// surface without a viewport keeps its ancestor clips, as the menus do. +func (menu *menuSurface) pushClip() { + if menu.viewport.Width > 0 && menu.viewport.Height > 0 { + menu.canvas.PushOverlayClip(menu.viewport) + } +} + +// popClip closes the clip pushClip opened. +func (menu *menuSurface) popClip() { + if menu.viewport.Width > 0 && menu.viewport.Height > 0 { + menu.canvas.PopOverlayClip() + } +} + // paintRow runs paint for a row on the menu's layer and scope, clipped to the // visible part of the surface when the row is cut by an edge. func (menu *menuSurface) paintRow(row gfx.Rect, paint func()) { + menu.pushClip() + defer menu.popClip() menu.pushOverlay() cut := row.Y < menu.top || row.Y+row.Height > menu.bottom if cut { @@ -833,6 +903,17 @@ func (menu *menuSurface) itemHeight() float32 { if menu.options.rowHeight > 0 { return menu.options.rowHeight } + return menuThemeRowHeight(menu.theme) +} + +// menuThemeRowHeight is the height of an item row in theme: its control +// height, so a compact theme packs its menus as densely as its buttons and +// inputs (32 at the default density, 26 at the compact one), and menuRowHeight +// for a theme without one. +func menuThemeRowHeight(theme gfx.Theme) float32 { + if height := theme.Metrics.ControlHeight; height > 0 { + return height + } return menuRowHeight } @@ -850,6 +931,14 @@ func (menu *menuSurface) addLabel(label string, inset bool) gfx.Rect { if inset { left = 32 } + if menu.options.unpainted { + menu.paintRow(row, func() { + if paint := menu.options.paintItem; paint != nil { + paint(MenuItemPaint{Canvas: menu.canvas, Theme: menu.theme, Bounds: row, Label: label, GroupLabel: true, Foreground: color}) + } + }) + return row + } menu.paintRow(row, func() { menu.canvas.Label(label, gfx.Rect{X: row.X + left, Y: row.Y, Width: max(0, row.Width-left-8), Height: row.Height}, gfx.TextStyle{ Size: size, Weight: weight, Color: color, @@ -863,6 +952,14 @@ func (menu *menuSurface) addSeparator() gfx.Rect { if !menu.take(row) { return gfx.Rect{} } + if menu.options.unpainted { + menu.paintRow(row, func() { + if paint := menu.options.paintItem; paint != nil { + paint(MenuItemPaint{Canvas: menu.canvas, Theme: menu.theme, Bounds: row, Separator: true, Foreground: menu.theme.Border}) + } + }) + return row + } menu.paintRow(row, func() { menu.canvas.Fill(gfx.Rect{X: row.X, Y: row.Y + 4, Width: row.Width, Height: 1}, menu.theme.Border) }) @@ -932,7 +1029,7 @@ func menuLineHeight(size float32) float32 { return size + 7 } func menuItemHeight(theme gfx.Theme, item menuItem, rowHeight float32) float32 { if rowHeight <= 0 { - rowHeight = menuRowHeight + rowHeight = menuThemeRowHeight(theme) } if item.Description != "" { lines := menuLineHeight(theme.Metrics.FontSizeM) + menuDescriptionGap + menuLineHeight(theme.Metrics.FontSizeS) @@ -941,13 +1038,13 @@ func menuItemHeight(theme gfx.Theme, item menuItem, rowHeight float32) float32 { return rowHeight } -func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { +// itemState is what a row does before it is painted: the pointer moves the +// menu's current row the way Radix does, entering a row focuses it, and the +// returned colors are the menu's own for the label. Both the painted and the +// unpainted row use it, so a menu of the application's own behaves the same. +func (menu *menuSurface) itemState(item menuItem) (active bool, foreground gfx.Color) { canvas, theme := menu.canvas, menu.theme enabled := !item.ID.IsZero() && !item.Disabled - // The pointer moves the menu's current row the way Radix does: entering a - // row focuses it, so the tint and Enter name one row instead of two. A - // pointer that rests in place never moves the row back, so the arrow keys - // keep working under it. hovered := canvas.Hovered() claim := canvas.HoverCrossed() && !hovered.IsZero() // While the pointer is over caller content inside the menu (a colour row, a @@ -965,27 +1062,64 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { } // Focused, not FocusVisible: a menu row the pointer focused is the current // row even though no key press made its focus ring visible. - active := enabled && !inContent && (claim && hovered == item.ID || !claim && canvas.Focused() == item.ID) + active = enabled && !inContent && (claim && hovered == item.ID || !claim && canvas.Focused() == item.ID) if item.Kind == menuSubmenu && item.Expanded { active = true } - foreground := theme.PopoverForeground + foreground = theme.PopoverForeground if item.Destructive { foreground = theme.Danger + } else if active { + foreground = theme.AccentForeground + } + if item.Disabled { + foreground.Alpha *= 0.50 + } + return active, foreground +} + +// declareItemHit gives a row the pointer, keyboard and assistive-technology +// behavior each path needs, painted or not. +func (menu *menuSurface) declareItemHit(bounds gfx.Rect, item menuItem) { + if item.ID.IsZero() { + return + } + hit := bounds + hit.Width -= menu.hitInset + menu.canvas.HitWithOptions(item.ID, hit, item.Label, gfx.HitOptions{ + Role: gfx.RoleMenuItem, Value: item.Value, Hint: item.Hint, Description: item.Description, + Disabled: item.Disabled, Checked: item.Kind == menuCheckbox && item.Checked, + Selected: item.Kind == menuRadio && item.Selected, + Expanded: item.Kind == menuSubmenu && item.Expanded, Expandable: item.Kind == menuSubmenu, + }) +} + +func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { + canvas, theme := menu.canvas, menu.theme + active, foreground := menu.itemState(item) + if menu.options.unpainted { + if paint := menu.options.paintItem; paint != nil { + paint(MenuItemPaint{ + Canvas: canvas, Theme: theme, Bounds: bounds, + Label: item.Label, Description: item.Description, Shortcut: item.Shortcut, + Checked: item.Kind == menuCheckbox && item.Checked, + Selected: item.Kind == menuRadio && item.Selected, + Expanded: item.Kind == menuSubmenu && item.Expanded, + Disabled: item.Disabled, Active: active, Destructive: item.Destructive, + Foreground: foreground, + }) + } + menu.declareItemHit(bounds, item) + return } if active { fill := theme.Accent if item.Destructive { fill = theme.Danger fill.Alpha = 0.10 - } else { - foreground = theme.AccentForeground } canvas.Rounded(bounds, theme.Metrics.RadiusItem(), fill) } - if item.Disabled { - foreground.Alpha *= 0.50 - } // A row with a description is two lines of type, not a taller one-line row: // the title keeps the system line height, the description follows one small // gap below it, and the pair is centered in the row. The indicator, icon and @@ -1057,16 +1191,7 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { Size: theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: color, }) } - if !item.ID.IsZero() { - hit := bounds - hit.Width -= menu.hitInset - canvas.HitWithOptions(item.ID, hit, item.Label, gfx.HitOptions{ - Role: gfx.RoleMenuItem, Value: item.Value, Hint: item.Hint, Description: item.Description, - Disabled: item.Disabled, Checked: item.Kind == menuCheckbox && item.Checked, - Selected: item.Kind == menuRadio && item.Selected, - Expanded: item.Kind == menuSubmenu && item.Expanded, Expandable: item.Kind == menuSubmenu, - }) - } + menu.declareItemHit(bounds, item) } // end paints a thin scrollbar thumb on the right edge when rows are scrolled out, @@ -1080,13 +1205,17 @@ func (menu *menuSurface) end() { thumb := max(view*view/(view+scroll.max), 18) at := menu.top + (view-thumb)*scroll.Offset/scroll.max scroll.barTop, scroll.thumb = menu.top, thumb + menu.pushClip() menu.pushOverlay() - menu.canvas.Rounded(gfx.Rect{X: menu.bounds.X + menu.bounds.Width - 6, Y: at, Width: 4, Height: thumb}, 2, menu.theme.Border) + if !menu.options.unpainted { + menu.canvas.Rounded(gfx.Rect{X: menu.bounds.X + menu.bounds.Width - 6, Y: at, Width: 4, Height: thumb}, 2, menu.theme.Border) + } if !scroll.BarID.IsZero() { menu.canvas.HitWithOptions(scroll.BarID, gfx.Rect{X: menu.bounds.X + menu.bounds.Width - 2 - menuBarWidth, Y: menu.top, Width: menuBarWidth, Height: view}, "Scroll", gfx.HitOptions{Role: gfx.RoleSlider, SkipFocus: true}) } menu.popOverlay() + menu.popClip() } if menu.animated { menu.canvas.EndPresence() diff --git a/components/input.go b/components/input.go index 53c12dcc7..cdf7c55cb 100644 --- a/components/input.go +++ b/components/input.go @@ -4,6 +4,7 @@ import ( "unicode/utf8" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" ) // InputSnapshot is one caller-owned single-line editor presentation. Value is @@ -36,12 +37,19 @@ type InputSnapshot struct { // can put the line a fraction of a pixel away from the canvas line; with the text // painted here it cannot move when the field opens. A fixed-pitch field does this // always (see InputTextStyle.Mono). - HideEditorText bool - NavigationKeys bool - ShowCaret bool - Caret int - SelectionStart int - SelectionEnd int + HideEditorText bool + NavigationKeys bool + ShowCaret bool + Caret int + SelectionStart int + SelectionEnd int + // SelectionRanges, when nonempty, replaces the single selection for + // painting: the selections of a multi-selection editor (see + // text.Editor.SelectionSpansInto). They are byte offsets into Value, in + // order, non-overlapping, and may sit anywhere on the line. Collapsed ones + // paint nothing. The caret is still Caret, so only the primary selection has + // one. + SelectionRanges []text.Span CompositionStart int CompositionEnd int // Text styles the text of the field: its size, weight and color. The zero value is the @@ -198,6 +206,9 @@ func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snaps snapshot.Caret = inputMaskOffset(snapshot.Value, snapshot.Caret) snapshot.SelectionStart = inputMaskOffset(snapshot.Value, snapshot.SelectionStart) snapshot.SelectionEnd = inputMaskOffset(snapshot.Value, snapshot.SelectionEnd) + // The offsets of a range would index the mask, not the value, and a + // password field has no multi-selection to paint. + snapshot.SelectionRanges = nil snapshot.CompositionStart = inputMaskOffset(snapshot.Value, snapshot.CompositionStart) snapshot.CompositionEnd = inputMaskOffset(snapshot.Value, snapshot.CompositionEnd) } @@ -229,15 +240,20 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, var ranges [4]gfx.Rect selectionStart, selectionEnd := inputRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) var selections []gfx.Rect - if selectionEnd > selectionStart && !placeholderShown { - selections = inputTextRanges(canvas, ranges[:0], bounds, bandTop, bandHeight, origin, value, textStyle, selectionStart, selectionEnd) - selectionColor, _ := selectionColors(theme) - if snapshot.Disabled { - selectionColor.Alpha *= 0.50 - } - for _, selection := range selections { - canvas.Fill(selection, selectionColor) + if len(snapshot.SelectionRanges) > 0 { + // A multi-selection editor: every range is painted, so two selections on + // the one line show as two bands. The primary's Caret is the only caret. + selections = ranges[:0] + for _, span := range snapshot.SelectionRanges { + start, end := inputRange(value, span.Start, span.End) + if end > start && !placeholderShown { + selections = inputTextRanges(canvas, selections, bounds, bandTop, bandHeight, origin, value, textStyle, start, end) + } } + selections = fillInputSelections(canvas, theme, snapshot, selections) + } else if selectionEnd > selectionStart && !placeholderShown { + selections = inputTextRanges(canvas, ranges[:0], bounds, bandTop, bandHeight, origin, value, textStyle, selectionStart, selectionEnd) + selections = fillInputSelections(canvas, theme, snapshot, selections) } compositionStart, compositionEnd := inputRange(value, snapshot.CompositionStart, snapshot.CompositionEnd) if compositionEnd > compositionStart && !placeholderShown { @@ -280,6 +296,23 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, canvas.Unclip() } +// fillInputSelections paints the bands of the field's selections and returns +// them, so the selected glyphs can be repainted in the selection foreground +// afterwards. +func fillInputSelections(canvas *gfx.Canvas, theme gfx.Theme, snapshot InputSnapshot, selections []gfx.Rect) []gfx.Rect { + if len(selections) == 0 { + return selections + } + selectionColor, _ := selectionColors(theme) + if snapshot.Disabled { + selectionColor.Alpha *= 0.50 + } + for _, selection := range selections { + canvas.Fill(selection, selectionColor) + } + return selections +} + // inputTextRanges appends the rectangles of the bytes [start, end) of value, a line drawn // from x = origin in bounds, clamped to bounds: one for left-to-right text, more where the // range crosses a change of direction. They fill the band of the line (inputLineBand), top diff --git a/components/input_multiselection_test.go b/components/input_multiselection_test.go new file mode 100644 index 000000000..42bb81e08 --- /dev/null +++ b/components/input_multiselection_test.go @@ -0,0 +1,78 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// A field bound to a multi-selection editor paints every selection on its one +// line, not the primary's band stretched over the gap between them. +func TestInputPaintsEverySelectionOnOneLine(t *testing.T) { + theme := gfx.LightTheme() + theme.Selection = gfx.RGB(1, 2, 3) + var canvas gfx.Canvas + canvas.SetMeasurer(func(value string, size, weight float32) float32 { + return float32(len(value)) * size / 2 + }) + bounds := gfx.Rect{X: 10, Y: 4, Width: 400, Height: 32} + PaintInputContent(&canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Name", Value: "abcdef", Focused: true, ShowCaret: true, Caret: 5, + SelectionRanges: []text.Span{{Start: 0, End: 1}, {Start: 3, End: 5}}, + }) + var fills []gfx.Rect + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == theme.Selection { + fills = append(fills, rectangle.Bounds) + } + } + if len(fills) != 2 { + t.Fatalf("selection fills = %+v", fills) + } + charWidth := float32(14) / 2 + origin := fills[0].X + if !near(fills[0].Width, charWidth) { + t.Fatalf("first fill = %+v", fills[0]) + } + if !near(fills[1].X, origin+3*charWidth) || !near(fills[1].Width, 2*charWidth) { + t.Fatalf("second fill = %+v, want x=%v width=%v", fills[1], origin+3*charWidth, 2*charWidth) + } +} + +// SelectionRanges replaces SelectionStart/End for painting, and an empty one +// keeps the single-selection path exactly as it was. +func TestInputSelectionRangesReplaceTheSingleSelection(t *testing.T) { + theme := gfx.LightTheme() + paint := func(snapshot InputSnapshot) []gfx.Rect { + var canvas gfx.Canvas + canvas.SetMeasurer(func(value string, size, weight float32) float32 { + return float32(len(value)) * size / 2 + }) + bounds := gfx.Rect{X: 10, Y: 4, Width: 400, Height: 32} + snapshot.ID, snapshot.Label = gfx.Item(1), "Name" + PaintInputContent(&canvas, theme, bounds, bounds, snapshot) + var fills []gfx.Rect + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == theme.Selection { + fills = append(fills, rectangle.Bounds) + } + } + return fills + } + // The wide single selection is one band; the two ranges are two. + wide := paint(InputSnapshot{Value: "abcdef", SelectionStart: 0, SelectionEnd: 5}) + narrow := paint(InputSnapshot{Value: "abcdef", SelectionStart: 0, SelectionEnd: 1, + SelectionRanges: []text.Span{{Start: 0, End: 1}, {Start: 3, End: 5}}}) + if len(wide) != 1 || len(narrow) != 2 { + t.Fatalf("single = %+v, ranges = %+v", wide, narrow) + } + if !near(narrow[0].X, wide[0].X) || !near(narrow[0].Width, wide[0].Width/5) { + t.Fatalf("the first range is not the first character of the single selection: %+v vs %+v", narrow[0], wide[0]) + } + // An empty ranges slice is the single selection again. + single := paint(InputSnapshot{Value: "abcdef", SelectionStart: 0, SelectionEnd: 5}) + if len(single) != 1 || single[0] != wide[0] { + t.Fatalf("empty ranges changed the paint: %+v", single) + } +} diff --git a/components/popover.go b/components/popover.go index 889f21249..08825b7fd 100644 --- a/components/popover.go +++ b/components/popover.go @@ -325,6 +325,14 @@ func PlaceOverlay(anchor gfx.Rect, size gfx.Size, viewport gfx.Rect, placement O return overlayClamp(bounds, viewport, placement.Margin), side } +// ClampOverlay keeps an overlay opened at point inside viewport, except for its +// margin. Unlike PlaceOverlay, a context menu that fits above the pointer but +// would clamp below it stays at the pointer's y; that is how a native context +// menu opens at the mouse rather than choosing a side. +func ClampOverlay(point gfx.Point, size gfx.Size, viewport gfx.Rect, margin float32) gfx.Rect { + return overlayClamp(gfx.Rect{X: point.X, Y: point.Y, Width: size.Width, Height: size.Height}, viewport, margin) +} + // overlayClamp shrinks bounds to fit viewport less margin and shifts them back // inside it. func overlayClamp(bounds, viewport gfx.Rect, margin float32) gfx.Rect { diff --git a/components/select.go b/components/select.go index aee3a4f6c..cd2575961 100644 --- a/components/select.go +++ b/components/select.go @@ -41,6 +41,11 @@ type SelectOptions struct { // whole window behind its surface, so pressing anywhere outside it, // including the trigger, reports DismissID (Escape reports it too). Leave // it empty to dismiss only on Escape and handle outside presses yourself. + // + // It also floats the open list: the popup is painted and hit-tested against + // the viewport instead of the clips around the select, so a list declared + // inside a scroll area is not cut by it. Leave it empty to keep the list + // inside the ancestor clips, as a component called without one always has. Viewport gfx.Rect // Scroll is the scroll position of a popup whose items do not all fit its // Content (see MenuScroll); without one such a popup shows only the items at @@ -146,12 +151,19 @@ func BeginSelect(canvas *gfx.Canvas, theme gfx.Theme, triggerBounds gfx.Rect, op options: menuSurfaceOptions{layer: options.Layer, scope: options.Scope, scroll: options.Scroll}, top: content.Y + menuPadding, bottom: content.Y + content.Height - menuPadding, viewHeight: max(content.Height-2*menuPadding, 0), + // An open list floats over the page: a select at the bottom of a scroll + // area shows its list whole instead of through the area's clip. The list + // stays inside the viewport when the caller gives one. + viewport: options.Viewport, } selectControl.rows.beginScroll() if options.Scroll != nil { options.Scroll.TabCloses = true } selectControl.pushOverlay() + // The popup and its backdrop float over the page: an ancestor scroll area's + // clip does not cut them, and the viewport bounds what shows. + selectControl.rows.pushClip() // Claim after pushing the popup's scope, so a select inside a dialog owns // the trap and Escape while it is open. if !options.Scope.IsZero() { @@ -173,6 +185,9 @@ func BeginSelect(canvas *gfx.Canvas, theme gfx.Theme, triggerBounds gfx.Rect, op if !options.Unpainted { paintPopupSurface(canvas, &theme, content, gfx.ShadowMD) // shadow-md } + // The surface is painted: the rows start their own overlay clip, so the two + // need not nest. Keep the popup's viewport open only through the surface. + selectControl.rows.popClip() selectControl.popOverlay() return selectControl } diff --git a/components/select_test.go b/components/select_test.go index 2d8fb65e8..350ef9a24 100644 --- a/components/select_test.go +++ b/components/select_test.go @@ -362,3 +362,95 @@ func TestSelectInsideADialogKeepsItsTrapAndEscape(t *testing.T) { t.Fatalf("closed select: trap=%d escape=%d, want the dialog's", closed.TrappedFocusScope(), closed.EscapeTarget()) } } + +// An open list declared inside a scroll area is not cut by it: its surface, rows +// and scrollbar are painted and hit-tested against the viewport, and the area +// still owns its clip when the select is done. +func TestSelectPopupEscapesAncestorScrollClip(t *testing.T) { + var scroll MenuScroll + viewport := gfx.Rect{Width: 400, Height: 300} + body := gfx.Rect{X: 10, Y: 10, Width: 200, Height: 80} + paint := func(withViewport bool) *gfx.Canvas { + var canvas gfx.Canvas + options := SelectOptions{ + TriggerID: gfx.Item(1), Label: "Density", Open: true, Layer: 6, Scope: gfx.Item(10), DismissID: gfx.Item(9), + Content: gfx.Rect{X: 10, Y: 70, Width: 200, Height: 8 + 32*6}, Scroll: &scroll, + } + if withViewport { + options.Viewport = viewport + } + canvas.Clip(body) + control := BeginSelect(&canvas, gfx.LightTheme(), gfx.Rect{X: 10, Y: 40, Width: 200}, options) + for index := range 6 { + control.AddItem(SelectItem{ID: gfx.Item(100 + index), Label: "Option"}) + } + control.End() + canvas.Unclip() + return &canvas + } + // The viewport reaches below the scroll area: the last row is painted whole and + // its hit is not cut at the area's bottom edge. + canvas := paint(true) + popup := gfx.Rect{X: 10, Y: 70, Width: 200, Height: 8 + 32*6} + foundSurface := false + for _, r := range canvas.Rectangles() { + if r.Bounds == popup { + foundSurface = true + if !r.HasClip || r.ClipOf != viewport { + t.Fatalf("popup surface inherited the scroll clip: %+v", r) + } + } + } + if !foundSurface { + t.Fatal("the popup surface was not painted") + } + var last gfx.Hit + for _, hit := range canvas.Hits() { + if hit.ID == gfx.Item(105) { + last = hit + } + } + if last.Bounds.Height != 32 || last.Bounds.Y+last.Bounds.Height > viewport.Y+viewport.Height { + t.Fatalf("the last row's hit is %+v, want a whole row inside the viewport", last.Bounds) + } + // Without a viewport the select keeps the ancestor clip, as it always has. + clipped := paint(false) + for _, r := range clipped.Rectangles() { + if r.Bounds == popup && r.ClipOf != body { + t.Fatalf("a select without a viewport left the scroll clip: %+v", r) + } + } +} + +// The popup's scrollbar floats with the rows: a list cut by a scroll area shows the +// bar inside the viewport too. +func TestSelectPopupScrollbarEscapesAncestorScrollClip(t *testing.T) { + var scroll MenuScroll + viewport := gfx.Rect{Width: 400, Height: 300} + var canvas gfx.Canvas + canvas.Clip(gfx.Rect{X: 10, Y: 10, Width: 200, Height: 80}) + control := BeginSelect(&canvas, gfx.LightTheme(), gfx.Rect{X: 10, Y: 40, Width: 200}, SelectOptions{ + TriggerID: gfx.Item(1), Open: true, Layer: 6, Viewport: viewport, + Content: gfx.Rect{X: 10, Y: 70, Width: 200, Height: 8 + 32*2}, Scroll: &scroll, + }) + for index := range 6 { + control.AddItem(SelectItem{ID: gfx.Item(100 + index), Label: "Option"}) + } + control.End() + canvas.Unclip() + if scroll.Max() <= 0 { + t.Fatal("the fixture did not overflow its popup") + } + bar := false + for _, r := range canvas.Rectangles() { + if r.Bounds.Width == 4 && r.Bounds.Height >= 18 && r.Bounds.X == 10+200-6 { + bar = true + if r.ClipOf != viewport { + t.Fatalf("the scrollbar is clipped to the scroll area: %+v", r) + } + } + } + if !bar { + t.Fatal("the scrollbar was not painted") + } +} diff --git a/components/single_select_test.go b/components/single_select_test.go index e92eefcec..d48d0e86a 100644 --- a/components/single_select_test.go +++ b/components/single_select_test.go @@ -560,3 +560,49 @@ func TestSingleSelectOptionIconTakesItsOwnColumn(t *testing.T) { t.Fatalf("the popup grew by %v for a %v wide icon", delta, menuIconSize) } } + +// The SingleSelect popup keeps its own viewport clip: it escapes an ancestor +// scroll area and still claims the whole viewport as its dismiss backdrop, as it +// did before Select shared the surface's viewport handling. +func TestSingleSelectPopupKeepsItsViewportClipBeyondAScrollArea(t *testing.T) { + var tree gfx.Tree + f := tree.Feature("single-select-scroll") + viewport := gfx.Rect{Width: 400, Height: 300} + body := gfx.Rect{X: 10, Y: 10, Width: 360, Height: 90} + o := SingleSelectOptions{ + InputID: tree.ID(f, "input"), TriggerID: tree.ID(f, "trigger"), ClearID: tree.ID(f, "clear"), + DismissID: tree.ID(f, "dismiss"), Scope: tree.ID(f, "scope"), ScrollID: tree.ID(f, "scroll"), + OptionIDs: tree.Sub(f, tree.Name("option")), Label: "Group", Viewport: viewport, Layer: 4, + } + s := singleSelectFixture() + s.SetOptions([]SingleSelectOption{{Value: "one"}, {Value: "two"}, {Value: "three"}}) + s.Open = true + var canvas gfx.Canvas + canvas.Clip(body) + layout := PaintSingleSelect(&canvas, gfx.LightTheme(), gfx.Rect{X: 20, Y: 60, Width: 240, Height: 32}, s, o) + canvas.Unclip() + if layout.Popup.Y+layout.Popup.Height <= body.Y+body.Height { + t.Fatalf("the fixture did not place the popup below the scroll area: %+v", layout.Popup) + } + surface := false + for _, r := range canvas.Rectangles() { + if r.Bounds == layout.Popup { + surface = true + if r.ClipOf != viewport { + t.Fatalf("the SingleSelect popup inherited the scroll clip: %+v", r) + } + } + } + if !surface { + t.Fatal("the SingleSelect popup surface was not painted") + } + var dismiss gfx.Hit + for _, hit := range canvas.Hits() { + if hit.ID == o.DismissID { + dismiss = hit + } + } + if dismiss.Bounds != viewport || !dismiss.Backdrop { + t.Fatalf("the dismiss backdrop is %+v, want the whole viewport", dismiss.Bounds) + } +} diff --git a/components/switch.go b/components/switch.go index 0fc7c82d8..f4901e127 100644 --- a/components/switch.go +++ b/components/switch.go @@ -28,6 +28,8 @@ type Switch struct { invalid bool size SwitchSize disabled bool + // recipe, when set, replaces SwitchRecipe; see Button.Recipe. + recipe func(gfx.Theme, gfx.State, float32) SwitchLook } // BeginSwitch starts a switch declaration. Zero-sized bounds select official @@ -43,6 +45,14 @@ func BeginSwitch(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect } } +// Recipe replaces the theme's switch recipe for this switch, progress being +// how far the thumb has travelled from off to on. A nil recipe keeps the +// theme's. +func (switchControl Switch) Recipe(recipe func(gfx.Theme, gfx.State, float32) SwitchLook) Switch { + switchControl.recipe = recipe + return switchControl +} + // Small selects the official compact switch size. func (switchControl Switch) Small() Switch { switchControl.size = SwitchSizeSmall @@ -134,6 +144,11 @@ func (switchControl Switch) Paint() SwitchResult { look := switchRecipe(&switchControl.theme, gfx.State{ FocusVisible: switchControl.focused, Invalid: switchControl.invalid, Disabled: switchControl.disabled, }, progress) + if switchControl.recipe != nil { + look = switchControl.recipe(switchControl.theme, gfx.State{ + FocusVisible: switchControl.focused, Invalid: switchControl.invalid, Disabled: switchControl.disabled, + }, progress) + } switchControl.canvas.Elevate(switchControl.bounds, switchControl.bounds.Height/2, look.Shadow) // shadow-xs if look.Bordered { switchControl.canvas.Rounded(expand(switchControl.bounds, look.RingWidth), switchControl.bounds.Height/2+look.RingWidth, look.Ring) diff --git a/components/textarea.go b/components/textarea.go index b5363bf43..d03a4f803 100644 --- a/components/textarea.go +++ b/components/textarea.go @@ -4,6 +4,7 @@ import ( "sort" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" ) // TextareaCommand is a request for the caller-owned editor. The component @@ -76,10 +77,15 @@ type TextareaSnapshot struct { // paints from its first row, which suits a box that shows what is in it. // With it, DisplayValue must be empty or the text of Value, whose byte // offsets Layout reports. - Layout *TextareaLayout - Caret int - SelectionStart int - SelectionEnd int + Layout *TextareaLayout + Caret int + SelectionStart int + SelectionEnd int + // SelectionRanges, when nonempty, replaces the single selection for + // painting: the selections of a multi-selection editor (see + // text.Editor.SelectionSpansInto), as byte offsets into Value in order and + // non-overlapping. Collapsed ones paint nothing; only the primary has Caret. + SelectionRanges []text.Span CompositionStart int CompositionEnd int } @@ -302,7 +308,17 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val holdsCaret = false } if !placeholderShown { - selections = textareaLineRanges(canvas, ranges[:0], labelBounds, origin, line, fontSize, row.Start, lineEnd, selectionStart, selectionEnd) + if len(snapshot.SelectionRanges) > 0 { + // A multi-selection editor paints every selection; two on one row + // show as two bands, and every row a range crosses gets its part. + selections = ranges[:0] + for _, span := range snapshot.SelectionRanges { + start, end := textareaRange(value, span.Start, span.End) + selections = textareaLineRanges(canvas, selections, labelBounds, origin, line, fontSize, row.Start, lineEnd, start, end) + } + } else { + selections = textareaLineRanges(canvas, ranges[:0], labelBounds, origin, line, fontSize, row.Start, lineEnd, selectionStart, selectionEnd) + } selectionColor, _ := selectionColors(theme) if snapshot.Disabled { selectionColor.Alpha *= 0.50 @@ -553,6 +569,26 @@ func (layout *TextareaLayout) ScrollBy(dy float32) { layout.scroll = layout.clampScroll(layout.scroll + dy) } +// Wheel scrolls the box by a wheel event over the text it last painted, as ScrollBy does, and +// reports whether the box moved. A wheel the box cannot move with (it is at the end the wheel +// points to, or it shows all its rows) reports false, so the page scrolls instead. +func (layout *TextareaLayout) Wheel(event gfx.ScrollEvent) bool { + content := layout.content + if !layout.painted || event.X < content.X || event.X >= content.X+content.Width || + event.Y < content.Y || event.Y >= content.Y+content.Height { + return false + } + dy := event.DeltaY + if !event.Precise && dy > 0 && dy < 24 { + dy = 24 + } else if !event.Precise && dy < 0 && dy > -24 { + dy = -24 + } + before := layout.scroll + layout.ScrollBy(dy) + return layout.scroll != before +} + // RowCount is how many rows text takes in a box of outer width width: one for // each line that fits and as many as a longer one wraps to, and an empty one // after a final newline. The rows it wraps are the ones the next paint at that diff --git a/components/textarea_multiselection_test.go b/components/textarea_multiselection_test.go new file mode 100644 index 000000000..4b3c5ce06 --- /dev/null +++ b/components/textarea_multiselection_test.go @@ -0,0 +1,49 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// A textarea paints every selection of a multi-selection editor: ranges on +// different rows each get their band, and two on one row do not join. +func TestTextareaPaintsEverySelection(t *testing.T) { + theme := gfx.LightTheme() + theme.Selection = gfx.RGB(1, 2, 3) + paint := func(snapshot TextareaSnapshot) []gfx.Rect { + var canvas gfx.Canvas + bounds := gfx.Rect{Width: 300, Height: 120} + PaintTextarea(&canvas, theme, bounds, snapshot) + var fills []gfx.Rect + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == theme.Selection { + fills = append(fills, rectangle.Bounds) + } + } + return fills + } + snapshot := TextareaSnapshot{Value: "abc\ndef\nghi", SelectionStart: 0, SelectionEnd: 1, + SelectionRanges: []text.Span{{Start: 0, End: 1}, {Start: 4, End: 5}, {Start: 8, End: 9}}} + fills := paint(snapshot) + if len(fills) != 3 { + t.Fatalf("selection fills = %+v, want one per row", fills) + } + if fills[0].Y >= fills[1].Y || fills[1].Y >= fills[2].Y { + t.Fatalf("fills are not one per row: %+v", fills) + } + // Two ranges on the first row stay two bands. + fills = paint(TextareaSnapshot{Value: "abcdef", SelectionRanges: []text.Span{{Start: 0, End: 1}, {Start: 3, End: 5}}}) + if len(fills) != 2 || fills[1].X <= fills[0].X+fills[0].Width { + t.Fatalf("one-row fills = %+v, want two separate bands", fills) + } + if fills[1].Width <= fills[0].Width { + t.Fatalf("the two-character band is not wider than the one-character one: %+v", fills) + } + // The single-selection path is untouched by an empty SelectionRanges. + single := paint(TextareaSnapshot{Value: "abcdef", SelectionStart: 0, SelectionEnd: 5}) + if len(single) != 1 { + t.Fatalf("single selection = %+v", single) + } +} diff --git a/components/textarea_wheel_test.go b/components/textarea_wheel_test.go new file mode 100644 index 000000000..c9c2657b8 --- /dev/null +++ b/components/textarea_wheel_test.go @@ -0,0 +1,45 @@ +package components + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A wheel over a TextareaLayout scrolls it while it can move in that direction, and reports +// nothing once it is at the end, so the page can scroll instead. +func TestTextareaWheelScrollsUntilItsEnd(t *testing.T) { + var lines []string + for index := range 40 { + lines = append(lines, "row "+string(rune('a'+index%26))) + } + text := strings.Join(lines, "\n") + box := newWrapBox(t, 100) + box.paint(TextareaSnapshot{Value: text, Caret: 0}) + center := gfx.Point{X: box.layout.content.X + 4, Y: box.layout.content.Y + 4} + + outside := gfx.ScrollEvent{X: box.layout.content.X - 10, Y: center.Y, DeltaY: 30} + if box.layout.Wheel(outside) { + t.Fatal("a wheel outside the text scrolled the box") + } + up := gfx.ScrollEvent{X: center.X, Y: center.Y, DeltaY: -30} + if box.layout.Wheel(up) { + t.Fatal("a wheel up at the top scrolled the box") + } + + down := gfx.ScrollEvent{X: center.X, Y: center.Y, DeltaY: 30} + if !box.layout.Wheel(down) { + t.Fatal("a wheel down over the text did not scroll the box") + } + for range 200 { + box.paint(TextareaSnapshot{Value: text, Caret: 0}) + if !box.layout.Wheel(down) { + break + } + } + box.paint(TextareaSnapshot{Value: text, Caret: 0}) + if box.layout.Wheel(down) { + t.Fatal("a wheel down at the end of the text still scrolled the box") + } +} diff --git a/docs/conformance.md b/docs/conformance.md index 3b8661e78..249f50128 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -91,10 +91,10 @@ mistakes an absence for an oversight. Items marked *measured* were tried or size | Toast notifications | Windows | They need a Start-menu shortcut carrying an AppUserModelID, and NSIS cannot write that property without a plugin. A balloon is shown instead. The process AppUserModelID is set only when the application sets `Config.Class`, so a pinned shortcut and its window group together. | | Notification click callbacks | all | `Notification` has none on any platform; adding it to one would make the three differ. | | Full-screen mode | Windows, Linux | `WindowActions` has no full-screen member. The Linux side already treats `_NET_WM_STATE_FULLSCREEN` like maximize (no margin); the API wants `ToggleFullscreen` and `Fullscreen`. | -| A native application menu | all | The contract has a status-item menu only; macOS installs a Quit item. | +| A native application menu | Windows, Linux | macOS installs an application menu bar with `Application.SetMenuBar`; Windows and Linux build the menu in the window with `components.Menubar`, as the platform's own menu bar is not part of the contract there. | | Colour management, HDR, wide gamut | all | Every backend writes sRGB-ish values; nothing converts. Not measured. | | Arm64 UI Automation | Windows | The floating-point thunk exists for amd64 only. | -| AppImage, rpm | Linux | AppImage needs an external runtime binary; rpm could not be checked here. `viva package` makes tar.gz, .deb, and a PKGBUILD for Arch. | +| AppImage | Linux | AppImage needs an external runtime binary. `viva package` makes tar.gz, .deb, a PKGBUILD for Arch, and (with `--format rpm`) an .rpm. The .rpm is checked with rpm 6's `rpm -qpl`, `rpm -qpi` and `rpm -K --nosignature`, and installed on Fedora 44 aarch64 with dnf (install, `rpm -V`, run, desktop-file-validate, remove). The GUI and amd64 on Fedora are not yet run. | | Native text events in `viva dev` | all | The worker protocol does not carry them; native Canvas examples do not run under `viva dev`. | | A flat accessibility tree | Windows, macOS | Every node hangs from the window; Linux derives parents from geometry. | | XIM input | Linux | Composition goes through IBus (IBus and Fcitx5's IBus frontend); XIM-only applications cannot compose. | diff --git a/docs/releases/0.6.4.md b/docs/releases/0.6.4.md new file mode 100644 index 000000000..d345aeea8 --- /dev/null +++ b/docs/releases/0.6.4.md @@ -0,0 +1,87 @@ +v0.6.4 是 v0.6.3 之后的 patch 版本:修复 macOS 增量安装、Windows 补丁路径、Linux 输入法生命周期与文本回调状态等问题,并新增签名增量更新、编辑器多选区、Select 图标与浮层、表格单元格矩形、无头测试时钟与可访问性查询等能力。已有导出 API 不变,升级不需要改调用点。macOS 是参考平台。 + +v0.6.4 is a patch release after v0.6.3: it fixes macOS delta installation, Windows patch paths, Linux input-method lifetimes and stale text callbacks, and adds signed delta updates, multi-selection in editors, Select icons and floating popups, table cell rectangles, and headless test clocks and accessibility queries. Existing exported APIs are unchanged, so upgrading needs no call-site edits. macOS is the reference platform. + +## 拿到它 · Getting it + +`go get github.com/vivaui/viva@v0.6.4`,需要 Go 1.26 或更新;系统依赖与 v0.6.3 相同。每个 Release 附带 `viva` 命令的预编译压缩包、`SHA256SUMS`,以及 Homebrew 与 Scoop 清单(`brew install vivaui/tap/viva`,或 `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` 后 `scoop install viva`);压缩包没有代码签名或公证,浏览器下载的 macOS 版会被 Gatekeeper 拦下,brew、curl 与 `go install` 不受影响。 + +`go get github.com/vivaui/viva@v0.6.4` needs Go 1.26 or newer; the system requirements are those of v0.6.3. Every Release carries prebuilt archives of the `viva` command, `SHA256SUMS`, and Homebrew and Scoop manifests (`brew install vivaui/tap/viva`, or `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` then `scoop install viva`); the archives are not code-signed or notarized, so a browser download on macOS is stopped by Gatekeeper while brew, curl and `go install` are not affected. + +## 有什么 · What is in it + +- 增量更新:签名 feed 可以为每个资产声明补丁(`viva feed --patch-from`);`DownloadPatch` 校验 feed 声明的字节,`ReadPatch` 与 `PatchReader.Apply` 校验它写入的每个文件,`ApplyPatch` 暂存结果,`Install` 用暂存 payload 替换应用;补丁不适配时回退全量包 +- Windows 的补丁携带便携 zip 的目录内容,同一补丁可用于 NSIS 安装与便携副本;PowerShell helper 保留备份,新程序启动失败时回滚;机器级安装回退完整安装器 +- `ContentWindow.Frame` 与 `ContentWindow.Minimized` 暴露内容窗口的 frame 与最小化状态,跨窗口拖放可以按 frame 命中 +- 单元格字形按字体自身的 box drawing 墨宽绘制,CoreText、DirectWrite 与 Pango 分别测量 light/heavy 字形;提示边框不再随显示缩放变细 +- `viva package --format pkgbuild` 生成 Arch Linux 的 `PKGBUILD` 与 `.SRCINFO`,应用可以通过 `[linux] arch_depends` 声明额外的 Arch 包 +- `ui.SelectIcon` 给每个选项一个图标,`Box.Icons` 在 Frame 层提供同一管线;没有图标时 Select 的绘制不变,warm frame 仍然零分配 +- `SelectOptions.Viewport` 让下拉列表浮在祖先滚动裁剪之外,行、滚动条与命中都按整页计算;滚动位置、焦点范围、Escape 与 dismiss 行为不变 +- `TableState.CellRect` 报告上次绘制中源单元格的窗口坐标矩形;行列是源索引,滚动与排序不会重编号,矩形也不会被裁剪 +- `CodeEditorRun.Italic` 让高亮器把注释画成斜体,固定宽度后端已经读取 `TextRun.Italic`,不需要新的平台代码 +- 编辑器支持多选区:`Selections`、`SelectionsInto`、`SelectionSpansInto`、`AddSelection`、`SetSelections` 与 `ClearSecondarySelections`,插入与删除作为一个 undo 单元;字段与代码编辑器绘制全部选区,光标只在主选区 +- 无头 session 的 `Now`、`Advance`、`Frame`、`Transitioning` 提供测试自己的时钟;`Access`、`AccessByRole`、`AccessByName` 读取上一帧的可访问性树,`Notifications` 返回应用发送的通知 +- macOS 上缺失路径的图标按文件类型解析 +- IBus 解码 `UpdatePreeditText`(`vub`)与 `UpdatePreeditTextWithMode`(`vubu`),保留 Update、Show、Hide 与 mode/visibility 来源;旧式 Update 清除 mode 来源,畸形 body 不能覆盖缓存快照 (contributed by @caichangqing1120) (PR [#258](https://github.com/vivaui/viva/pull/258)) +- IBus 的 `Context.Close` 改在 `org.freedesktop.IBus.Service` 上 Destroy,先摘本地 owner 再发送,已退休的 context 不再接受请求,重复 Close 或 path 被替换后也不会误删当前 owner 的 handler (contributed by @caichangqing1120) (PR [#267](https://github.com/vivaui/viva/pull/267)) +- GTK 窗口销毁前先 focus-out、清 client window、unref IM context,默认 delete-event 走同一条销毁路径;Fcitx 下关窗口不再触发 GLib critical (contributed by @caichangqing1120) (PR [#268](https://github.com/vivaui/viva/pull/268)) +- Linux 文本回调按 revision 区分过期确认、仅几何同步与过期重绘;关闭输入后作废在途回调、停止光标定时器并拒绝复活 (contributed by @caichangqing1120) (PR [#259](https://github.com/vivaui/viva/pull/259)) +- Linux rich clipboard 在声明 X11 selection 或调用桌面 hook 之前拒绝 NUL,并把这些 native 剪辑板、合成与图标契约测试加入 CI (contributed by @caichangqing1120) (PR [#264](https://github.com/vivaui/viva/pull/264)) +- 菜单行高跟随 `theme.Metrics.ControlHeight`(密度 compact 26、默认 32、large 40),绘制高度与 `ui.MenuItems` 的预留高度一致;显式 `RowHeight` 仍然优先 (contributed by @xiaoyumuxi) (PR [#265](https://github.com/vivaui/viva/pull/265)) +- textcache 的准入分为 probation 与 protected 两段 LRU,main hit 才提升,避免 Count-Min 冲突误杀正在复用的 shaping 行 (contributed by @caichangqing1120) (PR [#263](https://github.com/vivaui/viva/pull/263)) +- Windows payload 安装用 `Get-Item.FullName` 归一化 payload 与 backup 根路径,`RUNNER~1` 这类 8.3 短路径下不再把文件装到错误位置 (contributed by @caichangqing1120) (PR [#266](https://github.com/vivaui/viva/pull/266)) +- macOS 增量安装把 payload 以运行 bundle 的名字暂存,文档中的 `ApplyPatch → Install` 顺序恢复可用 (contributed by @xiaoyumuxi) (PR [#269](https://github.com/vivaui/viva/pull/269)) +- 补丁生成只为 Windows 便携 zip 生成补丁,不再尝试 diff NSIS setup +- `iconcompile` 支持 use 元素与顶点标记 + +- Delta updates: a signed feed may declare a patch per asset (`viva feed --patch-from`); `DownloadPatch` verifies the bytes the feed declares, `ReadPatch` and `PatchReader.Apply` verify every file a patch writes, `ApplyPatch` stages the result, and `Install` replaces the application from it; a patch that does not fit falls back to the full archive +- A Windows patch carries the portable zip's directory contents and applies to both an NSIS installation and a portable copy; the PowerShell helper keeps a backup and restores it when the new program fails to start, and a machine-wide installation falls back to the full installer +- `ContentWindow.Frame` and `ContentWindow.Minimized` expose the content window's frame and minimize state, so a drag across windows can hit-test by frame +- Cell glyphs use the font's own box-drawing ink width, measured separately by CoreText, DirectWrite and Pango for the light and heavy glyphs, so a prompt border no longer thins out with display scale +- `viva package --format pkgbuild` writes an Arch Linux `PKGBUILD` and `.SRCINFO`, and `[linux] arch_depends` names the extra Arch packages an application needs +- `ui.SelectIcon` gives every option an icon, with `Box.Icons` providing the same plumbing at the Frame's layer; a select without icons paints what it always painted and warm frames allocate nothing +- `SelectOptions.Viewport` floats the open list outside ancestor scroll clips, including its rows and scrollbar; scroll position, focus scope, Escape and dismiss behaviour are unchanged +- `TableState.CellRect` reports where a source cell was painted in window coordinates; rows and columns are source indices, so scrolling and sorting do not renumber them and the clip does not cut the rectangle +- `CodeEditorRun.Italic` lets a highlighter slant a comment; every fixed-pitch backend already reads `TextRun.Italic`, so no new platform code is needed +- Editors support multiple selections: `Selections`, `SelectionsInto`, `SelectionSpansInto`, `AddSelection`, `SetSelections` and `ClearSecondarySelections`, with insert and delete applied as one undo unit; fields and the code editor paint every selection and keep the caret on the primary one +- A headless session's `Now`, `Advance`, `Frame` and `Transitioning` give a test its own clock; `Access`, `AccessByRole` and `AccessByName` read the last frame's accessibility tree, and `Notifications` returns what the application sent +- On macOS, a missing path's icon is resolved from its type +- IBus decodes `UpdatePreeditText` (`vub`) and `UpdatePreeditTextWithMode` (`vubu`), preserving Update, Show, Hide and the mode/visibility provenance; an older Update clears the mode source, and a malformed body cannot replace the cached snapshot (contributed by @caichangqing1120) (PR [#258](https://github.com/vivaui/viva/pull/258)) +- IBus `Context.Close` destroys the context on `org.freedesktop.IBus.Service`, drops the local owner before sending, and refuses requests from retired contexts, so a repeated Close or a replaced path cannot remove the current owner's handler (contributed by @caichangqing1120) (PR [#267](https://github.com/vivaui/viva/pull/267)) +- A GTK window detaches its input method (focus-out, client window cleared, unref) before widget destruction, and the default delete event uses the same path, so closing a window under Fcitx no longer raises a GLib critical (contributed by @caichangqing1120) (PR [#268](https://github.com/vivaui/viva/pull/268)) +- Linux text callbacks use revisions to tell a stale acknowledgment from a geometry-only sync and a stale redraw; closing an input invalidates in-flight callbacks, stops its caret timer and refuses revival (contributed by @caichangqing1120) (PR [#259](https://github.com/vivaui/viva/pull/259)) +- Linux rich clipboard writes reject NUL before claiming the X11 selection or invoking the desktop hook, and the native clipboard, compositing and icon contract tests now run in CI (contributed by @caichangqing1120) (PR [#264](https://github.com/vivaui/viva/pull/264)) +- Menu rows take the theme's control height (26 at compact density, 32 at default, 40 at large) and move together with the height `ui.MenuItems` reserves; an explicit `RowHeight` still wins (contributed by @xiaoyumuxi) (PR [#265](https://github.com/vivaui/viva/pull/265)) +- The text cache splits admission into probation and protected LRU segments and promotes on a main hit, so Count-Min collisions no longer evict a reused shaped line (contributed by @caichangqing1120) (PR [#263](https://github.com/vivaui/viva/pull/263)) +- The Windows payload installer normalizes the payload and backup roots through `Get-Item.FullName`, so an 8.3 root such as `RUNNER~1` no longer installs files under the wrong path (contributed by @caichangqing1120) (PR [#266](https://github.com/vivaui/viva/pull/266)) +- A macOS delta install stages the payload under the running bundle's name, so the documented `ApplyPatch -> Install` order works (contributed by @xiaoyumuxi) (PR [#269](https://github.com/vivaui/viva/pull/269)) +- Patch generation only patches the portable Windows zip and no longer tries to diff the NSIS setup +- `iconcompile` learns use elements and vertex markers + +## 证据在哪 · Where the evidence is + +- 发布门禁在 macOS 与 Linux 上运行 `gofmt`、`go vet ./...`、`go test ./... -count=1`、darwin 与 `-tags vivahead` 的 vet,以及 linux/arm64、windows/amd64、windows/arm64 的交叉 vet 与 js/wasm 的 vet;`release.yml` 在发布前重跑同一套门禁 +- Windows 的安装、补丁覆盖与启动失败回滚在一台 Windows 11 虚拟机上实测,包括 portable 与 NSIS 两种安装 +- IBus 的 `vub`/`vubu` 线格式对照 IBus 1.5.11–1.5.31 的 `ibusinputcontext.c` 与 Fcitx5 的 IBus frontend 核对;GTK 的关闭顺序在 X11 与 GdkWayland 的原生探针上验证 +- 多选区、表格单元格矩形、Select 图标、菜单行高与 textcache 准入都有回归测试,其中表格矩形、Select 图标与 textcache 的 warm 路径带零分配断言 +- 发布后 `tools/releaseverify` 会核对标题、资产清单与校验和、tag 是否 annotated 且落在发布提交上,以及 Release 正文与 `docs/releases/0.6.4.md` 是否一致 + +- The release gate runs `gofmt`, `go vet ./...`, `go test ./... -count=1`, the darwin and `-tags vivahead` vet, and cross-vet for linux/arm64, windows/amd64 and windows/arm64 plus the js/wasm vet on macOS and Linux; `release.yml` runs the same gate again before publishing +- The Windows install, patch overlay and startup-failure rollback were exercised on a Windows 11 virtual machine, for both the portable and NSIS installations +- The IBus `vub`/`vubu` wire forms were checked against `ibusinputcontext.c` in IBus 1.5.11-1.5.31 and Fcitx5's IBus frontend; the GTK teardown order was verified with a native probe on X11 and GdkWayland +- Multi-selection, table cell rectangles, Select icons, menu row heights and text-cache admission carry regression tests, with zero-allocation assertions on the table, Select and warm cache paths +- After publishing, `tools/releaseverify` checks the title, the exact asset list and checksums, that the tag is annotated and on the release commit, and that the Release body matches `docs/releases/0.6.4.md` + +## 注意 · Caveats + +- 本版使用 patch 版本号,但包含新增 API;没有删除或改变已有导出 API,升级不需要迁移 +- Windows 的机器级安装仍然使用完整安装器;增量补丁覆盖便携副本与用户级安装 +- textcache 的准入改动让 warm hit 路径变慢:本机 `BenchmarkWorkingSet/512` 从约 9.1 µs 升到 11.6 µs(贡献者报告约 +42%),换来更稳定的复用命中;这部分会单独优化 +- 菜单行的默认高度仍是 32;只有 compact 与 large 主题分别变为 26 与 40 +- 组合输入、受限/覆盖编辑器、移动与 Undo/Redo 结束后只保留主选区 + +- This release uses a patch version number but adds APIs; no existing exported API is removed or changed, so no migration is needed +- Windows machine-wide installations still use the full installer; delta patches cover the portable copy and user-level installations +- The text-cache admission change slows the warm-hit path: `BenchmarkWorkingSet/512` goes from about 9.1 us to 11.6 us here (the contributor reports about +42%), in exchange for steadier reuse hits; that path will be optimized separately +- The default menu row height is still 32; only the compact and large themes change to 26 and 40 +- A composition, restricted or overwriting editor, movement, and Undo/Redo end with only the primary selection diff --git a/docs/system-integrations.md b/docs/system-integrations.md index edb7b293d..7864a0cf7 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -26,11 +26,14 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Font registration (`RegisterFontAsync`) | CoreText process registration | DirectWrite process registration | Fontconfig process registration | `FontFace` loaded from the application's data; family, weight and italic come from the sfnt tables | | Font enumeration (`FontFamilies`, `MonospaceFamilies`) | system list | system list | fontconfig list | empty: browsers do not expose installed fonts | | Dock badge (`Application.SetDockBadge`) | `NSDockTile.badgeLabel`: the red label macOS draws at the tile's top corner, and an empty label removes it | nothing to do: the taskbar badge a program can set is a picture, not a label | nothing to do: a launcher entry has no badge | nothing to do | -| File icon (`FileIcon`, returns `gfx.Bitmap`) | `NSWorkspace.iconForFile:`: the icon Finder shows, an application bundle's own included | `SHGetFileInfoW`: the icon the shell gives, an existing file or folder's own included; a missing path answers from its extension | `ErrUnsupported` | `ErrUnsupported` | +| File icon (`FileIcon`, returns `gfx.Bitmap`) | `NSWorkspace.iconForFile:`: the icon Finder shows, an application bundle's own included; a missing path answers from the type its extension names | `SHGetFileInfoW`: the icon the shell gives, an existing file or folder's own included; a missing path answers from its extension | `ErrUnsupported` | `ErrUnsupported` | | Preferred languages (`PreferredLanguages`, returns `[]string`) | `NSLocale.preferredLanguages` | `GetUserPreferredUILanguages` | `LANGUAGE`, `LC_ALL`, `LC_MESSAGES`, `LANG`; the C locale reports nothing | `navigator.languages` | | System appearance (`SystemAppearance`, `WatchSystemAppearance`; returns `Appearance`) | the application's effective appearance, watched by KVO | the `AppsUseLightTheme` setting, changes heard as `WM_SETTINGCHANGE` | the settings portal's `org.freedesktop.appearance` `color-scheme`, else the XSETTINGS manager, `GTK_THEME`, GTK's `settings.ini` and KDE's `ColorScheme`; changes heard as the portal's `SettingChanged` (one session-bus connection the event loop polls, open only while something watches) and as the XSETTINGS manager's property change; unknown when none says | `prefers-color-scheme`, watched with `matchMedia` | | Native look (`SetNativeAppearance`) | `NSApplication.appearance`: window buttons, menus, file dialogs and native text editing follow it | nothing to do: Viva draws the window buttons | nothing to do: Viva draws the window buttons | nothing to do | | Reduced motion (`ReduceMotion`, returns `bool`) | `NSWorkspace.accessibilityDisplayShouldReduceMotion` | `SPI_GETCLIENTAREAANIMATION` | the settings portal's `reduced-motion` or `enable-animations`, else XSETTINGS `Gtk/EnableAnimations`, else KDE's `AnimationDurationFactor` of 0; a change is applied to a running canvas | `prefers-reduced-motion`, read at mount and watched with `matchMedia` | +| Keep awake (`PreventSleep`) | an `IOPMAssertion` of type `PreventUserIdleSystemSleep`, named by the reason; `pmset -g assertions` lists it | a power request of type `SystemRequired`, created with the reason; `powercfg /requests` lists it | logind's `Manager.Inhibit("idle")` on the system bus, held by the returned descriptor; `systemd-inhibit --list` shows it. `ErrSleepPreventionUnavailable` without logind | `ErrSleepPreventionUnavailable`: a page cannot keep the machine awake | +| Application menu bar (`Application.SetMenuBar`) | the NSMenu bar's application and Window menus stay; the application's own menus sit between them, with their key equivalents, enablement, check marks, submenus and loop-thread actions | `ErrUnsupported`: a window's own menu bar is `components.Menubar` | `ErrUnsupported`: `components.Menubar` | `ErrUnsupported`: `components.Menubar` | +| System proxy (`app/proxy.SystemProxy`) | CFNetwork's settings for the URL: the static HTTP, HTTPS or SOCKS proxy with its bypass list. A PAC script is reported as `ErrSystemProxyUnavailable`, not silently bypassed | WinHTTP's automatic proxy: auto-detection (WPAD), the PAC script, or the static per-user settings | the environment only (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`); a proxy kept in GSettings is not read | `ErrSystemProxyUnavailable` | | Fullscreen (`RequestFullscreen`, `OnFullscreen`) | `NSWindow.toggleFullScreen:` | `SetWindowPos` / window style | window-manager fullscreen | `requestFullscreen` / `exitFullscreen`, reported by `fullscreenchange` | | Page visibility (`OnMinimize`) | window minimized/restored | window minimized/restored | window minimized/restored | `visibilitychange`; a hidden tab counts as minimized | | Window activation (`OnActivate`) | `NSWindowDidBecomeKeyNotification` | `WM_ACTIVATE`, when not `WA_INACTIVE` | an X11 `FocusIn` whose detail is `Ancestor` or `Nonlinear` outside a grab, or GTK's `focus-in-event` | the window `focus` event | diff --git a/docs/updating.md b/docs/updating.md index 5daf4e513..54ba6414d 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -172,11 +172,12 @@ A patch is made at release time from the previous release archive: ```sh viva feed -dir dist -base-url https://example.com/app/stable \ --patch-from darwin/arm64=1.4.1=old/Notes-1.4.1-darwin-arm64.zip \ - --patch-from linux/amd64=1.4.1=old/Notes-1.4.1-linux-amd64.tar.gz + --patch-from linux/amd64=1.4.1=old/Notes-1.4.1-linux-amd64.tar.gz \ + --patch-from windows/amd64=1.4.1=old/Notes-1.4.1-windows-amd64.zip ``` -Each `--patch-from` is `os/arch=version=archive`, repeatable, for `darwin` and -`linux` only. The previous archive is supplied by the release process; `viva +Each `--patch-from` is `os/arch=version=archive`, repeatable, for `darwin`, +`linux` and `windows`. The previous archive is supplied by the release process; `viva feed` extracts both releases and writes `..patch` beside the archives, listing it on the asset in the feed. A patch is a gzip tar holding `patch.json` and one bsdiff per changed file; `patch.json` names the app, both @@ -184,6 +185,15 @@ versions, the OS, the architecture and every file with its mode, size and SHA-256. The feed's signature covers the patch's URL, size and digest, and the client checks every file it writes against the digest in `patch.json`. +On Windows the payload is a **directory**: the program and the folders beside +it from the portable zip. The same patch applies to an NSIS installation and to +a portable copy, because both hold those files at the same paths. A portable +copy also holds the user's data folder; leave it out of the patch with +`--patch-exclude motty-data` (the path is relative to the payload). `Install` +replaces the files and starts the new program without running NSIS, so shortcuts +and the uninstall entry stay as they are. A machine-wide installation under +`Program Files` is not writable and falls back to the full installer. + The application decides whether to use a patch. The order that keeps the fallback simple: @@ -261,11 +271,11 @@ error nothing has been changed and `quit` was not called. | Archive | the signed `.app` in a zip | the signed NSIS installer | the executable in a tar.gz | | Checks | the bundle id and version in `Info.plist`, then `codesign --verify --deep --strict` | the installer's Authenticode signature when it has one; the feed's Ed25519 signature always | the feed's Ed25519 signature | | Replaces | the `.app` bundle, by swapping it with two renames while the previous one is kept until the new version starts | runs the installer silently (`/S`), user scope | renames the new executable over the old one; the old inode keeps running until exit | -| Relaunches | `open -n` through a detached helper after the process exits | a detached PowerShell helper waits, installs, and starts the program | starts the new executable, then the application quits | -| Refuses | a translocated bundle, a read-only parent, a bundle without a valid signature | an installer whose signature fails to verify, a read-only install directory | an AppImage, a `.deb` installed by dpkg, a read-only directory | +| Relaunches | `open -n` through a detached helper after the process exits | a detached PowerShell helper waits, installs a full setup with `/S` (or copies a patch's files over the installation), and starts the program | starts the new executable, then the application quits | +| Refuses | a translocated bundle, a read-only parent, a bundle without a valid signature | an installer whose signature fails to verify, a read-only install directory | an AppImage, a `.deb` or `.rpm` installed by its package manager, a read-only directory | A program that a package manager installed is not updated by itself. Linux -detects the `.deb` case with `dpkg-query` and reports +detects the `.deb` case with `dpkg-query` and the `.rpm` case with `rpm -qf`, and reports `update.ErrManagedExternally`; a macOS Homebrew Cask and a Windows package-managed install cannot be told apart from a drag-installed copy, so the application has to avoid offering self-update there. Windows installations made by the Viva NSIS @@ -332,19 +342,21 @@ warning. the macOS and Linux helpers give up without changing anything and without a message; the application keeps running the old version and can offer the update again. -- **No delta updates on Windows.** The NSIS installer owns the installation, so - there is no payload tree to patch; a Windows client always downloads the full - installer. A patch listed for Windows is refused with `ErrUnsupported`. +- **Windows patches replace the application's files.** The installer's + uninstaller, shortcuts and registry entries are not changed; a release that + adds or removes files needs the full installer. A machine-wide installation + under `Program Files` is not writable and reports `ErrNotWritable`. - **No update service.** The package checks a URL the application names. It does not host, stage, roll out or force anything. - **No automatic install.** The application decides when to check, whether to ask, and when to call `Install`. -- **No Linux AppImage support** and no self-update of a `.deb`. `viva package` - makes `tar.gz` and `.deb`; the `.deb` is the package manager's. +- **No Linux AppImage support** and no self-update of a `.deb` or `.rpm`. + `viva package` makes `tar.gz`, `.deb`, PKGBUILD and (with `--format rpm`) `.rpm`; + the `.deb` and `.rpm` are the package manager's. - **No elevation.** The Windows helper runs the installer without asking for - administrator rights, so a `[windows] scope = "machine"` installer cannot - replace a program installed under `Program Files`; the default per-user scope - needs none. + administrator rights, and a patch only writes a writable directory. A + `[windows] scope = "machine"` installation under `Program Files` cannot be + replaced without elevation; the default per-user scope needs none. - **macOS needs a code signature.** The new bundle is checked with `codesign`; an ad-hoc signature is enough for local testing, an unsigned build is refused. - **No Windows arm64 installer changes.** The NSIS installer is per-architecture, diff --git a/document/document.go b/document/document.go new file mode 100644 index 000000000..1b540cd7b --- /dev/null +++ b/document/document.go @@ -0,0 +1,147 @@ +// Package document reads and writes one file as a document: the bytes on disk, +// a revision that names them, and an atomic save that refuses to replace a file +// another program changed since it was read. +// +// It is the storage half of an editor, not an editor: the application owns the +// file format, the undo history and the autosave policy. A revision is the +// SHA-256 of the bytes, so a caller can compare what it read with what is on +// disk without keeping the whole file in memory. +package document + +import ( + "crypto/sha256" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" +) + +var ( + // ErrChanged means the file is not the one the caller read: another program + // wrote, replaced or removed it. The caller decides whether to reload, + // overwrite, or ask the user. + ErrChanged = errors.New("document: the file changed since it was read") + // ErrNotRegular means the path is not a regular file: a directory, a device, + // or a symbolic link. A document follows none of them. + ErrNotRegular = errors.New("document: not a regular file") +) + +// Revision names one version of a file's bytes: the SHA-256 of the content. +type Revision [sha256.Size]byte + +// Read returns the file's bytes and their revision. A symbolic link or a path +// that is not a regular file is ErrNotRegular. +func Read(path string) ([]byte, Revision, error) { + info, err := os.Lstat(path) + if err != nil { + return nil, Revision{}, err + } + if !info.Mode().IsRegular() { + return nil, Revision{}, fmt.Errorf("%w: %s", ErrNotRegular, path) + } + data, err := os.ReadFile(path) + if err != nil { + return nil, Revision{}, err + } + return data, Revision(sha256.Sum256(data)), nil +} + +// Save writes data to path atomically, refusing when the file on disk is not +// expected. The bytes go to a temporary file in the same directory, are synced, +// then renamed over the target: a crash leaves either the old file or the new +// one, never a half-written one. The mode of the existing file is kept; a new +// file (expected is the zero Revision) is created 0644. +// +// A file that is missing returns ErrChanged unless expected is zero. A symbolic +// link or another non-regular file is ErrNotRegular. The returned Revision is +// the one the saved bytes have, for the next Save or Read. +func Save(path string, data []byte, expected Revision) (Revision, error) { + info, err := os.Lstat(path) + mode := fs.FileMode(0o644) + switch { + case err == nil: + if !info.Mode().IsRegular() { + return Revision{}, fmt.Errorf("%w: %s", ErrNotRegular, path) + } + mode = info.Mode().Perm() + case errors.Is(err, os.ErrNotExist): + if expected != (Revision{}) { + return Revision{}, ErrChanged + } + default: + return Revision{}, err + } + if err == nil { + current, err := os.ReadFile(path) + if err != nil { + return Revision{}, err + } + if Revision(sha256.Sum256(current)) != expected { + return Revision{}, ErrChanged + } + } + revision := Revision(sha256.Sum256(data)) + temporary, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".tmp-*") + if err != nil { + return Revision{}, err + } + name := temporary.Name() + cleanup := func() { _ = os.Remove(name) } + if err := temporary.Chmod(mode); err != nil { + temporary.Close() + cleanup() + return Revision{}, err + } + _, err = temporary.Write(data) + if err == nil { + err = temporary.Sync() + } + if closeErr := temporary.Close(); err == nil { + err = closeErr + } + if err != nil { + cleanup() + return Revision{}, err + } + // The file may have changed while the temporary was written: look again + // before replacing it, as an editor does before its final rename. + current, err := os.ReadFile(path) + if err == nil && info == nil { + // A file appeared where there was none: it is not the empty document + // the caller meant to create. + cleanup() + return Revision{}, ErrChanged + } + if err == nil && info != nil { + if Revision(sha256.Sum256(current)) != expected { + cleanup() + return Revision{}, ErrChanged + } + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + cleanup() + return Revision{}, err + } else if err != nil && expected != (Revision{}) { + cleanup() + return Revision{}, ErrChanged + } + if err := os.Rename(name, path); err != nil { + cleanup() + return Revision{}, err + } + syncDirectory(filepath.Dir(path)) + return revision, nil +} + +// Changed reports whether the file on disk is not revision. A missing file is +// changed; the error says why it could not be read. +func Changed(path string, revision Revision) (bool, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return true, nil + } + if err != nil { + return false, err + } + return Revision(sha256.Sum256(data)) != revision, nil +} diff --git a/document/document_test.go b/document/document_test.go new file mode 100644 index 000000000..3e6a713ba --- /dev/null +++ b/document/document_test.go @@ -0,0 +1,151 @@ +package document + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestReadAndSaveKeepTheBytesAndRevision(t *testing.T) { + path := filepath.Join(t.TempDir(), "notes.txt") + if err := os.WriteFile(path, []byte("one\n"), 0o600); err != nil { + t.Fatal(err) + } + data, revision, err := Read(path) + if err != nil || string(data) != "one\n" { + t.Fatalf("Read = %q, %v", data, err) + } + if changed, err := Changed(path, revision); err != nil || changed { + t.Fatalf("Changed = %v, %v", changed, err) + } + next, err := Save(path, []byte("two\n"), revision) + if err != nil { + t.Fatal(err) + } + if changed, err := Changed(path, next); err != nil || changed { + t.Fatalf("Changed after Save = %v, %v", changed, err) + } + again, err := os.ReadFile(path) + if err != nil || string(again) != "two\n" { + t.Fatalf("file = %q, %v", again, err) + } +} + +func TestSaveRefusesAFileAnotherProgramChanged(t *testing.T) { + path := filepath.Join(t.TempDir(), "notes.txt") + if err := os.WriteFile(path, []byte("one\n"), 0o600); err != nil { + t.Fatal(err) + } + _, revision, err := Read(path) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("theirs\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := Save(path, []byte("ours\n"), revision); !errors.Is(err, ErrChanged) { + t.Fatalf("Save = %v, want ErrChanged", err) + } + actual, _ := os.ReadFile(path) + if string(actual) != "theirs\n" { + t.Fatalf("the file was replaced after a conflict: %q", actual) + } + temporary, _ := filepath.Glob(filepath.Join(filepath.Dir(path), ".notes.txt.tmp-*")) + if len(temporary) != 0 { + t.Fatalf("temporary files leaked: %v", temporary) + } +} + +func TestSaveKeepsTheModeAndLeavesNoTemporaryFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "run.sh") + if err := os.WriteFile(path, []byte("#!/bin/sh\n"), 0o750); err != nil { + t.Fatal(err) + } + _, revision, err := Read(path) + if err != nil { + t.Fatal(err) + } + if _, err := Save(path, []byte("#!/bin/sh\necho hi\n"), revision); err != nil { + t.Fatal(err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o750 { + t.Fatalf("mode = %v, want 0750", info.Mode().Perm()) + } + temporary, _ := filepath.Glob(filepath.Join(filepath.Dir(path), ".run.sh.tmp-*")) + if len(temporary) != 0 { + t.Fatalf("temporary files leaked: %v", temporary) + } +} + +func TestSaveCreatesANewFileOnlyWithTheZeroRevision(t *testing.T) { + path := filepath.Join(t.TempDir(), "new.txt") + if _, err := Save(path, []byte("hello\n"), Revision{}); err != nil { + t.Fatal(err) + } + actual, _ := os.ReadFile(path) + if string(actual) != "hello\n" { + t.Fatalf("file = %q", actual) + } + if _, err := Save(path, []byte("again\n"), Revision{}); !errors.Is(err, ErrChanged) { + t.Fatalf("Save over an existing file with the zero revision = %v, want ErrChanged", err) + } +} + +func TestReadAndSaveRejectSymbolicLinks(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "real.txt") + if err := os.WriteFile(target, []byte("real\n"), 0o600); err != nil { + t.Fatal(err) + } + link := filepath.Join(dir, "link.txt") + if err := os.Symlink(target, link); err != nil { + t.Skipf("symbolic links are unavailable: %v", err) + } + if _, _, err := Read(link); !errors.Is(err, ErrNotRegular) { + t.Fatalf("Read(link) = %v, want ErrNotRegular", err) + } + if _, err := Save(link, []byte("x"), Revision{}); !errors.Is(err, ErrNotRegular) { + t.Fatalf("Save(link) = %v, want ErrNotRegular", err) + } +} + +func TestChangedReportsAMissingFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "gone.txt") + changed, err := Changed(path, Revision{}) + if err != nil || !changed { + t.Fatalf("Changed = %v, %v; want changed", changed, err) + } +} + +func TestSaveLeavesTheOldFileOnAWriteFailure(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + dir := t.TempDir() + path := filepath.Join(dir, "notes.txt") + if err := os.WriteFile(path, []byte("old\n"), 0o600); err != nil { + t.Fatal(err) + } + _, revision, err := Read(path) + if err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + if _, err := Save(path, []byte(strings.Repeat("x", 4096)), revision); err == nil { + t.Fatal("Save succeeded in a directory it cannot write") + } + actual, err := os.ReadFile(path) + if err != nil || !bytes.Equal(actual, []byte("old\n")) { + t.Fatalf("the old file was damaged: %q, %v", actual, err) + } +} diff --git a/document/sync_dir_unix.go b/document/sync_dir_unix.go new file mode 100644 index 000000000..fb85d3cfe --- /dev/null +++ b/document/sync_dir_unix.go @@ -0,0 +1,17 @@ +//go:build !windows + +package document + +import "os" + +// syncDirectory makes a rename durable. A directory that cannot be opened or +// synced is not an error for the save: the rename already happened, and some +// filesystems refuse to sync a directory. +func syncDirectory(path string) { + dir, err := os.Open(path) + if err != nil { + return + } + _ = dir.Sync() + _ = dir.Close() +} diff --git a/document/sync_dir_windows.go b/document/sync_dir_windows.go new file mode 100644 index 000000000..bc7908b77 --- /dev/null +++ b/document/sync_dir_windows.go @@ -0,0 +1,7 @@ +//go:build windows + +package document + +// syncDirectory does nothing: Windows has no directory handle to sync, and the +// rename is durable once it returns. +func syncDirectory(string) {} diff --git a/gfx/canvas.go b/gfx/canvas.go index 4c5fa290b..9aa3f0209 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -1509,9 +1509,10 @@ func (canvas *Canvas) TextOffsetAtStyle(value string, style TextStyle, x float32 // LabelRuns appends one fixed-pitch line: value drawn in the system fixed-pitch // font with every character on a grid of cellWidth, each run of it in its own -// color and weight. A terminal row is one such line, however many colors it -// holds, so the number and order of labels stays stable while its content -// changes. Bounds is the whole line; its width should be columns*cellWidth. +// color, weight and slant (TextRun.Italic). A terminal row is one such line, +// however many colors it holds, so the number and order of labels stays stable +// while its content changes. Bounds is the whole line; its width should be +// columns*cellWidth. // runs must cover value (see TextRun); the canvas copies them, so the caller // may reuse the slice as soon as the call returns. func (canvas *Canvas) LabelRuns(value string, bounds Rect, style TextStyle, cellWidth float32, runs []TextRun) { diff --git a/gfx/label_runs_test.go b/gfx/label_runs_test.go index aae930f36..ad0bbc4df 100644 --- a/gfx/label_runs_test.go +++ b/gfx/label_runs_test.go @@ -7,7 +7,7 @@ import ( func TestLabelRunsCopiesItsRunsAndExposesThemPerText(t *testing.T) { var canvas Canvas - runs := []TextRun{{Column: 0, Bytes: 2, Cells: 2, Color: Color{Red: 1, Alpha: 1}, Ligatures: true}} + runs := []TextRun{{Column: 0, Bytes: 2, Cells: 2, Color: Color{Red: 1, Alpha: 1}, Ligatures: true, Italic: true}} identity := TextIdentity{Owner: 3, Item: 9} canvas.LabelRunsWithIdentity(identity, "hi", Rect{Width: 20, Height: 10}, TextStyle{Size: 12}, 6, runs) runs[0].Color = Color{Green: 1, Alpha: 1} // the caller reuses its buffer @@ -25,8 +25,12 @@ func TestLabelRunsCopiesItsRunsAndExposesThemPerText(t *testing.T) { if texts[0].Identity != identity || !texts[1].Identity.IsZero() { t.Errorf("identities = %+v and %+v, want %+v and none", texts[0].Identity, texts[1].Identity, identity) } - if got := canvas.TextRuns(texts[0]); len(got) != 1 || got[0].Color.Red != 1 || got[0].Color.Green != 0 || !got[0].Ligatures { - t.Errorf("first runs = %+v, want the red ligature run as it was when added", got) + if got := canvas.TextRuns(texts[0]); len(got) != 1 || got[0].Color.Red != 1 || got[0].Color.Green != 0 || !got[0].Ligatures || !got[0].Italic { + t.Errorf("first runs = %+v, want the red italic ligature run as it was when added", got) + } + // A run's slant is its own, not the label style's: a grid line may hold both. + if texts[0].Style.Italic { + t.Errorf("a run's italic leaked into the label style: %+v", texts[0].Style) } if got := canvas.TextRuns(texts[1]); len(got) != 2 || got[1].Column != 1 { t.Errorf("second runs = %+v", got) diff --git a/headless/application.go b/headless/application.go index 915cadec9..dd7dac503 100644 --- a/headless/application.go +++ b/headless/application.go @@ -75,6 +75,14 @@ func newApplicationSession(options Options) *applicationSession { } } +// Post implements app.Host. A headless session has one goroutine and no +// window thread apart from it, so the work runs where it was posted from. +func (application *applicationSession) Post(fn func()) { + if fn != nil { + fn() + } +} + // OpenWindow implements app.Host. func (application *applicationSession) OpenWindow(config app.Config, canvas *gfx.Canvas, closed func()) (app.WindowControl, error) { entry := &applicationWindow{} diff --git a/internal/componentdemo/code_editor.go b/internal/componentdemo/code_editor.go index d40b80d0e..45c5d4044 100644 --- a/internal/componentdemo/code_editor.go +++ b/internal/componentdemo/code_editor.go @@ -226,8 +226,9 @@ func allIndexes(value, needle string) []int { var demoKeywords = [...]string{"package", "import", "func", "for", "range", "if", "continue", "return", "var", "const", "type", "else"} -// demoCodeHighlight colors comments, strings and keywords of one Go line: a -// stand-in for the grammar an application owns. +// demoCodeHighlight colors comments, strings and keywords of one Go line, in +// the italic face for comments as editors draw them: a stand-in for the grammar +// an application owns. func demoCodeHighlight(_, line string, dst []components.CodeEditorRun) []components.CodeEditorRun { keyword, comment, literal := gfx.RGB(170, 59, 180), gfx.RGB(110, 130, 118), gfx.RGB(30, 120, 80) end := len(line) @@ -263,7 +264,7 @@ func demoCodeHighlight(_, line string, dst []components.CodeEditorRun) []compone dst = append(dst, components.CodeEditorRun{Start: open, End: from, Color: literal}) } if end < len(line) { - dst = append(dst, components.CodeEditorRun{Start: end, End: len(line), Color: comment}) + dst = append(dst, components.CodeEditorRun{Start: end, End: len(line), Color: comment, Italic: true}) } // The highlighter may return its runs in any order of discovery, but the // editor wants them in order. diff --git a/internal/dbus/conn.go b/internal/dbus/conn.go index 848cf7b98..501a0e0fd 100644 --- a/internal/dbus/conn.go +++ b/internal/dbus/conn.go @@ -28,6 +28,9 @@ type Conn struct { unique string in []byte pending []*Message + // fds are the descriptors the socket delivered for messages still being + // assembled, in arrival order; each message takes its header's count. + fds []int } // DialSession connects to the session bus named by DBUS_SESSION_BUS_ADDRESS, or @@ -40,6 +43,18 @@ func DialSession() (*Conn, error) { return Dial(address) } +// DialSystem connects to the system bus, where logind and other services that +// outlive one login session live. +func DialSystem() (*Conn, error) { + address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS") + if address == "" { + // /var/run is a link to /run on every current distribution; try both + // because a container may keep only one. + address = "unix:path=/var/run/dbus/system_bus_socket;unix:path=/run/dbus/system_bus_socket" + } + return Dial(address) +} + // Dial connects to the bus at a "unix:" address, or the first of several // separated by semicolons that accepts the connection. Other transports are not // understood. A daemon with a bus of its own, such as an input method framework, @@ -192,8 +207,17 @@ func (c *Conn) FD() int { return c.fd } // UniqueName is the name the bus gave this connection. func (c *Conn) UniqueName() string { return c.unique } -// Close ends the connection. +// Close ends the connection and closes every descriptor still attached to a +// message this client has not handed out. func (c *Conn) Close() { + for _, fd := range c.fds { + syscall.Close(fd) + } + c.fds = nil + for _, message := range c.pending { + message.CloseFDs() + } + c.pending = nil if c.fd >= 0 { syscall.Close(c.fd) c.fd = -1 @@ -206,7 +230,9 @@ func (c *Conn) nextSerial() uint32 { } // Call sends a method call and waits for its answer. Other messages that arrive -// meanwhile are kept for Receive. An error reply comes back as a *Error. +// meanwhile are kept for Receive. An error reply comes back as a *Error. The +// returned message owns any file descriptors it carries; close them when done, +// taking the ones to keep with TakeFD. func (c *Conn) Call(destination, path, iface, member, signature string, body []byte) (*Message, error) { serial := c.nextSerial() call := &Message{Type: TypeCall, Serial: serial, Destination: destination, Path: path, Interface: iface, Member: member, Signature: signature, Body: body} @@ -249,6 +275,7 @@ func answer(message *Message) (*Message, error) { if message.Signature == "s" { text = message.Args().String() } + message.CloseFDs() return nil, &Error{Name: message.ErrorName, Text: text} } return message, nil @@ -264,7 +291,8 @@ func (e *Error) Error() string { return e.Name + ": " + e.Text } -// Receive returns the messages that have arrived, without waiting. +// Receive returns the messages that have arrived, without waiting. The caller +// owns the file descriptors they carry. func (c *Conn) Receive() ([]*Message, error) { if err := c.fill(false); err != nil { return nil, err @@ -276,15 +304,17 @@ func (c *Conn) Receive() ([]*Message, error) { // fill reads from the socket and parses every complete message into pending. // Blocking, it waits for the first bytes (at most callTimeout) and reads once; -// otherwise it reads what is there and returns. +// otherwise it reads what is there and returns. File descriptors the socket +// delivers are held until the message whose header counts them is complete. func (c *Conn) fill(block bool) error { flags := syscall.MSG_DONTWAIT if block { flags = 0 } buffer := make([]byte, 16<<10) + oob := make([]byte, 4096) for { - n, _, err := syscall.Recvfrom(c.fd, buffer, flags) + n, oobn, _, _, err := syscall.Recvmsg(c.fd, buffer, oob, flags) if err == syscall.EAGAIN { if block { return errTimedOut @@ -297,6 +327,11 @@ func (c *Conn) fill(block bool) error { if err != nil { return err } + if oobn > 0 { + if err := c.appendControl(oob[:oobn]); err != nil { + return err + } + } if n == 0 { return errors.New("the bus closed the connection") } @@ -317,6 +352,14 @@ func (c *Conn) fill(block bool) error { if err != nil { return err } + for index := 0; index < message.unixFDCount; index++ { + if len(c.fds) == 0 { + message.CloseFDs() + return errors.New("dbus: a message arrived without the file descriptors it counts") + } + message.FDs = append(message.FDs, c.fds[0]) + c.fds = c.fds[1:] + } // Detach the body from the read buffer, which is about to be reused. message.Body = append([]byte(nil), message.Body...) c.pending = append(c.pending, message) @@ -327,6 +370,27 @@ func (c *Conn) fill(block bool) error { } } +// appendControl takes the file descriptors out of ancillary data set with a +// message, keeping them for the message that counts them. +func (c *Conn) appendControl(oob []byte) error { + messages, err := syscall.ParseSocketControlMessage(oob) + if err != nil { + return err + } + for index := range messages { + message := &messages[index] + if message.Header.Level != syscall.SOL_SOCKET || message.Header.Type != syscall.SCM_RIGHTS { + continue + } + fds, err := syscall.ParseUnixRights(message) + if err != nil { + return err + } + c.fds = append(c.fds, fds...) + } + return nil +} + // Reply answers a call with the given arguments. func (c *Conn) Reply(call *Message, signature string, body []byte) error { if call.NoReply() { diff --git a/internal/dbus/doc.go b/internal/dbus/doc.go index 29c8ee3bc..366ced8f2 100644 --- a/internal/dbus/doc.go +++ b/internal/dbus/doc.go @@ -1,8 +1,9 @@ // Package dbus is the smallest D-Bus client a status icon needs: connect to the -// session bus, authenticate as the current user, call methods, answer the calls -// an object receives, and emit signals. Values are encoded by typed methods, with -// no reflection, and only little-endian messages without file descriptors are -// understood, which is what every desktop bus speaks. +// session or system bus, authenticate as the current user, call methods, answer +// the calls an object receives, and emit signals. Values are encoded by typed +// methods, with no reflection; only little-endian messages are understood, and +// file descriptors can be received but not sent, which is what a status icon +// and logind's inhibitor lock need. // // A Conn is not safe for concurrent use; its owner drives it from one thread, // waiting on FD for the bus to have something to read. diff --git a/internal/dbus/fd_test.go b/internal/dbus/fd_test.go new file mode 100644 index 000000000..b895998ab --- /dev/null +++ b/internal/dbus/fd_test.go @@ -0,0 +1,97 @@ +//go:build unix + +package dbus + +import ( + "syscall" + "testing" +) + +// TestReceiveTakesTheFileDescriptorsAMessageCarries is the shape of logind's +// inhibitor answer: a message whose body names a descriptor index and whose +// header counts one descriptor, written in the same sendmsg. +func TestReceiveTakesTheFileDescriptorsAMessageCarries(t *testing.T) { + pair, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0) + if err != nil { + t.Fatal(err) + } + defer syscall.Close(pair[1]) + + var body Encoder + body.Uint32(0) + wire := (&Message{Type: TypeReturn, Serial: 1, Signature: "h", Body: body.Bytes(), unixFDCount: 1}).encode() + + fd, err := syscall.Open("/dev/null", syscall.O_RDONLY, 0) + if err != nil { + t.Fatal(err) + } + if err := syscall.Sendmsg(pair[1], wire, syscall.UnixRights(fd), nil, 0); err != nil { + syscall.Close(fd) + t.Fatal(err) + } + syscall.Close(fd) + + conn := &Conn{fd: pair[0]} + defer conn.Close() + messages, err := conn.Receive() + if err != nil { + t.Fatal(err) + } + if len(messages) != 1 { + t.Fatalf("received %d messages, want 1", len(messages)) + } + message := messages[0] + if len(message.FDs) != 1 { + t.Fatalf("message carries %d descriptors, want 1", len(message.FDs)) + } + if got := message.Args().UnixFD(); got != 0 { + t.Fatalf("fd index = %d, want 0", got) + } + received := message.TakeFD(0) + if received < 0 { + t.Fatal("TakeFD returned no descriptor") + } + if err := syscall.Close(received); err != nil { + t.Fatalf("closing the received descriptor: %v", err) + } + if len(message.FDs) != 0 { + t.Fatalf("TakeFD left %d descriptors", len(message.FDs)) + } +} + +// TestConnCloseClosesDescriptorsItHasNotHandedOut checks the leak that matters +// in a long-lived process: a descriptor still attached to a pending message is +// closed with the connection. +func TestConnCloseClosesDescriptorsItHasNotHandedOut(t *testing.T) { + pair, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0) + if err != nil { + t.Fatal(err) + } + defer syscall.Close(pair[1]) + + wire := (&Message{Type: TypeReturn, Serial: 1, Signature: "h", Body: nil, unixFDCount: 1}).encode() + fd, err := syscall.Open("/dev/null", syscall.O_RDONLY, 0) + if err != nil { + t.Fatal(err) + } + if err := syscall.Sendmsg(pair[1], wire, syscall.UnixRights(fd), nil, 0); err != nil { + syscall.Close(fd) + t.Fatal(err) + } + syscall.Close(fd) + + conn := &Conn{fd: pair[0]} + if err := conn.fill(false); err != nil { + t.Fatal(err) + } + if len(conn.pending) != 1 || len(conn.pending[0].FDs) != 1 { + t.Fatalf("parsed %d messages", len(conn.pending)) + } + received := conn.pending[0].FDs[0] + conn.Close() + if err := syscall.Close(received); err != syscall.EBADF { + if err == nil { + t.Fatal("the connection left a descriptor open") + } + } +} diff --git a/internal/dbus/fd_unix.go b/internal/dbus/fd_unix.go new file mode 100644 index 000000000..bd3e63793 --- /dev/null +++ b/internal/dbus/fd_unix.go @@ -0,0 +1,24 @@ +//go:build unix + +package dbus + +import "syscall" + +// TakeFD removes and returns the descriptor a body's unix fd index names, or +// -1 when the message carries none at that index. +func (m *Message) TakeFD(index int) int { + if index < 0 || index >= len(m.FDs) { + return -1 + } + fd := m.FDs[index] + m.FDs = append(m.FDs[:index], m.FDs[index+1:]...) + return fd +} + +// CloseFDs closes every descriptor the message still carries. +func (m *Message) CloseFDs() { + for _, fd := range m.FDs { + syscall.Close(fd) + } + m.FDs = nil +} diff --git a/internal/dbus/message.go b/internal/dbus/message.go index 9acb79b48..bed092d91 100644 --- a/internal/dbus/message.go +++ b/internal/dbus/message.go @@ -29,6 +29,7 @@ const ( fieldDestination = 6 fieldSender = 7 fieldSignature = 8 + fieldUnixFDs = 9 ) const maxMessage = 1 << 27 // the specification's limit, 128 MiB @@ -48,6 +49,14 @@ type Message struct { Sender string Signature string Body []byte + // FDs are the file descriptors the message carried, in the order its unix + // fd indices name; a body type 'h' is an index into this slice. The side + // that receives a message owns its descriptors and closes them: pass them + // to TakeFD and close what TakeFD does not hand out, or call CloseFDs. + FDs []int + // unixFDCount is the header's count of descriptors; fill matches it with + // the descriptors the socket delivered. + unixFDCount int } // NoReply reports whether the sender wants no answer to a call. @@ -96,6 +105,9 @@ func (m *Message) encode() []byte { if m.Signature != "" { field(fieldSignature, "g", func() { e.Signature(m.Signature) }) } + if m.unixFDCount > 0 { + field(fieldUnixFDs, "u", func() { e.Uint32(uint32(m.unixFDCount)) }) + } e.EndArray(start) e.Align(8) return append(e.Bytes(), m.Body...) @@ -156,6 +168,8 @@ func decodeMessage(buf []byte) (*Message, error) { m.Sender = d.String() case code == fieldSignature && sig == "g": m.Signature = d.Signature() + case code == fieldUnixFDs && sig == "u": + m.unixFDCount = int(d.Uint32()) default: d.Skip(sig) // a field this client has no use for } diff --git a/internal/dbus/wire.go b/internal/dbus/wire.go index 801da38bb..0b95e1075 100644 --- a/internal/dbus/wire.go +++ b/internal/dbus/wire.go @@ -162,6 +162,10 @@ func (d *Decoder) Signature() string { return string(b) } +// UnixFD reads a unix file descriptor index, which names an entry of the +// message's FDs. +func (d *Decoder) UnixFD() int { return int(d.Uint32()) } + // ArrayLength reads an array's byte length and aligns to its elements, and // returns the offset where they end. func (d *Decoder) ArrayLength(elem int) (end int) { @@ -218,6 +222,8 @@ func (d *Decoder) skip(sig string) (rest string, err error) { _ = d.String() case 'g': _ = d.Signature() + case 'h': + _ = d.UnixFD() case 'v': d.Skip(d.Signature()) case 'a': @@ -302,7 +308,7 @@ func alignment(kind byte) int { switch kind { case 'n', 'q': return 2 - case 'b', 'i', 'u', 's', 'o', 'a': + case 'b', 'i', 'u', 's', 'o', 'a', 'h': return 4 case 'x', 't', 'd', '(', '{': return 8 diff --git a/internal/ibus/ibus.go b/internal/ibus/ibus.go index 6b9f63089..50dfb82b0 100644 --- a/internal/ibus/ibus.go +++ b/internal/ibus/ibus.go @@ -76,11 +76,9 @@ type transport interface { type Handler struct { // Commit delivers text the user has chosen. Commit func(text string) - // Preedit shows, replaces or (visible false) hides the text being composed. - // cursor is a count of characters into text, and attrs style stretches of it: - // an engine marks the clause being converted with a background or a heavier - // underline. - Preedit func(text string, cursor int, visible bool, attrs []Attribute) + // Preedit preserves the signal's update/visibility provenance and optional + // focus-out mode. Attributes are context-owned and must not be modified. + Preedit func(PreeditEvent) // DeleteSurrounding asks the client to delete count characters of the text // around the caret, starting offset characters from it (a negative offset is // before it). The engine does so to replace text it is about to convert again. @@ -90,6 +88,33 @@ type Handler struct { Forward func(keysym, keycode, state uint32) } +// PreeditKind distinguishes a text update from visibility-only signals. +type PreeditKind uint8 + +const ( + PreeditUpdate PreeditKind = iota + PreeditShow + PreeditHide +) + +const ( + PreeditModeClear uint32 = 0 + PreeditModeCommit uint32 = 1 +) + +// PreeditEvent is one native signal. An empty Text is not a terminal phase; +// HasMode distinguishes the old signal from UpdatePreeditTextWithMode. Unknown +// mode values are preserved for the caller to handle without guessing policy. +type PreeditEvent struct { + Text string + Attributes []Attribute + Cursor int + Mode uint32 + Kind PreeditKind + Visible bool + HasMode bool +} + // Attribute styles the characters [Start, End) of preedit text. Kind is one of // the Attr constants and Value its argument: an underline style for // AttrUnderline (0 none, 1 single, 2 double, 3 low, 4 error), a color for the @@ -101,11 +126,13 @@ type Attribute struct { // Bus is a connection to the IBus daemon. type Bus struct { - conn transport - contexts map[string]*Context - pending []*pendingKey - err error - now func() time.Time + conn transport + contexts map[string]*Context + pending []*pendingKey + err error + now func() time.Time + dispatching bool + redispatch bool } type pendingKey struct { @@ -123,9 +150,7 @@ type Context struct { handler Handler // preedit remembers the last preedit text, for a daemon that hides and later // shows it again without sending it twice. - preedit string - preeditCursor int - preeditAttrs []Attribute + preedit PreeditEvent } // Address finds the IBus daemon's bus address the way libibus does: the @@ -272,22 +297,38 @@ func (bus *Bus) Dispatch() error { if bus.err != nil { return bus.err } - messages, err := bus.conn.Receive() - if err != nil { - bus.fail(err) - return err - } - for _, message := range messages { - switch message.Type { - case dbus.TypeSignal: - if context := bus.contexts[message.Path]; context != nil && message.Interface == contextInterface { - context.signal(message) + if bus.dispatching { + bus.redispatch = true + return nil + } + bus.dispatching = true + defer func() { bus.dispatching = false }() + for { + bus.redispatch = false + messages, err := bus.conn.Receive() + if err != nil { + bus.fail(err) + return err + } + for _, message := range messages { + switch message.Type { + case dbus.TypeSignal: + if context := bus.contexts[message.Path]; context != nil && message.Interface == contextInterface { + context.signal(message) + } + case dbus.TypeReturn, dbus.TypeError: + bus.answer(message) + } + if bus.err != nil { + return bus.err } - case dbus.TypeReturn, dbus.TypeError: - bus.answer(message) + } + // A synchronous call in a handler may have read newer messages. Finish + // this batch before delivering them, even when Dispatch was reentered. + if !bus.redispatch { + return nil } } - return bus.err } // answer records the engine's verdict on a key and releases the verdicts that @@ -330,7 +371,7 @@ func (bus *Bus) Expire() { } func (context *Context) send(member, signature string, body []byte) error { - if context.bus.err != nil { + if context.bus.err != nil || context.bus.contexts[context.path] != context { return ErrClosed } if _, err := context.bus.conn.Send(service, context.path, contextInterface, member, signature, body); err != nil { @@ -346,7 +387,7 @@ func (context *Context) send(member, signature string, body []byte) error { // (keycode less 8, as IBus counts), state as the X modifier mask, plus // ReleaseMask for a release. done may be nil for a release. func (context *Context) ProcessKey(keysym, keycode, state uint32, done func(handled bool)) error { - if context.bus.err != nil { + if context.bus.err != nil || context.bus.contexts[context.path] != context { return ErrClosed } var body dbus.Encoder @@ -368,6 +409,27 @@ func (context *Context) FocusIn() error { return context.send("FocusIn", "", nil // FocusOut tells the engine the text field lost the keyboard. func (context *Context) FocusOut() error { return context.send("FocusOut", "", nil) } +// SetEngine selects an installed engine for a focused context and waits for the +// daemon to finish selection. Buffered messages run before returning, or after +// the current batch when called from a handler. A refusal leaves the bus usable. +func (context *Context) SetEngine(name string) error { + if context.bus.err != nil || context.bus.contexts[context.path] != context { + return ErrClosed + } + var body dbus.Encoder + body.String(name) + _, err := context.bus.conn.Call(service, context.path, contextInterface, "SetEngine", "s", body.Bytes()) + var refusal *dbus.Error + if err != nil && !errors.As(err, &refusal) { + context.bus.fail(err) + return err + } + if dispatchErr := context.bus.Dispatch(); dispatchErr != nil { + return dispatchErr + } + return err +} + // Reset abandons the composition in progress. func (context *Context) Reset() error { return context.send("Reset", "", nil) } @@ -395,10 +457,15 @@ func (context *Context) SetCursorLocation(x, y, width, height int32) error { // Close destroys the input context. func (context *Context) Close() { - if context.bus.err == nil { - _ = context.send("Destroy", "", nil) + if context.bus.contexts[context.path] != context { + return } delete(context.bus.contexts, context.path) + if context.bus.err == nil { + if _, err := context.bus.conn.Send(service, context.path, "org.freedesktop.IBus.Service", "Destroy", "", nil); err != nil { + context.bus.fail(err) + } + } } func (context *Context) signal(message *dbus.Message) { @@ -408,27 +475,47 @@ func (context *Context) signal(message *dbus.Message) { if text, ok := readText(args, message.Signature); ok && context.handler.Commit != nil { context.handler.Commit(text) } - case "UpdatePreeditText": + case "UpdatePreeditText", "UpdatePreeditTextWithMode": + withMode := message.Member == "UpdatePreeditTextWithMode" + wantSignature := "vub" + if withMode { + wantSignature = "vubu" + } + if message.Signature != wantSignature { + return + } text, attrs, ok := readStyledText(args, message.Signature) if !ok { return } - cursor := int(args.Uint32()) - visible := args.Bool() - if args.Err() != nil { + event := PreeditEvent{Text: text, Attributes: attrs, Cursor: int(args.Uint32()), Visible: args.Bool(), HasMode: withMode} + if withMode { + event.Mode = args.Uint32() + } + if args.Err() != nil || args.Pos() != len(message.Body) { return } - context.preedit, context.preeditCursor, context.preeditAttrs = text, cursor, attrs + context.preedit = event if context.handler.Preedit != nil { - context.handler.Preedit(text, cursor, visible, attrs) + context.handler.Preedit(event) } case "ShowPreeditText": + if message.Signature != "" || len(message.Body) != 0 { + return + } if context.handler.Preedit != nil { - context.handler.Preedit(context.preedit, context.preeditCursor, true, context.preeditAttrs) + event := context.preedit + event.Kind, event.Visible = PreeditShow, true + context.handler.Preedit(event) } case "HidePreeditText": + if message.Signature != "" || len(message.Body) != 0 { + return + } if context.handler.Preedit != nil { - context.handler.Preedit(context.preedit, context.preeditCursor, false, context.preeditAttrs) + event := context.preedit + event.Kind, event.Visible = PreeditHide, false + context.handler.Preedit(event) } case "DeleteSurroundingText": offset, count := args.Int32(), args.Uint32() diff --git a/internal/ibus/ibus_test.go b/internal/ibus/ibus_test.go index 3121b6f51..b133f5a13 100644 --- a/internal/ibus/ibus_test.go +++ b/internal/ibus/ibus_test.go @@ -4,10 +4,12 @@ package ibus import ( "errors" + "fmt" "os" "reflect" "testing" "time" + "unsafe" "github.com/vivaui/viva/internal/dbus" ) @@ -15,11 +17,14 @@ import ( // fakeTransport is a daemon the test scripts: it records the calls the client // sends and hands back the messages the test queues. type fakeTransport struct { - serial uint32 - sent []sentCall - incoming []*dbus.Message - closed bool - sendErr error + serial uint32 + sent []sentCall + incoming []*dbus.Message + closed bool + sendErr error + engineErr error + // engineIncoming arrives while a synchronous engine selection reads its reply. + engineIncoming []*dbus.Message // createPath is what CreateInputContext answers. createPath string } @@ -39,6 +44,10 @@ func (f *fakeTransport) Call(destination, path, iface, member, signature string, return &dbus.Message{Type: dbus.TypeReturn, Signature: "o", Body: reply.Bytes()}, nil case "AddMatch": return &dbus.Message{Type: dbus.TypeReturn}, nil + case "SetEngine": + f.incoming = append(f.incoming, f.engineIncoming...) + f.engineIncoming = nil + return &dbus.Message{Type: dbus.TypeReturn}, f.engineErr } return nil, errors.New("unexpected call " + member) } @@ -99,8 +108,16 @@ func preeditSignal(path, text string, cursor uint32, visible bool) *dbus.Message ibusText(&body, text) body.Uint32(cursor) body.Bool(visible) - body.Uint32(0) // the mode newer daemons add - return &dbus.Message{Type: dbus.TypeSignal, Path: path, Interface: contextInterface, Member: "UpdatePreeditText", Signature: "vubu", Body: body.Bytes()} + return &dbus.Message{Type: dbus.TypeSignal, Path: path, Interface: contextInterface, Member: "UpdatePreeditText", Signature: "vub", Body: body.Bytes()} +} + +func preeditModeSignal(path, value string, cursor uint32, visible bool, mode uint32) *dbus.Message { + var body dbus.Encoder + ibusText(&body, value) + body.Uint32(cursor) + body.Bool(visible) + body.Uint32(mode) + return &dbus.Message{Type: dbus.TypeSignal, Path: path, Interface: contextInterface, Member: "UpdatePreeditTextWithMode", Signature: "vubu", Body: body.Bytes()} } func keyAnswer(serial uint32, handled bool) *dbus.Message { @@ -137,6 +154,243 @@ func TestNewContextAsksForPreeditFocusAndSurroundingTextCapabilities(t *testing. } } +func TestContextCloseUsesTheNativeServiceAndIsIdempotent(t *testing.T) { + _, context, transport := newTestBus(t, Handler{}) + context.Close() + calls := transport.calls("Destroy") + if len(calls) != 1 || calls[0].path != testContext || calls[0].iface != "org.freedesktop.IBus.Service" { + t.Fatalf("native destruction=%+v", calls) + } + context.Close() + if len(transport.calls("Destroy")) != 1 { + t.Fatal("closing the same context twice sent a second native destruction") + } +} + +func TestClosingAReplacedContextKeepsTheSuccessorsHandler(t *testing.T) { + bus, previous, transport := newTestBus(t, Handler{}) + var observed string + next, err := bus.NewContext("successor", Handler{Commit: func(value string) { observed = value }}) + if err != nil { + t.Fatal(err) + } + previous.Close() + transport.incoming = []*dbus.Message{commitSignal(testContext, "successor")} + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if observed != "successor" || len(transport.calls("Destroy")) != 0 { + t.Fatalf("retired owner destroyed successor: commit=%q calls=%+v", observed, transport.calls("Destroy")) + } + next.Close() + if len(transport.calls("Destroy")) != 1 { + t.Fatal("successor was not destroyed by its current owner") + } +} + +func TestRetiredContextsRefuseKeysAndContextSideEffects(t *testing.T) { + bus, context, transport := newTestBus(t, Handler{}) + context.Close() + sent := len(transport.sent) + if err := context.ProcessKey('n', 49, 0, nil); !errors.Is(err, ErrClosed) { + t.Fatalf("retired key=%v", err) + } + for _, err := range []error{ + context.FocusIn(), context.FocusOut(), context.Reset(), + context.SetCursorLocation(0, 0, 1, 10), context.SetSurroundingText("", 0, 0), + } { + if !errors.Is(err, ErrClosed) { + t.Fatalf("retired context side effect=%v", err) + } + } + if len(transport.sent) != sent || len(bus.pending) != 0 { + t.Fatal("retired context sent native requests or retained a pending key") + } +} + +func TestNativeContextRetirement(t *testing.T) { + if os.Getenv("VIVA_IBUS_NATIVE") != "1" { + t.Skip("native context retirement requires a private input-method service") + } + bus, err := Dial() + if err != nil { + t.Fatal(err) + } + defer bus.Close() + context, err := bus.NewContext("viva-retirement", Handler{}) + if err != nil { + t.Fatal(err) + } + defer context.Close() + if err := context.FocusIn(); err != nil { + t.Fatal(err) + } + engine := os.Getenv("VIVA_IBUS_ENGINE") + if engine == "" { + engine = "libpinyin" + } + var body dbus.Encoder + body.String(engine) + if _, err := bus.conn.Call(service, context.path, contextInterface, "SetEngine", "s", body.Bytes()); err != nil { + t.Fatal(err) + } + query := func() error { + _, err := bus.conn.Call(service, context.path, contextInterface, "GetEngine", "", nil) + return err + } + if err := query(); err != nil { + t.Fatalf("new native context is not callable: %v", err) + } + context.Close() + var refused *dbus.Error + if err := query(); !errors.As(err, &refused) { + t.Fatalf("closed native context still callable: %v", err) + } + if _, err := bus.NewContext("viva-successor", Handler{}); err != nil { + t.Fatalf("native destruction damaged the shared bus: %v", err) + } +} + +func TestEngineSelectionUsesItsContextConnectionAndSurfacesRefusal(t *testing.T) { + for _, refused := range []bool{false, true} { + bus, context, transport := newTestBus(t, Handler{}) + selector, ok := any(context).(interface{ SetEngine(string) error }) + if !ok { + t.Fatal("input context has no native engine selection") + } + if refused { + transport.engineErr = &dbus.Error{Name: "org.freedesktop.IBus.Error.Failed", Text: "engine unavailable"} + } + if err := selector.SetEngine("libpinyin"); !errors.Is(err, transport.engineErr) { + t.Fatalf("selection error=%v, want %v", err, transport.engineErr) + } + calls := transport.calls("SetEngine") + if len(calls) != 1 || calls[0].path != testContext || calls[0].iface != contextInterface || calls[0].signature != "s" || dbus.NewDecoder(calls[0].body).String() != "libpinyin" { + t.Fatalf("native selection call=%+v", calls) + } + if bus.Err() != nil || transport.closed { + t.Fatal("engine refusal closed the shared bus") + } + context.Close() + if err := selector.SetEngine("libpinyin"); !errors.Is(err, ErrClosed) || len(transport.calls("SetEngine")) != 1 { + t.Fatalf("closed context selection error=%v", err) + } + } +} + +func TestEngineSelectionTransportFailureClosesSharedBus(t *testing.T) { + bus, context, transport := newTestBus(t, Handler{}) + selector := any(context).(interface{ SetEngine(string) error }) + transport.engineErr = errors.New("write failed") + released := 0 + if err := context.ProcessKey('n', 49, 0, func(handled bool) { + if handled { + t.Error("failed bus consumed a pending key") + } + released++ + }); err != nil { + t.Fatal(err) + } + if err := selector.SetEngine("libpinyin"); !errors.Is(err, transport.engineErr) || !errors.Is(bus.Err(), err) || !transport.closed || released != 1 { + t.Fatalf("selection error=%v bus=%v closed=%t released=%d", err, bus.Err(), transport.closed, released) + } + if err := selector.SetEngine("libpinyin"); !errors.Is(err, ErrClosed) || len(transport.calls("SetEngine")) != 1 { + t.Fatalf("failed bus selection error=%v", err) + } +} + +func TestEngineSelectionDeliversRepliesBufferedByItsSynchronousCall(t *testing.T) { + for _, refused := range []bool{false, true} { + var observed []string + bus, context, transport := newTestBus(t, Handler{Commit: func(value string) { observed = append(observed, value) }}) + if err := context.ProcessKey('n', 49, 0, func(handled bool) { observed = append(observed, fmt.Sprintf("handled=%t", handled)) }); err != nil { + t.Fatal(err) + } + transport.incoming = []*dbus.Message{commitSignal(testContext, "chosen"), keyAnswer(transport.calls("ProcessKeyEvent")[0].serial, true)} + if refused { + transport.engineErr = &dbus.Error{Name: "org.freedesktop.IBus.Error.Failed", Text: "engine unavailable"} + } + if err := context.SetEngine("libpinyin"); !errors.Is(err, transport.engineErr) { + t.Fatalf("selection error=%v want=%v", err, transport.engineErr) + } + if !reflect.DeepEqual(observed, []string{"chosen", "handled=true"}) || bus.Err() != nil { + t.Fatalf("buffered events=%q bus=%v", observed, bus.Err()) + } + if _, waiting := bus.Deadline(); waiting { + t.Fatal("an already-answered key still waits for a socket-readability event") + } + } +} + +func TestDispatchFromHandlerPreservesDaemonMessageOrder(t *testing.T) { + var observed []string + bus, context, transport := newTestBus(t, Handler{}) + context.handler.Commit = func(value string) { + observed = append(observed, value) + if value == "A" { + transport.incoming = []*dbus.Message{ + commitSignal(testContext, "C"), keyAnswer(transport.calls("ProcessKeyEvent")[0].serial, true), + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + } + } + if err := context.ProcessKey('n', 49, 0, func(handled bool) { + observed = append(observed, fmt.Sprintf("handled=%t", handled)) + }); err != nil { + t.Fatal(err) + } + transport.incoming = []*dbus.Message{commitSignal(testContext, "A"), commitSignal(testContext, "B")} + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(observed, []string{"A", "B", "C", "handled=true"}) { + t.Fatalf("daemon callbacks=%q, want A, B, C, then the key answer", observed) + } + if _, waiting := bus.Deadline(); waiting { + t.Fatal("nested dispatch stranded an already-answered key") + } +} + +func TestEngineSelectionFromHandlerPreservesDaemonMessageOrder(t *testing.T) { + for _, refused := range []bool{false, true} { + t.Run(fmt.Sprintf("refused=%t", refused), func(t *testing.T) { + var observed []string + bus, context, transport := newTestBus(t, Handler{}) + context.handler.Commit = func(value string) { + observed = append(observed, value) + if value == "A" { + if err := context.SetEngine("libpinyin"); !errors.Is(err, transport.engineErr) { + t.Errorf("selection error=%v want=%v", err, transport.engineErr) + } + } + } + if refused { + transport.engineErr = &dbus.Error{Name: "org.freedesktop.IBus.Error.Failed", Text: "engine unavailable"} + } + if err := context.ProcessKey('n', 49, 0, func(handled bool) { + observed = append(observed, fmt.Sprintf("handled=%t", handled)) + }); err != nil { + t.Fatal(err) + } + transport.incoming = []*dbus.Message{commitSignal(testContext, "A"), commitSignal(testContext, "B")} + transport.engineIncoming = []*dbus.Message{ + commitSignal(testContext, "C"), keyAnswer(transport.calls("ProcessKeyEvent")[0].serial, true), + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(observed, []string{"A", "B", "C", "handled=true"}) { + t.Fatalf("daemon callbacks=%q, want A, B, C, then the key answer", observed) + } + if _, waiting := bus.Deadline(); waiting { + t.Fatal("nested engine selection stranded an already-answered key") + } + }) + } +} + func TestKeyAnswersArriveInTheOrderTheKeysWereTyped(t *testing.T) { bus, context, transport := newTestBus(t, Handler{}) var order []string @@ -211,8 +465,8 @@ func TestCommitAndPreeditSignalsReachTheHandler(t *testing.T) { var preedits []preedit bus, _, transport := newTestBus(t, Handler{ Commit: func(text string) { commits = append(commits, text) }, - Preedit: func(text string, cursor int, visible bool, _ []Attribute) { - preedits = append(preedits, preedit{text, cursor, visible}) + Preedit: func(event PreeditEvent) { + preedits = append(preedits, preedit{event.Text, event.Cursor, event.Visible}) }, }) hide := &dbus.Message{Type: dbus.TypeSignal, Path: testContext, Interface: contextInterface, Member: "HidePreeditText"} @@ -239,6 +493,92 @@ func TestCommitAndPreeditSignalsReachTheHandler(t *testing.T) { } } +func TestPreeditWithModeSignalsReachTheHandler(t *testing.T) { + var got []string + var events []PreeditEvent + bus, _, transport := newTestBus(t, Handler{Preedit: func(event PreeditEvent) { + got = append(got, fmt.Sprintf("%s/%t", event.Text, event.Visible)) + events = append(events, event) + }}) + update := preeditModeSignal(testContext, "n", 1, true, PreeditModeCommit) + transport.incoming = []*dbus.Message{ + update, + {Type: dbus.TypeSignal, Path: testContext, Interface: contextInterface, Member: "HidePreeditText"}, + {Type: dbus.TypeSignal, Path: testContext, Interface: contextInterface, Member: "ShowPreeditText"}, + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if want := []string{"n/true", "n/false", "n/true"}; !reflect.DeepEqual(got, want) { + t.Fatalf("mode-bearing preedit = %v, want %v", got, want) + } + for index, event := range events { + if event.Kind != []PreeditKind{PreeditUpdate, PreeditHide, PreeditShow}[index] || + !event.HasMode || event.Mode != PreeditModeCommit || event.Cursor != 1 { + t.Fatalf("preedit provenance[%d] = %+v", index, event) + } + } +} + +func TestPreeditEventsPreserveEmptyUpdatesAndResetModeProvenance(t *testing.T) { + var events []PreeditEvent + bus, _, transport := newTestBus(t, Handler{Preedit: func(event PreeditEvent) { events = append(events, event) }}) + transport.incoming = []*dbus.Message{ + preeditModeSignal(testContext, "n", 1, true, PreeditModeCommit), + preeditSignal(testContext, "", 0, true), + {Type: dbus.TypeSignal, Path: testContext, Interface: contextInterface, Member: "HidePreeditText"}, + preeditModeSignal(testContext, "", 0, false, ^uint32(0)), + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + want := []PreeditEvent{ + {Text: "n", Cursor: 1, Visible: true, Mode: PreeditModeCommit, HasMode: true}, + {Text: "", Visible: true}, + {Text: "", Kind: PreeditHide}, + {Text: "", Mode: ^uint32(0), HasMode: true}, + } + if !reflect.DeepEqual(events, want) { + t.Fatalf("preedit provenance = %+v, want %+v", events, want) + } +} + +func TestMalformedPreeditSignalCannotReplaceTheCachedSnapshot(t *testing.T) { + for _, name := range []string{"missing mode", "truncated mode", "mode on old member", "trailing body", "hide payload", "show signature"} { + t.Run(name, func(t *testing.T) { + var events []PreeditEvent + bus, _, transport := newTestBus(t, Handler{Preedit: func(event PreeditEvent) { events = append(events, event) }}) + bad := preeditModeSignal(testContext, "bad", 1, true, PreeditModeClear) + switch name { + case "missing mode": + bad = preeditSignal(testContext, "bad", 1, true) + bad.Member = "UpdatePreeditTextWithMode" + case "truncated mode": + bad.Body = bad.Body[:len(bad.Body)-1] + case "mode on old member": + bad.Member = "UpdatePreeditText" + case "trailing body": + bad.Body = append(bad.Body, 0, 0, 0, 0) + case "hide payload": + bad.Member = "HidePreeditText" + case "show signature": + bad.Member, bad.Signature, bad.Body = "ShowPreeditText", "u", nil + } + transport.incoming = []*dbus.Message{ + preeditModeSignal(testContext, "keep", 2, true, PreeditModeCommit), bad, + {Type: dbus.TypeSignal, Path: testContext, Interface: contextInterface, Member: "ShowPreeditText"}, + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if len(events) != 2 || events[1].Kind != PreeditShow || events[1].Text != "keep" || + !events[1].HasMode || events[1].Mode != PreeditModeCommit || events[1].Cursor != 2 { + t.Fatalf("malformed preedit changed cached provenance: %+v", events) + } + }) + } +} + // styledPreeditSignal is an UpdatePreeditText whose text carries attributes, as an // engine marking the clause being converted sends it. func styledPreeditSignal(path, text string, cursor uint32, attrs [][4]uint32) *dbus.Message { @@ -268,14 +608,13 @@ func styledPreeditSignal(path, text string, cursor uint32, attrs [][4]uint32) *d body.EndArray(list) body.Uint32(cursor) body.Bool(true) - body.Uint32(0) - return &dbus.Message{Type: dbus.TypeSignal, Path: path, Interface: contextInterface, Member: "UpdatePreeditText", Signature: "vubu", Body: body.Bytes()} + return &dbus.Message{Type: dbus.TypeSignal, Path: path, Interface: contextInterface, Member: "UpdatePreeditText", Signature: "vub", Body: body.Bytes()} } func TestPreeditAttributesReachTheHandler(t *testing.T) { var got []Attribute var gotText string - bus, _, transport := newTestBus(t, Handler{Preedit: func(text string, _ int, _ bool, attrs []Attribute) { gotText, got = text, attrs }}) + bus, _, transport := newTestBus(t, Handler{Preedit: func(event PreeditEvent) { gotText, got = event.Text, event.Attributes }}) transport.incoming = []*dbus.Message{styledPreeditSignal(testContext, "きょうは", 4, [][4]uint32{ {AttrUnderline, 1, 0, 4}, {AttrBackground, 0xd1eaff, 0, 2}, @@ -289,6 +628,61 @@ func TestPreeditAttributesReachTheHandler(t *testing.T) { } } +func TestPreeditModeVisibilityKeepsReadOnlyAttributeSnapshots(t *testing.T) { + var events []PreeditEvent + bus, _, transport := newTestBus(t, Handler{Preedit: func(event PreeditEvent) { events = append(events, event) }}) + update := styledPreeditSignal(testContext, "ab", 1, [][4]uint32{{AttrBackground, 0x123456, 0, 1}}) + var mode dbus.Encoder + mode.Uint32(PreeditModeCommit) + update.Member, update.Signature = "UpdatePreeditTextWithMode", "vubu" + update.Body = append(update.Body, mode.Bytes()...) + transport.incoming = []*dbus.Message{ + update, + {Type: dbus.TypeSignal, Path: testContext, Interface: contextInterface, Member: "HidePreeditText"}, + {Type: dbus.TypeSignal, Path: testContext, Interface: contextInterface, Member: "ShowPreeditText"}, + styledPreeditSignal(testContext, "cd", 2, [][4]uint32{{AttrUnderline, 2, 1, 2}}), + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if len(events) != 4 { + t.Fatalf("preedit events = %+v", events) + } + for index, event := range events[:3] { + if !event.HasMode || event.Mode != PreeditModeCommit || event.Text != "ab" || + event.Kind != []PreeditKind{PreeditUpdate, PreeditHide, PreeditShow}[index] || + !reflect.DeepEqual(event.Attributes, []Attribute{{Kind: AttrBackground, Value: 0x123456, Start: 0, End: 1}}) { + t.Fatalf("saved preedit attributes[%d] changed: %+v", index, event) + } + } + if events[3].HasMode || events[3].Text != "cd" || !reflect.DeepEqual(events[3].Attributes, []Attribute{{Kind: AttrUnderline, Value: 2, Start: 1, End: 2}}) { + t.Fatalf("new update retained old metadata: %+v", events[3]) + } +} + +var preeditBenchmarkText string +var preeditBenchmarkContext *Context + +func BenchmarkPreeditSignalDispatch(b *testing.B) { + context := &Context{handler: Handler{Preedit: func(event PreeditEvent) { preeditBenchmarkText = event.Text }}} + message := preeditSignal(testContext, "preedit", 3, true) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + context.signal(message) + } + b.ReportMetric(float64(unsafe.Sizeof(Context{})), "context-B") + b.ReportMetric(float64(unsafe.Sizeof(Handler{})), "handler-B") + b.ReportMetric(float64(unsafe.Sizeof(Bus{})), "bus-B") +} + +func BenchmarkPreeditContextConstruction(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + preeditBenchmarkContext = new(Context) + } +} + func TestDeleteSurroundingTextReachesTheHandler(t *testing.T) { var offset, count int bus, _, transport := newTestBus(t, Handler{DeleteSurrounding: func(o, c int) { offset, count = o, c }}) @@ -343,7 +737,7 @@ func TestMalformedSignalsAreIgnoredNotFatal(t *testing.T) { called := false bus, _, transport := newTestBus(t, Handler{ Commit: func(string) { called = true }, - Preedit: func(string, int, bool, []Attribute) { called = true }, + Preedit: func(PreeditEvent) { called = true }, Forward: func(_, _, _ uint32) { called = true }, }) truncated := commitSignal(testContext, "你好") @@ -407,6 +801,60 @@ func TestAFailedSendClosesTheBusAndReleasesPendingKeys(t *testing.T) { } } +func TestFailedContextDestructionReleasesBothContextsKeysDespiteReentry(t *testing.T) { + bus, first, transport := newTestBus(t, Handler{}) + transport.createPath = testContext + "_second" + second, err := bus.NewContext("second", Handler{}) + if err != nil { + t.Fatal(err) + } + var completed []string + completion := func(name string) func(bool) { + return func(handled bool) { + completed = append(completed, name) + if handled { + t.Errorf("%s key was handled after transport failure", name) + } + if bus.contexts[first.path] == first { + t.Error("destroyed context still owns its handler during failure callbacks") + } + first.Close() + second.Close() + for _, context := range []*Context{first, second} { + if err := context.ProcessKey('n', 49, 0, nil); !errors.Is(err, ErrClosed) { + t.Errorf("reentered key returned %v, want ErrClosed", err) + } + } + if _, err := bus.NewContext("reentered", Handler{}); !errors.Is(err, ErrClosed) { + t.Errorf("reentered context returned %v, want ErrClosed", err) + } + } + } + if err := first.ProcessKey('a', 38, 0, completion("first")); err != nil { + t.Fatal(err) + } + if err := second.ProcessKey('b', 56, 0, completion("second")); err != nil { + t.Fatal(err) + } + sent := len(transport.sent) + failure := errors.New("destroy: broken pipe") + transport.sendErr = failure + first.Close() + bus.Close() + first.Close() + second.Close() + if !errors.Is(bus.Err(), failure) || !transport.closed { + t.Fatalf("failure = %v, transport closed = %v", bus.Err(), transport.closed) + } + if !reflect.DeepEqual(completed, []string{"first", "second"}) { + t.Fatalf("completion order = %v, want each key released once in order", completed) + } + if len(bus.pending) != 0 || len(bus.contexts) != 0 || len(transport.sent) != sent { + t.Fatalf("after destruction: pending=%d contexts=%d sent=%d, want 0, 0, %d", + len(bus.pending), len(bus.contexts), len(transport.sent), sent) + } +} + func TestContextCalls(t *testing.T) { _, context, transport := newTestBus(t, Handler{}) if err := context.FocusIn(); err != nil { @@ -437,6 +885,27 @@ func TestContextCalls(t *testing.T) { } } +func BenchmarkHandledContextKey(b *testing.B) { + transport := &fakeTransport{createPath: testContext} + bus := newBus(transport) + context, err := bus.NewContext("benchmark", Handler{}) + if err != nil { + b.Fatal(err) + } + answer := dbus.Message{Type: dbus.TypeReturn, Signature: "b", Body: []byte{1, 0, 0, 0}} + transport.sent = transport.sent[:0] + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + if err := context.ProcessKey('a', 30, 0, nil); err != nil { + b.Fatal(err) + } + answer.ReplySerial = transport.serial + bus.answer(&answer) + transport.sent = transport.sent[:0] + } +} + func TestAddressPrefersTheEnvironmentThenTheDisplaysFile(t *testing.T) { files := map[string]string{ "/var/lib/dbus/machine-id": "abc123\n", @@ -496,15 +965,16 @@ func FuzzDispatchNeverPanics(f *testing.F) { good := commitSignal(testContext, "你好") f.Add(good.Body, "v", "CommitText") preedit := preeditSignal(testContext, "ni", 1, true) - f.Add(preedit.Body, "vubu", "UpdatePreeditText") - f.Add(styledPreeditSignal(testContext, "ni", 1, [][4]uint32{{AttrBackground, 1, 0, 2}}).Body, "vubu", "UpdatePreeditText") + f.Add(preedit.Body, "vub", "UpdatePreeditText") + f.Add(styledPreeditSignal(testContext, "ni", 1, [][4]uint32{{AttrBackground, 1, 0, 2}}).Body, "vub", "UpdatePreeditText") + f.Add(preeditModeSignal(testContext, "ni", 1, true, PreeditModeCommit).Body, "vubu", "UpdatePreeditTextWithMode") f.Add([]byte{1, 2, 3}, "uuu", "ForwardKeyEvent") f.Add([]byte{1, 2, 3}, "iu", "DeleteSurroundingText") f.Fuzz(func(t *testing.T, body []byte, signature, member string) { var seen int bus, _, transport := newTestBus(t, Handler{ Commit: func(string) { seen++ }, - Preedit: func(string, int, bool, []Attribute) { seen++ }, + Preedit: func(PreeditEvent) { seen++ }, Forward: func(_, _, _ uint32) { seen++ }, DeleteSurrounding: func(_, _ int) { seen++ }, diff --git a/internal/ibus/native_test.go b/internal/ibus/native_test.go new file mode 100644 index 000000000..ebb7da2dc --- /dev/null +++ b/internal/ibus/native_test.go @@ -0,0 +1,201 @@ +//go:build unix + +package ibus + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/vivaui/viva/internal/dbus" +) + +func TestNativeEngineLifecycle(t *testing.T) { + if os.Getenv("VIVA_IBUS_NATIVE") != "1" { + t.Skip("native IBus probe requires a private daemon and VIVA_IBUS_NATIVE=1") + } + engine := os.Getenv("VIVA_IBUS_ENGINE") + if engine == "" { + engine = "libpinyin" + } + var keycodes map[uint32]uint32 + if err := json.Unmarshal([]byte(os.Getenv("VIVA_IBUS_KEYCODES")), &keycodes); err != nil { + t.Fatalf("native keymap: %v", err) + } + for _, ending := range []string{"commit", "escape", "reset", "focus-out"} { + t.Run(ending, func(t *testing.T) { + bus, err := Dial() + if err != nil { + t.Fatal(err) + } + defer bus.Close() + var events []string + var committed []string + hasPreedit := false + visible, endingActive, cleared := false, false, false + wantClear := PreeditHide + if engine == "hangul" || ending == "focus-out" { + wantClear = PreeditUpdate + } + context, err := bus.NewContext("viva-native-probe", Handler{ + Commit: func(value string) { + events = append(events, "commit:"+value) + committed = append(committed, value) + }, + Preedit: func(event PreeditEvent) { + hasPreedit = hasPreedit || event.Kind == PreeditUpdate && event.Visible && event.Text != "" + visible = event.Visible + if endingActive && event.Kind == wantClear && !event.Visible && (event.Kind == PreeditHide || event.Text == "") { + cleared = true + } + events = append(events, fmt.Sprintf("preedit:%d:%q:cursor=%d:visible=%t:mode=%d:has-mode=%t", event.Kind, event.Text, event.Cursor, event.Visible, event.Mode, event.HasMode)) + }, + Forward: func(symbol, code, state uint32) { + events = append(events, fmt.Sprintf("forward:%#x:%d:%#x", symbol, code, state)) + }, + }) + if err != nil { + t.Fatal(err) + } + defer context.Close() + if err := context.FocusIn(); err != nil { + t.Fatal(err) + } + if ending == "commit" { + var refusal *dbus.Error + if err := context.SetEngine("viva-native-missing-engine"); !errors.As(err, &refusal) || bus.Err() != nil { + t.Fatalf("unknown engine refusal=%v bus=%v", err, bus.Err()) + } + } + nativeIBusSelectEngine(t, bus, context, engine) + reply, err := bus.conn.Call(service, context.path, contextInterface, "GetEngine", "", nil) + if err != nil || reply.Type == dbus.TypeError { + t.Fatalf("GetEngine: reply=%+v error=%v", reply, err) + } + args := reply.Args() + signature := args.Signature() + args.Align(8) + typeName := args.String() + args.Skip("a{sv}") + actual := args.String() + t.Logf("requested=%s actual=%s type=%s signature=%s", engine, actual, typeName, signature) + if actual != engine { + t.Fatalf("engine selection mismatch: %q", actual) + } + press := func(symbol, state uint32) { + t.Helper() + answered := false + if err := context.ProcessKey(symbol, keycodes[symbol], state, func(handled bool) { + events = append(events, fmt.Sprintf("answer:%#x:%t", symbol, handled)) + answered = true + }); err != nil { + t.Fatal(err) + } + nativeIBusDrain(t, bus, func() bool { return answered }, 2*time.Second) + } + keys := "nihao" + if engine == "hangul" { + press(0xff31, 0) + keys = "rksk" + } + for _, symbol := range keys { + press(uint32(symbol), 0) + } + if !hasPreedit || !visible { + t.Fatal("the native ending has no live preedit to settle") + } + endingActive = true + switch ending { + case "commit": + press(' ', 0) + case "escape": + press(0xff1b, 0) + case "reset": + if err := context.Reset(); err != nil { + t.Fatal(err) + } + case "focus-out": + if err := context.FocusOut(); err != nil { + t.Fatal(err) + } + } + until := time.Now().Add(150 * time.Millisecond) + nativeIBusDrain(t, bus, func() bool { return time.Now().After(until) }, time.Second) + for index, event := range events { + t.Logf("engine=%s event=%d %s", engine, index, event) + } + want := "" + if engine == "hangul" { + want = "가나" + } else if ending == "commit" { + want = "你好" + } + if !cleared || visible || strings.Join(committed, "") != want { + t.Fatalf("engine=%s ending=%s cleared=%t visible=%t committed=%q want=%q", engine, ending, cleared, visible, committed, want) + } + }) + } +} + +func nativeIBusSelectEngine(t *testing.T, bus *Bus, context *Context, engine string) { + t.Helper() + reply, err := bus.conn.Call(service, busPath, service, "GetUseGlobalEngine", "", nil) + if err != nil { + t.Fatalf("UseGlobalEngine: %v", err) + } + if reply.Signature != "b" { + t.Fatalf("UseGlobalEngine signature: %q", reply.Signature) + } + args := reply.Args() + global := args.Bool() + if err := args.Err(); err != nil { + t.Fatalf("UseGlobalEngine decode: %v", err) + } + t.Logf("daemon UseGlobalEngine=%t", global) + err = context.SetEngine(engine) + if !global { + if err != nil { + t.Fatalf("SetEngine(%q): %v", engine, err) + } + return + } + var refusal *dbus.Error + if err != nil && (!errors.As(err, &refusal) || refusal.Name != "org.freedesktop.DBus.Error.Failed" || + refusal.Text != "Cannot set engines when use-global-engine is enabled.") || bus.Err() != nil { + t.Fatalf("global mode context refusal=%v bus=%v", err, bus.Err()) + } + t.Logf("global mode context selection refused=%t", err != nil) + // Each case needs a fresh engine even when the daemon shares it globally. + for _, name := range []string{"xkb:us::eng", engine} { + var selection dbus.Encoder + selection.String(name) + if _, err := bus.conn.Call(service, busPath, service, "SetGlobalEngine", "s", selection.Bytes()); err != nil { + t.Fatalf("SetGlobalEngine(%q): %v", name, err) + } + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } +} + +func nativeIBusDrain(t *testing.T, bus *Bus, done func() bool, timeout time.Duration) { + t.Helper() + deadline := time.Now().Add(timeout) + for !done() { + if time.Now().After(deadline) { + t.Fatal("native IBus response timed out") + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + bus.Expire() + if err := bus.Err(); err != nil { + t.Fatal(err) + } + time.Sleep(time.Millisecond) + } +} diff --git a/internal/ibus/testdata/native-daemon.sh b/internal/ibus/testdata/native-daemon.sh new file mode 100644 index 000000000..e033b47d7 --- /dev/null +++ b/internal/ibus/testdata/native-daemon.sh @@ -0,0 +1,44 @@ +#!/bin/sh +set -eu +command -v gdbus >/dev/null +reference_client=$(dirname "$0")/reference-client.py +task_dir=$(dirname "$XDG_RUNTIME_DIR") +daemon_pid= +cleanup() { + if [ -n "$daemon_pid" ]; then + kill "$daemon_pid" 2>/dev/null || true + wait "$daemon_pid" 2>/dev/null || true + fi + if [ -f "$task_dir/daemon.log" ]; then cat "$task_dir/daemon.log"; fi +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' HUP TERM +ibus-daemon --panel=disable --config=/usr/libexec/ibus-dconf --emoji-extension=disable --cache=refresh --address "$IBUS_ADDRESS" > "$task_dir/daemon.log" 2>&1 & +daemon_pid=$! +attempt=0 +while [ ! -S "$task_dir/ibus-bus" ]; do + kill -0 "$daemon_pid" + attempt=$((attempt + 1)) + [ "$attempt" -lt 100 ] + sleep 0.02 +done +attempt=0 +while ! gdbus call --timeout 1 --address "$IBUS_ADDRESS" --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.NameHasOwner org.freedesktop.IBus.Config | grep -q true; do + kill -0 "$daemon_pid" + attempt=$((attempt + 1)) + [ "$attempt" -lt 100 ] + sleep 0.02 +done +ibus version +gdbus call --timeout 1 --address "$IBUS_ADDRESS" --dest org.freedesktop.IBus --object-path /org/freedesktop/IBus --method org.freedesktop.IBus.GetUseGlobalEngine +VIVA_IBUS_KEYCODES=$(/usr/bin/python3 "$reference_client" --keycodes) +export VIVA_IBUS_KEYCODES +printf 'Native keycodes: %s\n' "$VIVA_IBUS_KEYCODES" +for engine in "$@"; do + if [ "${VIVA_IBUS_REFERENCE:-0}" = 1 ]; then + VIVA_IBUS_ENGINE=$engine /usr/bin/python3 "$reference_client" + fi + VIVA_IBUS_NATIVE=1 VIVA_IBUS_ENGINE=$engine "$VIVA_IBUS_TEST_BINARY" -test.run "${VIVA_IBUS_TEST_RUN:-^TestNativeEngineLifecycle$}" -test.count=1 -test.v -test.timeout=30s +done +/usr/bin/python3 "$reference_client" --activation-environment diff --git a/internal/ibus/testdata/native-service.sh b/internal/ibus/testdata/native-service.sh new file mode 100644 index 000000000..eedf16fe6 --- /dev/null +++ b/internal/ibus/testdata/native-service.sh @@ -0,0 +1,34 @@ +#!/bin/sh +set -eu +[ "$#" -gt 0 ] +: "${VIVA_IBUS_TEST_BINARY:?set the native test binary path}" +command -v timeout >/dev/null +fixture_dir=$(dirname "$0") +umask 077 +task_dir=$(mktemp -d /tmp/viva-ibus-native.XXXXXX) +export XDG_RUNTIME_DIR=$task_dir/runtime +export XDG_CONFIG_HOME=$task_dir/config +export XDG_CACHE_HOME=$task_dir/cache +export XDG_DATA_HOME=$task_dir/data +export GDK_BACKEND=x11 +export NO_AT_BRIDGE=1 +mkdir -p "$XDG_RUNTIME_DIR" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME" "$XDG_DATA_HOME" +export IBUS_ADDRESS=unix:path=$task_dir/ibus-bus +session_pid= +cleanup() { + if [ -n "$session_pid" ]; then + kill "$session_pid" 2>/dev/null || true + wait "$session_pid" 2>/dev/null || true + fi + rm -rf "$task_dir" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' HUP TERM +# Activated services must inherit the profile when the session bus starts. +timeout --kill-after=5s 90s dbus-run-session -- sh "$fixture_dir/native-daemon.sh" "$@" & +session_pid=$! +status=0 +wait "$session_pid" || status=$? +session_pid= +exit "$status" diff --git a/internal/ibus/testdata/reference-client.py b/internal/ibus/testdata/reference-client.py new file mode 100644 index 000000000..6fdfe0e86 --- /dev/null +++ b/internal/ibus/testdata/reference-client.py @@ -0,0 +1,87 @@ +import json +import os +import subprocess +import sys +import time + +import gi + +gi.require_version("IBus", "1.0") +gi.require_version("Gdk", "3.0") +from gi.repository import Gdk, Gio, GLib, IBus + +if "--activation-environment" in sys.argv: + subprocess.run(["dconf", "write", "/viva/native-fixture/marker", "'isolated'"], check=True) + session = Gio.bus_get_sync(Gio.BusType.SESSION, None) + reply = session.call_sync( + "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", + "GetConnectionUnixProcessID", GLib.Variant("(s)", ("ca.desrt.dconf",)), + GLib.VariantType.new("(u)"), Gio.DBusCallFlags.NONE, 1000, None, + ) + pid = reply.unpack()[0] + with open(f"/proc/{pid}/environ", "rb") as stream: + activated = dict(entry.split(b"=", 1) for entry in stream.read().split(b"\0") if b"=" in entry) + names = ["XDG_RUNTIME_DIR", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME"] + checks = {name: activated.get(name.encode()) == os.environ[name].encode() for name in names} + print("Dconf activation environment:", json.dumps(checks), flush=True) + if not all(checks.values()): + raise RuntimeError("activated dconf service escaped the private profile") + marker = subprocess.check_output(["dconf", "read", "/viva/native-fixture/marker"]).strip() + database = os.path.join(os.environ["XDG_CONFIG_HOME"], "dconf", "user") + if marker != b"'isolated'" or not os.path.isfile(database): + raise RuntimeError("private dconf database was not written and read back") + print("Dconf private database: dconf/user, marker verified", flush=True) + sys.exit(0) + +Gdk.init([]) +keymap = Gdk.Keymap.get_for_display(Gdk.Display.get_default()) +keycodes = {} +for symbol in [ord(key) for key in "nihaorks "] + [0xff1b, 0xff31]: + found, entries = keymap.get_entries_for_keyval(symbol) + keycodes[symbol] = entries[0].keycode - 8 if found else 0 +if "--keycodes" in sys.argv: + print(json.dumps(keycodes)) + sys.exit(0) + +IBus.init() +bus = IBus.Bus() +print("reference connected", bus.is_connected(), flush=True) +context = bus.create_input_context("viva-reference-probe") +context.set_capabilities(IBus.Capabilite.PREEDIT_TEXT | IBus.Capabilite.FOCUS) +context.focus_in() +requested = os.environ.get("VIVA_IBUS_ENGINE", "libpinyin") +global_engine = bus.get_use_global_engine() +print("reference UseGlobalEngine", global_engine, flush=True) +if global_engine: + for name in ["xkb:us::eng", requested]: + if not bus.set_global_engine(name): + raise RuntimeError("reference global engine selection failed: " + name) +else: + context.set_engine(requested) +deadline = time.monotonic() + 5 +while True: + engine = context.get_engine() + if engine and engine.get_name() == requested: + break + if time.monotonic() >= deadline: + raise RuntimeError("reference engine did not become ready") + main = GLib.MainContext.default() + while main.pending(): + 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)) +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 "): + print("reference key", key, context.process_key_event(ord(key), keycodes[ord(key)], 0), flush=True) + main = GLib.MainContext.default() + while main.pending(): + main.iteration(False) +until = time.monotonic() + 0.15 +while time.monotonic() < until: + while main.pending(): + main.iteration(False) + time.sleep(0.001) +context.destroy() diff --git a/internal/platform/composition_dispatch_test.go b/internal/platform/composition_dispatch_test.go new file mode 100644 index 000000000..301cdede4 --- /dev/null +++ b/internal/platform/composition_dispatch_test.go @@ -0,0 +1,174 @@ +package platform + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/text" +) + +func TestTextEventApplyTaggedCompositionRoutesOnlyWithCapability(t *testing.T) { + for _, scenario := range []struct { + name string + enabled bool + phase text.CompositionPhase + }{ + {name: "disabled-tagged", phase: text.CompositionResult}, + {name: "disabled-zero"}, + {name: "enabled-zero", enabled: true}, + } { + t.Run(scenario.name, func(t *testing.T) { + editor := text.NewEditor("abc") + if scenario.enabled && !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + TextEvent{ + Kind: TextInsert, Text: "X", CompositionPhase: scenario.phase, + HasReplacement: true, Replacement: text.Range{Start: 1, End: 2}, + HasReplacementUTF16: true, ReplacementUTF16: text.UTF16Range{Start: 99, Length: 99}, + }.Apply(editor) + if got := editor.String(); got != "aXc" { + t.Fatalf("legacy rune targeting = %q, want aXc", got) + } + if editor.TentativeCompositionEnabled() != scenario.enabled || EditorState(editor).TentativeComposition != scenario.enabled { + t.Fatal("event routing changed the opt-in capability") + } + }) + } +} + +func TestTextEventApplyTaggedCompositionForwardsUpdateAndResult(t *testing.T) { + editor := text.NewEditor("abcd") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + cursor, _, ok := editor.TrackHistory() + if !ok { + t.Fatal("history setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + TextEvent{ + Kind: TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "\u00e9\U0001d11e", + MarkedSelection: text.Range{Start: 2, End: 2}, + }.Apply(editor) + if got := editor.String(); got != "a\u00e9\U0001d11ecd" { + t.Fatalf("tagged Update = %q", got) + } + if state := EditorState(editor); !state.Composing || !state.TentativeComposition { + t.Fatalf("tagged Update state = %+v", state) + } + frames, cursor, ok := editor.HistorySince(cursor) + if !ok || len(frames) != 1 || len(frames[0].Steps) != 3 { + t.Fatalf("tagged Update frames = %+v, want one complete three-scalar frame", frames) + } + TextEvent{ + Kind: TextInsert, CompositionPhase: text.CompositionResult, Text: "r", + HasReplacement: true, Replacement: text.Range{Start: 0, End: 1}, + HasReplacementUTF16: true, ReplacementUTF16: text.UTF16Range{Start: 5, Length: 1}, + }.Apply(editor) + if got := editor.String(); got != "acdr" { + t.Fatalf("tagged raw Result = %q, want acdr", got) + } + if state := EditorState(editor); state.Composing || !state.TentativeComposition { + t.Fatalf("tagged Result state = %+v", state) + } + frames, _, ok = editor.HistorySince(cursor) + if !ok || len(frames) != 1 || len(frames[0].Steps) != 3 || frames[0].BeforeBytes != 9 || frames[0].AfterBytes != 4 { + t.Fatalf("tagged Result frames = %+v, want one atomic post-rollback frame", frames) + } +} + +func TestTextEventApplyTaggedCompositionTerminalPhases(t *testing.T) { + for _, scenario := range []struct { + name string + phase text.CompositionPhase + want string + }{ + {name: "commit", phase: text.CompositionCommit, want: "abcx"}, + {name: "cancel", phase: text.CompositionCancel, want: "abc"}, + {name: "empty-commit", phase: text.CompositionEmptyCommit, want: "abc"}, + } { + t.Run(scenario.name, func(t *testing.T) { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + TextEvent{Kind: TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "x"}.Apply(editor) + TextEvent{Kind: TextInsert, CompositionPhase: scenario.phase, Text: "ignored"}.Apply(editor) + if got := editor.String(); got != scenario.want { + t.Fatalf("%v = %q, want %q", scenario.phase, got, scenario.want) + } + if state := EditorState(editor); state.Composing || !state.TentativeComposition { + t.Fatalf("%v state = %+v", scenario.phase, state) + } + }) + } +} + +func TestTextEventApplyTaggedCompositionRejectsWithoutFallback(t *testing.T) { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 1}) + before := EditorState(editor) + cursor, _, ok := editor.TrackHistory() + if !ok { + t.Fatal("history setup refused") + } + for name, event := range map[string]TextEvent{ + "invalid phase": {Kind: TextInsert, Text: "BAD", CompositionPhase: text.CompositionPhase(255), HasReplacement: true, Replacement: text.Range{Start: 0, End: 3}}, + "negative raw": {Kind: TextInsert, Text: "BAD", CompositionPhase: text.CompositionResult, HasReplacementUTF16: true, ReplacementUTF16: text.UTF16Range{Start: -1}}, + "capacity": {Kind: TextInsert, Text: strings.Repeat("x", 4*1024*1024+1), CompositionPhase: text.CompositionUpdate}, + } { + t.Run(name, func(t *testing.T) { + event.Apply(editor) + if editor.String() != "abc" || EditorState(editor) != before || editor.CanUndo() { + t.Fatal("rejected tagged event mutated editing state") + } + if frames, latest, ok := editor.HistorySince(cursor); !ok || len(frames) != 0 || latest != cursor { + t.Fatal("rejected event changed history metadata") + } + }) + } +} + +func TestEditorStateTentativeCompositionSnapshot(t *testing.T) { + editor := text.NewEditor("abc") + if EditorState(editor).TentativeComposition || EditorState(editor).CompositionIdentity != (text.CompositionIdentity{}) { + t.Fatal("default editor reported opt-in ownership") + } + if !editor.EnableTentativeComposition() || !EditorState(editor).TentativeComposition { + t.Fatal("capability snapshot did not follow opt-in") + } + identity := editor.TentativeCompositionIdentity() + TextEvent{Kind: TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: "x"}.Apply(editor) + if state := EditorState(editor); !state.Composing || !state.TentativeComposition || state.CompositionIdentity != identity { + t.Fatalf("live state = %+v", state) + } + TextEvent{Kind: TextInsert, CompositionPhase: text.CompositionCommit}.Apply(editor) + if state := EditorState(editor); state.Composing || !state.TentativeComposition || state.CompositionIdentity != identity { + t.Fatalf("idle state = %+v", state) + } + if !editor.DisableTentativeComposition() { + t.Fatal("disable refused") + } + if state := EditorState(editor); state.Composing || state.TentativeComposition || state.CompositionIdentity != (text.CompositionIdentity{}) { + t.Fatalf("passive disabled state = %+v", state) + } +} + +func TestTextEventLegacyCancellationPreservesSelectedSource(t *testing.T) { + for _, enabled := range []bool{false, true} { + editor := text.NewEditor("abc") + if enabled && !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + TextEvent{Kind: TextSetMarked, Text: "x"}.Apply(editor) + TextEvent{Kind: TextCancelComposition}.Apply(editor) + if editor.String() != "abc" || editor.Selection() != (text.Range{Start: 1, End: 2}) || editor.CanUndo() || editor.CanRedo() || editor.CompositionActive() { + t.Fatalf("zero-phase legacy Cancel changed selected-source policy: enabled=%t state=%+v", enabled, EditorState(editor)) + } + } +} diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 02ee5a0eb..68642d24c 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -47,6 +47,15 @@ type Config struct { TitlebarHeight float32 TrafficLightScale float32 ClearColor Color + // WindowBorderColor, when set, is read on the window thread with every + // frame and names the color of the border the desktop draws around a + // custom-titlebar window. Windows 11 composites that border against what + // is behind the window rather than against the window's own pixels, so + // the background shows through it; a color that matches the window's own + // edge makes the border continuous instead. Nil, or a color that is not + // opaque, leaves the system's border. Adapters without such a border + // ignore it. + WindowBorderColor func() Color WindowMaterials Rectangles []render.Rectangle TextLabels []TextLabel @@ -217,6 +226,10 @@ type Application interface { // Quit closes every window, bypassing close requests, and ends the loop. // It is thread-safe. Quit() + // Post runs fn on the application's event-loop thread. It is thread-safe, + // runs accepted functions in the order they were posted, and never blocks. + // A function posted after the loop has ended may not run. + Post(fn func()) } // Secret store errors, shared by the three adapters. An adapter returns these (or @@ -890,7 +903,8 @@ type TextInput struct { // would take, and the hotkeys that switch it, belong to the machine on the // other side of the surface, which runs its own input method. Text events // still arrive if a method commits anyway, so a paste keeps working. - // Implemented on Windows; the other platforms have not needed it yet. + // Implemented on macOS and Windows; Linux still offers its keys to the + // input method. DisableIME bool // NavigationKeys asks Up, Down, PageUp and PageDown to reach the // application as raw key events while the field is focused, while @@ -936,11 +950,16 @@ type TextState struct { Selection text.Range Composition text.Range Composing bool + // TentativeComposition snapshots the editor's explicit opt-in capability, + // independently of whether it currently has visible marked text. + TentativeComposition bool // Redraw asks for a frame after this event although the editor itself looks // the same: the application changed something else on screen in response, a // terminal drawing typed text ahead of the server's echo. It is not part of // the mirrored editor state and is cleared again before the next event. Redraw bool + // CompositionIdentity compares ownership without retaining an editor. + CompositionIdentity text.CompositionIdentity } // TextInputPresentationChanged reports whether applying a native text event @@ -1032,6 +1051,11 @@ type TextEvent struct { Replacement text.Range HasReplacement bool Command TextCommand + // CompositionPhase is authoritative only for an enabled editor. The zero + // value preserves the legacy event route and rune replacement coordinates. + CompositionPhase text.CompositionPhase + ReplacementUTF16 text.UTF16Range + HasReplacementUTF16 bool } // TextHandler applies one native edit and returns the complete new state. @@ -1043,7 +1067,21 @@ type TextHandler func(TextEvent) (TextState, error) // update that names the active composition itself is the input method continuing // that composition: selecting the range first would end it, so the cancel // snapshot would hold the preedit instead of the text the composition replaced. -func (event TextEvent) Apply(editor *text.Editor) { +// False reports refused explicit input; legacy events return true, including +// their ordinary no-ops. +func (event TextEvent) Apply(editor *text.Editor) bool { + if event.CompositionPhase != text.CompositionNone && editor.TentativeCompositionEnabled() { + // Rejected explicit input must not be retried as a legacy mutation. + return editor.ApplyComposition(text.CompositionEvent{ + Phase: event.CompositionPhase, + Text: event.Text, + Selected: event.MarkedSelection, + Replacement: event.Replacement, + HasReplacement: event.HasReplacement, + ReplacementUTF16: event.ReplacementUTF16, + HasReplacementUTF16: event.HasReplacementUTF16, + }) + } if event.HasReplacement && !event.actsOnActiveComposition(editor) { replacement := event.Replacement if selection := editor.Selection(); selection == replacement && selection.Start != selection.End && editor.Caret() == selection.Start { @@ -1124,6 +1162,7 @@ func (event TextEvent) Apply(editor *text.Editor) { editor.DeleteToLineBoundary(true) } } + return true } // actsOnActiveComposition reports whether the event updates or commits the @@ -1173,11 +1212,13 @@ func TextHistoryCommand(event KeyEvent) (TextCommand, bool) { func EditorState(editor *text.Editor) TextState { composition, composing := editor.Composition() return TextState{ - Value: editor.String(), - Selection: editor.Selection(), - SelectionReversed: editor.Selection().Start != editor.Selection().End && editor.Caret() == editor.Selection().Start, - Composition: composition, - Composing: composing, + Value: editor.String(), + Selection: editor.Selection(), + SelectionReversed: editor.Selection().Start != editor.Selection().End && editor.Caret() == editor.Selection().Start, + Composition: composition, + Composing: composing, + TentativeComposition: editor.TentativeCompositionEnabled(), + CompositionIdentity: editor.TentativeCompositionIdentity(), } } diff --git a/internal/platform/darwin/file_icon_darwin.go b/internal/platform/darwin/file_icon_darwin.go index 2cface877..35b394af0 100644 --- a/internal/platform/darwin/file_icon_darwin.go +++ b/internal/platform/darwin/file_icon_darwin.go @@ -3,7 +3,7 @@ package darwin /* -#cgo LDFLAGS: -framework Cocoa -framework CoreGraphics +#cgo LDFLAGS: -framework Cocoa -framework CoreGraphics -framework UniformTypeIdentifiers #include #include "file_icon_darwin.h" #include "system_darwin.h" diff --git a/internal/platform/darwin/file_icon_darwin.h b/internal/platform/darwin/file_icon_darwin.h index 0b8571d26..a021ab1f9 100644 --- a/internal/platform/darwin/file_icon_darwin.h +++ b/internal/platform/darwin/file_icon_darwin.h @@ -3,10 +3,12 @@ /* Draws the icon Finder shows for the file or folder at path into out, a * pixels x pixels buffer of premultiplied BGRA, top row first, which the - * caller owns and which this function overwrites. Returns 0, or -1 with - * *error_message set to a string the caller frees with viva_system_free. Safe - * from any thread: NSWorkspace documents iconForFile: that way, and the - * drawing goes to a private bitmap context. */ + * caller owns and which this function overwrites. A path that does not exist + * asks for the icon of the type its extension names, since there is no file + * for the system to look at. Returns 0, or -1 with *error_message set to a + * string the caller frees with viva_system_free. Safe from any thread: + * NSWorkspace documents iconForFile: that way, the type lookup only reads the + * system's database, and the drawing goes to a private bitmap context. */ int viva_file_icon_bgra(const char *path, int pixels, unsigned char *out, char **error_message); #endif diff --git a/internal/platform/darwin/file_icon_darwin.m b/internal/platform/darwin/file_icon_darwin.m index b64134765..9a0a9af86 100644 --- a/internal/platform/darwin/file_icon_darwin.m +++ b/internal/platform/darwin/file_icon_darwin.m @@ -1,6 +1,7 @@ #include "file_icon_darwin.h" #import +#import #include @@ -10,6 +11,27 @@ static void viva_file_icon_fail(char **error_message, const char *message) { } } +/* viva_file_icon_image returns the icon the system has for path. A path that + * exists keeps its own icon, a bundle and a folder included. A path that does + * not exist has no file for LaunchServices to inspect, and iconForFile: would + * answer every one of them with the generic document icon; its extension still + * names a type, so ask for that type's icon instead. */ +static NSImage *viva_file_icon_image(NSString *file) { + if (![NSFileManager.defaultManager fileExistsAtPath:file]) { + NSString *extension = file.pathExtension; + if (extension.length > 0) { + UTType *type = [UTType typeWithFilenameExtension:extension]; + if (type != nil) { + NSImage *icon = [NSWorkspace.sharedWorkspace iconForContentType:type]; + if (icon != nil) { + return icon; + } + } + } + } + return [NSWorkspace.sharedWorkspace iconForFile:file]; +} + int viva_file_icon_bgra(const char *path, int pixels, unsigned char *out, char **error_message) { if (path == NULL || out == NULL || pixels <= 0) { viva_file_icon_fail(error_message, "file icon request is incomplete"); @@ -21,7 +43,7 @@ int viva_file_icon_bgra(const char *path, int pixels, unsigned char *out, char * viva_file_icon_fail(error_message, "file icon path is not valid UTF-8"); return -1; } - NSImage *icon = [NSWorkspace.sharedWorkspace iconForFile:file]; + NSImage *icon = viva_file_icon_image(file); if (icon == nil) { viva_file_icon_fail(error_message, "the system has no icon for the file"); return -1; diff --git a/internal/platform/darwin/main_menu_darwin.m b/internal/platform/darwin/main_menu_darwin.m index 59b83ef0f..2825c3126 100644 --- a/internal/platform/darwin/main_menu_darwin.m +++ b/internal/platform/darwin/main_menu_darwin.m @@ -1,4 +1,8 @@ #include "main_menu_darwin.h" +#include "menu_bar_darwin.h" + +static NSString *viva_application_name; +static NSMutableArray *viva_pending_menus; static NSMenuItem *viva_menu_item(NSMenu *menu, NSString *title, SEL action, NSString *key, NSEventModifierFlags modifiers) { @@ -8,11 +12,7 @@ return item; } -void viva_install_main_menu(NSString *applicationName) { - NSMenu *menuBar = [[[NSMenu alloc] init] autorelease]; - - NSMenuItem *applicationItem = [[[NSMenuItem alloc] init] autorelease]; - [menuBar addItem:applicationItem]; +static NSMenu *viva_application_menu(NSString *applicationName) { NSMenu *applicationMenu = [[[NSMenu alloc] init] autorelease]; viva_menu_item(applicationMenu, [@"Hide " stringByAppendingString:applicationName], @selector(hide:), @"h", NSEventModifierFlagCommand); @@ -22,20 +22,65 @@ void viva_install_main_menu(NSString *applicationName) { [applicationMenu addItem:[NSMenuItem separatorItem]]; viva_menu_item(applicationMenu, [@"Quit " stringByAppendingString:applicationName], @selector(terminate:), @"q", NSEventModifierFlagCommand); - applicationItem.submenu = applicationMenu; + return applicationMenu; +} - NSMenuItem *windowItem = [[[NSMenuItem alloc] init] autorelease]; - [menuBar addItem:windowItem]; +static NSMenu *viva_window_menu(void) { NSMenu *windowMenu = [[[NSMenu alloc] initWithTitle:@"Window"] autorelease]; viva_menu_item(windowMenu, @"Minimize", @selector(performMiniaturize:), @"m", NSEventModifierFlagCommand); viva_menu_item(windowMenu, @"Zoom", @selector(performZoom:), @"", 0); viva_menu_item(windowMenu, @"Toggle Full Screen", @selector(toggleFullScreen:), @"f", - NSEventModifierFlagControl | NSEventModifierFlagCommand); + NSEventModifierFlagCommand | NSEventModifierFlagControl); [windowMenu addItem:[NSMenuItem separatorItem]]; viva_menu_item(windowMenu, @"Bring All to Front", @selector(arrangeInFront:), @"", 0); + return windowMenu; +} + +void viva_menu_bar_begin(void) { + [viva_pending_menus release]; + viva_pending_menus = [[NSMutableArray alloc] init]; +} + +void viva_menu_bar_add(void *handle) { + if (viva_pending_menus == nil) { + viva_menu_bar_begin(); + } + if (handle != NULL) { + [viva_pending_menus addObject:(NSMenu *)handle]; + [(NSMenu *)handle release]; + } +} + +void viva_menu_bar_install(void) { + NSString *applicationName = viva_application_name != nil ? viva_application_name : @""; + NSMenu *menuBar = [[[NSMenu alloc] init] autorelease]; + + NSMenuItem *applicationItem = [[[NSMenuItem alloc] init] autorelease]; + [menuBar addItem:applicationItem]; + NSMenu *applicationMenu = viva_application_menu(applicationName); + applicationItem.submenu = applicationMenu; + + for (NSMenu *menu in viva_pending_menus) { + NSMenuItem *item = [[[NSMenuItem alloc] init] autorelease]; + item.submenu = menu; + [menuBar addItem:item]; + } + + NSMenuItem *windowItem = [[[NSMenuItem alloc] init] autorelease]; + [menuBar addItem:windowItem]; + NSMenu *windowMenu = viva_window_menu(); windowItem.submenu = windowMenu; NSApp.mainMenu = menuBar; /* AppKit lists the open windows in this menu and keeps the checkmark. */ NSApp.windowsMenu = windowMenu; + + [viva_pending_menus release]; + viva_pending_menus = nil; +} + +void viva_install_main_menu(NSString *applicationName) { + viva_application_name = [applicationName retain]; + viva_menu_bar_begin(); + viva_menu_bar_install(); } diff --git a/internal/platform/darwin/main_menu_darwin_test.go b/internal/platform/darwin/main_menu_darwin_test.go index 4bfdf17e6..4165becc9 100644 --- a/internal/platform/darwin/main_menu_darwin_test.go +++ b/internal/platform/darwin/main_menu_darwin_test.go @@ -16,7 +16,7 @@ import ( func TestMainMenuCarriesTheSystemShortcutsAndLeavesCommandW(t *testing.T) { executable := filepath.Join(t.TempDir(), "main-menu") command := exec.Command("xcrun", "clang", "-fno-objc-arc", "-Werror", - "-Wno-deprecated-declarations", "testdata/main_menu.m", "main_menu_darwin.m", + "-Wno-deprecated-declarations", "testdata/main_menu.m", "main_menu_darwin.m", "menu_bar_darwin.m", "-o", executable, "-framework", "Cocoa") if output, err := command.CombinedOutput(); err != nil { t.Fatalf("compile native main menu test: %v\n%s", err, output) diff --git a/internal/platform/darwin/menu_bar_darwin.go b/internal/platform/darwin/menu_bar_darwin.go new file mode 100644 index 000000000..ed83ac01b --- /dev/null +++ b/internal/platform/darwin/menu_bar_darwin.go @@ -0,0 +1,89 @@ +//go:build darwin + +package darwin + +/* +#include +#include "menu_bar_darwin.h" +*/ +import "C" + +import ( + "sync" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// menuBarActions is what the current menu bar's entries run, by the id the C +// menu target carries. The menu bar is built on the event-loop thread and its +// entries run there too. +var menuBarActions struct { + sync.Mutex + actions map[int32]func() +} + +//export vivaMenuAction +func vivaMenuAction(action C.int32_t) { + menuBarActions.Lock() + fn := menuBarActions.actions[int32(action)] + menuBarActions.Unlock() + if fn != nil { + fn() + } +} + +// SetMenuBar installs the application's own menus between the application menu +// and the Window menu. +func (application *nativeApplication) SetMenuBar(menus []platform.MenuBarMenu) error { + menuBarActions.Lock() + menuBarActions.actions = make(map[int32]func()) + menuBarActions.Unlock() + var next int32 + C.viva_menu_bar_begin() + for _, menu := range menus { + title := C.CString(menu.Title) + handle := C.viva_menu_create(title) + C.free(unsafe.Pointer(title)) + addMenuBarItems(handle, menu.Items, &next) + C.viva_menu_bar_add(handle) + } + C.viva_menu_bar_install() + return nil +} + +func addMenuBarItems(menu unsafe.Pointer, items []platform.MenuBarItem, next *int32) { + for _, item := range items { + if item.Separator { + C.viva_menu_add_separator(menu) + continue + } + title := C.CString(item.Title) + if len(item.Items) > 0 { + submenu := C.viva_menu_create(title) + addMenuBarItems(submenu, item.Items, next) + C.viva_menu_add_submenu(menu, title, submenu) + C.free(unsafe.Pointer(title)) + continue + } + key := C.CString(item.Key) + action := *next + *next++ + if item.OnSelect != nil { + menuBarActions.Lock() + menuBarActions.actions[action] = item.OnSelect + menuBarActions.Unlock() + } + enabled := C.int(0) + if !item.Disabled { + enabled = 1 + } + checked := C.int(0) + if item.Checked { + checked = 1 + } + C.viva_menu_add_item(menu, title, key, C.uint32_t(item.Modifiers), enabled, checked, C.int32_t(action)) + C.free(unsafe.Pointer(title)) + C.free(unsafe.Pointer(key)) + } +} diff --git a/internal/platform/darwin/menu_bar_darwin.h b/internal/platform/darwin/menu_bar_darwin.h new file mode 100644 index 000000000..2a90d3b24 --- /dev/null +++ b/internal/platform/darwin/menu_bar_darwin.h @@ -0,0 +1,23 @@ +#ifndef VIVA_MENU_BAR_DARWIN_H +#define VIVA_MENU_BAR_DARWIN_H + +#include +#include + +/* Opaque menus: the header stays usable from a cgo preamble, which cannot parse + * Objective-C headers. viva_menu_create returns a retained menu; the adders + * take void* handles, and viva_menu_bar_add hands ownership to the pending bar. */ +void *viva_menu_create(const char *title); +void viva_menu_add_item(void *menu, const char *title, const char *key, uint32_t modifiers, + int enabled, int checked, int32_t action); +void viva_menu_add_separator(void *menu); +void viva_menu_add_submenu(void *menu, const char *title, void *submenu); + +/* Collects the application's menus and installs them between the application + * menu and the Window menu. begin may be called without add; install always + * rebuilds the bar and keeps the application name last installed. */ +void viva_menu_bar_begin(void); +void viva_menu_bar_add(void *menu); +void viva_menu_bar_install(void); + +#endif diff --git a/internal/platform/darwin/menu_bar_darwin.m b/internal/platform/darwin/menu_bar_darwin.m new file mode 100644 index 000000000..91ee12711 --- /dev/null +++ b/internal/platform/darwin/menu_bar_darwin.m @@ -0,0 +1,60 @@ +#import + +#include "menu_bar_darwin.h" + +#include + +extern void vivaMenuAction(int32_t action); + +@interface VivaMenuTarget : NSObject +- (void)vivaMenuSelected:(id)sender; +@end + +@implementation VivaMenuTarget +- (void)vivaMenuSelected:(id)sender { + vivaMenuAction((int32_t)[sender tag]); +} +@end + +static VivaMenuTarget *viva_menu_target; + +static NSString *viva_menu_string(const char *value) { + return value != NULL ? [NSString stringWithUTF8String:value] : @""; +} + +void *viva_menu_create(const char *title) { + NSMenu *menu = [[NSMenu alloc] initWithTitle:viva_menu_string(title)]; + menu.autoenablesItems = NO; + return menu; +} + +void viva_menu_add_item(void *handle, const char *title, const char *key, uint32_t modifiers, + int enabled, int checked, int32_t action) { + NSMenu *menu = (NSMenu *)handle; + if (viva_menu_target == nil) { + viva_menu_target = [[VivaMenuTarget alloc] init]; + } + NSString *equivalent = key != NULL ? viva_menu_string(key) : @""; + NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:viva_menu_string(title) + action:@selector(vivaMenuSelected:) + keyEquivalent:equivalent]; + item.keyEquivalentModifierMask = (NSEventModifierFlags)modifiers; + item.target = viva_menu_target; + item.tag = action; + item.enabled = enabled != 0; + item.state = checked ? NSControlStateValueOn : NSControlStateValueOff; + [menu addItem:item]; + [item release]; +} + +void viva_menu_add_separator(void *handle) { + [(NSMenu *)handle addItem:[NSMenuItem separatorItem]]; +} + +void viva_menu_add_submenu(void *handle, const char *title, void *submenu) { + NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:viva_menu_string(title) action:nil keyEquivalent:@""]; + item.submenu = (NSMenu *)submenu; + [(NSMenu *)handle addItem:item]; + [item release]; + [(NSMenu *)submenu release]; /* the item's submenu retains it */ +} diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 89787c103..fb30178f7 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -99,6 +99,10 @@ typedef struct { int alt_sends_escape; // Presses and releases of every key, modifier keys included. int key_releases; + // The host's input method stays off the surface: no key is offered to it + // and no composition session is opened, so the keys that switch and feed + // a method belong to the machine on the other side of the surface. + int disable_ime; // Navigation keys (Up, Down, PageUp, PageDown) reach the application raw. int navigation_keys; // The field lays its rows out itself: the pointer places its caret, row diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index ef951622e..9eae3f64f 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -983,6 +983,20 @@ static BOOL viva_key_is_named(unichar character) { return [event charactersByApplyingModifiers:modifiers & ~textModifiers]; } +// viva_key_base_characters is the character a key names with no modifier +// applied: "c" for Control+Shift+C, never "C". A raw terminal key carries this +// unmodified character in KeyEvent.Text as the key's identity, with what was +// held in Modifiers and what the key types in Typed (see gfx.KeyEvent). The +// layout's own character for the key is the fallback when it has no unmodified +// one. +static NSString *viva_key_base_characters(NSEvent *event) { + NSString *characters = [event charactersByApplyingModifiers:0]; + if (characters.length == 0) { + characters = event.charactersIgnoringModifiers; + } + return characters; +} + static int viva_key_code(unichar key) { switch (key) { case NSTabCharacter: return VIVA_KEY_TAB; @@ -3837,6 +3851,10 @@ @interface VivaMetalView : NSView { CGFloat _textBaseline; // the row of that cell its preedit stands on BOOL _textAltSendsEscape; BOOL _textKeyReleases; + // The surface runs the input method of the machine it shows, not this + // one's (platform.TextInput.DisableIME): keys never reach the host's text + // system and no composition session is opened. + BOOL _textDisableIME; BOOL _interpretingKey; BOOL _interpretedConsumed; BOOL _interpretedInsert; @@ -4050,6 +4068,7 @@ - (instancetype)initWithFrame:(NSRect)frame _textBaseline = textInput.baseline; _textAltSendsEscape = textInput.alt_sends_escape != 0; _textKeyReleases = textInput.key_releases != 0; + _textDisableIME = textInput.disable_ime != 0; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyWindowChanged:) name:NSWindowDidBecomeKeyNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyWindowChanged:) name:NSWindowDidResignKeyNotification object:nil]; _dynamicTextInput = dynamicTextInputEnabled; @@ -4362,7 +4381,9 @@ - (void)mouseDown:(NSEvent *)event { [self emitPointerEvent:VIVA_POINTER_DOWN fromEvent:event]; if (_textInputEnabled && !_textTerminal && [self eventIsInsideTextInput:event]) { [self.window makeFirstResponder:self]; - [self.inputContext activate]; + if (!_textDisableIME) { + [self.inputContext activate]; + } if (_textPlaced) { // The application puts the caret where the press landed, by rows. _textSelectionDragging = NO; @@ -4577,29 +4598,32 @@ - (void)keyDown:(NSEvent *)event { int shortcutKey = characters.length == 0 ? 0 : viva_terminal_key_code([characters characterAtIndex:0]); if (_textInputEnabled && !_hasMarkedText && !control && !command && shortcutKey == 0 && characters.length > 0 && _keyEventsEnabled && _callbackHandle != 0) { - // Let the input method start a composition before considering a plain - // or Option shortcut. An unchanged direct insertion is held until the - // application declines the chord; a composition or converted commit - // goes straight to the text service and never becomes a shortcut. NSString *typed = event.characters; - _interpretingKey = YES; - _interpretedConsumed = NO; - _interpretedInsert = NO; - _interpretedPlain = typed; - // handleEvent also reports asynchronous ownership: an input method - // can take the first key before it publishes any marked text. - NSTextInputContext *context = self.inputContext; - BOOL interpreted = context != nil && [context handleEvent:event]; - if (!interpreted) { - [self interpretKeyEvent:event]; - } - _interpretingKey = NO; - _interpretedPlain = nil; - if (_interpretedConsumed || _hasMarkedText || (interpreted && !_interpretedInsert)) { - return; + NSRange replacement = NSMakeRange(NSNotFound, 0); + if (!_textDisableIME) { + // Let the input method start a composition before considering a plain + // or Option shortcut. An unchanged direct insertion is held until the + // application declines the chord; a composition or converted commit + // goes straight to the text service and never becomes a shortcut. + _interpretingKey = YES; + _interpretedConsumed = NO; + _interpretedInsert = NO; + _interpretedPlain = typed; + // handleEvent also reports asynchronous ownership: an input method + // can take the first key before it publishes any marked text. + NSTextInputContext *context = self.inputContext; + BOOL interpreted = context != nil && [context handleEvent:event]; + if (!interpreted) { + [self interpretKeyEvent:event]; + } + _interpretingKey = NO; + _interpretedPlain = nil; + if (_interpretedConsumed || _hasMarkedText || (interpreted && !_interpretedInsert)) { + return; + } + replacement = _interpretedReplacement; } NSData *base = [characters dataUsingEncoding:NSUTF8StringEncoding]; - NSRange replacement = _interpretedReplacement; if (base.length > 0 && vivaShortcutEvent(_callbackHandle, self, 0, viva_modifier_flags(event.modifierFlags), event.isARepeat ? 1 : 0, base.bytes, base.length)) { return; @@ -4611,7 +4635,7 @@ - (void)keyDown:(NSEvent *)event { /* The key's text stays the unshifted character, as the rest of * the keyboard protocol expects; what the key types goes to * typed. */ - NSData *keyText = [[characters lowercaseString] dataUsingEncoding:NSUTF8StringEncoding]; + NSData *keyText = [viva_key_base_characters(event) dataUsingEncoding:NSUTF8StringEncoding]; NSData *typedText = alt ? nil : [typed dataUsingEncoding:NSUTF8StringEncoding]; vivaRawKeyEvent(_callbackHandle, self, 0, viva_modifier_flags(event.modifierFlags), event.isARepeat ? 1 : 0, (unsigned int)event.keyCode + 1, keyText.bytes, keyText.length, @@ -4620,6 +4644,13 @@ - (void)keyDown:(NSEvent *)event { vivaKeyEvent(_callbackHandle, self, 0, viva_modifier_flags(event.modifierFlags), event.isARepeat ? 1 : 0, base.bytes, base.length); } + } else if (_textDisableIME) { + // The host's input method never saw the key, so what the layout + // types is the key's text: an ordinary field takes it the way one + // on a platform whose raw keyboard delivers the character without + // a method in between. + [self emitTextKind:VIVA_TEXT_INSERT text:typed selectedRange:NSMakeRange(0, 0) + replacementRange:NSMakeRange(NSNotFound, 0) command:0]; } else if (_interpretedInsert) { [self emitTextKind:VIVA_TEXT_INSERT text:typed selectedRange:NSMakeRange(0, 0) replacementRange:replacement command:0]; @@ -4671,9 +4702,11 @@ - (void)keyDown:(NSEvent *)event { alt, _textAltSendsEscape || _textKeyReleases)) { // For a chord the application wants the character itself ("c" for - // Control+C); named keys carry no text. - NSData *text = named != 0 || characters.length == 0 ? nil - : [characters dataUsingEncoding:NSUTF8StringEncoding]; + // Control+C, and for Control+Shift+C too: Shift is in Modifiers); + // named keys carry no text. + NSString *chord = viva_key_base_characters(event); + NSData *text = named != 0 || chord.length == 0 ? nil + : [chord dataUsingEncoding:NSUTF8StringEncoding]; viva_key_event_count++; if (_textKeyReleases) { vivaRawKeyEvent(_callbackHandle, self, named, viva_modifier_flags(event.modifierFlags), @@ -4694,14 +4727,16 @@ - (void)keyDown:(NSEvent *)event { } if (_textKeyReleases && !_hasMarkedText && characters.length > 0) { NSString *typed = event.characters; - _interpretingKey = YES; _interpretedConsumed = NO; - _interpretedPlain = typed; - [self interpretKeyEvent:event]; - _interpretingKey = NO; - _interpretedPlain = nil; + if (!_textDisableIME) { + _interpretingKey = YES; + _interpretedPlain = typed; + [self interpretKeyEvent:event]; + _interpretingKey = NO; + _interpretedPlain = nil; + } if (!_interpretedConsumed && !_hasMarkedText) { - NSData *base = [[characters lowercaseString] dataUsingEncoding:NSUTF8StringEncoding]; + NSData *base = [viva_key_base_characters(event) dataUsingEncoding:NSUTF8StringEncoding]; NSData *typedText = [typed dataUsingEncoding:NSUTF8StringEncoding]; viva_key_event_count++; vivaRawKeyEvent(_callbackHandle, self, 0, viva_modifier_flags(event.modifierFlags), @@ -4710,14 +4745,17 @@ - (void)keyDown:(NSEvent *)event { } return; } - [self interpretKeyEvent:event]; + if (!_textDisableIME) { + [self interpretKeyEvent:event]; + } return; } int key = characters.length == 0 ? 0 : viva_key_code([characters characterAtIndex:0]); if (key == 0 && characters.length > 0) { key = viva_terminal_key_code([characters characterAtIndex:0]); } - if (!viva_text_input_row_key_is_raw(_textInputEnabled && _textPlaced, _hasMarkedText, key, command) && + if (!_textDisableIME && + !viva_text_input_row_key_is_raw(_textInputEnabled && _textPlaced, _hasMarkedText, key, command) && !viva_text_input_navigation_key_is_raw(_textInputEnabled && _textNavigationKeys, _hasMarkedText, key) && viva_text_input_should_interpret_key(_textInputEnabled, _textInputMultiline, _hasMarkedText, key)) { [self interpretKeyEvent:event]; @@ -5038,6 +5076,7 @@ - (void)shutdownTextInput { _hasMarkedText = NO; _textAltSendsEscape = NO; _textKeyReleases = NO; + _textDisableIME = NO; } - (void)detachCallbacks { @@ -5517,6 +5556,7 @@ - (int)updateTextInput:(viva_text_input_config)textInput keepComposition:(BOOL)k _textBaseline = 0; _textAltSendsEscape = NO; _textKeyReleases = NO; + _textDisableIME = NO; [_text release]; _text = [@"" retain]; [_textColor release]; @@ -5555,7 +5595,12 @@ - (int)updateTextInput:(viva_text_input_config)textInput keepComposition:(BOOL)k NSMakeRange(textInput.marked_start, textInput.marked_length), _text.length ); - _hasMarkedText = textInput.has_marked_text != 0; + _textAltSendsEscape = textInput.alt_sends_escape != 0; + _textKeyReleases = textInput.key_releases != 0; + _textDisableIME = textInput.disable_ime != 0; + // A surface that runs the other machine's input method has no composition + // of this one to mirror. + _hasMarkedText = textInput.has_marked_text != 0 && !_textDisableIME; _textInputMultiline = textInput.multiline != 0; _textPlaced = textInput.placed != 0; _textNavigationKeys = textInput.navigation_keys != 0; @@ -5567,8 +5612,6 @@ - (int)updateTextInput:(viva_text_input_config)textInput keepComposition:(BOOL)k _textMonoFace = textInput.mono_face; _textCellWidth = textInput.cell_width; _textBaseline = textInput.baseline; - _textAltSendsEscape = textInput.alt_sends_escape != 0; - _textKeyReleases = textInput.key_releases != 0; _textInputEnabled = YES; [self syncSecureEventInput]; _caretVisible = YES; @@ -5578,13 +5621,19 @@ - (int)updateTextInput:(viva_text_input_config)textInput keepComposition:(BOOL)k if (keep) { // The input context stays active and composing; only where it points // changed. - [self.inputContext invalidateCharacterCoordinates]; + if (!_textDisableIME) { + [self.inputContext invalidateCharacterCoordinates]; + } [self restartCaretBlink]; return 0; } [self.window makeFirstResponder:self]; - [self.inputContext activate]; - [self.inputContext invalidateCharacterCoordinates]; + if (!_textDisableIME) { + // A surface that runs the other machine's input method opens no + // session here: the method would compose the keys that belong there. + [self.inputContext activate]; + [self.inputContext invalidateCharacterCoordinates]; + } [self restartCaretBlink]; return 0; } diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 39377779c..ea29261b9 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -273,6 +273,7 @@ func (state *runState) textInputKeepsComposition(next *TextInput) bool { state.textInput.Target == next.Target && state.textInput.Multiline == next.Multiline && state.textInput.Secure == next.Secure && state.textInput.Terminal == next.Terminal && state.textInput.Placed == next.Placed && + state.textInput.DisableIME == next.DisableIME && state.textState == next.State.WithoutRedraw() } @@ -281,7 +282,7 @@ func sameTextInputPresentation(left, right TextInput) bool { left.Width == right.Width && left.Height == right.Height && left.FontSize == right.FontSize && left.FontGeneration == right.FontGeneration && left.Alignment == right.Alignment && left.Layer == right.Layer && left.Multiline == right.Multiline && left.Secure == right.Secure && - left.Terminal == right.Terminal && left.MonoFace == right.MonoFace && left.AltSendsEscape == right.AltSendsEscape && left.KeyReleases == right.KeyReleases && left.Color == right.Color && + left.Terminal == right.Terminal && left.MonoFace == right.MonoFace && left.AltSendsEscape == right.AltSendsEscape && left.KeyReleases == right.KeyReleases && left.DisableIME == right.DisableIME && left.Color == right.Color && left.CopyOverride == right.CopyOverride && left.State == right.State } @@ -851,6 +852,7 @@ func makeNativeTextInput(input TextInput, value unsafe.Pointer) C.viva_text_inpu baseline: C.float(input.Baseline), alt_sends_escape: C.int(boolInt(input.AltSendsEscape)), key_releases: C.int(boolInt(input.KeyReleases)), + disable_ime: C.int(boolInt(input.DisableIME)), navigation_keys: C.int(boolInt(input.NavigationKeys)), placed: C.int(boolInt(input.Placed)), layer: C.uint16_t(input.Layer), diff --git a/internal/platform/darwin/post_darwin.go b/internal/platform/darwin/post_darwin.go new file mode 100644 index 000000000..cb569c759 --- /dev/null +++ b/internal/platform/darwin/post_darwin.go @@ -0,0 +1,46 @@ +//go:build darwin + +package darwin + +/* +#include "post_darwin.h" +*/ +import "C" + +import "sync" + +// postQueue is the work other goroutines posted to the event-loop thread. One +// application runs in a process, so one queue is enough; the lock defines the +// order concurrent callers are accepted in. +var postQueue struct { + sync.Mutex + pending []func() +} + +// Post runs fn on the main queue. It never blocks. +func Post(fn func()) { + if fn == nil { + return + } + postQueue.Lock() + postQueue.pending = append(postQueue.pending, fn) + postQueue.Unlock() + C.viva_application_post() +} + +//export vivaApplicationDrain +func vivaApplicationDrain() { + for { + postQueue.Lock() + if len(postQueue.pending) == 0 { + postQueue.Unlock() + return + } + fn := postQueue.pending[0] + postQueue.pending = postQueue.pending[1:] + postQueue.Unlock() + fn() + } +} + +func (application *nativeApplication) Post(fn func()) { Post(fn) } diff --git a/internal/platform/darwin/post_darwin.h b/internal/platform/darwin/post_darwin.h new file mode 100644 index 000000000..f4f4c5cf1 --- /dev/null +++ b/internal/platform/darwin/post_darwin.h @@ -0,0 +1,7 @@ +#ifndef VIVA_POST_DARWIN_H +#define VIVA_POST_DARWIN_H + +/* Wakes the main queue and drains the functions the Go side posted to it. */ +void viva_application_post(void); + +#endif diff --git a/internal/platform/darwin/post_darwin.m b/internal/platform/darwin/post_darwin.m new file mode 100644 index 000000000..6a490a354 --- /dev/null +++ b/internal/platform/darwin/post_darwin.m @@ -0,0 +1,11 @@ +#import + +#include "post_darwin.h" + +extern void vivaApplicationDrain(void); + +void viva_application_post(void) { + dispatch_async(dispatch_get_main_queue(), ^{ + vivaApplicationDrain(); + }); +} diff --git a/internal/platform/darwin/post_darwin_test.go b/internal/platform/darwin/post_darwin_test.go new file mode 100644 index 000000000..d21847b73 --- /dev/null +++ b/internal/platform/darwin/post_darwin_test.go @@ -0,0 +1,33 @@ +//go:build darwin + +package darwin + +import "testing" + +func TestPostedFunctionsDrainInOrder(t *testing.T) { + postQueue.Lock() + postQueue.pending = nil + postQueue.Unlock() + var seen []int + Post(func() { seen = append(seen, 1) }) + Post(func() { seen = append(seen, 2) }) + vivaApplicationDrain() + if len(seen) != 2 || seen[0] != 1 || seen[1] != 2 { + t.Fatalf("seen = %v, want [1 2]", seen) + } +} + +func TestAFunctionPostedWhileDrainingRunsInTheSameDrain(t *testing.T) { + postQueue.Lock() + postQueue.pending = nil + postQueue.Unlock() + var seen []int + Post(func() { + seen = append(seen, 1) + Post(func() { seen = append(seen, 2) }) + }) + vivaApplicationDrain() + if len(seen) != 2 || seen[0] != 1 || seen[1] != 2 { + t.Fatalf("seen = %v, want [1 2]", seen) + } +} diff --git a/internal/platform/darwin/proxy_darwin.go b/internal/platform/darwin/proxy_darwin.go new file mode 100644 index 000000000..043e02b63 --- /dev/null +++ b/internal/platform/darwin/proxy_darwin.go @@ -0,0 +1,50 @@ +//go:build darwin + +package darwin + +/* +#cgo LDFLAGS: -framework CFNetwork -framework CoreFoundation +#include +#include "proxy_darwin.h" +#include "system_darwin.h" +*/ +import "C" + +import ( + "errors" + "fmt" + "net/url" + "unsafe" +) + +// ErrProxyUnavailable reports that the system's proxy policy could not be +// evaluated: it is a PAC script, or CFNetwork failed. +var ErrProxyUnavailable = errors.New("darwin: the system proxy settings cannot be read") + +// SystemProxy asks CFNetwork which proxy the system selects for target. +func SystemProxy(target string) (*url.URL, error) { + cTarget := C.CString(target) + defer C.free(unsafe.Pointer(cTarget)) + var value, nativeError *C.char + status := C.viva_system_proxy(cTarget, &value, &nativeError) + switch status { + case 0: + return nil, nil + case 1: + defer C.viva_system_free(unsafe.Pointer(value)) + proxy, err := url.Parse(C.GoString(value)) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrProxyUnavailable, err) + } + return proxy, nil + case 2: + return nil, fmt.Errorf("%w: the system uses a proxy auto-configuration script", ErrProxyUnavailable) + default: + message := "the system proxy settings could not be read" + if nativeError != nil { + message = C.GoString(nativeError) + C.viva_system_free(unsafe.Pointer(nativeError)) + } + return nil, fmt.Errorf("%w: %s", ErrProxyUnavailable, message) + } +} diff --git a/internal/platform/darwin/proxy_darwin.h b/internal/platform/darwin/proxy_darwin.h new file mode 100644 index 000000000..e58f22888 --- /dev/null +++ b/internal/platform/darwin/proxy_darwin.h @@ -0,0 +1,10 @@ +#ifndef VIVA_PROXY_DARWIN_H +#define VIVA_PROXY_DARWIN_H + +// viva_system_proxy asks CFNetwork which proxy the system's settings select for +// target (an absolute URL). Status: 0 direct (no proxy), 1 proxy in *value +// (free with viva_system_free), 2 the policy is a PAC script, which this +// function does not evaluate, -1 failure with *error_message. +int viva_system_proxy(const char *target, char **value, char **error_message); + +#endif diff --git a/internal/platform/darwin/proxy_darwin.m b/internal/platform/darwin/proxy_darwin.m new file mode 100644 index 000000000..eff703cdd --- /dev/null +++ b/internal/platform/darwin/proxy_darwin.m @@ -0,0 +1,93 @@ +#import +#import + +#include +#include +#include + +#include "proxy_darwin.h" + +static char *viva_proxy_copy_utf8(CFStringRef value) { + if (value == NULL) { + return NULL; + } + CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value), kCFStringEncodingUTF8) + 1; + char *buffer = calloc((size_t)length, 1); + if (buffer == NULL) { + return NULL; + } + if (!CFStringGetCString(value, buffer, length, kCFStringEncodingUTF8)) { + free(buffer); + return NULL; + } + return buffer; +} + +static void viva_proxy_set_error(char **error_message, const char *message) { + if (error_message != NULL) { + *error_message = strdup(message); + } +} + +int viva_system_proxy(const char *target, char **value, char **error_message) { + if (target == NULL || value == NULL) { + viva_proxy_set_error(error_message, "the target is missing"); + return -1; + } + *value = NULL; + CFURLRef url = CFURLCreateWithBytes(kCFAllocatorDefault, (const UInt8 *)target, (CFIndex)strlen(target), + kCFStringEncodingUTF8, NULL); + if (url == NULL) { + viva_proxy_set_error(error_message, "the target is not a UTF-8 URL"); + return -1; + } + CFDictionaryRef settings = CFNetworkCopySystemProxySettings(); + CFArrayRef proxies = CFNetworkCopyProxiesForURL(url, settings); + CFRelease(url); + if (settings != NULL) { + CFRelease(settings); + } + if (proxies == NULL || CFArrayGetCount(proxies) == 0) { + if (proxies != NULL) { + CFRelease(proxies); + } + return 0; + } + CFDictionaryRef proxy = (CFDictionaryRef)CFArrayGetValueAtIndex(proxies, 0); + CFStringRef type = (CFStringRef)CFDictionaryGetValue(proxy, kCFProxyTypeKey); + int status = 0; + if (type != NULL && CFStringCompare(type, kCFProxyTypeNone, 0) != kCFCompareEqualTo) { + if (CFStringCompare(type, kCFProxyTypeAutoConfigurationURL, 0) == 0 || + CFStringCompare(type, kCFProxyTypeAutoConfigurationJavaScript, 0) == 0) { + status = 2; + } else { + CFStringRef host = (CFStringRef)CFDictionaryGetValue(proxy, kCFProxyHostNameKey); + CFNumberRef port = (CFNumberRef)CFDictionaryGetValue(proxy, kCFProxyPortNumberKey); + char *host_text = viva_proxy_copy_utf8(host); + int port_value = 0; + if (port != NULL) { + CFNumberGetValue(port, kCFNumberIntType, &port_value); + } + if (host_text == NULL) { + viva_proxy_set_error(error_message, "the selected proxy has no host"); + status = -1; + } else { + const char *scheme = CFStringCompare(type, kCFProxyTypeSOCKS, 0) == 0 ? "socks5" : "http"; + char buffer[1024]; + if (port_value > 0) { + snprintf(buffer, sizeof buffer, "%s://%s:%d", scheme, host_text, port_value); + } else { + snprintf(buffer, sizeof buffer, "%s://%s", scheme, host_text); + } + *value = strdup(buffer); + free(host_text); + status = *value == NULL ? -1 : 1; + if (status < 0) { + viva_proxy_set_error(error_message, "the proxy URL could not be allocated"); + } + } + } + } + CFRelease(proxies); + return status; +} diff --git a/internal/platform/darwin/proxy_darwin_test.go b/internal/platform/darwin/proxy_darwin_test.go new file mode 100644 index 000000000..959de7e98 --- /dev/null +++ b/internal/platform/darwin/proxy_darwin_test.go @@ -0,0 +1,17 @@ +//go:build darwin + +package darwin + +import "testing" + +// The machine this runs on may or may not have a proxy; what must hold is that +// CFNetwork answers, and that an answer is a URL or a policy this package names. +func TestSystemProxyAnswersForAURL(t *testing.T) { + proxy, err := SystemProxy("https://example.com/") + if err != nil { + t.Skipf("the system's proxy policy is not readable here: %v", err) + } + if proxy != nil && proxy.Host == "" { + t.Fatalf("proxy = %+v, want a host", proxy) + } +} diff --git a/internal/platform/darwin/sleep_darwin.go b/internal/platform/darwin/sleep_darwin.go new file mode 100644 index 000000000..fee0f6421 --- /dev/null +++ b/internal/platform/darwin/sleep_darwin.go @@ -0,0 +1,42 @@ +//go:build darwin + +package darwin + +/* +#cgo LDFLAGS: -framework IOKit +#include +#include "sleep_darwin.h" +#include "system_darwin.h" +*/ +import "C" + +import ( + "errors" + "fmt" + "sync" + "unsafe" +) + +// ErrSleepUnavailable reports that IOKit refused the assertion. +var ErrSleepUnavailable = errors.New("darwin: sleep inhibition is unavailable") + +// PreventSleep asks IOKit to keep the machine out of idle sleep until release +// runs. The assertion is what pmset -g assertions lists beside the reason. +func PreventSleep(reason string) (release func(), err error) { + cReason := C.CString(reason) + defer C.free(unsafe.Pointer(cReason)) + var assertion C.uint32_t + var nativeError *C.char + if status := C.viva_system_keep_awake(cReason, &assertion, &nativeError); status != 0 { + text := "IOKit refused the assertion" + if nativeError != nil { + text = C.GoString(nativeError) + C.viva_system_free(unsafe.Pointer(nativeError)) + } + return nil, fmt.Errorf("%w: %s", ErrSleepUnavailable, text) + } + var once sync.Once + return func() { + once.Do(func() { C.viva_system_release_awake(assertion) }) + }, nil +} diff --git a/internal/platform/darwin/sleep_darwin.h b/internal/platform/darwin/sleep_darwin.h new file mode 100644 index 000000000..d407b1158 --- /dev/null +++ b/internal/platform/darwin/sleep_darwin.h @@ -0,0 +1,12 @@ +#ifndef VIVA_SLEEP_DARWIN_H +#define VIVA_SLEEP_DARWIN_H + +#include + +// Asks IOKit to keep the machine out of idle sleep until the assertion is +// released. The assertion id is written to *assertion on success; on failure +// *error_message holds a description to free with viva_system_free. +int viva_system_keep_awake(const char *reason, uint32_t *assertion, char **error_message); +void viva_system_release_awake(uint32_t assertion); + +#endif diff --git a/internal/platform/darwin/sleep_darwin.m b/internal/platform/darwin/sleep_darwin.m new file mode 100644 index 000000000..27911a5ca --- /dev/null +++ b/internal/platform/darwin/sleep_darwin.m @@ -0,0 +1,44 @@ +#import +#import + +#include +#include + +#include "sleep_darwin.h" + +int viva_system_keep_awake(const char *reason, uint32_t *assertion, char **error_message) { + if (assertion == NULL) { + if (error_message != NULL) { + *error_message = strdup("the assertion output is missing"); + } + return -1; + } + CFStringRef name = CFStringCreateWithCString( + kCFAllocatorDefault, reason != NULL ? reason : "", kCFStringEncodingUTF8); + if (name == NULL) { + if (error_message != NULL) { + *error_message = strdup("the reason is not UTF-8"); + } + return -1; + } + IOPMAssertionID identifier = kIOPMNullAssertionID; + IOReturn status = IOPMAssertionCreateWithName( + kIOPMAssertionTypePreventUserIdleSystemSleep, kIOPMAssertionLevelOn, name, &identifier); + CFRelease(name); + if (status != kIOReturnSuccess) { + if (error_message != NULL) { + char buffer[64]; + snprintf(buffer, sizeof buffer, "IOPMAssertionCreateWithName failed (0x%08x)", status); + *error_message = strdup(buffer); + } + return -1; + } + *assertion = (uint32_t)identifier; + return 0; +} + +void viva_system_release_awake(uint32_t assertion) { + if (assertion != kIOPMNullAssertionID) { + IOPMAssertionRelease((IOPMAssertionID)assertion); + } +} diff --git a/internal/platform/darwin/sleep_darwin_test.go b/internal/platform/darwin/sleep_darwin_test.go new file mode 100644 index 000000000..578dd8868 --- /dev/null +++ b/internal/platform/darwin/sleep_darwin_test.go @@ -0,0 +1,14 @@ +//go:build darwin + +package darwin + +import "testing" + +func TestPreventSleepHoldsAnAssertion(t *testing.T) { + release, err := PreventSleep("viva test: sleep inhibition") + if err != nil { + t.Fatal(err) + } + release() + release() +} diff --git a/internal/platform/darwin/testdata/main_menu.m b/internal/platform/darwin/testdata/main_menu.m index 5df5012fb..ca4e04563 100644 --- a/internal/platform/darwin/testdata/main_menu.m +++ b/internal/platform/darwin/testdata/main_menu.m @@ -1,12 +1,21 @@ /* The menu bar every Viva application has: the standard application and Window * items carry AppKit's own selectors and shortcuts, so Command+H hides, Command+M - * minimizes, and Command+W is left to the application. */ + * minimizes, and Command+W is left to the application. The application's own + * menus sit between them, with their key equivalents, enablement, check state + * and actions. */ #import #include "../main_menu_darwin.h" +#include "../menu_bar_darwin.h" static int failures; +static int32_t last_action; + +/* The Go side normally exports this; the harness records what a choice runs. */ +void vivaMenuAction(int32_t action) { + last_action = action; +} static NSMenuItem *find(NSMenu *menu, NSString *key, NSEventModifierFlags modifiers) { for (NSMenuItem *top in menu.itemArray) { @@ -19,6 +28,17 @@ return nil; } +static NSMenuItem *findTitle(NSMenu *menu, NSString *title) { + for (NSMenuItem *top in menu.itemArray) { + for (NSMenuItem *item in top.submenu.itemArray) { + if ([item.title isEqualToString:title]) { + return item; + } + } + } + return nil; +} + static void expectShortcut(NSMenu *menu, NSString *key, NSEventModifierFlags modifiers, SEL action, NSString *what) { NSMenuItem *item = find(menu, key, modifiers); if (item == nil || item.action != action || item.target != nil) { @@ -27,6 +47,22 @@ static void expectShortcut(NSMenu *menu, NSString *key, NSEventModifierFlags mod } } +static void build_application_menus(void) { + viva_menu_bar_begin(); + void *file = viva_menu_create("File"); + viva_menu_add_item(file, "New Window", "n", NSEventModifierFlagCommand, 1, 0, 7); + viva_menu_add_item(file, "Disabled Entry", "", 0, 0, 0, 8); + viva_menu_add_separator(file); + void *recent = viva_menu_create("Open Recent"); + viva_menu_add_item(recent, "alpha", "", 0, 1, 0, 9); + viva_menu_add_submenu(file, "Open Recent", recent); + viva_menu_bar_add(file); + void *view = viva_menu_create("View"); + viva_menu_add_item(view, "Show Sidebar", "", 0, 1, 1, 10); + viva_menu_bar_add(view); + viva_menu_bar_install(); +} + int main(void) { @autoreleasepool { [NSApplication sharedApplication]; @@ -44,15 +80,54 @@ int main(void) { fprintf(stderr, "Command+W is a menu key equivalent, so the application never sees it\n"); failures++; } - if (NSApp.windowsMenu == nil) { - fprintf(stderr, "the Window menu is not registered with AppKit\n"); - failures++; - } NSMenuItem *hide = menu.itemArray[0].submenu.itemArray[0]; if (![hide.title isEqualToString:@"Hide Demo"]) { fprintf(stderr, "Hide title = %s\n", [hide.title UTF8String]); failures++; } + + build_application_menus(); + menu = NSApp.mainMenu; + if (menu.itemArray.count != 4) { + fprintf(stderr, "menu bar has %lu top-level menus, want 4\n", (unsigned long)menu.itemArray.count); + failures++; + } + if (![[menu.itemArray[1] submenu].title isEqualToString:@"File"] || + ![[menu.itemArray[2] submenu].title isEqualToString:@"View"]) { + fprintf(stderr, "the application menus are not between the application and Window menus\n"); + failures++; + } + NSMenuItem *newWindow = findTitle(menu, @"New Window"); + if (newWindow == nil || ![newWindow.keyEquivalent isEqualToString:@"n"] || + newWindow.keyEquivalentModifierMask != command || newWindow.tag != 7 || !newWindow.enabled) { + fprintf(stderr, "the application item did not carry its shortcut, tag and enablement\n"); + failures++; + } + NSMenuItem *disabled = findTitle(menu, @"Disabled Entry"); + if (disabled == nil || disabled.enabled) { + fprintf(stderr, "a disabled entry was enabled\n"); + failures++; + } + NSMenuItem *checked = findTitle(menu, @"Show Sidebar"); + if (checked == nil || checked.state != NSControlStateValueOn) { + fprintf(stderr, "a checked entry was not checked\n"); + failures++; + } + NSMenuItem *recent = findTitle(menu, @"Open Recent"); + if (recent == nil || recent.submenu == nil || recent.submenu.itemArray.count != 1) { + fprintf(stderr, "a submenu was not installed\n"); + failures++; + } + last_action = -1; + [newWindow.target performSelector:newWindow.action withObject:newWindow]; + if (last_action != 7) { + fprintf(stderr, "choosing the item ran action %d, want 7\n", last_action); + failures++; + } + if (NSApp.windowsMenu == nil) { + fprintf(stderr, "the Window menu is not registered with AppKit\n"); + failures++; + } } return failures == 0 ? 0 : 1; } diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m index ceaa7add6..2d80e91ea 100644 --- a/internal/platform/darwin/testdata/text_selection.m +++ b/internal/platform/darwin/testdata/text_selection.m @@ -39,7 +39,26 @@ void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repe rawCount++; } } -void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} +// Raw presses delivered with their identity and the text they type, which is +// what a surface showing another machine's desktop takes. +static int rawEventCount; +static int rawEventKeys[16]; +static char rawEventText[16][8]; +static char rawEventTyped[16][8]; +void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) { + if (rawEventCount < 16) { + rawEventKeys[rawEventCount] = key; + memset(rawEventText[rawEventCount], 0, sizeof(rawEventText[0])); + memset(rawEventTyped[rawEventCount], 0, sizeof(rawEventTyped[0])); + if (utf8 != NULL) { + memcpy(rawEventText[rawEventCount], utf8, MIN(utf8Length, sizeof(rawEventText[0]) - 1)); + } + if (typed != NULL) { + memcpy(rawEventTyped[rawEventCount], typed, MIN(typedLength, sizeof(rawEventTyped[0]) - 1)); + } + rawEventCount++; + } +} void vivaWindowActivated(uintptr_t handle) {} void vivaFocusLost(uintptr_t handle, void *view) {} // The terminal's table, reduced to what these tests use: CJK ideographs take two cells, @@ -85,6 +104,7 @@ @interface RecordingInputContext : NSObject { NSUInteger activations; NSUInteger deactivations; NSUInteger invalidations; + NSUInteger handles; } @end @@ -93,6 +113,7 @@ - (void)discardMarkedText { discards++; } - (void)activate { activations++; } - (void)deactivate { deactivations++; } - (void)invalidateCharacterCoordinates { invalidations++; } +- (BOOL)handleEvent:(NSEvent *)event { handles++; return NO; } @end @interface SelectionView : VivaMetalView { @@ -136,6 +157,8 @@ - (void)beginComposition; - (void)setTerminal:(BOOL)value; - (void)setCopyOverride:(NSString *)value enabled:(BOOL)enabled; - (void)setCellWidth:(CGFloat)value; +- (void)setKeyReleases:(BOOL)value; +- (void)setDisableIME:(BOOL)value; - (void)enableKeyCallbacks; - (void)endComposition; - (BOOL)composing; @@ -180,6 +203,8 @@ - (void)resetText:(NSString *)value { lastText = nil; _textSecure = NO; _textInputMultiline = NO; + _textKeyReleases = NO; + _textDisableIME = NO; fakeMarkedMode = 0; } - (NSTextInputContext *)inputContext { return (NSTextInputContext *)recordingContext; } @@ -234,6 +259,8 @@ - (BOOL)hasCaretTimer { return _caretTimer != nil; } - (void)beginComposition { _hasMarkedText = YES; } - (void)setTerminal:(BOOL)value { _textTerminal = value; } - (void)setCellWidth:(CGFloat)value { _textCellWidth = value; } +- (void)setKeyReleases:(BOOL)value { _textKeyReleases = value; } +- (void)setDisableIME:(BOOL)value { _textDisableIME = value; } - (void)enableKeyCallbacks { _callbackHandle = 1; _keyEventsEnabled = YES; } - (void)endComposition { _hasMarkedText = NO; } - (BOOL)composing { return _hasMarkedText; } @@ -1101,6 +1128,79 @@ int main(void) { view->recordEdits = NO; viva_test_pasteboard = nil; + // A surface that shows another machine's desktop keeps the host's input + // method off its keys (DisableIME): a printable key is the remote's own + // key, delivered raw with its identity and what it types, and no + // composition is opened for it. + RecordingInputContext *method = [[RecordingInputContext alloc] init]; + view->recordingContext = method; + [view resetText:@""]; + [view setTerminal:YES]; + [view setKeyReleases:YES]; + [view setDisableIME:YES]; + [view enableKeyCallbacks]; + view->recordEdits = YES; + NSUInteger desktopEdits = view->editEvents; + rawEventCount = 0; + [view keyDown:keyEvent(@"z", 0)]; + assert(rawEventCount == 1); + // The key's identity is the layout's own base character, which a + // synthetic event has no physical key to resolve here; what it types + // is the event's character. + assert(strcmp(rawEventTyped[0], "z") == 0); + assert(method->handles == 0); + assert(view->editEvents == desktopEdits); + assert(![view composing]); + // A named key keeps going to the application, and a composition that + // was in flight is impossible: nothing here would own a key. + rawEventCount = 0; + [view keyDown:keyEvent(@"\r", 0)]; + assert(rawEventCount == 1 && rawEventKeys[0] == VIVA_KEY_ENTER); + assert(view->editEvents == desktopEdits); + // With the method back on, the same key reaches it again. + [view setDisableIME:NO]; + rawEventCount = 0; + [view keyDown:keyEvent(@"z", 0)]; + assert(method->handles > 0); + [view setKeyReleases:NO]; + [view setTerminal:NO]; + view->recordEdits = NO; + view->recordingContext = nil; + [method release]; + + // No composition session opens for such a surface, and one that does not + // ask for that still activates the input context. + { + RecordingInputContext *context = [[RecordingInputContext alloc] init]; + view->recordingContext = context; + [view resetText:@""]; + [view setEditing:NO]; + viva_text_input_config remote = {0}; + remote.enabled = 1; + remote.x = 40; + remote.y = 80; + remote.width = 260; + remote.height = 32; + remote.font_size = 16; + remote.alpha = 1; + remote.terminal = 1; + remote.key_releases = 1; + remote.disable_ime = 1; + // An application that mirrors a composition anyway must not make + // the host's method open one here. + remote.has_marked_text = 1; + assert([view updateTextInput:remote] == 0); + assert(context->activations == 0 && context->deactivations == 0); + assert(![view hasMarkedText]); + remote.disable_ime = 0; + remote.has_marked_text = 0; + assert([view updateTextInput:remote] == 0); + assert(context->activations == 1 && context->deactivations == 1); + assert([view updateTextInput:(viva_text_input_config){0}] == 0); + view->recordingContext = nil; + [context release]; + } + // A terminal's preedit is laid on the terminal's cells, as its grid is: a wide // character takes two, a combining mark none, and the caret, the hit test and the // candidate window follow them, not the advances of the font. diff --git a/internal/platform/darwin/text_italic_regression_test.go b/internal/platform/darwin/text_italic_regression_test.go index 7ede15dd3..1e5723eef 100644 --- a/internal/platform/darwin/text_italic_regression_test.go +++ b/internal/platform/darwin/text_italic_regression_test.go @@ -103,3 +103,51 @@ func TestItalicLabelSlantsGlyphsOfFontsWithoutAnItalicFace(t *testing.T) { } } } + +// A fixed-pitch grid run carries its own slant, as a code editor's comment does: the +// same cells drawn with a slanted run must lean further right than the upright line. +// The run flag word is what the native renderer reads. +func TestItalicGridRunSlantsItsCells(t *testing.T) { + if got := textRunFlags(gfx.TextRun{Italic: true}); got&runItalic == 0 { + t.Fatalf("flags = %d, want the italic bit", got) + } + if got := textRunFlags(gfx.TextRun{Underline: true}); got&runItalic != 0 { + t.Fatalf("an upright run packed the italic bit: %d", got) + } + color := platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1} + const ( + value = "comment text" + cell = float32(12) + ) + render := func(italic bool) ([]byte, int, int) { + offscreen, err := NewOffscreen(240, 40, 2, Color{Alpha: 1}) + if err != nil { + t.Skipf("no Metal device: %v", err) + } + defer offscreen.Close() + runs := []gfx.TextRun{{ + Bytes: int32(len(value)), Cells: int32(len(value)), + Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, Italic: italic, + }} + err = offscreen.Set(nil, []TextLabel{{ + Value: value, X: 0, Y: 4, Width: 240, Height: 30, FontSize: 20, + Color: color, Mono: true, CellWidth: cell, Runs: runs, + }}, nil) + if err != nil { + t.Fatal(err) + } + pixels, width, height, err := offscreen.Render() + if err != nil { + t.Fatal(err) + } + return pixels, width, height + } + upright, width, height := render(false) + slanted, _, _ := render(true) + if bytes.Equal(upright, slanted) { + t.Fatal("an italic grid run drew the upright glyphs") + } + if up, slant := leanOf(upright, width, height), leanOf(slanted, width, height); slant < up+0.5 { + t.Errorf("italic grid run leans %.2f px, upright %.2f; want the italic to lean right", slant, up) + } +} diff --git a/internal/platform/darwin/text_test.go b/internal/platform/darwin/text_test.go index d21c662f1..2e5846871 100644 --- a/internal/platform/darwin/text_test.go +++ b/internal/platform/darwin/text_test.go @@ -394,6 +394,27 @@ func TestNativeTextInputCarriesAltSendsEscape(t *testing.T) { } } +func TestNativeTextInputCarriesDisableIME(t *testing.T) { + native := makeNativeTextInput(TextInput{DisableIME: true}, nil) + if native.disable_ime == 0 { + t.Fatal("DisableIME was not passed to AppKit") + } +} + +// A surface that keeps the input method off must not take a composition as +// kept: its text state belongs to the machine it shows. +func TestTextInputThatDisablesIMEKeepsNoComposition(t *testing.T) { + state := runState{textInputActive: true, textInput: TextInput{Target: gfx.Item(1), DisableIME: true}} + next := TextInput{Target: gfx.Item(1), DisableIME: false} + if state.textInputKeepsComposition(&next) { + t.Fatal("a surface that stopped disabling the input method kept a composition") + } + state.textInput.DisableIME = false + if !state.textInputKeepsComposition(&next) { + t.Fatal("an unchanged field no longer kept its composition") + } +} + // A focused field has no editing command for the function keys, so they must // reach the application as Windows and Linux deliver them; an input method that // converts on F6-F10 keeps them for as long as it composes. diff --git a/internal/platform/linux/clipboard_html_linux_test.go b/internal/platform/linux/clipboard_html_linux_test.go index 676d82e11..7576ad37a 100644 --- a/internal/platform/linux/clipboard_html_linux_test.go +++ b/internal/platform/linux/clipboard_html_linux_test.go @@ -78,25 +78,68 @@ func newSelectionWindowWithHTML(recorder *selectionRecorder, text, html string) func TestSetClipboardHTMLClaimsTheBoardAndRefusesBadInput(t *testing.T) { recorder := &selectionRecorder{masks: map[uint32]uint32{}, incrAtom: 77} win := &window{api: recorder.api(), connection: 1, id: 2, clipboardAtom: 10, utf8Atom: 11, textAtom: 12, targetsAtom: 13, htmlAtom: 17, uriListAtom: 15, gnomeFilesAtom: 16} + previousWindow, previousHooks := activeWindow.Load(), shellHooks.Load() activeWindow.Store(win) - t.Cleanup(func() { activeWindow.Store(nil) }) + shellHooks.Store(nil) + t.Cleanup(func() { + activeWindow.Store(previousWindow) + shellHooks.Store(previousHooks) + }) if err := SetClipboardHTML("x", "x"); err != nil { t.Fatal(err) } if !win.ownsClipboard || win.clipboard != "x" || win.clipboardHTML != "x" || len(win.clipboardFiles) != 0 { t.Fatalf("the board holds %q/%q owned=%v files=%d", win.clipboard, win.clipboardHTML, win.ownsClipboard, len(win.clipboardFiles)) } - if err := SetClipboardHTML("a\x00b", "alt"); err == nil { - t.Fatal("html with NUL was accepted") - } - if err := SetClipboardHTML("t", "a\x00b"); err == nil { - t.Fatal("alt with NUL was accepted") - } - if err := SetClipboardHTML("bad\xff", "alt"); err == nil { - t.Fatal("invalid UTF-8 was accepted") + for _, pair := range []struct{ name, html, alt string }{ + {"html NUL", "a\x00b", "alt"}, + {"text NUL", "t", "a\x00b"}, + {"html UTF-8", "bad\xff", "alt"}, + {"text UTF-8", "t", "bad\xff"}, + } { + t.Run(pair.name, func(t *testing.T) { + claims, text, html := len(recorder.ownerCalls), win.clipboard, win.clipboardHTML + if err := SetClipboardHTML(pair.html, pair.alt); err == nil { + t.Error("invalid rich clipboard pair was accepted") + } + if len(recorder.ownerCalls) != claims || !win.ownsClipboard || win.clipboard != text || win.clipboardHTML != html || len(win.clipboardFiles) != 0 { + t.Errorf("invalid input changed the board: claims=%d text=%q html=%q", len(recorder.ownerCalls), win.clipboard, win.clipboardHTML) + } + }) } activeWindow.Store(nil) if err := SetClipboardHTML("x", "x"); err == nil || err.Error() == "" { t.Fatal("a copy without a window was accepted") } } + +func TestSetClipboardHTMLRejectsInvalidPairBeforeDesktopHook(t *testing.T) { + previous := shellHooks.Load() + t.Cleanup(func() { shellHooks.Store(previous) }) + writes := 0 + var html, alt string + shellHooks.Store(&desktopHooks{setClipboardHTML: func(nextHTML, nextAlt string) error { + writes++ + html, alt = nextHTML, nextAlt + return nil + }}) + if err := SetClipboardHTML("ok", "ok"); err != nil || writes != 1 { + t.Fatalf("valid pair: error=%v writes=%d", err, writes) + } + for _, pair := range []struct{ name, html, alt string }{ + {"html NUL", "a\x00b", "alt"}, + {"text NUL", "t", "a\x00b"}, + {"html UTF-8", "bad\xff", "alt"}, + {"text UTF-8", "t", "bad\xff"}, + } { + t.Run(pair.name, func(t *testing.T) { + before, previousHTML, previousAlt := writes, html, alt + if err := SetClipboardHTML(pair.html, pair.alt); err == nil { + t.Error("invalid rich clipboard pair was accepted") + } + if writes != before || html != previousHTML || alt != previousAlt { + t.Errorf("invalid input reached the desktop: writes=%d html=%q text=%q", writes, html, alt) + } + }) + } +} diff --git a/internal/platform/linux/clipboard_html_write_linux.go b/internal/platform/linux/clipboard_html_write_linux.go index 3815b7fa5..ccc726dd7 100644 --- a/internal/platform/linux/clipboard_html_write_linux.go +++ b/internal/platform/linux/clipboard_html_write_linux.go @@ -2,6 +2,7 @@ package linux import ( "fmt" + "strings" "unicode/utf8" ) @@ -14,6 +15,9 @@ func SetClipboardHTML(html, alt string) error { if len(html) > maxClipboardBytes { return fmt.Errorf("linux: clipboard html exceeds 64 MiB") } + if strings.IndexByte(html, 0) >= 0 || strings.IndexByte(alt, 0) >= 0 { + return fmt.Errorf("linux: clipboard html or text contains NUL") + } if !utf8.ValidString(html) || !utf8.ValidString(alt) { return fmt.Errorf("linux: clipboard html is not valid UTF-8") } diff --git a/internal/platform/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go index 65ed1c15c..ec072f500 100644 --- a/internal/platform/linux/gtk_app_linux.go +++ b/internal/platform/linux/gtk_app_linux.go @@ -49,6 +49,8 @@ type gtkApplication struct { // watched are the descriptors of the session bus connections the loop listens to, by the id // of the GLib source that does. watched map[int]uint32 + // Retired input contexts stay alive until the native callback stack returns. + retiredIMESources []uint32 } // gtkTasks are the functions other goroutines asked the loop to run. @@ -94,6 +96,7 @@ func RunGTKApplication(start platform.ApplicationStart) error { return fmt.Errorf("linux: the GTK shell is already running") } defer gtkRunning.Store(nil) + defer application.releaseRetiredIME() callbacks() application.mainThread = syscall.Gettid() application.installHooks() @@ -151,6 +154,35 @@ func (a *gtkApplication) enqueue(function func()) { a.g.idleAdd(callbacks().task, a.tasks.add(function)) } +func (a *gtkApplication) retireIME(context uintptr) { + active := a.retiredIMESources[:0] + for _, source := range a.retiredIMESources { + if a.g.sourceFind(0, source) != 0 { + active = append(active, source) + } + } + cb := callbacks() + source := a.g.idleAddFull(200, cb.retireIME, context, cb.releaseIME) + a.retiredIMESources = append(active, source) +} + +func (a *gtkApplication) releaseRetiredIME() { + for _, source := range a.retiredIMESources { + if a.g.sourceFind(0, source) != 0 { + a.g.sourceRemove(source) + } + } + a.retiredIMESources = nil +} + +// Post runs fn on the main loop. GLib's idle callbacks keep the order work was +// enqueued in, and the task table takes concurrent callers under one lock. +func (a *gtkApplication) Post(fn func()) { + if fn != nil { + a.enqueue(fn) + } +} + // fail ends the loop with an error, once. func (a *gtkApplication) fail(err error) { if a.firstErr == nil { @@ -280,7 +312,7 @@ func typeNameOf(g *gtkLibrary, object uintptr) string { // frees a callback and allows a fixed number, so a window must not make its own. The window a call // is for travels in the data pointer, as its id. type gtkCallbacks struct { - task, descriptor, settings, dragMotion, dragLeave, dragDrop, dragData, event, draw, allocate, destroy, deleteEvent, mapped, unmapped, commit, preedit, surrounding, deleteSurrounding, redraw, webMessage, webLoad, webScheme, webDecide, webCreate, webDownload, webDestination uintptr + task, descriptor, settings, dragMotion, dragLeave, dragDrop, dragData, event, draw, allocate, destroy, deleteEvent, mapped, unmapped, commit, preedit, surrounding, deleteSurrounding, retireIME, releaseIME, redraw, webMessage, webLoad, webScheme, webDecide, webCreate, webDownload, webDestination uintptr } var ( @@ -374,8 +406,11 @@ func callbacks() *gtkCallbacks { return 0 }), deleteEvent: purego.NewCallback(func(widget, event, id uintptr) uintptr { - if w := gtkWindowByID(id); w != nil && w.closeRequested() { - return 1 // the application decides + if w := gtkWindowByID(id); w != nil { + if !w.closeRequested() { + w.destroy() + } + return 1 } return 0 }), @@ -451,29 +486,34 @@ func callbacks() *gtkCallbacks { return 1 }), commit: purego.NewCallback(func(context, text, id uintptr) uintptr { - if w := gtkWindowByID(id); w != nil && w.ime != nil { - w.ime.commit(goString(text)) + if ime := gtkIMEByContext(context, id); ime != nil { + ime.commit(goString(text)) } return 0 }), preedit: purego.NewCallback(func(context, id uintptr) uintptr { - if w := gtkWindowByID(id); w != nil && w.ime != nil { - w.ime.preeditChanged() + if ime := gtkIMEByContext(context, id); ime != nil { + ime.preeditChanged() } return 0 }), surrounding: purego.NewCallback(func(context, id uintptr) uintptr { - if w := gtkWindowByID(id); w != nil && w.ime != nil { - return w.ime.retrieveSurrounding() + if ime := gtkIMEByContext(context, id); ime != nil { + return ime.retrieveSurrounding() } return 0 }), deleteSurrounding: purego.NewCallback(func(context, offset, count, id uintptr) uintptr { - if w := gtkWindowByID(id); w != nil && w.ime != nil { - return w.ime.deleteSurrounding(int(int32(offset)), int(int32(count))) + if ime := gtkIMEByContext(context, id); ime != nil { + return ime.deleteSurrounding(int(int32(offset)), int(int32(count))) } return 0 }), + retireIME: purego.NewCallback(func(uintptr) uintptr { return 0 }), + releaseIME: purego.NewCallback(func(context uintptr) uintptr { + gtkLoaded.objectUnref(context) + return 0 + }), } }) return &callbackSet @@ -487,3 +527,10 @@ func gtkWindowByID(id uintptr) *gtkWindow { } return nil } + +func gtkIMEByContext(context, id uintptr) *gtkIME { + if w := gtkWindowByID(id); w != nil && !w.closed && w.ime != nil && context != 0 && w.ime.ctx == context && w.text.enabled && w.ime.target == w.text.input.Target { + return w.ime + } + return nil +} diff --git a/internal/platform/linux/gtk_clipboard_html_linux_test.go b/internal/platform/linux/gtk_clipboard_html_linux_test.go index 73b8d715e..3ededcb59 100644 --- a/internal/platform/linux/gtk_clipboard_html_linux_test.go +++ b/internal/platform/linux/gtk_clipboard_html_linux_test.go @@ -24,7 +24,8 @@ func TestGTKClipboardHTMLWriteReportsUnsupportedWithoutSetWithData(t *testing.T) textWrites := 0 clipboards = gtkClipboards{ ok: true, clipboard: 17, - setText: func(board uintptr, value *byte, length int32) { textWrites++ }, + setText: func(board uintptr, value *byte, length int32) { textWrites++ }, + atomIntern: func(*byte, int32) uintptr { return 1 }, } application := >kApplication{mainThread: syscall.Gettid()} application.installHooks() diff --git a/internal/platform/linux/gtk_ime_linux.go b/internal/platform/linux/gtk_ime_linux.go index f3ebd371d..11de443c2 100644 --- a/internal/platform/linux/gtk_ime_linux.go +++ b/internal/platform/linux/gtk_ime_linux.go @@ -6,6 +6,7 @@ import ( "unicode/utf8" "unsafe" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/text" ) @@ -17,9 +18,10 @@ import ( // and commits the choice as it does on the other platforms. The input method owns the candidate // window; this side says when the field has the keyboard and where its caret is. type gtkIME struct { - w *gtkWindow - g *gtkLibrary - ctx uintptr + w *gtkWindow + g *gtkLibrary + ctx uintptr + target gfx.ID // focused is whether the window has the keyboard; active is whether the context was told the // field does. focused bool @@ -37,33 +39,51 @@ type gtkIME struct { } func newGTKIME(w *gtkWindow) *gtkIME { - g := w.g - ime := >kIME{w: w, g: g, ctx: g.imMulticontextNew()} + ime := >kIME{w: w, g: w.g, target: w.text.input.Target} + ime.open() + return ime +} + +func (ime *gtkIME) open() { + g, w := ime.g, ime.w + ime.ctx = g.imMulticontextNew() cb := callbacks() g.connect(ime.ctx, "commit", cb.commit, w.id) g.connect(ime.ctx, "preedit-changed", cb.preedit, w.id) g.connect(ime.ctx, "retrieve-surrounding", cb.surrounding, w.id) g.connect(ime.ctx, "delete-surrounding", cb.deleteSurrounding, w.id) - return ime } // realized gives the context its window, which exists once the toplevel is realized. func (ime *gtkIME) realized() { if window := ime.g.widgetGetWindow(ime.w.toplevel); window != 0 { - ime.g.imSetClientWindow(ime.ctx, window) + ime.callContext(ime.ctx, func(context uintptr) { ime.g.imSetClientWindow(context, window) }) } } func (ime *gtkIME) close() { - if ime.ctx == 0 { + context := ime.ctx + if context == 0 { return } - if ime.active { - ime.g.imFocusOut(ime.ctx) + active := ime.active + ime.ctx, ime.active, ime.engineComposing = 0, false, false + ime.haveCursor, ime.hasSources, ime.sent = false, false, false + ime.shortcutKey = nil + if active { + ime.callContext(context, ime.g.imFocusOut) + } + ime.callContext(context, func(context uintptr) { ime.g.imSetClientWindow(context, 0) }) + ime.w.app.retireIME(context) +} + +func (ime *gtkIME) callContext(context uintptr, call func(uintptr)) { + if context == 0 { + return } - ime.g.imSetClientWindow(ime.ctx, 0) - ime.g.objectUnref(ime.ctx) - ime.ctx, ime.active = 0, false + ime.g.objectRef(context) + defer ime.g.objectUnref(context) + call(context) } // setFocused records whether the window has the keyboard. @@ -78,7 +98,14 @@ func (ime *gtkIME) filtering() bool { return ime.ctx != 0 && ime.active } // filter gives a key event to the context and reports whether it took it. Whatever it composes // arrives later as a commit or a preedit change. func (ime *gtkIME) filter(event uintptr) bool { - return ime.g.imFilterKeypress(ime.ctx, event) != 0 + context := ime.ctx + if context == 0 || ime.w.closed { + return false + } + // A signal may replace the target while the native filter still uses it. + ime.g.objectRef(context) + defer ime.g.objectUnref(context) + return ime.g.imFilterKeypress(context, event) != 0 } func (ime *gtkIME) filterShortcut(event uintptr, key platform.KeyEvent, directText string) bool { @@ -94,25 +121,40 @@ func (ime *gtkIME) filterShortcut(event uintptr, key platform.KeyEvent, directTe // sync brings the context's idea of focus and caret in line with the field. It runs after every // frame, which is when the field changes, and does nothing when nothing has. func (ime *gtkIME) sync() { - if ime.ctx == 0 { + if ime.ctx == 0 || ime.w.closed { return } text := ime.w.text + if text.input.Target != ime.target { + ime.close() + if ime.w.closed { + return + } + ime.target = text.input.Target + ime.open() + } + context := ime.ctx want := ime.focused && text.enabled && !ime.w.nativeKeys switch { case want && !ime.active: ime.realized() + if ime.ctx != context || ime.w.closed { + return + } ime.active, ime.haveCursor, ime.hasSources, ime.sent = true, false, false, false - ime.g.imFocusIn(ime.ctx) + ime.callContext(context, ime.g.imFocusIn) case !want && ime.active: ime.active = false if ime.engineComposing { ime.engineComposing = false - ime.g.imReset(ime.ctx) + ime.callContext(context, ime.g.imReset) } - ime.g.imFocusOut(ime.ctx) + if ime.ctx != context || ime.w.closed || ime.focused && text.enabled && !ime.w.nativeKeys { + return + } + ime.callContext(context, ime.g.imFocusOut) } - if !ime.active { + if !ime.active || ime.ctx != context || ime.w.closed { return } // The field stopped composing without the context (a click moved the caret, the application @@ -120,7 +162,10 @@ func (ime *gtkIME) sync() { // longer sees. if ime.engineComposing && !text.state.Composing { ime.engineComposing = false - ime.g.imReset(ime.ctx) + ime.callContext(context, ime.g.imReset) + if ime.ctx != context || ime.w.closed { + return + } } ime.updateCursor() ime.updateSurrounding() @@ -137,7 +182,7 @@ func (ime *gtkIME) updateCursor() { return } ime.cursor, ime.haveCursor = location, true - ime.g.imSetCursorRect(ime.ctx, &location) + ime.callContext(ime.ctx, func(context uintptr) { ime.g.imSetCursorRect(context, &location) }) } // caretRectangle is the caret in window coordinates: the line the field draws, or for a terminal, @@ -182,8 +227,10 @@ func (ime *gtkIME) retrieveSurrounding() uintptr { cursor := min(max(window.Cursor, 0), len(runes)) bytesBefore := len(string(runes[:cursor])) data := cString(window.Text) - ime.g.imSetSurrounding(ime.ctx, &data[0], int32(len(data)-1), int32(bytesBefore)) ime.sent = true + ime.callContext(ime.ctx, func(context uintptr) { + ime.g.imSetSurrounding(context, &data[0], int32(len(data)-1), int32(bytesBefore)) + }) return 1 } @@ -201,10 +248,22 @@ func (ime *gtkIME) deleteSurrounding(offset, count int) uintptr { } func (ime *gtkIME) commit(value string) { + context, revision := ime.ctx, ime.w.text.stateRevision if key := ime.shortcutKey; key != nil && !ime.engineComposing && !ime.w.text.state.Composing && value == key.Typed { + frameRevision := ime.w.text.inputRevision frame, handled, err := ime.w.config.OnShortcut(*key) - ime.w.present(frame, err) - if handled || err != nil { + if err != nil { + ime.w.present(platform.Frame{}, err) + return + } + if ime.ctx != context || ime.w.closed || ime.w.text.stateRevision != revision { + return + } + // A geometry-only update invalidates the returned frame, not this key. + if ime.w.text.inputRevision == frameRevision { + ime.w.present(frame, nil) + } + if handled || ime.ctx != context || ime.w.closed || ime.w.text.stateRevision != revision { return } } @@ -214,9 +273,16 @@ func (ime *gtkIME) commit(value string) { // preeditChanged shows the text being composed as marked text, or removes it. func (ime *gtkIME) preeditChanged() { + context := ime.ctx + if context == 0 || ime.w.closed { + return + } + ime.g.objectRef(context) + defer ime.g.objectUnref(context) + revision := ime.w.text.stateRevision var str, attrs uintptr var cursor int32 - ime.g.imGetPreedit(ime.ctx, &str, &attrs, &cursor) + ime.g.imGetPreedit(context, &str, &attrs, &cursor) value := goString(str) if str != 0 { ime.g.gFree(str) @@ -231,10 +297,16 @@ func (ime *gtkIME) preeditChanged() { } ime.g.attrListUnref(attrs) } + if ime.ctx != context || ime.w.closed || ime.w.text.stateRevision != revision { + return + } if value == "" { ime.engineComposing = false if ime.w.text.state.Composing { ime.apply(platform.TextEvent{Kind: platform.TextSetMarked}) + if ime.ctx != context || ime.w.closed || ime.w.text.stateRevision != revision+1 { + return + } ime.apply(platform.TextEvent{Kind: platform.TextUnmark}) } return diff --git a/internal/platform/linux/gtk_ime_native_linux_test.go b/internal/platform/linux/gtk_ime_native_linux_test.go new file mode 100644 index 000000000..fea60bca4 --- /dev/null +++ b/internal/platform/linux/gtk_ime_native_linux_test.go @@ -0,0 +1,471 @@ +//go:build linux && vivagtk + +package linux + +import ( + "fmt" + "os" + "slices" + "sync" + "testing" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +type gtkIMEProbeKeys struct { + newEvent func(int32) uintptr + freeEvent func(uintptr) + setDevice func(uintptr, uintptr) + keyboard func(uintptr) uintptr + ref func(uintptr) uintptr + weakRef func(uintptr, uintptr, uintptr) + emit func(uintptr, *byte, *byte) + entries func(uintptr, uint32, *uintptr, *int32) int32 + translate func(uintptr, uint32, uint32, int32, *uint32, *int32, *int32, *uint32) int32 +} + +type gtkIMEProbeKey struct { + Code uint32 + Group, Level int32 +} + +type gtkIMEProbeTrial struct { + name, value string + signals []string + events []string + failures []string +} + +type gtkIMEProbe struct { + w *gtkWindow + keys gtkIMEProbeKeys + editor *text.Editor + context uintptr + signals []string + events []platform.TextEvent + hook func(platform.TextEvent) + shortcut bool + trials []gtkIMEProbeTrial + freed map[uintptr]bool +} + +var gtkIMEProbeActive *gtkIMEProbe +var gtkIMEProbeOnce sync.Once +var gtkIMEProbeSignals struct{ start, changed, end, commit, finalized uintptr } + +func (p *gtkIMEProbe) observe() { + gtkIMEProbeOnce.Do(func() { + gtkIMEProbeSignals.start = purego.NewCallback(func(ctx, _ uintptr) uintptr { + if p := gtkIMEProbeActive; p != nil && p.context == ctx { + p.signals = append(p.signals, "start") + } + return 0 + }) + gtkIMEProbeSignals.changed = purego.NewCallback(func(ctx, _ uintptr) uintptr { + if p := gtkIMEProbeActive; p != nil && p.context == ctx { + var value, attrs uintptr + var cursor int32 + p.w.g.imGetPreedit(ctx, &value, &attrs, &cursor) + p.signals = append(p.signals, "preedit:"+goString(value)) + if value != 0 { + p.w.g.gFree(value) + } + if attrs != 0 { + p.w.g.attrListUnref(attrs) + } + } + return 0 + }) + gtkIMEProbeSignals.end = purego.NewCallback(func(ctx, _ uintptr) uintptr { + if p := gtkIMEProbeActive; p != nil && p.context == ctx { + p.signals = append(p.signals, "end") + } + return 0 + }) + gtkIMEProbeSignals.commit = purego.NewCallback(func(ctx, value, _ uintptr) uintptr { + if p := gtkIMEProbeActive; p != nil && p.context == ctx { + p.signals = append(p.signals, "commit:"+goString(value)) + } + return 0 + }) + gtkIMEProbeSignals.finalized = purego.NewCallback(func(ctx, _ uintptr) uintptr { + if p := gtkIMEProbeActive; p != nil { + p.freed[ctx] = true + } + return 0 + }) + }) + ctx := p.w.ime.ctx + if ctx != p.context { + p.w.g.connect(ctx, "preedit-start", gtkIMEProbeSignals.start, 0) + p.w.g.connect(ctx, "preedit-changed", gtkIMEProbeSignals.changed, 0) + p.w.g.connect(ctx, "preedit-end", gtkIMEProbeSignals.end, 0) + p.w.g.connect(ctx, "commit", gtkIMEProbeSignals.commit, 0) + p.keys.weakRef(ctx, gtkIMEProbeSignals.finalized, ctx) + p.freed[ctx] = false + p.context = ctx + } +} + +func (p *gtkIMEProbe) install(editor *text.Editor, target gfx.ID) { + p.editor = editor + field := platform.TextInput{ + Target: target, X: 20, Y: 20, Width: 300, Height: 100, FontSize: 16, + Multiline: true, Color: platform.Color{Alpha: 1}, State: platform.EditorState(editor), + OnEvent: func(event platform.TextEvent) (platform.TextState, error) { + p.events = append(p.events, event) + event.Apply(editor) + next := platform.EditorState(editor) + if p.hook != nil { + p.hook(event) + } + return next, nil + }, + } + p.w.present(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}, nil) + p.w.ime.setFocused(true) + p.observe() + p.signals, p.events = nil, nil +} + +func (p *gtkIMEProbe) press(ctx uintptr, symbol, state uint32) error { + g := p.w.g + keymap := g.gdkKeymapDefault() + var entries uintptr + var count int32 + if p.keys.entries(keymap, symbol, &entries, &count) == 0 || entries == 0 || count == 0 { + return fmt.Errorf("no native keymap entry for %#x", symbol) + } + key := *(*gtkIMEProbeKey)(unsafePointer(entries)) + g.gFree(entries) + var value, consumed uint32 + var group, level int32 + if p.keys.translate(keymap, key.Code, state, key.Group, &value, &group, &level, &consumed) == 0 { + return fmt.Errorf("native keymap did not translate %#x", symbol) + } + window := g.widgetGetWindow(p.w.toplevel) + device := p.keys.keyboard(g.gdkDisplaySeat(g.gdkDisplayDefault())) + if window == 0 || device == 0 || ctx == 0 { + return fmt.Errorf("native window/keyboard/context unavailable") + } + event := p.keys.newEvent(int32(gdkKeyPress)) + defer p.keys.freeEvent(event) + record := (*gdkEventKey)(unsafePointer(event)) + record.Window, record.SendEvent = p.keys.ref(window), 1 + record.State, record.Keyval = state, value + record.HardwareKeycode, record.Group = uint16(key.Code), uint8(group) + p.keys.setDevice(event, device) + handled := false + if ctx == p.w.ime.ctx { + if p.shortcut { + handled = p.w.ime.filterShortcut(event, platform.KeyEvent{}, string(rune(value))) + } else { + handled = p.w.ime.filter(event) + } + } else { + handled = g.imFilterKeypress(ctx, event) != 0 + } + if !handled { + return fmt.Errorf("native GTK did not consume key %#x (translated %#x)", symbol, value) + } + return nil +} + +func (p *gtkIMEProbe) compose() error { + for _, symbol := range []uint32{'U', '3', 'A', '9'} { + if err := p.press(p.w.ime.ctx, symbol, (1<<2)|(1<<0)); err != nil { + return err + } + } + return nil +} + +func (p *gtkIMEProbe) record(name string, failures ...string) { + trial := gtkIMEProbeTrial{name: name, value: p.editor.String(), signals: append([]string(nil), p.signals...), failures: failures} + for _, event := range p.events { + trial.events = append(trial.events, fmt.Sprintf("%d:%q", event.Kind, event.Text)) + } + if mirror := p.w.text.state; !p.w.closed && mirror != platform.EditorState(p.editor).WithoutRedraw() { + trial.failures = append(trial.failures, fmt.Sprintf("model/mirror differ: model=%+v mirror=%+v", platform.EditorState(p.editor), mirror)) + } + p.trials = append(p.trials, trial) +} + +func (p *gtkIMEProbe) run() { + for _, ending := range []string{"commit", "escape", "reset", "focus-out", "window-focus-out"} { + editor := text.NewEditor("abc") + editor.SetSelection(text.Range{Start: 1, End: 2}) + p.install(editor, gfx.Item(1)) + if err := p.compose(); err != nil { + p.record(ending, err.Error()) + continue + } + var failures []string + prefix := []string{"start", "preedit:u", "preedit:u3", "preedit:u3A", "preedit:u3A9"} + if !slices.Equal(p.signals, prefix) || editor.String() != "au3A9c" { + failures = append(failures, fmt.Sprintf("preedit signals=%q text=%q", p.signals, editor.String())) + } + switch ending { + case "commit": + if err := p.press(p.w.ime.ctx, ' ', (1<<2)|(1<<0)); err != nil { + failures = append(failures, err.Error()) + } + case "escape": + if err := p.press(p.w.ime.ctx, 0xff1b, (1<<2)|(1<<0)); err != nil { + failures = append(failures, err.Error()) + } + case "reset": + p.w.g.imReset(p.w.ime.ctx) + case "focus-out": + p.w.g.imFocusOut(p.w.ime.ctx) + if !slices.Equal(p.signals, prefix) || editor.String() != "au3A9c" { + failures = append(failures, "GtkIMContextSimple focus-out unexpectedly settled preedit") + } + p.w.g.imReset(p.w.ime.ctx) + case "window-focus-out": + p.w.ime.setFocused(false) + } + wantSignals := append(prefix, "preedit:", "end") + wantText := "ac" + if ending == "commit" { + wantSignals = append(wantSignals, "commit:\u03a9") + wantText = "a\u03a9c" + } + if !slices.Equal(p.signals, wantSignals) || editor.String() != wantText || p.w.text.state.Composing { + failures = append(failures, fmt.Sprintf("ending signals=%q text=%q composing=%t", p.signals, editor.String(), p.w.text.state.Composing)) + } + p.record(ending, failures...) + if !editor.Undo() || ending == "commit" && editor.String() != "ac" || ending != "commit" && editor.String() != "abc" { + p.trials[len(p.trials)-1].failures = append(p.trials[len(p.trials)-1].failures, fmt.Sprintf("first Undo=%q", editor.String())) + } + if ending == "commit" && (!editor.Undo() || editor.String() != "abc") { + p.trials[len(p.trials)-1].failures = append(p.trials[len(p.trials)-1].failures, fmt.Sprintf("second Undo=%q", editor.String())) + } + } + plain := text.NewEditor("abc") + p.install(plain, gfx.Item(1)) + var failures []string + for _, symbol := range []uint32{'r', 's'} { + if err := p.press(p.w.ime.ctx, symbol, 0); err != nil { + failures = append(failures, err.Error()) + } + } + if plain.String() != "abcrs" || !slices.Equal(p.signals, []string{"commit:r", "commit:s"}) { + failures = append(failures, "ordinary native commits changed text or signal order") + } + p.record("plain", failures...) + if !plain.Undo() || plain.String() != "abc" { + p.trials[len(p.trials)-1].failures = append(p.trials[len(p.trials)-1].failures, "ordinary GTK commits stopped coalescing") + } + old := text.NewEditor("abc") + p.install(old, gfx.Item(1)) + oldContext := p.keys.ref(p.w.ime.ctx) + defer p.w.g.objectUnref(oldContext) + next := text.NewEditor("abc") + p.install(next, gfx.Item(2)) + p.w.g.imReset(oldContext) + failures = nil + signal, value := cString("commit"), cString("z") + p.keys.emit(oldContext, &signal[0], &value[0]) + if p.w.ime.ctx == oldContext || next.String() != "abc" || len(p.events) != 0 { + failures = append(failures, fmt.Sprintf("old native context reached replacement input: reused=%t text=%q events=%d", p.w.ime.ctx == oldContext, next.String(), len(p.events))) + } + p.record("target replacement", failures...) + + p.install(text.NewEditor("abc"), gfx.Item(1)) + p.editor.SetSelection(text.Range{Start: 1, End: 2}) + field := p.w.text.input + field.State = platform.EditorState(p.editor) + p.w.present(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}, nil) + if err := p.compose(); err != nil { + p.record("native callback handoff", err.Error()) + return + } + p.hook = func(event platform.TextEvent) { + if event.Kind == platform.TextSetMarked && event.Text == "" { + p.hook = nil + p.install(text.NewEditor("next"), gfx.Item(2)) + } + } + failures = nil + if err := p.press(p.w.ime.ctx, ' ', (1<<2)|(1<<0)); err != nil { + failures = append(failures, err.Error()) + } + if p.hook != nil || p.editor.String() != "next" || len(p.events) != 0 { + failures = append(failures, fmt.Sprintf("native clear/end/commit tail entered replacement: hook=%t text=%q events=%d", p.hook != nil, p.editor.String(), len(p.events))) + } + p.hook = nil + p.record("native callback handoff", failures...) + for _, disabled := range []bool{false, true} { + p.frameHandoff(disabled) + } + for _, geometry := range []bool{false, true} { + p.shortcutHandoff(geometry) + } +} + +func (p *gtkIMEProbe) frameHandoff(disabled bool) { + p.install(text.NewEditor("abc"), gfx.Item(1)) + context := p.keys.ref(p.w.ime.ctx) + defer p.w.g.objectUnref(context) + called := false + p.w.config.FramePresented = func() { + p.w.config.FramePresented = nil + called = true + signal, value := cString("commit"), cString("z") + p.keys.emit(context, &signal[0], &value[0]) + } + name := "frame presentation handoff" + if disabled { + name = "disabled frame presentation" + p.w.present(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true}}, nil) + } else { + p.install(text.NewEditor("next"), gfx.Item(2)) + } + var failures []string + if !called || !disabled && p.editor.String() != "next" || disabled && p.editor.String() != "abc" { + failures = append(failures, fmt.Sprintf("retired context entered pending frame: called=%t text=%q", called, p.editor.String())) + } + if disabled && p.w.text.enabled { + failures = append(failures, "late native signal re-enabled disabled input") + } + if disabled { + p.install(p.editor, gfx.Item(1)) + } + p.record(name, failures...) +} + +func (p *gtkIMEProbe) shortcutHandoff(geometry bool) { + p.install(text.NewEditor("abc"), gfx.Item(1)) + old := p.w.text.input + called := false + p.w.config.OnShortcut = func(platform.KeyEvent) (platform.Frame, bool, error) { + called = true + if geometry { + current := p.w.text.input + current.Width = old.Width + 20 + p.w.present(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: ¤t}}, nil) + } else { + p.install(text.NewEditor("next"), gfx.Item(2)) + } + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &old}}, false, nil + } + p.shortcut = true + var failures []string + if err := p.press(p.w.ime.ctx, 'r', 0); err != nil { + failures = append(failures, err.Error()) + } + p.shortcut, p.w.config.OnShortcut = false, nil + name, want := "shortcut target handoff", "next" + if geometry { + name, want = "shortcut geometry handoff", "abcr" + if p.w.text.input.Width != old.Width+20 { + failures = append(failures, "stale shortcut frame overwrote newer input geometry") + } + } + if !called || p.editor.String() != want { + failures = append(failures, fmt.Sprintf("shortcut handoff: called=%t text=%q, want %q", called, p.editor.String(), want)) + } + p.record(name, failures...) +} + +func (p *gtkIMEProbe) closeDuringCommit() { + p.install(text.NewEditor("abc"), gfx.Item(1)) + p.editor.SetSelection(text.Range{Start: 1, End: 2}) + field := p.w.text.input + field.State = platform.EditorState(p.editor) + p.w.present(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}, nil) + if err := p.compose(); err != nil { + p.record("close during native commit", err.Error()) + p.w.destroy() + return + } + p.hook = func(event platform.TextEvent) { + if event.Kind == platform.TextSetMarked && event.Text == "" { + p.hook = nil + p.w.destroy() + } + } + p.events = nil + var failures []string + if err := p.press(p.w.ime.ctx, ' ', (1<<2)|(1<<0)); err != nil { + failures = append(failures, err.Error()) + } + if !p.w.closed || p.w.ime != nil || p.w.text.enabled || p.editor.String() != "ac" || len(p.events) != 1 { + failures = append(failures, fmt.Sprintf("close in native callback: closed=%t ime=%t enabled=%t text=%q events=%d", p.w.closed, p.w.ime != nil, p.w.text.enabled, p.editor.String(), len(p.events))) + } + p.hook = nil + p.record("close during native commit", failures...) + p.w.destroy() +} + +func TestGTKNativeComposition(t *testing.T) { + if os.Getenv("VIVA_GTK_IME_NATIVE") != "1" { + t.Skip("native GTK IME probe requires VIVA_GTK_IME_NATIVE=1 and a private display") + } + p := >kIMEProbe{freed: make(map[uintptr]bool)} + gtkIMEProbeActive = p + defer func() { gtkIMEProbeActive = nil }() + err := RunGTKApplication(func(application platform.Application) error { + a := application.(*gtkApplication) + for _, binding := range []struct { + function any + name string + }{ + {&p.keys.newEvent, "gdk_event_new"}, {&p.keys.freeEvent, "gdk_event_free"}, + {&p.keys.setDevice, "gdk_event_set_device"}, {&p.keys.keyboard, "gdk_seat_get_keyboard"}, + {&p.keys.ref, "g_object_ref"}, {&p.keys.entries, "gdk_keymap_get_entries_for_keyval"}, + {&p.keys.weakRef, "g_object_weak_ref"}, + {&p.keys.emit, "g_signal_emit_by_name"}, + {&p.keys.translate, "gdk_keymap_translate_keyboard_state"}, + } { + if !a.g.lookup(binding.function, binding.name) { + return fmt.Errorf("native probe cannot bind %s", binding.name) + } + } + window, err := application.OpenWindow(platform.Config{ + Title: "Viva native IME probe", Width: 360, Height: 160, + ClearColor: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + DynamicTextInput: true, OnRedraw: func() (platform.Frame, error) { return platform.Frame{}, nil }, + }) + if err != nil { + return err + } + p.w = window.(*gtkWindow) + a.enqueue(func() { + p.run() + // Run after default-priority idle releases, while the main loop is alive. + a.g.idleAddFull(300, callbacks().task, a.tasks.add(func() { + var failures []string + for context, freed := range p.freed { + if context != p.w.ime.ctx && !freed { + failures = append(failures, fmt.Sprintf("retired context %#x retained before shutdown", context)) + } + } + p.record("idle retirement", failures...) + p.closeDuringCommit() + }), 0) + }) + return nil + }) + if err != nil { + t.Fatal(err) + } + if len(p.trials) != 14 { + t.Fatalf("native trials=%d, want 14", len(p.trials)) + } + for _, trial := range p.trials { + t.Logf("%s signals=%q text=%q events=%q", trial.name, trial.signals, trial.value, trial.events) + for _, failure := range trial.failures { + t.Errorf("%s: %s", trial.name, failure) + } + } + for ctx, freed := range p.freed { + if !freed { + t.Errorf("native context %#x was not finalized after application shutdown", ctx) + } + } +} diff --git a/internal/platform/linux/gtk_input_linux.go b/internal/platform/linux/gtk_input_linux.go index 70cdbd63b..2142f0aba 100644 --- a/internal/platform/linux/gtk_input_linux.go +++ b/internal/platform/linux/gtk_input_linux.go @@ -435,7 +435,9 @@ func (w *gtkWindow) keyEvent(event uintptr) uintptr { keyEvent := platform.KeyEvent{Key: key, Modifiers: modifiers, Repeat: repeat} if modifiers&(input.ModifierControl|input.ModifierMeta) != 0 { // A chord is the same on every layout: Ctrl+C is the key that types c. - keyEvent.Text = w.shortcutText(e, e.State&gdkShiftMask != 0) + // Shift is one of its modifiers, so Ctrl+Shift+C still names the base + // character (gfx.KeyEvent.Text) rather than the capital. + keyEvent.Text = w.shortcutText(e, false) } else if r, ok := keysymRune(e.Keyval); ok { keyEvent.Text = string(r) } diff --git a/internal/platform/linux/gtk_library_linux.go b/internal/platform/linux/gtk_library_linux.go index 5cbec5448..afae981c0 100644 --- a/internal/platform/linux/gtk_library_linux.go +++ b/internal/platform/linux/gtk_library_linux.go @@ -25,10 +25,13 @@ type gtkLibrary struct { signalConnect func(instance uintptr, signal *byte, handler, data, destroy uintptr, flags int32) uint64 signalDisc func(instance uintptr, id uint64) idleAdd func(function, data uintptr) uint32 + idleAddFull func(priority int32, function, data, destroy uintptr) uint32 + sourceFind func(context uintptr, id uint32) uintptr timeoutAdd func(interval uint32, function, data uintptr) uint32 sourceRemove func(id uint32) int32 gFree func(pointer uintptr) objectUnref func(object uintptr) + objectRef func(object uintptr) uintptr setPrgname func(name *byte) typeName func(gtype uintptr) uintptr slistFree func(list uintptr) @@ -296,10 +299,13 @@ func (g *gtkLibrary) bindAll() { b(&g.signalConnect, "g_signal_connect_data") b(&g.signalDisc, "g_signal_handler_disconnect") b(&g.idleAdd, "g_idle_add") + b(&g.idleAddFull, "g_idle_add_full") + b(&g.sourceFind, "g_main_context_find_source_by_id") b(&g.timeoutAdd, "g_timeout_add") b(&g.sourceRemove, "g_source_remove") b(&g.gFree, "g_free") b(&g.objectUnref, "g_object_unref") + b(&g.objectRef, "g_object_ref") b(&g.setPrgname, "g_set_prgname") b(&g.typeName, "g_type_name") b(&g.slistFree, "g_slist_free") diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index 01f6418b3..ca8504ed1 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -374,6 +374,11 @@ func (w *gtkWindow) destroy() { return } w.destroying = true + // Input modules may disconnect signals from the widget that owns this window. + if ime := w.ime; ime != nil { + w.ime = nil + ime.close() + } w.g.widgetDestroy(w.toplevel) } diff --git a/internal/platform/linux/gtk_window_teardown_linux_test.go b/internal/platform/linux/gtk_window_teardown_linux_test.go new file mode 100644 index 000000000..68167ff57 --- /dev/null +++ b/internal/platform/linux/gtk_window_teardown_linux_test.go @@ -0,0 +1,171 @@ +//go:build linux && vivagtk + +package linux + +import ( + "fmt" + "os" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +func TestGTKDestroyDetachesInputMethodBeforeNativeWidget(t *testing.T) { + g := >kLibrary{} + a := >kApplication{g: g} + w := >kWindow{app: a, g: g, toplevel: 17} + w.ime = >kIME{w: w, g: g, ctx: 23, active: true} + detached, destroyed := false, 0 + references, retired := 1, false + g.objectRef = func(context uintptr) uintptr { + if context != 23 || references == 0 { + t.Fatal("native call referenced a released input context") + } + references++ + return context + } + g.objectUnref = func(context uintptr) { + if context != 23 || references == 0 { + t.Fatal("input context released more than once") + } + references-- + } + g.idleAddFull = func(priority int32, function, data, destroy uintptr) uint32 { + if priority != 200 || function != callbacks().retireIME || data != 23 || destroy != callbacks().releaseIME || !detached || destroyed != 0 || references != 1 || retired { + t.Error("input context retirement did not retain its final native reference") + } + retired = true + return 1 + } + g.sourceFind = func(context uintptr, id uint32) uintptr { + if context != 0 || id != 1 { + t.Error("unexpected retired input context source") + } + if retired { + return 23 + } + return 0 + } + g.sourceRemove = func(id uint32) int32 { + if id != 1 || !retired { + t.Fatal("retired input context source removed more than once") + } + retired = false + g.objectUnref(23) + return 1 + } + g.imFocusOut = func(context uintptr) { + if context != 23 || !w.destroying || w.ime != nil { + t.Error("native focus-out did not keep the context and destruction guard") + } + w.destroy() + } + g.imSetClientWindow = func(context, window uintptr) { + if context != 23 || window != 0 || destroyed != 0 { + t.Errorf("detach context=%d window=%d after %d native destructions", context, window, destroyed) + } + detached = true + } + g.widgetDestroy = func(window uintptr) { + destroyed++ + if window != 17 || !detached || w.ime != nil || references != 1 || !retired { + t.Error("native widget destruction preceded input-method detachment") + } + } + w.destroy() + w.destroy() + if destroyed != 1 || !detached { + t.Fatalf("native destruction count=%d detached=%t", destroyed, detached) + } + a.releaseRetiredIME() + a.releaseRetiredIME() + if references != 0 || retired || len(a.retiredIMESources) != 0 { + t.Fatalf("shutdown retained context: references=%d retired=%t sources=%v", references, retired, a.retiredIMESources) + } +} + +func TestGTKNativeInputMethodWindowTeardown(t *testing.T) { + if os.Getenv("VIVA_GTK_CLOSE_NATIVE") != "1" { + t.Skip("native close probe requires a private display and the Fcitx GTK module") + } + for _, mode := range []string{"programmatic", "default", "deferred"} { + t.Run(mode, func(t *testing.T) { + closed, requests, events := 0, 0, 0 + allowed := false + var failures []string + err := RunGTKApplication(func(application platform.Application) error { + a := application.(*gtkApplication) + window, err := application.OpenWindow(platform.Config{ + Title: "Viva native input method close probe", Width: 360, Height: 160, + DynamicTextInput: true, OnRedraw: func() (platform.Frame, error) { return platform.Frame{}, nil }, + }) + if err != nil { + return err + } + w := window.(*gtkWindow) + a.enqueue(func() { + editor := text.NewEditor("abc") + field := platform.TextInput{ + Target: gfx.Item(1), X: 20, Y: 20, Width: 300, Height: 100, FontSize: 16, + State: platform.EditorState(editor), + OnEvent: func(event platform.TextEvent) (platform.TextState, error) { + events++ + event.Apply(editor) + return platform.EditorState(editor), nil + }, + } + w.present(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}, nil) + w.ime.setFocused(true) + ime, before := w.ime, events + var typeFromName func(*byte) uintptr + var closeWindow func(uintptr) + if !a.g.lookup(&typeFromName, "g_type_from_name") || !a.g.lookup(&closeWindow, "gtk_window_close") { + a.fail(fmt.Errorf("native close probe cannot bind GTK/GObject functions")) + return + } + name := cString("FcitxIMContext") + if typeFromName(&name[0]) == 0 { + a.fail(fmt.Errorf("native close probe did not load FcitxIMContext")) + return + } + t.Logf("native backend=%s input module=FcitxIMContext mode=%s", typeNameOf(a.g, a.g.gdkDisplayDefault()), mode) + w.config.OnClosed = func() { + closed++ + if !w.closed || w.ime != nil || ime.ctx != 0 || events != before || editor.String() != "abc" || closed != 1 { + failures = append(failures, "native close retained input ownership, ran twice or delivered a closing edit") + } + if mode == "deferred" && (!allowed || requests != 1) { + failures = append(failures, "native close bypassed application approval") + } + } + if mode == "deferred" { + w.config.OnCloseRequest = func(allow func()) { + requests++ + a.g.timeoutAdd(20, callbacks().task, a.tasks.add(func() { + if w.closed || w.destroying || w.ime != ime || !ime.active { + failures = append(failures, "native close tore down input before application approval") + } + allowed = true + allow() + })) + } + } + if mode == "programmatic" { + w.Close() + } else { + closeWindow(w.toplevel) + } + }) + return nil + }) + if err != nil || closed != 1 { + t.Fatalf("native application error=%v close count=%d", err, closed) + } + for _, failure := range failures { + t.Error(failure) + } + }) + } +} diff --git a/internal/platform/linux/ime_linux.go b/internal/platform/linux/ime_linux.go index 9830ea5cf..02760e0f4 100644 --- a/internal/platform/linux/ime_linux.go +++ b/internal/platform/linux/ime_linux.go @@ -67,8 +67,10 @@ func (application *linuxApplication) newIME(win *window, textInput *linuxTextInp } ime := &linuxIME{app: application, text: textInput, router: router, origin: win.contentOrigin} context, err := bus.NewContext("viva", ibus.Handler{ - Commit: ime.commit, - Preedit: ime.preedit, + Commit: ime.commit, + Preedit: func(event ibus.PreeditEvent) { + ime.preedit(event.Text, event.Cursor, event.Visible, event.Attributes) + }, Forward: ime.forward, DeleteSurrounding: ime.deleteSurrounding, diff --git a/internal/platform/linux/input_linux.go b/internal/platform/linux/input_linux.go index 649018f2d..7c3a81c9a 100644 --- a/internal/platform/linux/input_linux.go +++ b/internal/platform/linux/input_linux.go @@ -218,7 +218,9 @@ func (router eventRouter) key(keymap *xcbKeymap, event *xcbInputEvent, repeat bo keyEvent := platform.KeyEvent{Key: key, Modifiers: modifiers, Repeat: repeat} if modifiers&(input.ModifierControl|input.ModifierMeta) != 0 { // A chord is the same on every layout: Ctrl+C is the key that types c. - keyEvent.Text = keymap.shortcutText(event.Detail, event.State) + // Shift is a modifier like the others, so Ctrl+Shift+C carries the same + // base character as Ctrl+C (gfx.KeyEvent.Text), not the capital. + keyEvent.Text = keymap.shortcutText(event.Detail, 0) } else { keyEvent.Text = keymap.text(event.Detail, event.State) } diff --git a/internal/platform/linux/input_linux_test.go b/internal/platform/linux/input_linux_test.go index 2cf80cbf8..979671de4 100644 --- a/internal/platform/linux/input_linux_test.go +++ b/internal/platform/linux/input_linux_test.go @@ -470,6 +470,32 @@ func TestTerminalThatAsksForReleasesGetsPairedKeysAndModifiers(t *testing.T) { } } +// A Control chord names its base key, Shift or not: Control+Shift+C arrives as +// Text "c" with Shift in Modifiers, the same as Control+C. KeyEvent.Text is the +// character without modifiers (see gfx.KeyEvent), so an application looking for +// "c" finds the copy chord whether or not Shift came along. +func TestControlShiftChordNamesTheBaseCharacter(t *testing.T) { + var keys []platform.KeyEvent + router := eventRouter{ + config: platform.Config{OnKey: func(event platform.KeyEvent) (platform.Frame, error) { + keys = append(keys, event) + return platform.Frame{}, nil + }}, + text: &linuxTextInput{enabled: true, input: platform.TextInput{Terminal: true}}, + present: func(platform.Frame) error { return nil }, + modifierKeys: newModifierTracker(), + } + // Keycode 9 types c and C. + keymap := xcbKeymap{first: 9, last: 9, perKeycode: 2, keysyms: []uint32{'c', 'C'}} + if err := router.key(&keymap, &xcbInputEvent{Detail: 9, State: xcbModShift | xcbModControl}, false); err != nil { + t.Fatal(err) + } + want := []platform.KeyEvent{{Modifiers: input.ModifierShift | input.ModifierControl, Text: "c"}} + if !reflect.DeepEqual(keys, want) { + t.Fatalf("keys =\n%+v\nwant\n%+v", keys, want) + } +} + func TestModifierKeysAreNotDeliveredToTerminalsThatDidNotAsk(t *testing.T) { called := false router := eventRouter{ diff --git a/internal/platform/linux/layers_test.go b/internal/platform/linux/layers_test.go index 28eda5afa..d2230b7c2 100644 --- a/internal/platform/linux/layers_test.go +++ b/internal/platform/linux/layers_test.go @@ -46,9 +46,9 @@ func TestBitmapCacheResizesWithoutRecreatingImage(t *testing.T) { func TestCompositingLayersInterleaveRectanglesAndText(t *testing.T) { rectangles := []render.Rectangle{{Layer: 0}, {Layer: 2}, {Layer: 2}, {Layer: 5}} labels := []vulkanLabelTexture{ - {label: platform.TextLabel{Value: "back", Layer: 0, ShapesBefore: 1}}, - {label: platform.TextLabel{Value: "middle", Layer: 2, ShapesBefore: 3}}, {label: platform.TextLabel{Value: "top", Layer: 5, ShapesBefore: 4}}, + {label: platform.TextLabel{Value: "middle", Layer: 2, ShapesBefore: 3}}, + {label: platform.TextLabel{Value: "back", Layer: 0, ShapesBefore: 1}}, } rectangleBatches := render.GroupBatches(nil, rectangles) order := groupTextLayers(labels, nil) @@ -67,3 +67,29 @@ func TestCompositingLayersInterleaveRectanglesAndText(t *testing.T) { t.Fatalf("text order = %v", order) } } + +func TestCompositingLayersSplitAShapeBatchAroundText(t *testing.T) { + rectangles := render.GroupBatches(nil, []render.Rectangle{{Layer: 2}, {Layer: 2}, {Layer: 2}}) + labels := []vulkanLabelTexture{ + {label: platform.TextLabel{Value: "before", Layer: 2}}, + {label: platform.TextLabel{Value: "between", Layer: 2, ShapesBefore: 1}}, + {label: platform.TextLabel{Value: "after", Layer: 2, ShapesBefore: 3}}, + } + order := groupTextLayers(labels, nil) + batches := groupCompositingLayers(rectangles, labels, order, nil) + want := []compositingBatch{ + {Kind: compositeText, Layer: 2, First: 0, Count: 1}, + {Kind: compositeRectangles, Layer: 2, First: 0, Count: 1}, + {Kind: compositeText, Layer: 2, First: 1, Count: 1}, + {Kind: compositeRectangles, Layer: 2, First: 1, Count: 2}, + {Kind: compositeText, Layer: 2, First: 2, Count: 1}, + } + if len(batches) != len(want) { + t.Fatalf("batches = %+v, want %+v", batches, want) + } + for index := range want { + if batches[index] != want[index] { + t.Errorf("batch %d = %+v, want %+v", index, batches[index], want[index]) + } + } +} diff --git a/internal/platform/linux/post_linux.go b/internal/platform/linux/post_linux.go new file mode 100644 index 000000000..9bce0c37e --- /dev/null +++ b/internal/platform/linux/post_linux.go @@ -0,0 +1,33 @@ +//go:build linux + +package linux + +// Post runs fn on the event loop; it is safe from any goroutine. +func (application *linuxApplication) Post(fn func()) { + if fn == nil { + return + } + application.postMu.Lock() + application.posts = append(application.posts, fn) + application.postMu.Unlock() + if application.postWake.CompareAndSwap(false, true) { + application.post(commandPost) + } +} + +// drainPosts runs the functions accepted since the last drain, in order. A +// function that posts another is picked up by this same drain. +func (application *linuxApplication) drainPosts() { + application.postWake.Store(false) + for { + application.postMu.Lock() + if len(application.posts) == 0 { + application.postMu.Unlock() + return + } + fn := application.posts[0] + application.posts = application.posts[1:] + application.postMu.Unlock() + fn() + } +} diff --git a/internal/platform/linux/post_linux_test.go b/internal/platform/linux/post_linux_test.go new file mode 100644 index 000000000..63232d8b5 --- /dev/null +++ b/internal/platform/linux/post_linux_test.go @@ -0,0 +1,29 @@ +//go:build linux + +package linux + +import "testing" + +func TestPostDrainsInOrder(t *testing.T) { + application := &linuxApplication{} + var seen []int + application.Post(func() { seen = append(seen, 1) }) + application.Post(func() { seen = append(seen, 2) }) + application.drainPosts() + if len(seen) != 2 || seen[0] != 1 || seen[1] != 2 { + t.Fatalf("seen = %v, want [1 2]", seen) + } +} + +func TestAWindowsDrainPicksUpWorkPostedWhileItRuns(t *testing.T) { + application := &linuxApplication{} + var seen []int + application.Post(func() { + seen = append(seen, 1) + application.Post(func() { seen = append(seen, 2) }) + }) + application.drainPosts() + if len(seen) != 2 || seen[0] != 1 || seen[1] != 2 { + t.Fatalf("seen = %v, want [1 2]", seen) + } +} diff --git a/internal/platform/linux/sleep_linux.go b/internal/platform/linux/sleep_linux.go new file mode 100644 index 000000000..0c077bf03 --- /dev/null +++ b/internal/platform/linux/sleep_linux.go @@ -0,0 +1,55 @@ +//go:build linux + +package linux + +import ( + "errors" + "fmt" + "sync" + "syscall" + + "github.com/vivaui/viva/internal/dbus" +) + +// ErrSleepUnavailable reports that this system has no logind to hold an +// inhibitor lock, or that it refused one. +var ErrSleepUnavailable = errors.New("linux: sleep inhibition is unavailable") + +// PreventSleep asks logind to keep the machine out of idle sleep until release +// runs. logind answers with a lock held through file descriptor; the connection +// and the descriptor stay open for as long as the lock is wanted, and the lock +// is gone when release closes them. +func PreventSleep(reason string) (release func(), err error) { + conn, err := dbus.DialSystem() + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrSleepUnavailable, err) + } + var body dbus.Encoder + body.String("idle") + body.String(reason) + body.String(reason) + body.String("block") + reply, err := conn.Call( + "org.freedesktop.login1", "/org/freedesktop/login1", + "org.freedesktop.login1.Manager", "Inhibit", "ssss", body.Bytes(), + ) + if err != nil { + conn.Close() + return nil, fmt.Errorf("%w: %v", ErrSleepUnavailable, err) + } + lock := reply.TakeFD(reply.Args().UnixFD()) + reply.CloseFDs() + if lock < 0 { + conn.Close() + return nil, fmt.Errorf("%w: logind returned no lock", ErrSleepUnavailable) + } + var once sync.Once + return func() { + once.Do(func() { + // Closing the descriptor releases the lock; closing the + // connection ends the session that held it. + syscall.Close(lock) + conn.Close() + }) + }, nil +} diff --git a/internal/platform/linux/sleep_linux_test.go b/internal/platform/linux/sleep_linux_test.go new file mode 100644 index 000000000..aabf6352c --- /dev/null +++ b/internal/platform/linux/sleep_linux_test.go @@ -0,0 +1,23 @@ +//go:build linux + +package linux + +import ( + "errors" + "testing" +) + +// TestPreventSleepWhenLogindIsThere holds a lock only where the machine has +// one. A build container or a session without logind has no system bus to ask, +// and skipping there hides nothing this code promises. +func TestPreventSleepWhenLogindIsThere(t *testing.T) { + release, err := PreventSleep("viva test: sleep inhibition") + if errors.Is(err, ErrSleepUnavailable) { + t.Skipf("no logind inhibitor: %v", err) + } + if err != nil { + t.Fatal(err) + } + release() + release() // releasing twice is not an error and does not close another lock +} diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 66af1ef33..11d47aed9 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -199,6 +199,8 @@ func (state *linuxWindowState) command(command uint32, data []byte) error { state.application.drainStatusRemovals() case commandDesktop: state.application.syncDesktopWatch() + case commandPost: + state.application.drainPosts() } return nil } diff --git a/internal/platform/linux/text_callback_linux_test.go b/internal/platform/linux/text_callback_linux_test.go new file mode 100644 index 000000000..77c47ca8f --- /dev/null +++ b/internal/platform/linux/text_callback_linux_test.go @@ -0,0 +1,350 @@ +package linux + +import ( + "errors" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/text" +) + +func callbackTextField(editor *text.Editor) platform.TextInput { + return platform.TextInput{ + Target: gfx.Scope(1).At(1), Width: 120, Height: 28, FontSize: 16, + State: platform.EditorState(editor), + OnEvent: func(event platform.TextEvent) (platform.TextState, error) { + event.Apply(editor) + return platform.EditorState(editor), nil + }, + } +} + +func prepareCallbackFrame(t *testing.T, state *linuxTextInput, frame platform.Frame) platform.Frame { + t.Helper() + merged, _, err := state.prepare(frame) + if err != nil { + t.Fatal(err) + } + return merged +} + +func TestLinuxTextCallbackKeepsInputInstalledDuringEvent(t *testing.T) { + for _, scenario := range []struct { + name, replacement string + disable bool + }{ + {name: "different value", replacement: "new"}, + {name: "same value", replacement: "old"}, + {name: "disabled", disable: true}, + } { + t.Run(scenario.name, func(t *testing.T) { + state := &linuxTextInput{ + config: &platform.Config{DynamicTextInput: true}, engine: fixedAdvanceEngine{}, + } + t.Cleanup(state.close) + old := callbackTextField(text.NewEditor("old")) + next := callbackTextField(text.NewEditor(scenario.replacement)) + next.Target, next.Width = gfx.Scope(1).At(2), 240 + old.OnEvent = func(platform.TextEvent) (platform.TextState, error) { + var replacement *platform.TextInput + if !scenario.disable { + replacement = &next + } + prepareCallbackFrame(t, state, platform.Frame{ + TextInput: platform.TextInputUpdate{Changed: true, Input: replacement}, + }) + // A stale acknowledgment is not valid for the replacement owner. + stale := old.State + stale.Selection.End = 100 + return stale, nil + } + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &old}}) + frame, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "x"}) + if err != nil { + t.Fatalf("superseded acknowledgment was validated: %v", err) + } + merged := prepareCallbackFrame(t, state, frame) + if scenario.disable { + if state.enabled || state.state != (platform.TextState{}) || len(merged.TextLabels) != 0 { + t.Fatalf("disabled input was resurrected: enabled=%t state=%+v labels=%v", state.enabled, state.state, merged.TextLabels) + } + return + } + if !state.enabled || state.input.Target != next.Target || state.input.Width != 240 || state.state != next.State { + t.Fatalf("replacement input was overwritten: input=%+v state=%+v", state.input, state.state) + } + if len(merged.TextLabels) != 1 || merged.TextLabels[0].Value != scenario.replacement { + t.Fatalf("replacement visuals = %v", merged.TextLabels) + } + }) + } +} + +func TestLinuxTextCallbackKeepsNestedEventAcknowledgment(t *testing.T) { + editor := text.NewEditor("abc") + state := &linuxTextInput{ + config: &platform.Config{DynamicTextInput: true}, engine: fixedAdvanceEngine{}, + } + t.Cleanup(state.close) + field := callbackTextField(editor) + nested := false + field.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + event.Apply(editor) + next := platform.EditorState(editor) + if !nested { + nested = true + if _, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "n"}); err != nil { + t.Fatal(err) + } + } + return next, nil + } + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}) + frame, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "x"}) + if err != nil { + t.Fatal(err) + } + merged := prepareCallbackFrame(t, state, frame) + if editor.String() != "abcxn" || state.state.Value != "abcxn" || state.input.State.Value != "abcxn" || + len(merged.TextLabels) != 1 || merged.TextLabels[0].Value != "abcxn" { + t.Fatalf("nested edit lost: editor=%q state=%+v labels=%v", editor.String(), state.state, merged.TextLabels) + } +} + +func TestLinuxTextCallbackAcceptsEventAcrossGeometryUpdate(t *testing.T) { + for _, beforeEdit := range []bool{true, false} { + t.Run(map[bool]string{true: "before edit", false: "after edit"}[beforeEdit], func(t *testing.T) { + editor := text.NewEditor("abc") + redraws := 0 + state := &linuxTextInput{ + config: &platform.Config{DynamicTextInput: true, OnRedraw: func() (platform.Frame, error) { + redraws++ + return platform.Frame{}, nil + }}, + engine: fixedAdvanceEngine{}, + } + t.Cleanup(state.close) + field := callbackTextField(editor) + field.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + if beforeEdit { + geometry := state.input + geometry.Width = 240 + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &geometry}}) + } + event.Apply(editor) + if !beforeEdit { + geometry := state.input + geometry.Width = 240 + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &geometry}}) + } + return platform.EditorState(editor), nil + } + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}) + frame, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "x"}) + if err != nil { + t.Fatal(err) + } + merged := prepareCallbackFrame(t, state, frame) + if editor.String() != "abcx" || state.state.Value != "abcx" || state.input.Width != 240 || redraws != 1 || + len(merged.TextLabels) != 1 || merged.TextLabels[0].Value != "abcx" { + t.Fatalf("geometry update lost valid edit: editor=%q state=%+v width=%v redraws=%d labels=%v", editor.String(), state.state, state.input.Width, redraws, merged.TextLabels) + } + }) + } +} + +func TestLinuxTextCallbackDiscardsSupersededRedraw(t *testing.T) { + for _, scenario := range []string{"replacement", "same-value replacement", "disabled", "nested edit", "same-value acknowledgment"} { + t.Run(scenario, func(t *testing.T) { + editor := text.NewEditor("abc") + config := &platform.Config{DynamicTextInput: true} + state := &linuxTextInput{config: config, engine: fixedAdvanceEngine{}} + t.Cleanup(state.close) + field := callbackTextField(editor) + field.Terminal = scenario == "same-value acknowledgment" + prepareCallbackFrame(t, state, platform.Frame{ + Update: render.Update{Count: 1, Rebuild: true}, Rectangles: []render.Rectangle{{Layer: 7}}, + TextLabels: []platform.TextLabel{{Value: "current scene"}}, + TextInput: platform.TextInputUpdate{Changed: true, Input: &field}, + }) + redraws := 0 + config.OnRedraw = func() (platform.Frame, error) { + redraws++ + if redraws > 1 { + return platform.Frame{}, nil + } + oldInput := state.input + switch scenario { + case "replacement", "same-value replacement": + value := "new" + if scenario == "same-value replacement" { + value = editor.String() + } + replacement := callbackTextField(text.NewEditor(value)) + replacement.Width = 240 + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &replacement}}) + case "disabled": + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true}}) + case "nested edit": + if _, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "n"}); err != nil { + t.Fatal(err) + } + case "same-value acknowledgment": + if _, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert}); err != nil { + t.Fatal(err) + } + } + return platform.Frame{ + Update: render.Update{Count: 1, Rebuild: true}, Rectangles: []render.Rectangle{{Layer: 99}}, + TextLabels: []platform.TextLabel{{Value: "superseded scene"}}, + Accessibility: []platform.AccessibilityNode{{Value: "superseded input"}}, + TextInput: platform.TextInputUpdate{Changed: true, Input: &oldInput}, + NativeViews: []platform.NativeView{{}}, + }, nil + } + frame, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "x"}) + if err != nil { + t.Fatal(err) + } + if !frame.Update.Empty() || frame.Rectangles != nil || frame.TextLabels != nil || frame.Accessibility != nil || frame.NativeViews != nil { + t.Fatalf("superseded application scene survived: %+v", frame) + } + prepareCallbackFrame(t, state, frame) + if state.baseRectangles[0].Layer != 7 || state.baseLabels[0].Value != "current scene" { + t.Fatalf("retained scene overwritten: rectangles=%v labels=%v", state.baseRectangles, state.baseLabels) + } + switch scenario { + case "replacement": + if state.state.Value != "new" || state.input.Width != 240 { + t.Fatalf("replacement overwritten: %+v", state.input) + } + case "same-value replacement": + if state.state.Value != "abcx" || state.input.Width != 240 { + t.Fatalf("same-value input overwritten: %+v", state.input) + } + case "disabled": + if state.enabled { + t.Fatal("disabled input resurrected") + } + case "nested edit": + if state.state.Value != "abcxn" { + t.Fatalf("nested edit overwritten: %+v", state.state) + } + case "same-value acknowledgment": + if !state.input.Terminal || redraws != 1 { + t.Fatalf("terminal acknowledgment was overwritten or redrawn: terminal=%t redraws=%d", state.input.Terminal, redraws) + } + } + }) + } +} + +func TestLinuxTextCallbackRejectsEventAfterInputModeChange(t *testing.T) { + for _, scenario := range []struct { + name string + change func(*platform.TextInput) + }{ + {"secure", func(input *platform.TextInput) { input.Secure = true }}, + {"terminal", func(input *platform.TextInput) { input.Terminal = true }}, + {"placed", func(input *platform.TextInput) { input.Placed = true }}, + } { + t.Run(scenario.name, func(t *testing.T) { + editor := text.NewEditor("abc") + state := &linuxTextInput{config: &platform.Config{DynamicTextInput: true}, engine: fixedAdvanceEngine{}} + t.Cleanup(state.close) + field := callbackTextField(editor) + field.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + next := state.input + scenario.change(&next) + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &next}}) + event.Apply(editor) + return platform.EditorState(editor), nil + } + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}) + frame, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "x"}) + if err != nil { + t.Fatal(err) + } + prepareCallbackFrame(t, state, frame) + if editor.String() != "abcx" || state.state.Value != "abc" || state.input.State.Value != "abc" { + t.Fatalf("old-mode acknowledgment crossed into new mode: editor=%q state=%+v", editor.String(), state.state) + } + }) + } +} + +func TestLinuxTextCallbackCannotReviveClosedInput(t *testing.T) { + for _, duringRedraw := range []bool{false, true} { + t.Run(map[bool]string{true: "during redraw", false: "during event"}[duringRedraw], func(t *testing.T) { + editor := text.NewEditor("abc") + state := &linuxTextInput{config: &platform.Config{DynamicTextInput: true}, engine: fixedAdvanceEngine{}} + state.postCaret = func(uint32) {} + t.Cleanup(state.close) + field := callbackTextField(editor) + if !duringRedraw { + field.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + event.Apply(editor) + state.close() + return platform.EditorState(editor), nil + } + } + redraws := 0 + state.config.OnRedraw = func() (platform.Frame, error) { + redraws++ + state.close() + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}, nil + } + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}) + if state.caretTimer == nil { + t.Fatal("fixture did not arm the caret timer") + } + frame, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "x"}) + if err != nil { + t.Fatal(err) + } + if state.enabled || state.state != (platform.TextState{}) || state.caretTimer != nil || frame.TextInput.Changed || + redraws != map[bool]int{true: 1, false: 0}[duringRedraw] { + t.Fatalf("closed input revived: enabled=%t state=%+v timer=%v redraws=%d frame=%+v", state.enabled, state.state, state.caretTimer, redraws, frame) + } + if _, changed, err := state.prepare(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}); err != nil || changed || state.enabled { + t.Fatalf("late frame revived closed input: changed=%t enabled=%t err=%v", changed, state.enabled, err) + } + if frame, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "late"}); err != nil || frame.TextInput.Changed || editor.String() != "abcx" { + t.Fatalf("closed input accepted a late event: editor=%q frame=%+v err=%v", editor.String(), frame, err) + } + }) + } +} + +func TestLinuxTextCallbackPreservesErrorsAfterReentry(t *testing.T) { + for _, duringRedraw := range []bool{false, true} { + t.Run(map[bool]string{true: "redraw error", false: "event error"}[duringRedraw], func(t *testing.T) { + sentinel := errors.New("callback failed") + state := &linuxTextInput{config: &platform.Config{DynamicTextInput: true}, engine: fixedAdvanceEngine{}} + t.Cleanup(state.close) + field := callbackTextField(text.NewEditor("abc")) + replacement := callbackTextField(text.NewEditor("new")) + replacement.Target = gfx.Scope(1).At(2) + replace := func() { + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &replacement}}) + } + if duringRedraw { + state.config.OnRedraw = func() (platform.Frame, error) { + replace() + return platform.Frame{}, sentinel + } + } else { + field.OnEvent = func(platform.TextEvent) (platform.TextState, error) { + replace() + return field.State, sentinel + } + } + prepareCallbackFrame(t, state, platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}) + if _, err := state.textEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "x"}); err != sentinel || state.state.Value != "new" || state.input.Target != replacement.Target { + t.Fatalf("callback error or newer input lost: err=%v state=%+v input=%+v", err, state.state, state.input) + } + }) + } +} diff --git a/internal/platform/linux/text_input_linux.go b/internal/platform/linux/text_input_linux.go index 71d020bb9..7ac85b3f8 100644 --- a/internal/platform/linux/text_input_linux.go +++ b/internal/platform/linux/text_input_linux.go @@ -26,6 +26,11 @@ type linuxTextInput struct { input platform.TextInput state platform.TextState enabled bool + closed bool + // Every acknowledgment advances both counters, even if its value is the + // same. Geometry alone supersedes a redraw, but not an event's text result. + stateRevision uint64 + inputRevision uint64 caretVisible bool caretGeneration uint32 @@ -83,7 +88,15 @@ func newLinuxTextInput(config *platform.Config) (*linuxTextInput, error) { } func (state *linuxTextInput) close() { + if state.closed { + return + } + state.closed, state.enabled = true, false + state.stateRevision++ + state.inputRevision++ state.stopCaretBlink() + state.input = platform.TextInput{} + state.state = platform.TextState{} state.engine = nil } @@ -164,6 +177,9 @@ func (state *linuxTextInput) initial() ([]render.Rectangle, []platform.TextLabel } func (state *linuxTextInput) prepare(frame platform.Frame) (platform.Frame, bool, error) { + if state.closed { + return platform.Frame{}, false, nil + } rectanglesChanged := !frame.Update.Empty() labelsChanged := frame.TextLabels != nil if rectanglesChanged { @@ -221,7 +237,7 @@ func (state *linuxTextInput) prepare(frame platform.Frame) (platform.Frame, bool } func (state *linuxTextInput) applyUpdate(update platform.TextInputUpdate) (bool, error) { - if !update.Changed { + if !update.Changed || state.closed { return false, nil } if !state.config.DynamicTextInput { @@ -230,6 +246,10 @@ func (state *linuxTextInput) applyUpdate(update platform.TextInputUpdate) (bool, if err := validateLinuxTextInput(update.Input); err != nil { return false, err } + state.inputRevision++ + if !state.enabled || update.Input == nil || !sameLinuxTextSession(state.input, *update.Input) { + state.stateRevision++ + } if update.Input == nil { state.stopCaretBlink() state.compose.reset() @@ -251,6 +271,15 @@ func (state *linuxTextInput) applyUpdate(update platform.TextInputUpdate) (bool, return true, nil } +func sameLinuxTextSession(previous, next platform.TextInput) bool { + return previous.Target == next.Target && previous.State == next.State && + previous.Multiline == next.Multiline && previous.Secure == next.Secure && + previous.Terminal == next.Terminal && previous.CopyOverride == next.CopyOverride && + previous.AltSendsEscape == next.AltSendsEscape && previous.KeyReleases == next.KeyReleases && + previous.DisableIME == next.DisableIME && previous.NavigationKeys == next.NavigationKeys && + previous.Placed == next.Placed +} + func (state *linuxTextInput) rebuild() error { extraRectangles, extraLabels := 0, 0 if state.enabled { @@ -618,7 +647,11 @@ func (state *linuxTextInput) textEvent(event platform.TextEvent) (platform.Frame return platform.Frame{}, nil } previous := state.state + revision := state.stateRevision next, err := state.input.OnEvent(event) + if err == nil && state.stateRevision != revision { + return state.currentTextFrame(), nil + } if err == nil { err = validateLinuxTextState(next) } @@ -627,6 +660,8 @@ func (state *linuxTextInput) textEvent(event platform.TextEvent) (platform.Frame } redraw := platform.TextInputPresentationChanged(state.input.Terminal, previous, next) next = next.WithoutRedraw() // a one-shot request, not editor state + state.stateRevision++ + state.inputRevision++ state.state = next state.input.State = next state.publishPrimary(previous, next) @@ -634,8 +669,14 @@ func (state *linuxTextInput) textEvent(event platform.TextEvent) (platform.Frame return platform.Frame{}, nil } state.restartCaretBlink() + revision = state.inputRevision if state.config.OnRedraw != nil { frame, err := state.config.OnRedraw() + if err == nil && state.inputRevision != revision { + // The callback's scene and input belong to an older acknowledgment. + // Refresh the current mirror, including after a nested terminal no-op. + return state.currentTextFrame(), nil + } if err == nil && !frame.TextInput.Changed { frame.TextInput = platform.TextInputUpdate{Changed: true, Input: &state.input} } @@ -644,6 +685,17 @@ func (state *linuxTextInput) textEvent(event platform.TextEvent) (platform.Frame return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &state.input}}, nil } +func (state *linuxTextInput) currentTextFrame() platform.Frame { + if state.closed { + return platform.Frame{} + } + var current *platform.TextInput + if state.enabled { + current = &state.input + } + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: current}} +} + // caretShown says whether the field has a native caret to draw: not a terminal, // not while a component paints its own caret, not while composing, and not // over a selection. diff --git a/internal/platform/linux/window_icon_linux_test.go b/internal/platform/linux/window_icon_linux_test.go index 6823e121d..9ded6f7e2 100644 --- a/internal/platform/linux/window_icon_linux_test.go +++ b/internal/platform/linux/window_icon_linux_test.go @@ -37,7 +37,8 @@ func TestNetWMIconOffersEverySizeTheSourceCanFill(t *testing.T) { func TestNetWMIconCarriesTheMarkInTheImagesAPanelDraws(t *testing.T) { // A dark mark a quarter of the side on white. The 16 px image a panel asks - // for must carry the mark, not the canvas margin around it. + // for must carry the mark at the shared seven-tenths side policy, with + // breathing room. Area coverage is not the mark's width or height. const side = 64 pixels := make([]byte, side*side*4) for index := 0; index < len(pixels); index += 4 { @@ -52,15 +53,22 @@ func TestNetWMIconCarriesTheMarkInTheImagesAPanelDraws(t *testing.T) { for offset := 0; offset < len(data); { width := int(data[offset]) if width == 16 { - dark := 0 + left, top, right, bottom := width, width, -1, -1 for index := 0; index < width*width; index++ { pixel := data[offset+2+index] if pixel>>24 > 128 && (pixel>>16)&0xff < 64 { - dark++ + x, y := index%width, index/width + left, top = min(left, x), min(top, y) + right, bottom = max(right, x), max(bottom, y) } } - if share := float64(dark) / float64(width*width); share < 0.6 { - t.Errorf("the 16 px image is %.0f%% mark: the panel would show the canvas margin", share*100) + for _, span := range []int{right - left + 1, bottom - top + 1} { + if share := float64(span) / float64(width); share < 0.6 || share > 0.8 { + t.Errorf("the 16 px mark spans %d px: want roughly seven tenths of each side", span) + } + } + if left == 0 || top == 0 || right == width-1 || bottom == width-1 { + t.Error("the small mark lost its surrounding margin") } return } diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index f4dbc8b42..9dd1c8b1f 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -183,6 +183,12 @@ type linuxApplication struct { // from there. liveMu sync.Mutex live []*window + + // posts are the functions other goroutines handed to Post; the loop drains + // them when commandPost arrives. postWake coalesces the messages. + postMu sync.Mutex + posts []func() + postWake atomic.Bool } // Commands another goroutine posts to a window's event loop through @@ -196,6 +202,7 @@ const ( commandEnterFullscreen commandExitFullscreen commandSetSize + commandPost ) type nativeWindow struct { diff --git a/internal/platform/menu_bar.go b/internal/platform/menu_bar.go new file mode 100644 index 000000000..f47b09bda --- /dev/null +++ b/internal/platform/menu_bar.go @@ -0,0 +1,21 @@ +package platform + +// MenuBarMenu is one top-level application menu. See app.Menu. +type MenuBarMenu struct { + Title string + Items []MenuBarItem +} + +// MenuBarItem is one entry of a MenuBarMenu. +type MenuBarItem struct { + Title string + Separator bool + Disabled bool + Checked bool + // Key is a single lowercase character the system offers as the shortcut; + // empty shows none. Modifiers are NSEventModifierFlags on macOS. + Key string + Modifiers uint32 + Items []MenuBarItem + OnSelect func() +} diff --git a/internal/platform/windows/border_windows.go b/internal/platform/windows/border_windows.go new file mode 100644 index 000000000..f31ee8c9a --- /dev/null +++ b/internal/platform/windows/border_windows.go @@ -0,0 +1,66 @@ +package windows + +import ( + "math" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +const ( + // dwmBorderColor is DWMWA_BORDER_COLOR, Windows 11 21H2 (build 22000) and + // later. The system draws a window's border in this color; without one it + // blends the border with what is behind the window. + dwmBorderColor = 34 + // dwmColorDefault is DWMWA_COLOR_DEFAULT: the system's own border color. + dwmColorDefault = 0xFFFFFFFF +) + +// colorRef is a color as the COLORREF DwmSetWindowAttribute takes, a +// 0x00BBGGRR word. Components outside 0..1 clamp to the nearest byte. +func colorRef(color platform.Color) uint32 { + channel := func(value float64) uint32 { + return uint32(math.Round(min(max(value, 0), 1) * 255)) + } + return channel(color.Red) | channel(color.Green)<<8 | channel(color.Blue)<<16 +} + +// applyBorderColor gives a custom-titlebar window's system border the color of +// the window's own edge. A window that extends its frame to keep the shadow +// gets a border that the system composites over the desktop, not over the +// window, so it is translucent: the desktop shows through a 1 DIP ring around +// the window at 100% scale and wider at higher scale, which reads as a +// transparent edge in light mode. An opaque color the window is painted with +// makes the border continuous. Material-backed windows and ones that name no +// opaque color keep the system's border. +func (state *windowState) applyBorderColor() { + if state.window == 0 { + return + } + value, colored := windowBorderColor(state.config, state.customFrame(), state.backdropActive) + if !colored && !state.borderColored { + return + } + if state.borderColored == colored && state.borderColor == value { + return + } + state.borderColored, state.borderColor = colored, value + dwmSetWindowAttribute.Call(state.window, dwmBorderColor, uintptr(unsafe.Pointer(&value)), unsafe.Sizeof(value)) +} + +// windowBorderColor is the border color a window asks for, and whether it asks +// for one at all: a custom-titlebar window that is not backed by a material and +// whose edge color is opaque. +func windowBorderColor(config platform.Config, customFrame, backdropActive bool) (uint32, bool) { + if !customFrame || backdropActive { + return dwmColorDefault, false + } + color := config.ClearColor + if config.WindowBorderColor != nil { + color = config.WindowBorderColor() + } + if color.Alpha < 1 { + return dwmColorDefault, false + } + return colorRef(color), true +} diff --git a/internal/platform/windows/border_windows_test.go b/internal/platform/windows/border_windows_test.go new file mode 100644 index 000000000..74c738bc4 --- /dev/null +++ b/internal/platform/windows/border_windows_test.go @@ -0,0 +1,74 @@ +package windows + +import ( + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +func TestColorRefPacksWindowsChannelOrder(t *testing.T) { + color := platform.Color{Red: 0.1, Green: 0.2, Blue: 0.3, Alpha: 1} + if got, want := colorRef(color), uint32(0x004D331A); got != want { + t.Fatalf("colorRef(%v) = %#08x, want %#08x", color, got, want) + } + clamped := platform.Color{Red: 2, Green: -1, Blue: 0.5, Alpha: 1} + if got, want := colorRef(clamped), uint32(0x008000FF); got != want { + t.Fatalf("colorRef(%v) = %#08x, want %#08x", clamped, got, want) + } +} + +func TestWindowBorderColorFollowsTheWindowEdge(t *testing.T) { + clear := platform.Color{Red: 0.94, Green: 0.94, Blue: 0.95, Alpha: 1} + tests := []struct { + name string + config platform.Config + custom bool + backdrop bool + wantColor uint32 + wantColored bool + }{ + { + name: "custom titlebar uses the clear color", + config: platform.Config{ClearColor: clear}, + custom: true, + wantColor: colorRef(clear), + wantColored: true, + }, + { + name: "the application's color wins over the clear color", + config: platform.Config{ + ClearColor: clear, + WindowBorderColor: func() platform.Color { return platform.Color{Red: 1, Green: 0, Blue: 0, Alpha: 1} }, + }, + custom: true, + wantColor: 0x000000FF, + wantColored: true, + }, + { + name: "a material keeps the system border", + config: platform.Config{ClearColor: clear}, + custom: true, + backdrop: true, + wantColor: dwmColorDefault, + }, + { + name: "a transparent window keeps the system border", + config: platform.Config{ClearColor: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 0.5}}, + custom: true, + wantColor: dwmColorDefault, + }, + { + name: "a system frame keeps its own border", + config: platform.Config{ClearColor: clear}, + wantColor: dwmColorDefault, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + color, colored := windowBorderColor(test.config, test.custom, test.backdrop) + if color != test.wantColor || colored != test.wantColored { + t.Fatalf("windowBorderColor = %#08x, %v; want %#08x, %v", color, colored, test.wantColor, test.wantColored) + } + }) + } +} diff --git a/internal/platform/windows/clipboard_html_windows.go b/internal/platform/windows/clipboard_html_windows.go index c35fdf5a5..d9c57c723 100644 --- a/internal/platform/windows/clipboard_html_windows.go +++ b/internal/platform/windows/clipboard_html_windows.go @@ -3,7 +3,6 @@ package windows import ( "encoding/binary" "fmt" - "strconv" "sync" "syscall" "unsafe" @@ -82,25 +81,16 @@ func cfHTML(html string) []byte { // The header is fixed once its values are ten digits wide; the // numbers only name byte offsets, never change the width. lands = "Version:0.9\r\n" + - "StartHTML:0000000000\r\n" + - "EndHTML:0000000000\r\n" + - "StartFragment:0000000000\r\n" + - "EndFragment:0000000000\r\n" + "StartHTML:%010d\r\n" + + "EndHTML:%010d\r\n" + + "StartFragment:%010d\r\n" + + "EndFragment:%010d\r\n" ) - startHTML := len(lands) + startHTML := len(fmt.Sprintf(lands, 0, 0, 0, 0)) startFragment := startHTML + len(front) endFragment := startFragment + len(html) endHTML := endFragment + len(back) - block := make([]byte, 0, endHTML) - block = append(block, "Version:0.9\r\n"...) - block = strconv.AppendUint(block, uint64(startHTML), 10) - block = append(block, "\r\nEndHTML:"...) - block = strconv.AppendUint(block, uint64(endHTML), 10) - block = append(block, "\r\nStartFragment:"...) - block = strconv.AppendUint(block, uint64(startFragment), 10) - block = append(block, "\r\nEndFragment:"...) - block = strconv.AppendUint(block, uint64(endFragment), 10) - block = append(block, "\r\n"...) + block := []byte(fmt.Sprintf(lands, startHTML, endHTML, startFragment, endFragment)) block = append(block, front...) block = append(block, html...) block = append(block, back...) diff --git a/internal/platform/windows/cursor_image_windows.go b/internal/platform/windows/cursor_image_windows.go index 37e9d2225..6ceb0d373 100644 --- a/internal/platform/windows/cursor_image_windows.go +++ b/internal/platform/windows/cursor_image_windows.go @@ -64,36 +64,42 @@ func retireCustomCursor(handle uintptr, image *gfx.CursorImage, scale float32) { // the system and never destroyed, so a preset recreated per request would leak // one per change. var grabbingCursor = struct { - once sync.Once + sync.Mutex + built bool image *gfx.CursorImage handle uintptr failure error }{} func grabbingCursorHandle() (uintptr, error) { - grabbingCursor.once.Do(func() { + grabbingCursor.Lock() + defer grabbingCursor.Unlock() + if !grabbingCursor.built { + grabbingCursor.built = true + grabbingCursor.image, grabbingCursor.handle, grabbingCursor.failure = nil, 0, nil image, err := gfx.NewCursorImage(16, 16, 6, 3, 1, grabbingCursorPixels()) if err != nil { grabbingCursor.failure = err - return - } - handle, err := newCursorHandle(image, 1) - if err != nil { + } else if handle, err := newCursorHandle(image, 1); err != nil { grabbingCursor.failure = err - return + } else { + grabbingCursor.image, grabbingCursor.handle = image, handle } - grabbingCursor.image, grabbingCursor.handle = image, handle - }) + } return grabbingCursor.handle, grabbingCursor.failure } // closeGrabbingCursor destroys the cached cursor as the process exits its last -// window; the stock shapes need nothing. +// window; the stock shapes need nothing. A later window makes a new one: the +// cache is rebuilt rather than remembering a destroyed handle. func closeGrabbingCursor() { + grabbingCursor.Lock() + defer grabbingCursor.Unlock() if handle := grabbingCursor.handle; handle != 0 { grabbingCursor.handle = 0 destroyIcon.Call(handle) } + grabbingCursor.image, grabbingCursor.built, grabbingCursor.failure = nil, false, nil } func grabbingCursorPixels() []byte { diff --git a/internal/platform/windows/cursor_windows_test.go b/internal/platform/windows/cursor_windows_test.go index ec8eef341..2153d2f8e 100644 --- a/internal/platform/windows/cursor_windows_test.go +++ b/internal/platform/windows/cursor_windows_test.go @@ -41,8 +41,8 @@ func TestGrabbingCursorIsMadeOnce(t *testing.T) { if err != nil { t.Fatal(err) } - if third == 0 || third == first { - t.Fatalf("re-made grabbing cursor = %d, want a fresh handle after the close", third) + if third == 0 { + t.Fatal("no grabbing cursor after the cached one was closed") } closeGrabbingCursor() } diff --git a/internal/platform/windows/post_windows.go b/internal/platform/windows/post_windows.go new file mode 100644 index 000000000..f4e9c2ed0 --- /dev/null +++ b/internal/platform/windows/post_windows.go @@ -0,0 +1,33 @@ +//go:build windows + +package windows + +// Post runs fn on the event-loop thread; it is safe from any goroutine. +func (application *windowsApplication) Post(fn func()) { + if fn == nil { + return + } + application.postMu.Lock() + application.posts = append(application.posts, fn) + application.postMu.Unlock() + if application.postWake.CompareAndSwap(false, true) { + postThreadMessage.Call(uintptr(application.thread), wmPost, 0, 0) + } +} + +// drainPosts runs the functions accepted since the last drain, in order. A +// function that posts another is picked up by this same drain. +func (application *windowsApplication) drainPosts() { + application.postWake.Store(false) + for { + application.postMu.Lock() + if len(application.posts) == 0 { + application.postMu.Unlock() + return + } + fn := application.posts[0] + application.posts = application.posts[1:] + application.postMu.Unlock() + fn() + } +} diff --git a/internal/platform/windows/post_windows_test.go b/internal/platform/windows/post_windows_test.go new file mode 100644 index 000000000..311f8bb93 --- /dev/null +++ b/internal/platform/windows/post_windows_test.go @@ -0,0 +1,29 @@ +//go:build windows + +package windows + +import "testing" + +func TestDrainPostsRunsWorkInOrder(t *testing.T) { + application := &windowsApplication{} + var seen []int + application.Post(func() { seen = append(seen, 1) }) + application.Post(func() { seen = append(seen, 2) }) + application.drainPosts() + if len(seen) != 2 || seen[0] != 1 || seen[1] != 2 { + t.Fatalf("seen = %v, want [1 2]", seen) + } +} + +func TestADrainPicksUpWorkPostedWhileItRuns(t *testing.T) { + application := &windowsApplication{} + var seen []int + application.Post(func() { + seen = append(seen, 1) + application.Post(func() { seen = append(seen, 2) }) + }) + application.drainPosts() + if len(seen) != 2 || seen[0] != 1 || seen[1] != 2 { + t.Fatalf("seen = %v, want [1 2]", seen) + } +} diff --git a/internal/platform/windows/proxy_windows.go b/internal/platform/windows/proxy_windows.go new file mode 100644 index 000000000..3fce8ef23 --- /dev/null +++ b/internal/platform/windows/proxy_windows.go @@ -0,0 +1,184 @@ +//go:build windows + +package windows + +import ( + "errors" + "fmt" + "net/url" + "strings" + "syscall" + "unsafe" +) + +// ErrProxyUnavailable reports that WinHTTP refused or failed the automatic +// proxy request. +var ErrProxyUnavailable = errors.New("windows: the system proxy settings cannot be read") + +const ( + winHTTPAccessTypeAutomaticProxy = 4 + winHTTPAutoproxyAutoDetect = 1 + winHTTPAutoproxyConfigURL = 2 + winHTTPAutoDetectDHCP = 1 + winHTTPAutoDetectDNS = 2 + winHTTPAccessTypeNoProxy = 1 +) + +var ( + winhttp = systemDLL("winhttp.dll") + winHTTPOpen = winhttp.NewProc("WinHttpOpen") + winHTTPGetIEProxy = winhttp.NewProc("WinHttpGetIEProxyConfigForCurrentUser") + winHTTPGetProxyFor = winhttp.NewProc("WinHttpGetProxyForUrl") + winHTTPClose = winhttp.NewProc("WinHttpCloseHandle") + winHTTPFree = kernel.NewProc("GlobalFree") +) + +// The next three types are WinHTTP's structures; the layout is checked by the +// package's Windows test, which reads what the system answers for a URL. +type winHTTPAutoproxyOptions struct { + Flags uint32 + AutoDetectFlags uint32 + AutoConfigURL *uint16 + Reserved unsafe.Pointer + ReservedDWORD uint32 + AutoLogonIfChallenged int32 +} + +type winHTTPProxyInfo struct { + AccessType uint32 + Proxy *uint16 + ProxyBypass *uint16 +} + +type winHTTPCurrentUserIEProxyConfig struct { + AutoDetect int32 + AutoConfigURL *uint16 + Proxy *uint16 + ProxyBypass *uint16 +} + +// SystemProxy asks WinHTTP which proxy the system selects for target: the +// per-user static settings, auto-detection (WPAD), or a PAC script, whichever +// the machine uses. +func SystemProxy(target string) (*url.URL, error) { + session, _, callErr := winHTTPOpen.Call(0, winHTTPAccessTypeAutomaticProxy, 0, 0, 0) + if session == 0 { + return nil, fmt.Errorf("%w: WinHttpOpen: %v", ErrProxyUnavailable, callErr) + } + defer winHTTPClose.Call(session) + var config winHTTPCurrentUserIEProxyConfig + if ok, _, callErr := winHTTPGetIEProxy.Call(uintptr(unsafe.Pointer(&config))); ok == 0 { + return nil, fmt.Errorf("%w: WinHttpGetIEProxyConfigForCurrentUser: %v", ErrProxyUnavailable, callErr) + } + defer freeWinHTTPString(config.AutoConfigURL) + defer freeWinHTTPString(config.Proxy) + defer freeWinHTTPString(config.ProxyBypass) + // A machine with neither auto-detection nor a PAC script has no policy to + // evaluate: either the static proxy is the answer, or traffic goes direct. + if config.AutoDetect == 0 && config.AutoConfigURL == nil { + if config.Proxy == nil { + return nil, nil + } + return parseWinHTTPProxy(utf16PtrToString(config.Proxy), target) + } + options := winHTTPAutoproxyOptions{ + Flags: winHTTPAutoproxyAutoDetect, + AutoDetectFlags: winHTTPAutoDetectDHCP | winHTTPAutoDetectDNS, + AutoLogonIfChallenged: 1, + } + if config.AutoConfigURL != nil { + options.Flags |= winHTTPAutoproxyConfigURL + options.AutoConfigURL = config.AutoConfigURL + } + pointer, err := syscall.UTF16PtrFromString(target) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrProxyUnavailable, err) + } + var info winHTTPProxyInfo + if ok, _, callErr := winHTTPGetProxyFor.Call( + session, uintptr(unsafe.Pointer(pointer)), + uintptr(unsafe.Pointer(&options)), uintptr(unsafe.Pointer(&info)), + ); ok == 0 { + // Auto-detection that finds no WPAD server is the normal answer on a + // machine without one: the static settings, or direct, are what the + // system itself would use. A PAC script that fails is a policy that + // could not be evaluated, and is reported instead of bypassed. + if config.Proxy != nil { + return parseWinHTTPProxy(utf16PtrToString(config.Proxy), target) + } + if config.AutoConfigURL != nil { + return nil, fmt.Errorf("%w: WinHttpGetProxyForUrl: %v", ErrProxyUnavailable, callErr) + } + return nil, nil + } + defer freeWinHTTPString(info.Proxy) + defer freeWinHTTPString(info.ProxyBypass) + if info.AccessType == winHTTPAccessTypeNoProxy { + return nil, nil + } + text := utf16PtrToString(info.Proxy) + if text == "" && config.Proxy != nil { + text = utf16PtrToString(config.Proxy) + } + return parseWinHTTPProxy(text, target) +} + +// utf16PtrToString reads a NUL-terminated UTF-16 string the system allocated. +func utf16PtrToString(value *uint16) string { + if value == nil { + return "" + } + length := 0 + for pointer := unsafe.Pointer(value); *(*uint16)(pointer) != 0; pointer = unsafe.Add(pointer, 2) { + length++ + } + if length == 0 { + return "" + } + return syscall.UTF16ToString(unsafe.Slice(value, length)) +} + +// parseWinHTTPProxy turns WinHTTP's "host:port" or "http=host:port;https=..." into +// a URL for target's scheme. +func parseWinHTTPProxy(text, target string) (*url.URL, error) { + text = strings.TrimSpace(text) + if text == "" { + return nil, nil + } + hostPort := text + if strings.Contains(text, "=") { + wanted := "http" + if strings.HasPrefix(target, "https:") { + wanted = "https" + } + chosen := "" + for _, part := range strings.Split(text, ";") { + scheme, value, ok := strings.Cut(strings.TrimSpace(part), "=") + if !ok { + continue + } + if scheme == wanted { + chosen = value + break + } + if scheme == "http" && chosen == "" { + chosen = value + } + } + if chosen == "" { + return nil, nil + } + hostPort = strings.TrimSpace(chosen) + } + proxy, err := url.Parse("http://" + hostPort) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrProxyUnavailable, err) + } + return proxy, nil +} + +func freeWinHTTPString(value *uint16) { + if value != nil { + winHTTPFree.Call(uintptr(unsafe.Pointer(value))) + } +} diff --git a/internal/platform/windows/proxy_windows_test.go b/internal/platform/windows/proxy_windows_test.go new file mode 100644 index 000000000..ed9d8fc09 --- /dev/null +++ b/internal/platform/windows/proxy_windows_test.go @@ -0,0 +1,15 @@ +//go:build windows + +package windows + +import "testing" + +func TestSystemProxyAnswersForAURL(t *testing.T) { + proxy, err := SystemProxy("https://example.com/") + if err != nil { + t.Fatalf("a normal session must answer, direct or through a proxy: %v", err) + } + if proxy != nil && proxy.Host == "" { + t.Fatalf("proxy = %+v, want a host", proxy) + } +} diff --git a/internal/platform/windows/renderer_windows_test.go b/internal/platform/windows/renderer_windows_test.go index 6800efa6c..1f5359b1d 100644 --- a/internal/platform/windows/renderer_windows_test.go +++ b/internal/platform/windows/renderer_windows_test.go @@ -187,8 +187,10 @@ func TestGroupCompositingLayersInterleavesByLayer(t *testing.T) { {Kind: compositeRectangles, Layer: 0, First: 3, Count: 1}, {Kind: compositeText, Layer: 1, First: 2, Count: 1}, {Kind: compositeRectangles, Layer: 1, First: 2, Count: 1}, - {Kind: compositeText, Layer: 2, First: 3, Count: 1}, + // Layer 2's shape is painted before the label: the label says three + // shapes came before it, and that shape is the first. {Kind: compositeRectangles, Layer: 2, First: 0, Count: 1}, + {Kind: compositeText, Layer: 2, First: 3, Count: 1}, } if len(got) != len(want) { t.Fatalf("got %d batches, want %d: %+v", len(got), len(want), got) diff --git a/internal/platform/windows/sleep_windows.go b/internal/platform/windows/sleep_windows.go new file mode 100644 index 000000000..1b042529d --- /dev/null +++ b/internal/platform/windows/sleep_windows.go @@ -0,0 +1,77 @@ +//go:build windows + +package windows + +import ( + "errors" + "fmt" + "runtime" + "sync" + "syscall" + "unsafe" +) + +// ErrSleepUnavailable reports that the system refused a power request. +var ErrSleepUnavailable = errors.New("windows: sleep inhibition is unavailable") + +const ( + // POWER_REQUEST_CONTEXT_VERSION is 0, the only version PowerCreateRequest + // accepts. + powerRequestContextVersion = 0 + // POWER_REQUEST_CONTEXT_SIMPLE_STRING makes the context carry one string. + powerRequestContextSimpleString = 1 + // PowerRequestSystemRequired keeps the system out of idle sleep without + // keeping the display on. + powerRequestSystemRequired = 1 +) + +// reasonContext is REASON_CONTEXT. The union is laid out as its detailed form, +// which is at least as large as the simple string pointer it also holds. +type reasonContext struct { + version uint32 + flags uint32 + reason reasonDetailed +} + +type reasonDetailed struct { + module uintptr + id uint32 + count uint32 + strings uintptr +} + +var ( + powerCreateRequest = kernel.NewProc("PowerCreateRequest") + powerSetRequest = kernel.NewProc("PowerSetRequest") + powerClearRequest = kernel.NewProc("PowerClearRequest") +) + +// PreventSleep asks the system to stay out of idle sleep until release runs. +// The reason is what powercfg /requests shows beside the request. +func PreventSleep(reason string) (release func(), err error) { + text, err := syscall.UTF16FromString(reason) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrSleepUnavailable, err) + } + context := reasonContext{version: powerRequestContextVersion, flags: powerRequestContextSimpleString} + context.reason.module = uintptr(unsafe.Pointer(&text[0])) + request, _, callErr := powerCreateRequest.Call(uintptr(unsafe.Pointer(&context))) + runtime.KeepAlive(text) + if request == 0 { + return nil, fmt.Errorf("%w: PowerCreateRequest: %v", ErrSleepUnavailable, callErr) + } + if ok, _, callErr := powerSetRequest.Call(request, powerRequestSystemRequired); ok == 0 { + closeHandle.Call(request) + return nil, fmt.Errorf("%w: PowerSetRequest: %v", ErrSleepUnavailable, callErr) + } + var once sync.Once + return func() { + once.Do(func() { + powerClearRequest.Call(request, powerRequestSystemRequired) + closeHandle.Call(request) + // The request copies the reason, but keeping the string live until + // the request ends costs nothing and does not rely on that. + runtime.KeepAlive(text) + }) + }, nil +} diff --git a/internal/platform/windows/sleep_windows_test.go b/internal/platform/windows/sleep_windows_test.go new file mode 100644 index 000000000..b5c4db392 --- /dev/null +++ b/internal/platform/windows/sleep_windows_test.go @@ -0,0 +1,20 @@ +//go:build windows + +package windows + +import "testing" + +func TestPreventSleepHoldsAndReleasesAPowerRequest(t *testing.T) { + release, err := PreventSleep("viva test: sleep inhibition") + if err != nil { + t.Skipf("this session cannot hold a power request: %v", err) + } + release() + release() +} + +func TestPreventSleepRejectsANulInTheReason(t *testing.T) { + if _, err := PreventSleep("a\x00b"); err == nil { + t.Fatal("a reason with a NUL was accepted") + } +} diff --git a/internal/platform/windows/status_item_windows.go b/internal/platform/windows/status_item_windows.go index d7fbf4040..b6c73c459 100644 --- a/internal/platform/windows/status_item_windows.go +++ b/internal/platform/windows/status_item_windows.go @@ -19,8 +19,10 @@ const ( wmStatusNotify = 0x8010 // wmStatusRemove asks the status window to remove the item named in wParam. wmStatusRemove = 0x8011 - // wmQuitApplication is posted to the event-loop thread, not to a window. + // wmQuitApplication and wmPost are posted to the event-loop thread, not to + // a window: the first ends it, the second drains the work Post accepted. wmQuitApplication = 0x8012 + wmPost = 0x8013 // wmHideWindow and wmShowWindow are posted to a window. wmHideWindow = 32772 wmShowWindow = 32773 diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 637595ea0..a7e29bab2 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -142,7 +142,11 @@ type windowState struct { imeTarget text.Range imeHasTarget bool titlebarThemed, titlebarDark bool - web *webHost + // borderColored says the window's border was given an application color, + // and borderColor is that color; see applyBorderColor. + borderColored bool + borderColor uint32 + web *webHost } var active atomic.Pointer[windowState] @@ -176,6 +180,11 @@ type windowsApplication struct { // again. taskbar uintptr taskbarTried bool + // posts are the functions other goroutines handed to Post; they are drained + // on the event-loop thread. postWake coalesces the messages that wake it. + postMu sync.Mutex + posts []func() + postWake atomic.Bool } type nativeWindow struct { @@ -264,6 +273,10 @@ func RunApplication(start platform.ApplicationStart) error { application.closeAll() continue } + if event.Window == 0 && event.Kind == wmPost { + application.drainPosts() + continue + } // A handled printable shortcut must never reach TranslateMessage: // it would enqueue WM_CHAR even if windowProc consumes WM_KEYDOWN. if offerQueuedShortcut(&event) { @@ -383,6 +396,7 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf } state.watchBackdropPower() state.applyBackdrop() + state.applyBorderColor() state.ready = true if state.activeBackdrop() { postMessage.Call(state.window, wmRedraw, 0, 0) @@ -949,6 +963,7 @@ func (state *windowState) frameWithText(frame platform.Frame, err error, nativeV views := frame.NativeViews if err == nil { state.applyBackdrop() + state.applyBorderColor() defer func() { if state.web != nil && state.ready { state.web.frame(views) diff --git a/internal/textcache/admission_test.go b/internal/textcache/admission_test.go new file mode 100644 index 000000000..aacea2b62 --- /dev/null +++ b/internal/textcache/admission_test.go @@ -0,0 +1,98 @@ +package textcache + +import ( + "encoding/json" + "fmt" + "hash/maphash" + "os" + "strings" + "testing" +) + +func TestOversizedScanRetainsReusedLinesWithCapturedCollisions(t *testing.T) { + data, err := os.ReadFile("testdata/adverse-scan-traces.json") + if err != nil { + t.Fatal(err) + } + var traces []struct { + Hits int `json:"hits"` + Hashes []uint64 `json:"hashes"` + } + if err := json.Unmarshal(data, &traces); err != nil { + t.Fatal(err) + } + if len(traces) != 3 { + t.Fatalf("got %d captured traces, want 3", len(traces)) + } + const limit = 32 + keys := workingSet(8 * limit) + for index, trace := range traces { + t.Run(fmt.Sprint(index), func(t *testing.T) { + if len(trace.Hashes) != len(keys) { + t.Fatalf("trace has %d hashes, want %d", len(trace.Hashes), len(keys)) + } + cache := New[int](limit, nil) + transformed := make(map[uint64]uint64, len(keys)) + for index, key := range keys { + transformed[maphash.Comparable(cache.seed, key.identity())] = trace.Hashes[index] + } + cache.hashTransform = func(hash uint64) uint64 { + captured, ok := transformed[hash] + if !ok { + t.Fatalf("hash %x is absent from the captured working set", hash) + } + return captured + } + queryLines(cache, keys) + hits := 0 + for frame := 0; frame < 40; frame++ { + hits += len(keys) - queryLines(cache, keys) + if cache.Len() > 2*limit { + t.Fatalf("cache exceeded its capacity: %d", cache.Len()) + } + } + if hits < 40*limit/2 { + t.Fatalf("captured collisions retained %d hits, want at least %d (baseline %d)", hits, 40*limit/2, trace.Hits) + } + }) + } +} + +func TestInitialWindowHitSurvivesCollidingColdAdmissions(t *testing.T) { + cache := New[int](2, nil) + hot := Key{Value: "hot"} + hotHash := maphash.Comparable(cache.seed, hot.identity()) + cache.hashTransform = func(hash uint64) uint64 { + if hash == hotHash { + return 0 + } + return 0x0001000100010001 + } + cache.Put(hot, 1) + cache.Put(Key{Value: "idle"}, 2) + for generation := 0; generation < 60; generation++ { + if _, ok := cache.Get(hot); !ok { + t.Fatalf("generation %d: the repeatedly accessed initial line was evicted", generation) + } + cache.Put(Key{Value: strings.Repeat("x", generation+1)}, 100+generation) + } +} + +func TestReplacementWorkingSetReclaimsProtectedCapacity(t *testing.T) { + const limit = 16 + cache := New[int](limit, nil) + old := workingSet(2*limit + 1) + for frame := 0; frame < 20; frame++ { + queryLines(cache, old) + } + current := workingSet(2 * limit) + for index := range current { + current[index].Value += " new" + } + for frame := 0; frame < 100; frame++ { + if queryLines(cache, current) == 0 { + return + } + } + t.Fatal("protected obsolete lines prevented the full replacement working set from warming") +} diff --git a/internal/textcache/testdata/adverse-scan-traces.json b/internal/textcache/testdata/adverse-scan-traces.json new file mode 100644 index 000000000..d87facc9e --- /dev/null +++ b/internal/textcache/testdata/adverse-scan-traces.json @@ -0,0 +1,788 @@ +[ + { + "attempt": 73, + "hits": 616, + "hashes": [ + 4752443503139517943, + 7830679531044315561, + 89133694730399199, + 15735921532557821877, + 15388442030274752408, + 315576745479038231, + 10229344656404877316, + 15478383653066134015, + 937910937743145505, + 3729080203148436011, + 4784725546020996232, + 8737284834813911379, + 13977781225462749332, + 16923076212164438257, + 7880132910538998147, + 9321032952033507716, + 9922778171848319137, + 5869829979613835998, + 13740710586558605022, + 14168430144832691471, + 16182535092217311073, + 3516357016928298228, + 8120098586982239689, + 10900272738346563746, + 9262209920794357959, + 18364688254176677377, + 3303980812151389129, + 12693501592258129052, + 16919231534660771625, + 13151724421115635818, + 3743634827795797424, + 1889442967393857996, + 2485248992052870370, + 11238765291976071070, + 15119943736136886758, + 7327562729457079953, + 5449651355802201241, + 15096021821489589878, + 7325667374588724359, + 2567386649064687489, + 5425901030338825172, + 1876442276199543359, + 9256106748117346924, + 9014002088239419573, + 5993745211857941155, + 2608202024181433683, + 15429551994181953827, + 14173728928386235882, + 1241511892176957287, + 1096765139384854547, + 15076761889362230909, + 14692857121614543448, + 6705436742487240813, + 2916633555063853570, + 12621954867532200228, + 6628768701806009860, + 1794731484362047660, + 14095425919294490125, + 13217238568418486652, + 14516657382376429593, + 4145289830699445089, + 12274640829495387040, + 16889289410166001113, + 17767801374213754722, + 15620801953008055257, + 11344070348884259093, + 3612796328297668229, + 966864492029329839, + 7307451251796297646, + 17915788815063576830, + 707973219209315327, + 17276288537540443801, + 13824899353127296314, + 9879360435417345350, + 12743080964999970557, + 8921677135650239304, + 99769903137516134, + 3955100166775769766, + 5752607267063494296, + 15053102538946929787, + 12277401729039954260, + 6912736635721230509, + 3750047738061160166, + 673720137601719443, + 12840383676564450081, + 1000485988541777400, + 559573661241433671, + 7695951192249854207, + 7509353784644284951, + 1862256360293848697, + 1321310693870856483, + 6630679919703167501, + 13022893320849905886, + 282911880613126136, + 3387069751151248321, + 15842374300645152429, + 8274734941064014742, + 11756590647651863123, + 17437910298958398604, + 14409388133771311592, + 9696513912233365070, + 6798909731981331948, + 4287340712650647235, + 4216159742091434004, + 13687705388646336304, + 13654643608192554940, + 11058330936850681471, + 5905319409438178454, + 8584286533228812563, + 4954451721650381331, + 14988415308304614553, + 17061350610030780999, + 9661188031348634264, + 267564197341588897, + 7729485896905829973, + 6741492929898529041, + 7966969956151960699, + 2975674368256206535, + 12495829819950054662, + 14816347758391276631, + 14020321222941316197, + 17516706799808060991, + 10637405758486534363, + 16340216399229476088, + 2368603751383894961, + 5058023149029736401, + 2323489300861720136, + 18219460018338003670, + 3215802451653081762, + 14751457169965789322, + 17546643982763108658, + 13061266753386710823, + 12585858594761363683, + 4360700758725596973, + 6984279371758236607, + 12304524450483006284, + 4555191031883546890, + 10544740950927166810, + 4442453876660611224, + 15018981228667946869, + 15386620703039727795, + 3861346675360822524, + 10349277883411262675, + 13150796461621929963, + 2445805782666514324, + 10939477262363219454, + 2339812915520186338, + 8971351256911569034, + 9852498803315977297, + 822183919439258119, + 7214134957060515044, + 4205339292438335215, + 12085432353704012618, + 16673280592300734368, + 4600337794646036011, + 16919028443092744437, + 1763177620742866454, + 12620475935075248572, + 7526541045766500434, + 9243397552382687807, + 12407680070252581821, + 14507113033765202292, + 6996884404490548354, + 12543280327550039195, + 589037329278853931, + 14403251618468083499, + 4316120922688933443, + 12085625058459336577, + 13313703137551912293, + 12854973294909068233, + 2873014807284209888, + 15397913268012731419, + 18083970435999355417, + 4108218291813127095, + 14719113303464964836, + 8197843337033984238, + 3932355496091205322, + 6134121054402620671, + 1087856965900767028, + 2367516487020344865, + 12792766380700040035, + 11203520428941317298, + 10973756864696899819, + 2529386483714400867, + 10790346136860161822, + 17506969024000236810, + 11820235505021726011, + 9917416138394956372, + 4639567299013216146, + 1322073113599191118, + 7688535805896703411, + 17241665977590891290, + 16202540887137496385, + 1073508674991945688, + 15049330482057354015, + 16065157000720083, + 8416771920711871462, + 13730602509938610103, + 17140126962726768370, + 9258864708687045716, + 17509363914672308363, + 982631340627144467, + 7989041822084201625, + 6522105213383271214, + 9347288581000417544, + 16449950322318752225, + 1999912690967790706, + 4219269030353310621, + 1754330263899437483, + 11603990754803654696, + 9930074768430123401, + 4529364655791563925, + 2600326488925093097, + 4324722529465769353, + 2067518416550329868, + 2458800089524245105, + 7260884279071323314, + 6552659532469046935, + 14773870961369732490, + 4878297458986115653, + 9074096656436513852, + 15599028666753974239, + 9199003500858891054, + 10159362225100063072, + 17744125107785043277, + 12617048037273093416, + 17224460362805083388, + 1120902156131701598, + 9589208027748011686, + 8403708388967478839, + 4510027401508456029, + 4982968271253242217, + 15884151215146970053, + 16062121591001106167, + 16596064438095228888, + 16003627124676914801, + 1019409465818680162, + 17855550595547740513, + 7793086672315972867, + 5324561573947664513, + 16970462669861645739, + 11020774359152890832, + 16189887050440067284, + 7271751032055492627, + 2913068152569511108, + 5222641021521241366, + 6307869749199094288, + 3767920435989080016, + 9531637797115369472, + 3638420006010449861, + 1655555032105095055, + 11100837609069491487, + 16092840041173501755, + 59611018447734146, + 3384722329888445177, + 17517018098906567337 + ] + }, + { + "attempt": 393, + "hits": 614, + "hashes": [ + 12367006227768114119, + 1530925435743156974, + 482348427915647420, + 6839386783259018392, + 5203265684388309370, + 8392516905552348596, + 16148849773695396383, + 17909073047578162915, + 2769068143412475882, + 14065159603882927775, + 15058919852822081404, + 3332233983492951952, + 1180172211934480216, + 17151817959148782984, + 14048187077373198086, + 9974040405672876029, + 5104313253676178280, + 885934329112246225, + 3973992856598484420, + 5832373462651139353, + 12625078628300522560, + 15382813216133718692, + 1577938206459365659, + 18189033018434839723, + 14555764220225022894, + 13092897441565153488, + 1660804779096557341, + 8118422176898306279, + 1723098811980425040, + 8932676758787217471, + 9012446074758743642, + 12621909302206420848, + 3449821151028971154, + 10584772660172284047, + 8986042266105813362, + 12440262167287977037, + 5789869373908885521, + 14180540182271450584, + 13914025422259213636, + 7862487349353380424, + 1773077367577756586, + 1353337513186437452, + 14167360730058234080, + 17090091877164823402, + 5950693318804702092, + 13061121123835706741, + 5773478090015905055, + 15153638599763672727, + 14217919604753123592, + 9312010276295748825, + 14160816207031784360, + 8176104593839409474, + 15796459965912854359, + 10607721020020050517, + 5618381470258460549, + 10414165510979195644, + 12847388873044415727, + 6497943365417582635, + 2806029498301254397, + 13612180894730516158, + 4769920601825228361, + 11215907023682095508, + 16613988044189589133, + 6454591951000277148, + 9337533972471094223, + 16431307314918836579, + 6080815084548718817, + 13790707660791572309, + 2178965788456802661, + 15552475547325040527, + 8487008298031987936, + 14651625008944818641, + 13475344050447140475, + 1411152236679286108, + 10162800625617299870, + 12180221196947666865, + 8492250317090350864, + 11375508789726096561, + 6896793691139488147, + 5418635651758644568, + 537712547450509589, + 11991469383798480307, + 10452209609920046119, + 17368944403663381371, + 17995377000157889862, + 7565297121845931521, + 1546742637257666025, + 5847298394877035917, + 2378147923279647770, + 2469251936664047255, + 2056590457249106780, + 3873379522918106986, + 5782195593639011993, + 8298478956193279858, + 18271505621775975796, + 18071388827059816439, + 12399502485727138030, + 11439729814632074143, + 3280364945670936588, + 16967068113564570, + 4964763614080873654, + 5042986486524218104, + 10199979719508094601, + 16754910082380579989, + 12027247929389909956, + 6277716602977583791, + 4856817173342208773, + 1337438769582165492, + 15930984608201807056, + 10214931014116116181, + 13152235071777016069, + 7277906268070706227, + 1864924891208855859, + 12689674867964789575, + 8635807551174342225, + 10892329962702694404, + 16620979324006636872, + 9830161445668656938, + 793500700117871353, + 12575614750210706934, + 7123729169213632498, + 18376270733854180296, + 834103100729695543, + 478403537188157546, + 16020016324170833226, + 6235065477728388866, + 8069431878888342754, + 13453086770151591167, + 5606942746452961294, + 11632227214736016208, + 17254021778155134174, + 2728571516473788752, + 10191643779805593190, + 6143112640144302322, + 18109021561730056638, + 15263167581936477531, + 5684843911637473157, + 3927456793613433514, + 7683305221611110251, + 14837942963782455444, + 2527285859335488089, + 1829543609839501491, + 8385463141869580211, + 145417571356020043, + 4586959645170767110, + 17706782603164767859, + 7649324658106962770, + 4762505066996914020, + 1189063582054471198, + 7706730615937202329, + 14656190510871553067, + 10456806956795598773, + 15500015276850976283, + 8324892281039827250, + 8463501716905127514, + 13633625320088807148, + 17205486169134036606, + 8922664625870232881, + 17713132314065558275, + 14748253469023022595, + 11627098535727419682, + 14855577605435372642, + 12888144019832064609, + 2040351003547036780, + 17228912921401177700, + 4512417305545113461, + 18396309649629033229, + 6871578780501800, + 3075579737352245336, + 12829151148235323522, + 6108270435211193906, + 14664600904812686435, + 15248647358197296933, + 55485090365559733, + 3841719100379905536, + 17124773651766924604, + 3592247262912238567, + 2400583860073725882, + 18326808990982703578, + 3208455322900329693, + 2632123120478891905, + 12327214563777226812, + 6992467165417586690, + 14816692051922385194, + 564762998347453194, + 16348365172303858523, + 9051324337283639195, + 12234948214788012101, + 7913537191969497608, + 6766284331528268912, + 15012842688554888329, + 17930384141573640913, + 14059954904747051397, + 5957058883547514742, + 1704552870371232629, + 5751721904258592100, + 17828500684572711301, + 1491915695992290638, + 1795048016629186065, + 18111362326717574202, + 15475432766664216764, + 172620830061539450, + 16056985099716601537, + 17008730075627773756, + 17905096448167654991, + 10275058010755643239, + 10259106149329831135, + 9015610920126887560, + 8297599290720125184, + 12066052111271748475, + 14829847323489422763, + 14144200872246882404, + 4052793540665687264, + 17809631200912583346, + 16816634894180575973, + 11841010269801235387, + 11018731237731461277, + 5768362238237347734, + 10802720703196377361, + 15512089805351037322, + 6570092923228118642, + 17206655705239659262, + 6344867028655145287, + 12703689100511118277, + 13292043858828707541, + 4525740761408479693, + 9170647341567936184, + 11546958313114768217, + 2775262075797230450, + 4268837204909111383, + 3981951104612449430, + 15708268521926107460, + 3698261808668803063, + 17433946601334029710, + 4534757407263834591, + 324705830015622045, + 10232728765189168886, + 7900228368302304980, + 2120922818466782932, + 10275433756214804130, + 9348400508240525189, + 14096834266057804614, + 8790943224361202718, + 10381506561245526360, + 6963731643869413942, + 9113975949667750095, + 8212829995337912599, + 7564603676714008119, + 10496396001262646777, + 15677909660268569733, + 8687367776820418399, + 16057162283829208637, + 3493677165840890413, + 14463576290742665761, + 10859482822223320395, + 7699889181347859236 + ] + }, + { + "attempt": 433, + "hits": 639, + "hashes": [ + 10953722269697675360, + 13464665644543120012, + 1458140963863232883, + 6721567276618268455, + 7282568734423374602, + 1419432843723784216, + 1645668805444402068, + 2938241986123426298, + 15516192074271502680, + 13434114989466928254, + 13972750009523309619, + 5378864287419119566, + 11771630874689299994, + 12129356447789439003, + 12555257275879181301, + 3506916994887365990, + 15590421225769898851, + 8752020120774702328, + 12403623934763483912, + 6138372083085956199, + 8739018614464713133, + 3038539567930271886, + 9335077314639283189, + 7259049323630959695, + 15431961553270603762, + 14692019398307205265, + 5616032530049896500, + 9217423893173465727, + 3145154701856055892, + 17566826355975559808, + 1398299508391216772, + 8672370197661214064, + 17524311227937307925, + 5991740414993370414, + 15161095415301922278, + 4014398256419374158, + 9014442560263568761, + 14047462447448351694, + 4919091955768296624, + 5165531880369087325, + 8611701501765668203, + 4716086590803736356, + 13984059134301071184, + 8840434144250674898, + 18146980666598276202, + 17851792007251926151, + 7884466623066033210, + 4403353387607745485, + 153785815792941943, + 12215076160268821571, + 13214777536439259010, + 15373492002465564015, + 14139644022776360659, + 12924121548057151693, + 13669517677129483686, + 14275500303056528333, + 3322300232871686969, + 689250917908896132, + 4493584888554218171, + 16868439112719906421, + 4463264605334488048, + 3028807933556047878, + 7298734577100744156, + 6149309830801309649, + 9896937184162717934, + 15074232190168879422, + 15058561647487447538, + 6596101517411820690, + 26739670092030031, + 5676922827367999567, + 6670279966418324755, + 11430753330713854582, + 14995212809143625401, + 3053524361178493703, + 14414550592096514210, + 14326307215537556115, + 5956000105399890029, + 10980332545492691826, + 8406539373169739522, + 3474951344090563635, + 10099917877497603503, + 14679808365553844691, + 13655174197625405569, + 6755138637065178042, + 1375956903406017512, + 3181305599806620628, + 10532811007304551838, + 8788933999550811665, + 3408927006658930145, + 9203517167910610074, + 13186730794076573293, + 2927737294500070595, + 8361047115664426433, + 2552598549231059044, + 3479307871529629075, + 16159182339637622161, + 1533230430686693791, + 11210273488268955625, + 7015280420615153509, + 6905428218655922241, + 4338304018985773578, + 16543686026925884209, + 15903135977751829954, + 13578177415643851251, + 8345345256633676485, + 5836373490086658051, + 9263931877702572620, + 17624852442583609669, + 493995683465409579, + 10929560533048007158, + 13741887614824148586, + 3628363338404893386, + 12905356604478376268, + 9675474573830042102, + 10059256796221116454, + 7063763176890220831, + 16937333734145364379, + 17648737856732976915, + 4424097806178324724, + 2223505780478399712, + 4799282548589202558, + 11777484438683386644, + 12022015138179774424, + 16209463317852768534, + 333407523522408055, + 2136907218929688250, + 15745161625429179572, + 10938993149589629125, + 9741740664970226213, + 9271456180811844161, + 17571102050652611786, + 765003825585253004, + 6850429006606398352, + 14486007494516566137, + 16181030804367702402, + 466325553186869316, + 2976592677750571161, + 9523271284515867642, + 8052268992839952401, + 5359058617026221024, + 15758052812163677873, + 11851237234242417676, + 4914709227575001289, + 5029979368328496743, + 17948689737350453165, + 16497430515402428088, + 3930115199942152188, + 6705175116818049574, + 14887312263115336634, + 6470322418947324691, + 14396805986215989805, + 17855616793401153452, + 41114475811625959, + 8177465696763720908, + 3632272734597847034, + 10451589115899956693, + 446811960981336533, + 3258470042814004440, + 10022816086512192935, + 12072640959614247070, + 17013681270484116400, + 17472521494630640686, + 17784645209043143607, + 16588147649317923094, + 13764311042388977219, + 16654116525109627476, + 7943134548589490047, + 7817318145359924214, + 12018862860224524749, + 17577602394632977951, + 3914981196841322818, + 2191128201813972696, + 3497168977366612048, + 9344072096312002362, + 10378215679145969744, + 9217650812819658303, + 18077540477487623668, + 484859258381608785, + 12916888314220321965, + 7209089664449947509, + 17998814928449738468, + 649968091035002202, + 18096112492077944924, + 6659861805213131355, + 6476412503013960158, + 8352369722919944884, + 13515700303931271414, + 641245153417798610, + 742085041781910531, + 2315489079802996089, + 6403452164701037895, + 8057211375252754523, + 5858381717079332921, + 3694449281235367813, + 12593885535155311900, + 1509985259270487635, + 589750201518254732, + 6199067209591928932, + 16659918349556878451, + 17990402956584848474, + 7395444201160495338, + 11957240390333639751, + 6135431283448206520, + 5141261238355400508, + 7759482155733639962, + 2770085654465452730, + 3453569546009156562, + 7502377512769943265, + 2955495699790758017, + 4676868714656345395, + 2737454150798352929, + 8362804888086482798, + 8807223745495234680, + 16880495965680099835, + 16816242977769920270, + 11577263688577387266, + 598230041627026028, + 2229070800412009659, + 2666233423367702140, + 3953379387267804096, + 13121037197946643674, + 9021439346198788525, + 16353555630468095638, + 12811676994852014284, + 6730620974710822843, + 11471218057942191108, + 16764225306303238895, + 6167197280063725080, + 12748757639739604795, + 4655721712850442754, + 110708136583430612, + 10893419824468528220, + 17872570159839847763, + 3363224329644814117, + 8492016826633119412, + 11341288869259853976, + 11913335131519561866, + 12347844525420756111, + 1344308129282613212, + 4800762529887064082, + 12284452205986821152, + 18015383518008421166, + 7990487310878166981, + 7576343780416871034, + 16037099167385251927, + 15954634391394663237, + 15646433601448728206, + 12036801868799462918, + 13287702316205214539, + 12330995570506687491, + 16066087675284766796, + 10019729286155164029, + 14317022901756501430, + 14139088191349544902, + 9887403389814886778, + 9934982601232674084 + ] + } +] \ No newline at end of file diff --git a/internal/textcache/textcache.go b/internal/textcache/textcache.go index a5a5d8927..32fac0f90 100644 --- a/internal/textcache/textcache.go +++ b/internal/textcache/textcache.go @@ -3,7 +3,9 @@ // // A working set within capacity stays warm without allocations. A Window TinyLFU // admission policy keeps oversized scans from flushing every reused line: recent -// lines enter an LRU window and compete by frequency for the main LRU cache. +// lines enter an LRU window and compete by frequency for the main cache's +// probationary segment. Reused main entries move to a protected LRU segment, +// so approximate frequency estimates cannot evict them before another main hit. // Admission tracking starts only when the resident budget is exceeded. Frequency // history is bounded and ages with requests, without background work. // Not safe for concurrent use; the owning engine serializes access. @@ -43,12 +45,15 @@ type Cache[V any] struct { entries []entry[V] window queue main queue + protected queue free int limit int release func(V) seed maphash.Seed - frequency frequencySketch - admission bool + // hashTransform lets tests replay a captured collision distribution. + hashTransform func(uint64) uint64 + frequency frequencySketch + admission bool } type entry[V any] struct { @@ -57,6 +62,7 @@ type entry[V any] struct { hash uint64 prev, next int window bool + protected bool epoch uint32 } @@ -85,12 +91,12 @@ func (cache *Cache[V]) Get(key Key) (V, bool) { if cache.admission { cache.frequency.record(stored.hash) stored.epoch = cache.frequency.epoch - cache.touch(index) } + cache.touch(index) return stored.value, true } if cache.admission { - cache.frequency.record(maphash.Comparable(cache.seed, identity)) + cache.frequency.record(cache.hash(identity)) } var zero V return zero, false @@ -112,7 +118,7 @@ func (cache *Cache[V]) Put(key Key, value V) { } if cache.window.length == cache.limit { candidate := cache.window.tail - if cache.main.length < cache.limit { + if cache.main.length+cache.protected.length < cache.limit { cache.admit(candidate) } else { if !cache.admission { @@ -120,7 +126,7 @@ func (cache *Cache[V]) Put(key Key, value V) { cache.frequency = newFrequencySketch(2 * cache.limit) } cache.admission = true - cache.frequency.record(maphash.Comparable(cache.seed, identity)) + cache.frequency.record(cache.hash(identity)) } victim := cache.main.tail if cache.score(candidate) > cache.score(victim) { @@ -134,7 +140,7 @@ func (cache *Cache[V]) Put(key Key, value V) { identity.value = strings.Clone(identity.value) index := cache.free cache.free = cache.entries[index].next - hash := maphash.Comparable(cache.seed, identity) + hash := cache.hash(identity) cache.entries[index] = entry[V]{ key: identity, value: value, hash: hash, window: true, epoch: cache.frequency.epoch, @@ -143,6 +149,14 @@ func (cache *Cache[V]) Put(key Key, value V) { cache.pushFront(&cache.window, index) } +func (cache *Cache[V]) hash(key cacheKey) uint64 { + hash := maphash.Comparable(cache.seed, key) + if cache.hashTransform != nil { + return cache.hashTransform(hash) + } + return hash +} + func (cache *Cache[V]) score(index int) uint8 { stored := &cache.entries[index] if cache.frequency.epoch-stored.epoch >= frequencyBits { @@ -155,6 +169,19 @@ func (cache *Cache[V]) touch(index int) { queue := &cache.main if cache.entries[index].window { queue = &cache.window + } else if cache.entries[index].protected { + queue = &cache.protected + } else if protectedLimit := cache.limit * 4 / 5; protectedLimit > 0 { + cache.remove(&cache.main, index) + if cache.protected.length == protectedLimit { + demoted := cache.protected.tail + cache.remove(&cache.protected, demoted) + cache.entries[demoted].protected = false + cache.pushFront(&cache.main, demoted) + } + cache.entries[index].protected = true + cache.pushFront(&cache.protected, index) + return } if queue.head != index { cache.remove(queue, index) @@ -173,6 +200,8 @@ func (cache *Cache[V]) evict(index int) { queue := &cache.main if stored.window { queue = &cache.window + } else if stored.protected { + queue = &cache.protected } cache.remove(queue, index) delete(cache.index, stored.key) @@ -225,6 +254,7 @@ func (cache *Cache[V]) Clear() { clear(cache.entries) cache.window = queue{} cache.main = queue{} + cache.protected = queue{} cache.resetFree() cache.frequency.clear() cache.admission = false diff --git a/text/code.go b/text/code.go index 2882ecd57..3e973df99 100644 --- a/text/code.go +++ b/text/code.go @@ -102,11 +102,15 @@ func (editor *Editor) column(index, tabWidth int) int { // editBlock replaces target with replacement as one undo unit, and leaves the // selection at anchor and caret in the new text. func (editor *Editor) editBlock(target Range, replacement []rune, anchor, caret int) { + // The block commands are line commands: they act on the primary selection, + // and the set of carets they leave is the one they compute here. before := editor.selectionState() change := editor.replace(target, string(replacement), false) + editor.clearSecondary() editor.anchor = clamp(anchor, 0, len(editor.runes)) editor.caret = clamp(caret, 0, len(editor.runes)) editor.composing = false + editor.releaseCompositionHistory() editor.record(change, before, editor.selectionState(), editSeparate) } @@ -462,7 +466,9 @@ func (editor *Editor) DeleteLines() { // or the same quote, so an apostrophe in a word stays alone. func (editor *Editor) TypeCode(value string, options CodeOptions) { runes := []rune(value) - if !options.AutoClose || editor.composing || len(runes) != 1 { + // Pairing is decided against the primary selection's neighbours; with several + // selections the plain multi-selection insert is what every one of them gets. + if !options.AutoClose || editor.composing || len(runes) != 1 || editor.SelectionCount() > 1 { editor.Insert(value) return } @@ -508,7 +514,9 @@ func (editor *Editor) mayPair(typed rune, index int) bool { // previous tab stop. Anything else is DeleteBackward. func (editor *Editor) DeleteBackwardCode(options CodeOptions) { selection := editor.Selection() - if editor.composing || selection.Start != selection.End || selection.Start == 0 { + // Bracket and indent pairing look at the primary selection; every selection + // of a multi-selection deletes by the plain rule instead. + if editor.composing || editor.SelectionCount() > 1 || selection.Start != selection.End || selection.Start == 0 { editor.DeleteBackward() return } @@ -677,10 +685,13 @@ func (editor *Editor) Backspace() { // the caret after what it inserted: how a find bar replaces a match, or all of // them. It ends an active composition, which the replaced text may include. func (editor *Editor) ReplaceRange(target Range, value string) { + editor.sealTentativeHistory() target = normalizeRange(target, len(editor.runes)) before := editor.selectionState() change := editor.replace(target, value, false) + editor.clearSecondary() // one range replaced, one caret left editor.collapse(target.Start + len(change.inserted)) editor.composing = false + editor.releaseCompositionHistory() editor.record(change, before, editor.selectionState(), editSeparate) } diff --git a/text/composition.go b/text/composition.go new file mode 100644 index 000000000..d1e032692 --- /dev/null +++ b/text/composition.go @@ -0,0 +1,1064 @@ +package text + +import ( + "sync/atomic" + "unicode/utf8" + "unsafe" +) + +// CompositionPhase is the explicit opt-in tentative-composition event phase. +// CompositionNone is the zero value used by disabled clients. +type CompositionPhase uint8 + +const ( + CompositionNone CompositionPhase = iota + CompositionUpdate + CompositionResult + CompositionCommit + CompositionCancel + CompositionEmptyCommit +) + +// UTF16Range is a raw native UTF-16 start/length pair, converted after any +// tentative rollback exactly like the source PositionsFromCharacters path. +type UTF16Range struct { + Start, Length int +} + +// CompositionEvent is the opt-in editor ingress for tentative composition. +// Text is UTF-8 for Update/Result; Selected is relative to that text. Raw +// UTF-16 replacement coordinates take precedence over the rune Replacement. +type CompositionEvent struct { + Phase CompositionPhase + Text string + Selected Range + Replacement Range + HasReplacement bool + ReplacementUTF16 UTF16Range + HasReplacementUTF16 bool +} + +// CompositionIdentity is the comparable, opaque owner of one enabled +// composition capability. The zero value denotes an unowned snapshot. +type CompositionIdentity struct { + source uint64 +} + +var compositionIdentities atomic.Uint64 + +func nextCompositionIdentity() CompositionIdentity { + source := compositionIdentities.Add(1) + for source == 0 { + source = compositionIdentities.Add(1) + } + return CompositionIdentity{source: source} +} + +// compositionState is the optional sidecar. It owns the physical tentative +// boundary, the one pending producer frame and the bounded retention +// descriptor; it never copies source text. +type compositionState struct { + owner *Editor + identity CompositionIdentity + ops compositionOps + event *historyEvent + cost int + // unitStart is the rollback boundary: the first tentative unit after any + // ordinary pre-start deletion. eventStart is the atomic delivery boundary: + // it also includes that ordinary deletion. They are deliberately distinct. + unitStart int + eventStart int + pendingUnits int + completedStart int + start int + retainEqual bool + pending bool + active bool + enabled bool + live bool + completed bool + passive bool +} + +type compositionOps struct { + apply func(*compositionState, CompositionEvent) bool + committed func(*compositionState) (string, bool) + settle func(*compositionState) + trimCost func(*compositionState, int) int + trim func(*compositionState) +} + +const compositionHeaderRunes = int((unsafe.Sizeof(compositionState{}) + unsafe.Sizeof(rune(0)) - 1) / unsafe.Sizeof(rune(0))) + +// EnableTentativeComposition opts an unrestricted editor into source-scalar +// insertion/overwrite composition without changing its current editing state. +// It never edits text, selection, journal revisions, source identity/generation +// or ordinary Undo/Redo/save state. +func (editor *Editor) EnableTentativeComposition() (ok bool) { + if editor == nil { + return false + } + journal := editor.journal + if journal != nil && journal.private { + return false + } + if history := journal.historyJournal(); history != nil && history.owner != editor { + return false + } + if journal != nil && journal.compositionState() != nil { + state := journal.compositionState() + if state.owner != editor { + return false + } + if state.enabled { + return true + } + // A passive descriptor survives an inactive Disable while it protects a + // complete physical action. Re-enable reuses that owner; it does not + // allocate a second sidecar or change text/history/frames/cursors. + if editor.composing || editor.accept != nil || editor.maxRunes > 0 { + return false + } + state.enabled = true + state.passive = false + state.identity = nextCompositionIdentity() + return true + } + if editor.composing || editor.accept != nil || editor.maxRunes > 0 { + return false + } + if journal == nil { + journal = &editJournal{} + } + cost := editor.compositionBaseCost() + total := editor.historyCost() + cost + if total > maxHistoryRunes { + // Charging the sidecar must not silently force ordinary unit or frame + // pruning. A lone oversized action may still use its single-action room. + if journal.historyJournal() != nil && len(journal.historyJournal().frames) > 0 { + return false + } + if len(editor.history) > 1 || total > maxSingleEditRunes { + return false + } + } + editor.journal = journal + journal.setCompositionState(&compositionState{ + owner: editor, + identity: nextCompositionIdentity(), + ops: compositionOps{apply: applyCompositionOwned, committed: compositionCommittedText, settle: settleCompositionStorage, trimCost: compositionTrimCostOwned, trim: trimCompositionHistoryOwned}, + cost: cost, + unitStart: -1, + eventStart: -1, + enabled: true, + }) + return true +} + +// DisableTentativeComposition disables explicit input without changing ordinary +// units, producer frames/cursors or visible marking. Completed protection or +// oversized retired storage keeps a charged disabled descriptor until a later +// mutation or Clear can release it. +func (editor *Editor) DisableTentativeComposition() (ok bool) { + if editor == nil { + return false + } + journal := editor.journal + if journal != nil && journal.private { + return false + } + if journal == nil { + return true + } + state := journal.compositionState() + if state == nil { + return true + } + if state.owner != editor { + return false + } + if editor.composing || state.active { + return false + } + if !state.enabled { + return true + } + if state.completed { + // Inactive Disable leaves text/history/frames/cursors intact. Keep one + // passive charged descriptor so the next trim cannot cut the completed + // action; the enabled getter reports false meanwhile. + state.enabled = false + state.passive = true + return true + } + state.enabled = false + if state.ops.settle != nil { + state.ops.settle(state) + } + return true +} + +// CompositionActive reports whether a pre-edit currently owns rollback state: +// either the legacy composing flag or a live tentative composition. Callers use +// it to refuse operations that would strand an in-flight composition. +func (editor *Editor) CompositionActive() bool { + if editor == nil { + return false + } + if editor.composing { + return true + } + state := editor.compositionState() + return state != nil && state.active +} + +// TentativeCompositionEnabled is a nil-safe, allocation-free capability read. +func (editor *Editor) TentativeCompositionEnabled() bool { + state := editor.compositionState() + return state != nil && state.enabled +} + +// TentativeCompositionActive reports an owned explicit rollback boundary. A +// legacy marked string alone does not establish that boundary. The read is +// nil-safe and does not allocate or enable optional state. +func (editor *Editor) TentativeCompositionActive() bool { + return editor.tentativeActive() +} + +// TentativeCompositionIdentity snapshots ownership without allocating, +// enabling optional state or retaining the editor. Disabled owners are zero. +func (editor *Editor) TentativeCompositionIdentity() CompositionIdentity { + state := editor.compositionState() + if state != nil && state.enabled { + return state.identity + } + return CompositionIdentity{} +} + +// ApplyComposition handles one explicit event. True includes valid no-ops; +// false rejects without source mutation. +func (editor *Editor) ApplyComposition(event CompositionEvent) (handled bool) { + if editor == nil || editor.journal == nil || editor.journal.compositionState() == nil { + return false + } + state := editor.compositionState() + if state == nil || !state.enabled { + return false + } + apply := state.ops.apply + if apply == nil { + return false + } + return apply(state, event) +} + +func applyCompositionOwned(state *compositionState, event CompositionEvent) bool { + if state == nil || state.owner == nil { + return false + } + editor := state.owner + state.retainEqual = true + defer func() { state.retainEqual = false }() + switch event.Phase { + case CompositionUpdate, CompositionResult, CompositionCommit, CompositionCancel, CompositionEmptyCommit: + default: + return false + } + if editor.composing && !state.active { + // A legacy/Clear residue has no owned tentative boundary; fail closed + // until the legacy Unmark path ends it. + return false + } + var text []rune + if event.Phase == CompositionUpdate || event.Phase == CompositionResult { + if !utf8.ValidString(event.Text) { + return false + } + text = []rune(event.Text) + } + usesReplacement := event.Phase == CompositionResult || + event.Phase == CompositionUpdate && len(text) > 0 || + event.Phase == CompositionEmptyCommit && !state.active + if event.HasReplacementUTF16 && usesReplacement { + if event.ReplacementUTF16.Start < 0 || event.ReplacementUTF16.Length < 0 { + return false + } + } + if event.Phase == CompositionUpdate && state.active && (event.HasReplacement || event.HasReplacementUTF16) { + return false + } + plan, ok := editor.planCompositionEvent(state, event, text) + if !ok { + return false + } + if plan.mutate { + // Retiring completed protection is a descriptor-only action. It happens + // after a successful preflight, so a refused event never retires it, and + // before any byte/history mutation. + editor.retireCompletedRetention() + // Redo belongs to the old branch. Remove it before recording physical + // tentative indices, after preflight has guaranteed this event is handled. + editor.dropRedo() + } + newUnits := plan.units + if plan.joinsPrevious { + newUnits-- + } + if newUnits > 0 && !state.active { + // Active update/result events roll back first and reserve their exact + // post-rollback suffix capacity inside the apply step. + editor.reserveCompositionHistory(len(editor.history) + newUnits) + } + state.pending = true + state.pendingUnits = plan.units + editor.chargeCompositionCapacity() + pending := editor.beginCompositionHistory(state, plan) + switch event.Phase { + case CompositionUpdate: + editor.applyCompositionUpdate(state, event, text, pending, plan.units) + case CompositionResult: + editor.applyCompositionResult(state, event, text, pending, plan) + case CompositionCommit: + editor.applyCompositionCommit(state) + case CompositionCancel: + editor.applyCompositionCancel(state) + case CompositionEmptyCommit: + editor.applyCompositionEmptyCommit(state, event) + } + if plan.units > 0 { + editor.ownCompositionEventText(state) + } + editor.finishCompositionHistory(state, pending) + state.pending = false + state.pendingUnits = 0 + editor.chargeCompositionCapacity() + return true +} + +// compositionPlan is the physical and producer-shape preflight for one explicit +// event. payload counts rune slots retained by ordinary history, units counts +// the ordinary units that must survive, and steps counts source primitives. +type compositionPlan struct { + steps int + units int + payload int + + mutate bool + joinsPrevious bool +} + +// planCompositionEvent separates the editor's hard cancelability preflight from +// metadata reservation. A false result never mutates text, history or selection. +func (editor *Editor) planCompositionEvent(state *compositionState, event CompositionEvent, text []rune) (plan compositionPlan, ok bool) { + if state.active && (state.unitStart < 0 || state.unitStart > len(editor.history)) { + return plan, false + } + if state.active && event.Phase != CompositionCommit { + plan.steps += editor.compositionRollbackSteps(state) + } + needBase := false + switch event.Phase { + case CompositionUpdate: + needBase = len(text) > 0 + case CompositionResult: + needBase = len(text) > 0 || event.HasReplacement || event.HasReplacementUTF16 + case CompositionEmptyCommit: + needBase = !state.active + } + base := editor.runes + if needBase { + var baseOK bool + base, baseOK = editor.compositionPlanBase(state) + if !baseOK { + return plan, false + } + } + switch event.Phase { + case CompositionUpdate: + if len(text) == 0 { + plan.mutate = state.active // empty update is cancel + return plan, true + } + plan.mutate = true + if state.active { + editor.compositionPlanScalars(&plan, base, state.start, text, 0, 0) + return plan, editor.compositionPlanFits(state, plan) + } + target := editor.compositionReplacementRangeFor(base, event) + deleted := target.End - target.Start + if deleted > 0 { + plan.steps++ + plan.units++ + plan.payload += deleted + + } + editor.compositionPlanScalars(&plan, base, target.Start, text, deleted, 0) + case CompositionResult: + hasExplicit := event.HasReplacement || event.HasReplacementUTF16 + if hasExplicit { + target := editor.compositionReplacementRangeFor(base, event) + deleted := target.End - target.Start + if deleted > 0 { + plan.steps++ + plan.units++ + plan.payload += deleted + + } + if len(text) > 0 { + editor.compositionPlanScalars(&plan, base, target.Start, text, deleted, 0) + if !state.active && deleted == 0 { + editor.compositionPlanPreviousInsert(&plan, target.Start) + } + } + plan.mutate = state.active || len(text) > 0 || deleted > 0 + return plan, editor.compositionPlanFits(state, plan) + } + if state.active { + if len(text) > 0 { + editor.compositionPlanScalars(&plan, base, state.start, text, 0, 0) + } + plan.mutate = true + return plan, editor.compositionPlanFits(state, plan) + } + selection := editor.Selection() + grouped := 0 + if len(text) > 0 { + grouped = selection.End - selection.Start + } + if len(text) > 0 { + editor.compositionPlanScalars(&plan, base, selection.Start, text, 0, grouped) + if grouped == 0 { + editor.compositionPlanPreviousInsert(&plan, selection.Start) + } + } + plan.mutate = len(text) > 0 + case CompositionEmptyCommit: + if state.active { + plan.mutate = true + return plan, true + } + target := editor.compositionReplacementRangeFor(base, event) + deleted := target.End - target.Start + if deleted > 0 { + plan.steps++ + plan.units++ + plan.payload += deleted + + plan.mutate = true + } + case CompositionCommit: + plan.mutate = state.active + case CompositionCancel: + plan.mutate = state.active + } + if plan.units == 0 { + return plan, true + } + return plan, editor.compositionPlanFits(state, plan) +} + +func (editor *Editor) compositionPlanPreviousInsert(plan *compositionPlan, start int) { + if editor.overwrite || editor.coalescing != editInsert || editor.historyIndex == 0 || editor.historyIndex != len(editor.history) || editor.AtSavePoint() { + return + } + previous := &editor.history[editor.historyIndex-1] + if previous.kind != editInsert || previous.after != (editorSelection{anchor: start, caret: start}) || len(previous.removed) != 0 || previous.start+len(previous.inserted) != start { + return + } + // The source scalar loop coalesces into this existing unit. Its text + // cannot be pruned independently of the accepted new input. + plan.payload += len(previous.inserted) + plan.joinsPrevious = true +} + +// compositionPlanFits applies the physical single-action bound independently of +// discardable producer metadata and of the replaced generation. An active +// update rolls back its old tentative suffix before inserting the new one, so +// charging state.cost (which includes the old unit-array capacity) in addition +// to the new units would count two mutually exclusive generations. Only the +// post-rollback event's own unit headers and retained rune text are required to +// stay cancelable within the single-action bound. +func (editor *Editor) compositionPlanFits(state *compositionState, plan compositionPlan) bool { + room := maxSingleEditRunes - compositionHeaderRunes - editorSidecarRunes + if plan.payload < 0 || plan.units < 0 || plan.payload > room { + return false + } + return plan.units <= (room-plan.payload)/historyEditRunes +} + +// compositionPlanScalars simulates the source scalar loop without mutating the +// editor. base is post-rollback text; deleted counts an ordinary pre-start or +// explicit deletion before the scalars; grouped counts an implicit selection +// deletion that belongs to the first scalar's ordinary unit. +func (editor *Editor) compositionPlanScalars(plan *compositionPlan, base []rune, start int, text []rune, deleted, grouped int) { + if len(text) == 0 { + return + } + plan.payload += len(text) + overwrite := editor.overwrite + + if overwrite { + plan.units += len(text) + } else if len(text) > 1 && grouped > 0 { + // An implicit selection replacement owns the first scalar's unit. + // Other scalars coalesce into one new suffix, even at a save point. + plan.units += 2 + } else { + plan.units++ + } + shift := -deleted + cursor := start + for index := range text { + switch { + case index == 0 && grouped > 0: + plan.payload += grouped + plan.steps += 2 + shift -= grouped + case overwrite: + position := cursor - shift + if cursor < len(base)+shift && position >= 0 && position < len(base) && !compositionLineEnd(base[position]) { + plan.payload++ + plan.steps += 2 + } else { + plan.steps++ + shift++ + } + default: + plan.steps++ + shift++ + } + cursor++ + } +} + +// compositionPlanBase reconstructs the text after rolling back the owned +// tentative suffix, without touching the live editor. Inactive events use the +// current text directly. +func (editor *Editor) compositionPlanBase(state *compositionState) ([]rune, bool) { + if !state.active { + return editor.runes, true + } + return editor.compositionRollbackRunes(state) +} + +// compositionRollbackRunes reconstructs the post-rollback text in one forward +// pass over the final buffer and the owned suffix units. Each unit's recorded +// start is its final rune position; replacing those inserted segments with the +// recorded removed text restores the pre-event buffer without copying the whole +// document once per unit. The returned slice is owned by the caller. +func (editor *Editor) compositionRollbackRunes(state *compositionState) ([]rune, bool) { + if state == nil || !state.active { + return editor.runes, true + } + if state.unitStart < 0 || state.unitStart > len(editor.history) { + return nil, false + } + final := editor.runes + capacity := len(final) + for index := state.unitStart; index < len(editor.history); index++ { + edit := &editor.history[index] + capacity += len(edit.removed) - len(edit.inserted) + } + if capacity < 0 { + capacity = 0 + } + base := make([]rune, 0, capacity) + previous := 0 + for index := state.unitStart; index < len(editor.history); index++ { + edit := &editor.history[index] + start := edit.start + if start < previous || start < 0 || start > len(final) || start+len(edit.inserted) > len(final) { + return nil, false + } + if !runesEqual(final[start:start+len(edit.inserted)], edit.inserted) { + return nil, false + } + base = append(base, final[previous:start]...) + base = append(base, edit.removed...) + previous = start + len(edit.inserted) + } + base = append(base, final[previous:]...) + return base, true +} + +// compositionCommittedText is installed only by EnableTentativeComposition so a +// default client that never enables the capability does not link the rollback +// reconstruction merely by calling CommittedString. +func compositionCommittedText(state *compositionState) (string, bool) { + if state == nil || state.owner == nil { + return "", false + } + committed, ok := state.owner.compositionRollbackRunes(state) + if !ok { + return "", false + } + return string(committed), true +} + +func compositionLineEnd(value rune) bool { + return value == '\n' || value == '\r' +} + +// compositionRollbackSteps counts the inverse source primitives that a private +// rollback will emit. It never treats a unit ordinal as the producer Current. +func (editor *Editor) compositionRollbackSteps(state *compositionState) int { + count := 0 + for index := state.unitStart; index < len(editor.history); index++ { + edit := &editor.history[index] + if len(edit.primitives) == 0 { + if len(edit.removed) > 0 { + count++ + } + if len(edit.inserted) > 0 { + count++ + } + continue + } + for _, primitive := range edit.primitives { + if primitive.Removed != 0 { + count++ + } + if primitive.Inserted != 0 { + count++ + } + } + } + return count +} + +func (editor *Editor) compositionReplacementRange(event CompositionEvent) Range { + return editor.compositionReplacementRangeFor(editor.runes, event) +} + +func (editor *Editor) compositionReplacementRangeFor(base []rune, event CompositionEvent) Range { + if event.HasReplacementUTF16 { + return editor.compositionUTF16RangeFor(base, event.ReplacementUTF16) + } + if event.HasReplacement { + return normalizeRange(event.Replacement, len(base)) + } + if len(base) == len(editor.runes) { + return editor.Selection() + } + return Range{Start: editor.caret, End: editor.caret} +} + +func (editor *Editor) applyCompositionUpdate(state *compositionState, event CompositionEvent, text []rune, pending *historyEvent, units int) { + if len(text) == 0 { + editor.applyCompositionCancel(state) + return + } + var start int + if state.active { + start = editor.rollbackComposition(state, pending) + state.eventStart = len(editor.history) + editor.reserveCompositionHistory(len(editor.history) + units) + } else { + state.eventStart = len(editor.history) + target := editor.compositionReplacementRange(event) + editor.compositionDeleteOrdinary(target) + start = target.Start + } + editor.BreakUndoGroup() + insertStart := start + state.start = insertStart + state.unitStart = len(editor.history) + state.live = true + state.completed = false + state.completedStart = -1 + start = editor.compositionInsertEventScalars(start, text, true) + editor.composition = Range{Start: insertStart, End: start} + editor.composing = true + selected := normalizeRange(event.Selected, len(text)) + editor.anchor = insertStart + selected.Start + editor.caret = insertStart + selected.End + if state.unitStart >= 0 && state.unitStart < len(editor.history) { + // The merged tentative unit must restore the event's final Selected on + // Redo, not the transient caret left by the last scalar insertion. + editor.history[state.unitStart].after = editor.selectionState() + } + state.active = true +} + +func (editor *Editor) applyCompositionResult(state *compositionState, event CompositionEvent, text []rune, pending *historyEvent, plan compositionPlan) { + wasActive := state.active + if wasActive { + editor.rollbackComposition(state, pending) + editor.reserveCompositionHistory(len(editor.history) + plan.units) + } + var explicit Range + hasExplicit := false + switch { + case event.HasReplacementUTF16: + explicit = editor.compositionUTF16Range(event.ReplacementUTF16) + hasExplicit = true + case event.HasReplacement: + explicit = normalizeRange(event.Replacement, len(editor.runes)) + hasExplicit = true + } + if !wasActive && len(text) == 0 && (!hasExplicit || explicit.Start == explicit.End) { + // Valid no-op result: never retire completed retention or change bytes. + editor.composing = false + editor.composition = Range{} + return + } + state.eventStart = len(editor.history) + if plan.joinsPrevious { + state.eventStart-- + } + state.live = false + state.completed = false + state.completedStart = -1 + editor.composing = false + editor.composition = Range{} + if hasExplicit { + deleted := editor.compositionDeleteOrdinary(explicit) + editor.collapse(explicit.Start) + if len(text) > 0 { + editor.compositionInsertEventScalars(explicit.Start, text, deleted) + } + editor.compositionComplete(state) + editor.composing = false + editor.composition = Range{} + return + } + if len(text) == 0 { + // Empty result never deletes an implicit selection. + editor.composing = false + editor.composition = Range{} + return + } + selection := editor.Selection() + if selection.Start != selection.End { + editor.compositionReplaceAndInsert(selection, text) + } else { + editor.compositionInsertEventScalars(selection.Start, text, false) + } + editor.compositionComplete(state) + editor.composing = false + editor.composition = Range{} +} + +func (editor *Editor) applyCompositionCommit(state *compositionState) { + if !state.active { + return + } + state.active = false + state.live = false + editor.compositionComplete(state) + editor.composing = false + editor.composition = Range{} + editor.dropRedo() + editor.syncCompositionTail() +} + +func (editor *Editor) applyCompositionCancel(state *compositionState) { + if !state.active { + return + } + editor.rollbackComposition(state, editor.compositionEvent()) + editor.composing = false + editor.composition = Range{} + editor.dropRedo() + editor.syncCompositionTail() +} + +func (editor *Editor) applyCompositionEmptyCommit(state *compositionState, event CompositionEvent) { + if state.active { + editor.rollbackComposition(state, editor.compositionEvent()) + editor.composing = false + editor.composition = Range{} + editor.dropRedo() + editor.syncCompositionTail() + return + } + state.eventStart = len(editor.history) + target := editor.compositionReplacementRange(event) + editor.compositionDeleteOrdinary(target) + editor.dropRedo() + editor.syncCompositionTail() + editor.compositionComplete(state) + editor.composing = false + editor.composition = Range{} +} + +// compositionComplete transfers live protection to one newest completed action +// only when the accepted event actually retained ordinary units. +func (editor *Editor) compositionComplete(state *compositionState) { + if state.eventStart >= 0 && state.eventStart < len(editor.history) { + state.completed = true + state.completedStart = state.eventStart + } +} + +// rollbackComposition reverses only the owned tentative suffix, newest unit +// first, and truncates the suffix privately. It never touches the ordinary +// pre-start deletion. The producer frame is assembled by the event capture. +func (editor *Editor) rollbackComposition(state *compositionState, pending *historyEvent) int { + if !state.active || state.unitStart < 0 || state.unitStart > len(editor.history) { + state.active = false + return state.start + } + for index := len(editor.history) - 1; index >= state.unitStart; index-- { + edit := &editor.history[index] + if pending != nil && editor.historyState() != nil { + editor.captureHistoryReplay(edit, true) + } + editor.replaceHistory(edit, true) + } + editor.truncateCompositionUnits(state.unitStart) + state.active = false + state.live = false + state.completed = false + state.completedStart = -1 + state.eventStart = -1 + editor.collapse(clamp(state.start, 0, len(editor.runes))) + editor.BreakUndoGroup() + if pending != nil { + pending.retainedTo = pending.current + } + return editor.caret +} + +func (editor *Editor) truncateCompositionUnits(from int) { + from = clamp(from, 0, len(editor.history)) + for index := from; index < len(editor.history); index++ { + edit := &editor.history[index] + editor.historyRunes -= editor.historyUnitRunes(edit) + editor.forgetLineBatch(edit) + + } + clear(editor.history[from:]) + editor.history = editor.history[:from] + if editor.historyIndex > from { + editor.historyIndex = from + } + if point := editor.savePointIndex(); point != nil && *point > from { + *point = -1 + } + editor.coalescing = 0 + editor.compactCompositionHistory() +} + +func (editor *Editor) compositionDeleteOrdinary(target Range) bool { + target = normalizeRange(target, len(editor.runes)) + if target.Start == target.End { + return false + } + before := editor.selectionState() + editor.collapse(target.Start) + change := editor.replace(target, "", false) + editor.collapse(target.Start) + editor.record(change, before, editor.selectionState(), editSeparate) + return true +} + +// compositionRecord is the explicit-event record path. Unlike the default +// record it retains a nonempty equal replacement (a valid source action) without +// requiring save-point or producer state, keeping the default retainEqualEdits +// fast path unchanged. +func (editor *Editor) compositionRecord(change textChange, before, after editorSelection, kind editKind) { + if runesEqual(change.removed, change.inserted) && len(change.removed) == 0 { + return + } + editor.dropRedo() + var primitive Edit + historyOwned := false + if kind == editComposition { + editor.invalidateHistoryFrom(0) + } else if history := editor.historyState(); history != nil { + primitive, historyOwned = history.ops.record(history, change, kind) + } + unitOwned := historyOwned && kind != editSeparate + if editor.merge(change, before, after, kind, primitive, unitOwned) { + editor.trimHistory() + return + } + edit := historyEdit{ + start: change.start, removed: change.removed, inserted: change.inserted, + before: before, after: after, kind: kind, + } + if unitOwned { + edit.primitives = []Edit{primitive} + } + editor.appendHistory(edit) +} + +func (editor *Editor) compositionInsertScalarsWithBreak(start int, text []rune, breakBefore bool) int { + if len(text) == 0 { + return start + } + if breakBefore { + editor.BreakUndoGroup() + } + start = clamp(start, 0, len(editor.runes)) + editor.collapse(start) + for index := range text { + before := editor.selectionState() + change := editor.replaceRunes(Range{Start: start, End: start}, text[index:index+1], false) + editor.collapse(start + 1) + editor.compositionRecord(change, before, editor.selectionState(), editInsert) + start++ + } + return start +} + +// compositionInsertEventScalars applies the source scalar loop. Overwrite mode +// emits one isolated ordinary Undo unit per scalar and deletes exactly one code +// point outside the line terminator/EOF; insertion mode keeps E1's coalescing. +func (editor *Editor) compositionInsertEventScalars(start int, text []rune, breakFirst bool) int { + if len(text) == 0 { + return start + } + if !editor.overwrite { + return editor.compositionInsertScalarsWithBreak(start, text, breakFirst) + } + start = clamp(start, 0, len(editor.runes)) + editor.collapse(start) + for _, value := range text { + start = editor.compositionOverwriteScalar(start, value) + } + return start +} + +// compositionOverwriteScalar is the exact source InsertCharacter empty-selection +// overwrite step: delete one code point when the caret is before EOF and not in +// a line terminator, then insert the scalar. It uses one ordinary change/unit, +// so it neither deletes a grapheme cluster nor the whole replacement width. +func (editor *Editor) compositionOverwriteScalar(start int, value rune) int { + start = clamp(start, 0, len(editor.runes)) + target := Range{Start: start, End: start} + if start < len(editor.runes) && !compositionLineEnd(editor.runes[start]) { + target.End = start + 1 + } + before := editor.selectionState() + editor.collapse(start) + var scalar [1]rune + scalar[0] = value + change := editor.replaceRunes(target, scalar[:], false) + editor.collapse(start + 1) + editor.compositionRecord(change, before, editor.selectionState(), editSeparate) + return start + 1 +} + +// compositionReplaceAndInsert is the source Result grouping: an implicit +// selection deletion shares one ordinary unit with the first scalar, while the +// producer still receives the exact ordered delete and per-scalar inserts. +func (editor *Editor) compositionReplaceAndInsert(target Range, text []rune) { + target = normalizeRange(target, len(editor.runes)) + if target.Start == target.End || len(text) == 0 { + editor.compositionInsertEventScalars(target.Start, text, false) + return + } + // Source InsertCharacter grouping: the implicit selection deletion shares + // its ordinary unit with the FIRST scalar. EndUndoAction then makes the + // following scalars a separate source group. + before := editor.selectionState() + editor.collapse(target.Start) + change := editor.replaceRunes(target, text[:1], false) + editor.collapse(target.Start + 1) + editor.compositionRecord(change, before, editor.selectionState(), editSeparate) + if len(text) > 1 { + editor.compositionInsertEventScalars(target.Start+1, text[1:], true) + } +} + +// compositionUTF16Range converts raw code units after any rollback. Start is +// measured from zero and Length relative to that start. Valid boundaries follow +// the pinned source start-from-zero/relative-length conversion; out-of-range or +// split-surrogate boundaries fall to the document end as the E1 contract binds. +func (editor *Editor) compositionUTF16Range(raw UTF16Range) Range { + return editor.compositionUTF16RangeFor(editor.runes, raw) +} + +func (editor *Editor) compositionUTF16RangeFor(text []rune, raw UTF16Range) Range { + total := editor.compositionUTF16Length(text) + start, startOK := editor.compositionUTF16StartIn(text, raw.Start, total) + if !startOK { + // An invalid start maps both ends to the document end. + end := len(text) + return Range{Start: end, End: end} + } + end, endOK := editor.compositionUTF16RelativeIn(text, start, raw.Length) + if !endOK { + end = len(text) + } + if end < start { + end = start + } + return Range{Start: start, End: end} +} + +// compositionUTF16Relative converts a nonnegative code-unit length relative to +// an already resolved rune start. It never adds the raw start and length, so a +// huge positive length simply falls to the document end instead of overflowing. +func (editor *Editor) compositionUTF16Relative(start, units int) (int, bool) { + return editor.compositionUTF16RelativeIn(editor.runes, start, units) +} + +func (editor *Editor) compositionUTF16RelativeIn(text []rune, start, units int) (int, bool) { + if units == 0 { + return start, true + } + if start < 0 || start > len(text) { + return 0, false + } + remaining := units + for index := start; index < len(text); index++ { + width := 1 + if text[index] > 0xffff { + width = 2 + } + if remaining < width { + return 0, false + } + remaining -= width + if remaining == 0 { + return index + 1, true + } + } + return 0, false +} + +func (editor *Editor) compositionUTF16Start(units, total int) (int, bool) { + return editor.compositionUTF16StartIn(editor.runes, units, total) +} + +func (editor *Editor) compositionUTF16StartIn(text []rune, units, total int) (int, bool) { + if units < 0 || units > total { + return 0, false + } + consumed := 0 + for index, character := range text { + width := 1 + if character > 0xffff { + width = 2 + } + if consumed == units { + return index, true + } + if consumed+width > units { + // The raw position splits a surrogate pair. + return 0, false + } + consumed += width + if consumed == units { + return index + 1, true + } + } + if consumed == units { + return len(text), true + } + return 0, false +} + +func (editor *Editor) compositionUTF16Length(text []rune) int { + units := 0 + for _, value := range text { + if value > 0xffff { + units += 2 + } else { + units++ + } + } + return units +} diff --git a/text/composition_history.go b/text/composition_history.go new file mode 100644 index 000000000..feb49eb7a --- /dev/null +++ b/text/composition_history.go @@ -0,0 +1,206 @@ +package text + +import "unsafe" + +// One pending event owns the complete mixed primitive stream before mutation. +// Ordinary physical units remain the rollback and Undo source of truth. +type historyEvent struct { + from HistoryCursor + startBytes int + bytes int + current int + retainedTo int + steps []HistoryStep + cost int + failed bool +} + +const historyEventRunes = int((unsafe.Sizeof(historyEvent{}) + unsafe.Sizeof(rune(0)) - 1) / unsafe.Sizeof(rune(0))) + +func (editor *Editor) beginCompositionHistory(state *compositionState, plan compositionPlan) *historyEvent { + history := editor.historyState() + steps := plan.steps + if history == nil || steps <= 0 { + return nil + } + if steps > (maxSingleEditRunes-historyFrameRunes-historyEventRunes)/historyStepRunes { + editor.invalidateHistoryFrom(0) + return nil + } + cost := steps*historyStepRunes + historyFrameRunes + historyEventRunes + // Active replacements reserve their physical array after rollback. Price + // that complete generation now, including frame backing eviction cannot free, + // so an impossible frame cannot force per-scalar array compaction later. + physical := compositionHeaderRunes + plan.payload + plan.units*historyEditRunes + backing := historyHeaderRunes + history.frameCapacity*historyFrameRunes + if physical+backing+cost > maxSingleEditRunes { + editor.invalidateHistoryFrom(0) + return nil + } + for len(history.frames) > 0 && editor.historyCost()+cost > maxHistoryRunes { + history.dropOldestFrame() + } + if editor.historyCost()+cost > maxSingleEditRunes { + editor.invalidateHistoryFrom(0) + return nil + } + history.cost += cost + event := &historyEvent{ + from: history.cursor(), startBytes: history.bytes, bytes: history.bytes, + current: history.current, retainedTo: history.retainedTo, cost: cost, + steps: make([]HistoryStep, 0, steps), + } + state.event = event + return event +} + +func (editor *Editor) finishCompositionHistory(state *compositionState, event *historyEvent) { + state.event = nil + if event == nil { + return + } + history := editor.historyState() + if history == nil { + return + } + history.cost -= event.cost + if event.failed || event.from != history.cursor() { + editor.invalidateHistoryFrom(0) + return + } + if len(event.steps) == 0 { + history.current, history.bytes, history.retainedTo = event.current, event.bytes, event.retainedTo + return + } + if !validateCompositionHistoryEvent(event) { + editor.invalidateHistoryFrom(0) + return + } + editor.appendHistoryFrameWithTail(event.steps, event.startBytes, event.bytes, event.current, event.retainedTo) +} + +func validateCompositionHistoryEvent(event *historyEvent) bool { + running := event.startBytes + for _, step := range event.steps { + if step.Position < 0 || step.Length < 0 || step.BeforeBytes != running { + return false + } + switch step.Primitive { + case HistoryDelete: + if step.AfterBytes != running-step.Length || step.Position > running-step.Length { + return false + } + case HistoryInsert: + if step.AfterBytes != running+step.Length || step.Position > running { + return false + } + default: + return false + } + switch step.Operation { + case HistoryForward, HistoryUndo, HistoryRedo: + default: + return false + } + running = step.AfterBytes + } + return running == event.bytes && event.current >= 0 && event.retainedTo >= event.current +} + +func (editor *Editor) appendEventForwardPrimitive(event *historyEvent, primitive Edit) { + if event == nil || primitive.Removed == 0 && primitive.Inserted == 0 { + return + } + history := editor.historyState() + if history == nil { + event.failed = true + return + } + running := event.bytes + if primitive.Removed > 0 { + after := running - primitive.Removed + editor.appendEventForwardStep(history, event, HistoryDelete, primitive.Start, primitive.Removed, running, after) + running = after + } + if primitive.Inserted > 0 { + after := running + primitive.Inserted + editor.appendEventForwardStep(history, event, HistoryInsert, primitive.Start, primitive.Inserted, running, after) + running = after + } + event.bytes = running +} + +func (editor *Editor) appendEventForwardStep(history *historyJournal, event *historyEvent, primitive HistoryPrimitive, position, length, before, after int) { + if len(event.steps) >= cap(event.steps) { + event.failed = true + editor.invalidateHistoryFrom(0) + return + } + boundary := event.current + editor.updateHistoryBranch(boundary) + event.steps = append(event.steps, HistoryStep{HistoryForward, primitive, position, length, before, after, history.context(boundary+1, boundary+1)}) + event.current, event.retainedTo, event.bytes = boundary+1, boundary+1, after +} + +func (editor *Editor) appendEventReplayStep(history *historyJournal, event *historyEvent, operation HistoryOperation, primitive HistoryPrimitive, position, length, before, after int) { + if len(event.steps) >= cap(event.steps) { + event.failed = true + editor.invalidateHistoryFrom(0) + return + } + event.steps = append(event.steps, HistoryStep{operation, primitive, position, length, before, after, history.context(event.current, event.retainedTo)}) + if operation == HistoryUndo { + event.current-- + } else { + event.current++ + } + if event.current < 0 { + event.failed = true + editor.invalidateHistoryFrom(0) + } + event.bytes = after +} + +func (editor *Editor) appendEventPrimitives(event *historyEvent, primitives []Edit) { + for _, primitive := range primitives { + editor.appendEventForwardPrimitive(event, primitive) + } +} + +func (editor *Editor) captureEventReplay(event *historyEvent, edit *historyEdit, inverse bool) { + history := editor.historyState() + if history == nil { + event.failed = true + return + } + primitives := editor.historyReplayPrimitives(edit) + operation := HistoryRedo + if inverse { + operation = HistoryUndo + } + for index := range len(primitives) { + at := index + if inverse { + at = len(primitives) - 1 - index + } + primitive := primitives[at] + if inverse { + if primitive.kind == HistoryInsert { + primitive.kind = HistoryDelete + } else { + primitive.kind = HistoryInsert + } + } + before := event.bytes + after := before + primitive.length + if primitive.kind == HistoryDelete { + after = before - primitive.length + } + if after < 0 { + event.failed = true + editor.invalidateHistoryFrom(0) + return + } + editor.appendEventReplayStep(history, event, operation, primitive.kind, primitive.position, primitive.length, before, after) + } +} diff --git a/text/composition_identity_test.go b/text/composition_identity_test.go new file mode 100644 index 000000000..3b1795c5e --- /dev/null +++ b/text/composition_identity_test.go @@ -0,0 +1,129 @@ +package text + +import "testing" + +func TestTentativeCompositionActiveExcludesLegacyAndForeignOwners(t *testing.T) { + var absent *Editor + editor := NewEditor("abc") + if absent.TentativeCompositionActive() || editor.TentativeCompositionActive() || editor.journal != nil { + t.Fatal("inactive read allocated state or reported rollback ownership") + } + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetMarkedText("legacy", Range{}) + if !editor.CompositionActive() || editor.TentativeCompositionActive() { + t.Fatal("legacy marking was mistaken for explicit rollback ownership") + } + editor.Unmark() + if !editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: "p"}) || !editor.TentativeCompositionActive() { + t.Fatal("explicit Update did not expose its live rollback boundary") + } + foreign := *editor + if foreign.TentativeCompositionActive() { + t.Fatal("a copied receiver borrowed another editor's rollback boundary") + } + if allocations := testing.AllocsPerRun(100, func() { + if !editor.TentativeCompositionActive() { + t.Fatal("read changed live rollback ownership") + } + }); allocations != 0 { + t.Fatalf("active reads allocated %.0f times", allocations) + } + if !editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate}) || editor.TentativeCompositionActive() || editor.CompositionActive() { + t.Fatal("empty Update did not end the explicit rollback boundary") + } +} + +func TestCompositionIdentityTracksOnlyAnEnabledCapability(t *testing.T) { + var absent *Editor + first, second := NewEditor("same"), NewEditor("same") + if absent.TentativeCompositionIdentity() != (CompositionIdentity{}) || first.TentativeCompositionIdentity() != (CompositionIdentity{}) || first.journal != nil { + t.Fatal("reading default identity enabled or retained optional state") + } + if !first.EnableTentativeComposition() || !second.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + identity := first.TentativeCompositionIdentity() + if identity == (CompositionIdentity{}) || identity == second.TentativeCompositionIdentity() { + t.Fatal("different enabled capabilities have no distinct identities") + } + if !first.EnableTentativeComposition() || first.TentativeCompositionIdentity() != identity { + t.Fatal("an already-enabled capability changed identity") + } + if !first.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: "x"}) { + t.Fatal("composition update refused") + } + before, selection := first.String(), first.Selection() + if allocations := testing.AllocsPerRun(100, func() { + if first.TentativeCompositionIdentity() != identity { + t.Fatal("an active snapshot changed ownership") + } + }); allocations != 0 { + t.Fatalf("identity snapshots allocate: %v", allocations) + } + if first.String() != before || first.Selection() != selection || !first.CompositionActive() { + t.Fatal("identity lookup changed the live composition") + } + foreign := *first + if foreign.TentativeCompositionIdentity() != (CompositionIdentity{}) || foreign.TentativeCompositionEnabled() { + t.Fatal("a value copy borrowed its source's capability ownership") + } + if !first.ApplyComposition(CompositionEvent{Phase: CompositionCancel}) { + t.Fatal("composition cancel refused") + } + first.ClearHistory() + if first.TentativeCompositionIdentity() != identity { + t.Fatal("clearing history changed the enabled editor's ownership") + } + if !first.DisableTentativeComposition() || first.TentativeCompositionIdentity() != (CompositionIdentity{}) { + t.Fatal("disabled capability retained a visible identity") + } + if !first.EnableTentativeComposition() || first.TentativeCompositionIdentity() == identity || first.TentativeCompositionIdentity() == (CompositionIdentity{}) { + t.Fatal("re-enabling a released capability reused stale ownership") + } +} + +func TestCompositionIdentityRefreshesWhenPassiveStorageIsReenabled(t *testing.T) { + editor := NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + identity := editor.TentativeCompositionIdentity() + if _, _, ok := editor.TrackHistory(); !ok { + t.Fatal("history setup refused") + } + if !editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: "x"}) || + !editor.ApplyComposition(CompositionEvent{Phase: CompositionResult, Text: "z"}) { + t.Fatal("composition result setup refused") + } + state := editor.compositionState() + if state == nil || !state.completed || !editor.DisableTentativeComposition() || !state.passive { + t.Fatal("completed action did not retain passive storage") + } + if editor.TentativeCompositionIdentity() != (CompositionIdentity{}) { + t.Fatal("passive storage reported enabled ownership") + } + before, selection := editor.String(), editor.Selection() + undo, redo := editor.CanUndo(), editor.CanRedo() + cursor, _, ok := editor.TrackHistory() + if !ok { + t.Fatal("history cursor setup refused") + } + _, cursor, ok = editor.HistorySince(cursor) + if !ok { + t.Fatal("history prefix was unavailable before re-enable") + } + if !editor.EnableTentativeComposition() || editor.compositionState() != state { + t.Fatal("re-enable did not reuse the existing charged storage") + } + if got := editor.TentativeCompositionIdentity(); got == identity || got == (CompositionIdentity{}) { + t.Fatal("re-enable resurrected the retired native capability identity") + } + if editor.String() != before || editor.Selection() != selection || editor.CanUndo() != undo || editor.CanRedo() != redo { + t.Fatal("identity refresh changed editing or history state") + } + if frames, latest, ok := editor.HistorySince(cursor); !ok || len(frames) != 0 || latest != cursor { + t.Fatal("identity refresh published or invalidated history metadata") + } +} diff --git a/text/composition_link.go b/text/composition_link.go new file mode 100644 index 000000000..dc80e78c7 --- /dev/null +++ b/text/composition_link.go @@ -0,0 +1,111 @@ +package text + +// This file is the thin private boundary between ordinary editor paths and the +// optional composition subgraph. Default editors keep a nil sidecar and never +// reach the per-scalar transaction or producer-accumulator implementation. + +func (editor *Editor) compositionState() *compositionState { + if editor == nil || editor.journal == nil { + return nil + } + state := editor.journal.compositionState() + if state == nil || state.owner != editor { + return nil + } + return state +} + +func (editor *Editor) tentativeActive() bool { + state := editor.compositionState() + return state != nil && state.active +} + +func (editor *Editor) compositionEvent() *historyEvent { + state := editor.compositionState() + if state == nil { + return nil + } + return state.event +} + +func (editor *Editor) compositionRetainEqual() bool { + state := editor.compositionState() + return state != nil && state.retainEqual +} + +// syncCompositionTail reflects a private no-callback redo truncation in the +// producer's retained tail without publishing a frame or advancing sequence. +func (editor *Editor) syncCompositionTail() { + if history := editor.historyState(); history != nil { + history.retainedTo = history.current + } +} + +func (editor *Editor) compositionCost() int { + state := editor.compositionState() + if state == nil { + return 0 + } + return state.cost +} + +// sealTentativeHistory is the explicit legacy compatibility escape. It ends +// only the tentative history boundary, keeps the visible text/mark/selection +// unchanged, truncates redo and invalidates producer metadata before the legacy +// operation runs with its original UI composition targeting. +func (editor *Editor) sealTentativeHistory() { + state := editor.compositionState() + if state == nil || !state.active { + return + } + editor.sealTentativeHistorySlow() +} + +// sealTentativeHistorySlow keeps the ordinary-path seal inlinable. It only runs +// for an owned active tentative, so the invalidation/redo work is never a +// dormant default-path call. +func (editor *Editor) sealTentativeHistorySlow() { + state := editor.journal.compositionState() + state.active = false + state.live = false + state.completed = false + state.completedStart = -1 + state.eventStart = -1 + state.unitStart = -1 + editor.chargeCompositionCapacity() + editor.invalidateHistoryFrom(0) + editor.dropRedo() +} + +// disableTentativeForConfiguration seals an active tentative, releases only the +// capability sidecar and leaves visible/UI marking untouched. The caller then +// performs its normal restriction or overwrite change. +func (editor *Editor) disableTentativeForConfiguration() { + state := editor.compositionState() + if state == nil { + return + } + if state.active { + // The visible units stay Undoable, so they become one passive completed + // physical boundary rather than unprotected history that the next trim + // could cut. Producer metadata still invalidates on this escape. + state.active = false + state.live = false + editor.compositionComplete(state) + editor.invalidateHistoryFrom(0) + editor.dropRedo() + } + state.event = nil + state.enabled = false + editor.chargeCompositionCapacity() + if state.completed { + state.passive = true + return + } + if cap(editor.history) > maxHistoryEntries { + // The backing is large enough to remain a charged nonprotecting owner. + state.passive = false + return + } + editor.journal.setCompositionState(nil) +} diff --git a/text/composition_retention.go b/text/composition_retention.go new file mode 100644 index 000000000..1ff8c151d --- /dev/null +++ b/text/composition_retention.go @@ -0,0 +1,306 @@ +package text + +import "unsafe" + +// historyEditRunes is the actual per-slot backing of the ordinary history +// array. Retention charges real capacity in rune-sized budget units rather than +// only the used lengths; the capability descriptor and producer metadata are +// charged separately by compositionHeaderRunes/historyJournal.cost. +const historyEditRunes = int((unsafe.Sizeof(historyEdit{}) + unsafe.Sizeof(rune(0)) - 1) / unsafe.Sizeof(rune(0))) + +// retentionActive reports whether this capability currently owns a live, +// pending or completed physical boundary. An enabled idle sidecar retains no +// history capacity charge. +func (state *compositionState) retentionActive() bool { + return state != nil && (state.live || state.completed || state.pending || state.active) +} + +// ownRunes returns an exact-capacity copy of values. Composition units use it +// only when their current backing is larger than the used length, so actual +// retained rune capacity equals the charged length instead of hiding allocator +// slack or sharing an oversized event buffer across units. +func ownRunes(values []rune) []rune { + if len(values) == 0 { + return nil + } + owned := make([]rune, len(values)) + copy(owned, values) + return owned +} + +// ownCompositionEventText makes every unit created by the current event own +// exactly its used removed/inserted rune slots. The event delivery boundary +// includes the ordinary pre-start/explicit deletion, so it is compacted too. +// Unit indices, text, primitives and producer frames are unchanged. +func (editor *Editor) ownCompositionEventText(state *compositionState) { + if state == nil { + return + } + from := state.eventStart + if from < 0 { + from = state.unitStart + } + if from < 0 || from > len(editor.history) { + return + } + for index := from; index < len(editor.history); index++ { + editor.ownCompositionUnitText(&editor.history[index]) + } +} + +func (editor *Editor) ownCompositionUnitText(edit *historyEdit) { + + if cap(edit.removed) != len(edit.removed) { + edit.removed = ownRunes(edit.removed) + } + if cap(edit.inserted) != len(edit.inserted) { + edit.inserted = ownRunes(edit.inserted) + } + +} + +// reserveCompositionHistory gives the planned event exact backing capacity so +// the physical preflight charge is the capacity actually retained, not a +// post-hoc growth guess. It never shrinks or mutates units. +func (editor *Editor) reserveCompositionHistory(need int) { + if need <= 0 || need <= cap(editor.history) { + return + } + next := make([]historyEdit, len(editor.history), need) + copy(next, editor.history) + editor.history = next + editor.chargeCompositionCapacity() +} + +// compactCompositionHistory releases prefix capacity after rollback/trim. Only +// composition-owned history is compacted; default editors keep their exact +// legacy growth behavior. +func (editor *Editor) compactCompositionHistory() { + if editor == nil || editor.journal == nil || editor.journal.compositionState() == nil { + return + } + if cap(editor.history) == len(editor.history) { + return + } + next := make([]historyEdit, len(editor.history)) + copy(next, editor.history) + editor.history = next + editor.chargeCompositionCapacity() +} + +// chargeCompositionCapacity recomputes the descriptor header charge from the +// actual history array capacity. It is called only from composition-owned +// reserve/compact/boundary code, never from the default typing path. +func (editor *Editor) chargeCompositionCapacity() { + if editor == nil || editor.journal == nil || editor.journal.compositionState() == nil { + return + } + state := editor.journal.compositionState() + state.cost = editor.compositionBaseCost() + if state.retentionActive() { + state.cost += cap(editor.history) * historyEditRunes + return + } + // After protection retires, the first maxHistoryEntries slots are the + // accepted ordinary baseline. Larger composition-owned backing is still real + // until compacted, so a nonprotecting owner keeps charging its extra slots. + if extra := cap(editor.history) - maxHistoryEntries; extra > 0 { + state.cost += extra * historyEditRunes + } +} + +// compositionTrimCost is the eviction predicate cost for a retired +// nonprotecting owner. It models the backing that will exist after the trim +// settles (capacity compacted to the surviving length) instead of letting stale +// oversized capacity force eviction below the ordinary entry limit. The actual +// charge is restored by settleCompositionStorage before the trim returns. +func (editor *Editor) compositionTrimCost(state *compositionState, remaining int) int { + cost := editor.historyCost() + if state == nil || state.retentionActive() { + return cost + } + excess := cap(editor.history) - max(remaining, maxHistoryEntries) + if excess > 0 { + cost -= excess * historyEditRunes + } + return cost +} + +func compositionTrimCostOwned(state *compositionState, remaining int) int { + if state == nil || state.owner == nil { + return 0 + } + return state.owner.compositionTrimCost(state, remaining) +} + +// settleCompositionStorage is the post-protection owner. It compacts excess +// array capacity when no live/completed boundary protects the units, keeps the +// actual extra slots charged while a large used array remains for Undo/Redo, +// and releases a disabled nonprotecting owner once the backing is ordinary. +// It is called from trim after units have been processed, never with an +// in-flight historyEdit pointer. +func settleCompositionStorage(state *compositionState) { + if state == nil || state.owner == nil { + return + } + editor := state.owner + if state.retentionActive() { + editor.chargeCompositionCapacity() + return + } + if cap(editor.history) > maxHistoryEntries && cap(editor.history) != len(editor.history) { + next := make([]historyEdit, len(editor.history)) + copy(next, editor.history) + editor.history = next + } + // Ordinary units that survive alongside the retired composition suffix can + // also carry allocator slack (for example a one-rune append with cap 2). + // With a live composition-owned storage owner, own exact text capacity for + // the whole retained array so the charge equals the actual cap. + for index := range editor.history { + editor.ownCompositionUnitText(&editor.history[index]) + } + editor.chargeCompositionCapacity() + if !state.enabled && !state.live && !state.active && !state.completed && cap(editor.history) <= maxHistoryEntries { + editor.journal.setCompositionState(nil) + } +} + +// retireCompletedRetention releases the previous completed action before an +// accepted mutation. It is descriptor-only and never touches text, units, +// frames or cursors. A passive disabled owner is released entirely. +func (editor *Editor) retireCompletedRetention() { + if editor == nil || editor.journal == nil { + return + } + state := editor.journal.compositionState() + if state == nil || !state.completed { + return + } + state.completed = false + state.completedStart = -1 + state.passive = false + editor.chargeCompositionCapacity() + if !state.enabled && !state.live && !state.active && cap(editor.history) <= maxHistoryEntries { + editor.journal.setCompositionState(nil) + } +} + +// recordRetiresCompleted is the ordinary-mutation hook. It runs only when a +// real ordinary change/unit is about to be accepted, so refusals, valid no-ops, +// reads, getters and selection-only operations keep completed retention. +func (editor *Editor) recordRetiresCompleted() { + editor.retireCompletedRetention() +} + +func trimCompositionHistoryOwned(state *compositionState) { + if state != nil && state.owner != nil { + state.owner.trimCompositionHistory() + } +} + +// Only the enable-time dispatch links retention-aware trimming. Ordinary +// clients keep the existing trim path and never acquire physical protection. +func (editor *Editor) trimCompositionHistory() { + journal := editor.journal + state := editor.compositionState() + if state != nil && state.completed { + state.completed, state.passive = false, false + state.completedStart = -1 + editor.chargeCompositionCapacity() + if !state.enabled && !state.live && !state.active && cap(editor.history) <= maxHistoryEntries { + journal.setCompositionState(nil) + state = nil + } + } + if history := editor.historyState(); history != nil { + history.ops.enforce(history) + } + protected := -1 + if state != nil { + if state.live || state.active || state.pending { + protected = state.eventStart + if (state.live || state.active) && (protected < 0 || state.unitStart >= 0 && state.unitStart < protected) { + protected = state.unitStart + } + } + if state.completed && (protected < 0 || state.completedStart >= 0 && state.completedStart < protected) { + protected = state.completedStart + } + } + remove, limit := 0, len(editor.history)-1 + if protected >= 0 && protected < limit { + limit = protected + } + for remove < limit { + remaining := len(editor.history) - remove + if remaining <= maxHistoryEntries { + cost := editor.historyCost() + if state != nil && state.ops.trimCost != nil { + cost = state.ops.trimCost(state, remaining) + } + if cost <= maxHistoryRunes { + break + } + } + edit := editor.history[remove] + editor.historyRunes -= editor.historyUnitRunes(&edit) + editor.forgetLineBatch(&editor.history[remove]) + remove++ + } + if remove > 0 { + editor.invalidateHistoryFrom(remove) + if point := editor.savePointIndex(); point != nil && *point >= 0 { + *point -= remove + if *point < 0 { + *point = -1 + } + } + copy(editor.history, editor.history[remove:]) + clear(editor.history[len(editor.history)-remove:]) + editor.history = editor.history[:len(editor.history)-remove] + editor.historyIndex = max(0, editor.historyIndex-remove) + if state != nil { + if state.eventStart >= 0 { + state.eventStart = max(0, state.eventStart-remove) + } + if state.unitStart >= 0 { + state.unitStart = max(0, state.unitStart-remove) + } + if state.completedStart >= 0 { + state.completedStart = max(0, state.completedStart-remove) + } + } + } + if state != nil && state.ops.settle != nil { + state.ops.settle(state) + if journal.compositionState() != state { + state = nil + } + } + if editor.historyCost() <= maxSingleEditRunes { + return + } + if state != nil && state.retentionActive() { + capacity := len(editor.history) + if state.pending && state.eventStart >= 0 { + // Prefix eviction must preserve the accepted event's future slots. + // Shrinking to the first scalar would restart slice growth near the + // hard limit and repeatedly allocate/compact the same large array. + capacity = max(capacity, state.eventStart+state.pendingUnits) + } + if cap(editor.history) != capacity { + next := make([]historyEdit, len(editor.history), capacity) + copy(next, editor.history) + editor.history = next + editor.chargeCompositionCapacity() + } + if editor.historyCost() > maxSingleEditRunes { + editor.invalidateHistoryFrom(0) + } + return + } + editor.clearHistory(false) + if point := editor.savePointIndex(); point != nil { + *point = -1 + } +} diff --git a/text/edit_journal.go b/text/edit_journal.go index 75bd3b72f..988dded9f 100644 --- a/text/edit_journal.go +++ b/text/edit_journal.go @@ -13,13 +13,17 @@ type Edit struct { const EditJournalLimit = 1024 type editJournal struct { - revision uint64 - entries []Edit - oldest int - unlimited bool - tracking bool - savePoint *int - lines *lineJournal + revision uint64 + entries []Edit + // oldest addresses only the bounded 1024-entry ring; unlimited drafts keep zero. + oldest uint16 + unlimited bool + tracking bool + retainEqual bool + private bool + savePoint *int + lines *lineJournal + optional *editorSidecar } // TrackEdits enables a bounded mutation journal and returns its current cursor. @@ -52,14 +56,14 @@ func (editor *Editor) EditsSince(cursor uint64, dst []Edit) ([]Edit, uint64, boo } first := len(journal.entries) - int(journal.revision-cursor) for index := first; index < len(journal.entries); index++ { - position := (journal.oldest + index) % len(journal.entries) + position := (int(journal.oldest) + index) % len(journal.entries) dst = append(dst, journal.entries[position]) } return dst, journal.revision, true } func (editor *Editor) prepareEdit(start, end int, replacement []rune) Edit { - if editor.journal == nil || !editor.journal.tracking { + if editor.journal == nil || !editor.journal.tracking && editor.historyState() == nil { return Edit{} } at, offset := editor.offsets.index, editor.offsets.offset @@ -77,6 +81,9 @@ func (editor *Editor) prepareEdit(start, end int, replacement []rune) Edit { offset -= runeBytes(editor.runes[at]) } editor.offsets = offsetMemo{index: start, offset: offset} + if !editor.journal.tracking { + return Edit{} + } edit := Edit{Start: offset} for _, character := range editor.runes[start:end] { edit.Removed += runeBytes(character) @@ -151,8 +158,15 @@ func (editor *Editor) recordBatchEdits(primitives []Edit, contexts []lineContext func (editor *Editor) replaceHistory(edit *historyEdit, inverse bool) { journal := editor.journal - contexts := editor.lineBatchContexts(edit.primitives) - if len(edit.primitives) > 0 { + if labels := editor.lfLabelState(); labels != nil { + labels.replaying = true + defer func() { labels.replaying = false }() + labels.ops.replay(labels, lfLabelHistoryKey(edit), inverse) + } + batch := edit.kind == editSeparate && len(edit.primitives) > 0 + var contexts []lineContext + if batch { + contexts = editor.lineBatchContexts(edit.primitives) editor.journal = nil } if inverse { @@ -161,5 +175,7 @@ func (editor *Editor) replaceHistory(edit *historyEdit, inverse bool) { editor.replaceExact(edit.start, len(edit.removed), edit.inserted) } editor.journal = journal - editor.recordBatchEdits(edit.primitives, contexts, inverse) + if batch { + editor.recordBatchEdits(edit.primitives, contexts, inverse) + } } diff --git a/text/editing.go b/text/editing.go index 74902501a..8ae9d32f0 100644 --- a/text/editing.go +++ b/text/editing.go @@ -114,10 +114,33 @@ func WordRange(value string, index int) Range { return Range{Start: start, End: end} } +// LineRange returns the logical line around a pointer position, including its +// trailing newline when it has one. It is the selection a triple click takes. +func LineRange(value string, index int) Range { + runes := []rune(value) + if len(runes) == 0 { + return Range{} + } + index = max(0, min(index, len(runes)-1)) + start := index + for start > 0 && runes[start-1] != '\n' { + start-- + } + end := index + for end < len(runes) && runes[end] != '\n' { + end++ + } + if end < len(runes) { + end++ // the newline belongs to the line it ends + } + return Range{Start: start, End: end} +} + // DeleteWord removes a selection or a word as one undo unit. Undo restores the // original caret, rather than an artificial selection used to delete the word. func (editor *Editor) DeleteWord(forward bool) { editor.BreakUndoGroup() + editor.clearSecondary() // a word deletion is a single-selection edit if editor.Selection().Start != editor.Selection().End || editor.composing { editor.DeleteBackward() editor.BreakUndoGroup() @@ -160,6 +183,7 @@ func (editor *Editor) MoveLineBoundary(end, extend bool) { // by them with MoveTo. func (editor *Editor) DeleteToLineBoundary(end bool) { editor.BreakUndoGroup() + editor.clearSecondary() // a line deletion is a single-selection edit selection := editor.Selection() if selection.Start != selection.End || editor.composing { editor.DeleteBackward() diff --git a/text/editing_test.go b/text/editing_test.go index 4b1147e08..91c66f590 100644 --- a/text/editing_test.go +++ b/text/editing_test.go @@ -35,6 +35,12 @@ func TestAddressWordBoundariesAndLineNavigation(t *testing.T) { if got := WordRange("e\u0301 👩‍💻 host", 4); got != (Range{Start: 3, End: 6}) { t.Fatalf("emoji word = %+v", got) } + if got := LineRange("first\nsecond line\nthird", 9); got != (Range{Start: 6, End: 18}) { + t.Fatalf("line = %+v", got) + } + if got := LineRange("first\nsecond line\nthird", 18); got != (Range{Start: 18, End: 23}) { + t.Fatalf("last line = %+v", got) + } editor = NewEditor("first\nsecond") editor.MoveLineBoundary(false, true) if editor.Selection() != (Range{Start: 6, End: 12}) || editor.Caret() != 6 { diff --git a/text/editor.go b/text/editor.go index 1e7a950d6..a946dc67a 100644 --- a/text/editor.go +++ b/text/editor.go @@ -68,9 +68,13 @@ type textChange struct { // thread, where native input and painting run. Read a string snapshot there // before starting background work; the returned string remains valid after edits. type Editor struct { - runes []rune - anchor int - caret int + runes []rune + anchor int + caret int + // secondary is the multi-selection's other selections, normalized: ordered + // and disjoint from the primary. It is empty in every editor that never + // calls AddSelection or SetSelections. See multiselection.go. + secondary []editorSelection composition Range composing bool compositionOriginal []rune @@ -80,6 +84,7 @@ type Editor struct { // compositionBaseValid says compositionBase holds the built value. The value // itself may legitimately be empty, so it cannot serve as its own sentinel. compositionBaseValid bool + legacyComposition bool // compositionHistory and its counters are the history a cancel restores. The // provisional composition edit may drop redo, merge, or trim older units. compositionHistory []historyEdit @@ -153,6 +158,11 @@ func (editor *Editor) String() string { // Like String, it populates a cache and is not safe for concurrent use. func (editor *Editor) CommittedString() string { if editor.composing { + if state := editor.compositionState(); state != nil && state.active && state.enabled && state.ops.committed != nil { + if value, ok := state.ops.committed(state); ok { + return value + } + } if !editor.compositionBaseValid { committed := make([]rune, 0, len(editor.runes)-editor.composition.End+editor.composition.Start+len(editor.compositionOriginal)) committed = append(committed, editor.runes[:editor.composition.Start]...) @@ -177,6 +187,7 @@ func (editor *Editor) CommittedString() string { // empty six-digit editor leaves "123456". Text already present is left alone, // and deleting is never restricted. func (editor *Editor) Restrict(accept func(rune) bool, maxRunes int) { + editor.disableTentativeForConfiguration() editor.accept = accept editor.maxRunes = maxRunes } @@ -212,6 +223,7 @@ func (editor *Editor) Caret() int { // Start is after its End is a selection made backwards: the caret is at the // Start, as Caret reports, and Selection still returns it in order. func (editor *Editor) SetSelection(selection Range) { + editor.sealTentativeHistory() anchor := clamp(selection.Start, 0, len(editor.runes)) caret := clamp(selection.End, 0, len(editor.runes)) if editor.anchor != anchor || editor.caret != caret || editor.composing { @@ -219,6 +231,7 @@ func (editor *Editor) SetSelection(selection Range) { } editor.anchor = anchor editor.caret = caret + editor.clearSecondary() editor.composing = false editor.releaseCompositionHistory() } @@ -226,8 +239,10 @@ func (editor *Editor) SetSelection(selection Range) { // MoveTo puts the caret at rune index, or with extend moves it there from where // it was and keeps the other end of the selection where it is. It is how an // editor applies a movement the text itself does not know, such as one line up -// in text a view has wrapped. It ends active composition. +// in text a view has wrapped. It ends active composition and, like any single +// selection movement, drops the secondary selections. func (editor *Editor) MoveTo(index int, extend bool) { + editor.sealTentativeHistory() editor.BreakUndoGroup() index = clamp(index, 0, len(editor.runes)) if extend { @@ -235,6 +250,7 @@ func (editor *Editor) MoveTo(index int, extend bool) { } else { editor.collapse(index) } + editor.clearSecondary() editor.composing = false editor.releaseCompositionHistory() } @@ -245,11 +261,18 @@ func (editor *Editor) Composition() (Range, bool) { } // Insert replaces the current selection or composition and places the caret -// after inserted text. +// after inserted text. With several selections it replaces every one and leaves +// a caret after each copy, as CodeMirror does; a composition, an overwriting +// editor and a restricted one take the primary alone. func (editor *Editor) Insert(value string) { + if editor.multiInsert(value) { + return + } target := editor.Selection() wasComposing := editor.composing if wasComposing { + editor.sealTentativeHistory() + editor.invalidateHistoryFrom(0) target = editor.composition } overwrite := editor.overwrite && !wasComposing && target.Start == target.End @@ -275,6 +298,7 @@ func (editor *Editor) Insert(value string) { // Paste inserts text as one undo unit, separate from adjacent typing. func (editor *Editor) Paste(value string) { + editor.sealTentativeHistory() editor.BreakUndoGroup() editor.Insert(value) editor.BreakUndoGroup() @@ -283,6 +307,8 @@ func (editor *Editor) Paste(value string) { // SetMarkedText replaces the current composition or selection with marked // text. selected is relative to the marked text, matching native IME APIs. func (editor *Editor) SetMarkedText(value string, selected Range) { + editor.sealTentativeHistory() + editor.invalidateHistoryFrom(0) wasComposing := editor.composing target := editor.Selection() if wasComposing { @@ -291,6 +317,9 @@ func (editor *Editor) SetMarkedText(value string, selected Range) { before := editor.selectionState() change := editor.replace(target, value, false) if !wasComposing { + // End the multi-selection after replacement policy has accepted the + // change, so a rejected marked update leaves the selection set intact. + editor.clearSecondary() editor.compositionOriginal = change.removed editor.compositionBase = "" editor.compositionBaseValid = false @@ -302,6 +331,10 @@ func (editor *Editor) SetMarkedText(value string, selected Range) { editor.compositionHistoryRunes = editor.historyRunes editor.compositionCoalescing = editor.coalescing editor.compositionHistoryHeld = true + if labels := editor.lfLabelState(); labels != nil { + labels.ops.hold(labels, change) + } + editor.legacyComposition = true } inserted := len(change.inserted) if inserted == 0 && value != "" { @@ -323,6 +356,7 @@ func (editor *Editor) SetMarkedText(value string, selected Range) { // Unmark commits the current marked text without changing it. func (editor *Editor) Unmark() { + editor.sealTentativeHistory() editor.composing = false editor.releaseCompositionHistory() editor.BreakUndoGroup() @@ -336,11 +370,26 @@ func (editor *Editor) CancelComposition() bool { if !editor.composing { return false } + if !editor.legacyComposition { + if editor.tentativeActive() { + return editor.ApplyComposition(CompositionEvent{Phase: CompositionCancel}) + } + return false + } target := editor.composition + labels := editor.lfLabelState() + if labels != nil { + labels.replaying = true + defer func() { labels.replaying = false }() + } editor.replaceExact(target.Start, target.End-target.Start, editor.compositionOriginal) + if labels != nil { + labels.ops.cancel(labels) + } editor.anchor = clamp(editor.compositionAnchor, 0, len(editor.runes)) editor.caret = clamp(editor.compositionCaret, 0, len(editor.runes)) editor.composing = false + editor.legacyComposition = false editor.composition = Range{} editor.compositionOriginal = nil editor.compositionBase = "" @@ -361,8 +410,13 @@ func (editor *Editor) CancelComposition() bool { return true } -// DeleteBackward removes the selection or previous grapheme cluster. +// DeleteBackward removes the selection or previous grapheme cluster. With +// several selections it removes at every one, as one undo unit. func (editor *Editor) DeleteBackward() bool { + editor.sealTentativeHistory() + if editor.multiDelete(false) { + return true + } if editor.deleteSelectionOrComposition() { return true } @@ -383,8 +437,13 @@ func (editor *Editor) DeleteBackward() bool { return true } -// DeleteForward removes the selection or next grapheme cluster. +// DeleteForward removes the selection or next grapheme cluster. With several +// selections it removes at every one, as one undo unit. func (editor *Editor) DeleteForward() bool { + editor.sealTentativeHistory() + if editor.multiDelete(true) { + return true + } if editor.deleteSelectionOrComposition() { return true } @@ -405,7 +464,9 @@ func (editor *Editor) DeleteForward() bool { // the previous one, except in a line with right-to-left text, where the order is the one // UAX #9 displays it in. func (editor *Editor) MoveLeft(extend bool) bool { + editor.sealTentativeHistory() editor.BreakUndoGroup() + editor.clearSecondary() // a movement moves the primary selection alone editor.composing = false editor.releaseCompositionHistory() selection := editor.Selection() @@ -429,7 +490,9 @@ func (editor *Editor) MoveLeft(extend bool) bool { // MoveRight moves or extends selection by one grapheme cluster to the right on the screen // (see MoveLeft). func (editor *Editor) MoveRight(extend bool) bool { + editor.sealTentativeHistory() editor.BreakUndoGroup() + editor.clearSecondary() // see MoveLeft editor.composing = false editor.releaseCompositionHistory() selection := editor.Selection() @@ -507,6 +570,7 @@ func (editor *Editor) deleteSelectionOrComposition() bool { func (editor *Editor) collapse(index int) { editor.anchor = index editor.caret = index + editor.clearSecondary() } // replace swaps target for value, applying the Restrict limits, and returns the @@ -515,8 +579,13 @@ func (editor *Editor) collapse(index int) { // the replacement began, which differs from target.Start only when a full field // had to replace its last rune. func (editor *Editor) replace(target Range, value string, overwrite bool) textChange { + return editor.replaceRunes(target, []rune(value), overwrite) +} + +// Explicit composition passes one borrowed scalar at a time; ordinary callers +// still pass the same newly allocated rune slice through replace. +func (editor *Editor) replaceRunes(target Range, replacement []rune, overwrite bool) textChange { target = normalizeRange(target, len(editor.runes)) - replacement := []rune(value) if editor.accept != nil { kept := replacement[:0] for _, r := range replacement { @@ -554,6 +623,9 @@ func (editor *Editor) replace(target Range, value string, overwrite bool) textCh context = editor.prepareLineContext(target.Start, target.End, replacement) } } + if lines != nil && lines.labels != nil { + lines.labels.ops.replace(lines.labels, context.line, change.removed, replacement) + } editor.textValid = false editor.offsets.trim(target.Start) delta := len(replacement) - removed @@ -580,27 +652,50 @@ func (editor *Editor) CanRedo() bool { return editor.historyIndex < len(editor.h // Undo restores the text and selection before the latest undo unit. func (editor *Editor) Undo() bool { + if editor.composing && editor.tentativeActive() { + return false + } if !editor.CanUndo() { return false } + if labels := editor.lfLabelState(); labels != nil && labels.mapping { + panic("text: LF label mapper reentered Undo") + } + editor.retireCompletedRetention() editor.historyIndex-- edit := &editor.history[editor.historyIndex] editor.replaceHistory(edit, true) editor.restoreSelection(edit.before) editor.BreakUndoGroup() + if history := editor.historyState(); history != nil { + history.ops.replay(history, editor.historyIndex, true) + } + if state := editor.compositionState(); state != nil && state.ops.settle != nil { + state.ops.settle(state) + } return true } // Redo reapplies the next undone edit and restores its resulting selection. func (editor *Editor) Redo() bool { + if editor.composing && editor.tentativeActive() { + return false + } if !editor.CanRedo() { return false } + editor.retireCompletedRetention() edit := &editor.history[editor.historyIndex] editor.replaceHistory(edit, false) editor.restoreSelection(edit.after) editor.historyIndex++ editor.BreakUndoGroup() + if history := editor.historyState(); history != nil { + history.ops.replay(history, editor.historyIndex-1, false) + } + if state := editor.compositionState(); state != nil && state.ops.settle != nil { + state.ops.settle(state) + } return true } @@ -609,15 +704,41 @@ func (editor *Editor) Redo() bool { // automatically; applications may call it at another semantic boundary. func (editor *Editor) BreakUndoGroup() { editor.coalescing = 0 } -func (editor *Editor) clearHistory() { +func (editor *Editor) clearHistory(manual bool) { + if labels := editor.lfLabelState(); labels != nil && labels.mapping { + panic("text: LF label mapper reentered history reset") + } + state := editor.compositionState() + if editor.composing || state != nil && state.active { + if state != nil { + state.active = false + } + editor.invalidateHistoryFrom(0) + } else if history := editor.historyState(); history != nil { + history.ops.clear(history, manual && !editor.composing) + } if editor.journal != nil && editor.journal.lines != nil { editor.journal.lines.batches = nil editor.journal.lines.delivery = nil + if labels := editor.journal.lines.labels; labels != nil { + labels.ops.clear(labels) + } } editor.history = nil editor.historyIndex = 0 editor.historyRunes = 0 + if labels := editor.lfLabelState(); labels != nil { + editor.historyRunes = labels.ops.extra(labels) + } editor.coalescing = 0 + if state != nil { + state.live, state.completed, state.passive = false, false, false + state.eventStart, state.completedStart, state.unitStart = -1, -1, -1 + state.cost = editor.compositionBaseCost() + if !state.enabled && !state.active { + editor.journal.setCompositionState(nil) + } + } if point := editor.savePointIndex(); point != nil { *point = 0 } @@ -626,8 +747,13 @@ func (editor *Editor) clearHistory() { // ClearHistory forgets every undo and redo unit without changing the text. It // also forgets the history a cancel could restore, so a composition active // while it is called cannot bring back cleared units. +// A proven complete-history producer starts a new generation; an unavailable +// producer stays unavailable. Use ClearChangeHistory to preserve unsaved truth. func (editor *Editor) ClearHistory() { - editor.clearHistory() + editor.clearHistory(true) + if labels := editor.lfLabelState(); labels != nil { + labels.ops.discard(labels) + } editor.compositionHistoryIndex = 0 editor.compositionHistoryRunes = 0 editor.compositionCoalescing = 0 @@ -635,6 +761,12 @@ func (editor *Editor) ClearHistory() { } func (editor *Editor) releaseCompositionHistory() { + if labels := editor.lfLabelState(); labels != nil { + labels.ops.release(labels) + } + if !editor.composing { + editor.legacyComposition = false + } if !editor.compositionHistoryHeld { return } @@ -659,23 +791,35 @@ func (editor *Editor) selectionState() editorSelection { func (editor *Editor) restoreSelection(selection editorSelection) { editor.anchor = clamp(selection.anchor, 0, len(editor.runes)) editor.caret = clamp(selection.caret, 0, len(editor.runes)) + editor.clearSecondary() editor.composing = false editor.releaseCompositionHistory() } func (editor *Editor) record(change textChange, before, after editorSelection, kind editKind) { - if runesEqual(change.removed, change.inserted) && (len(change.removed) == 0 || editor.savePointIndex() == nil) { + if runesEqual(change.removed, change.inserted) && !editor.pendingLFLabels() && (len(change.removed) == 0 || !editor.retainEqualEdits()) { return } + editor.recordRetiresCompleted() editor.dropRedo() - if editor.merge(change, before, after, kind) { + var primitive Edit + owned := false + if history := editor.historyState(); history != nil { + primitive, owned = history.ops.record(history, change, kind) + } + owned = owned && kind != editSeparate + if editor.merge(change, before, after, kind, primitive, owned) { editor.trimHistory() return } - editor.appendHistory(historyEdit{ + edit := historyEdit{ start: change.start, removed: change.removed, inserted: change.inserted, before: before, after: after, kind: kind, - }) + } + if owned { + edit.primitives = []Edit{primitive} + } + editor.appendHistory(edit) } func (editor *Editor) recordWithPrimitives(change textChange, before, after editorSelection, kind editKind, primitives []Edit) { @@ -683,10 +827,14 @@ func (editor *Editor) recordWithPrimitives(change textChange, before, after edit editor.record(change, before, after, kind) return } - if runesEqual(change.removed, change.inserted) && editor.savePointIndex() == nil { + if runesEqual(change.removed, change.inserted) && !editor.pendingLFLabels() && !editor.retainEqualEdits() && !editor.compositionRetainEqual() { return } + editor.recordRetiresCompleted() editor.dropRedo() + if history := editor.historyState(); history != nil { + history.ops.capturePrimitives(history, primitives) + } editor.appendHistory(historyEdit{ start: change.start, removed: change.removed, inserted: change.inserted, before: before, after: after, kind: kind, @@ -697,7 +845,10 @@ func (editor *Editor) recordWithPrimitives(change textChange, before, after edit func (editor *Editor) appendHistory(edit historyEdit) { editor.history = append(editor.history, edit) editor.historyIndex = len(editor.history) - editor.historyRunes += edit.retainedRunes() + if labels := editor.lfLabelState(); labels != nil { + labels.ops.record(labels, nil, lfLabelHistoryKey(&editor.history[editor.historyIndex-1])) + } + editor.historyRunes += editor.historyUnitRunes(&edit) if edit.kind == editSeparate { editor.coalescing = 0 } else { @@ -706,7 +857,7 @@ func (editor *Editor) appendHistory(edit historyEdit) { editor.trimHistory() } -func (editor *Editor) merge(change textChange, before, after editorSelection, kind editKind) bool { +func (editor *Editor) merge(change textChange, before, after editorSelection, kind editKind, primitive Edit, owned bool) bool { if editor.coalescing != kind || editor.historyIndex == 0 || editor.historyIndex != len(editor.history) { return false } @@ -717,6 +868,13 @@ func (editor *Editor) merge(change textChange, before, after editorSelection, ki if previous.kind != kind || previous.after != before { return false } + labels := editor.lfLabelState() + var labelKey *rune + labelRunes := 0 + if labels != nil { + labelKey = lfLabelHistoryKey(previous) + labelRunes = labels.ops.cost(labels, labelKey) + } switch kind { case editInsert: if len(previous.removed) != 0 || len(change.removed) != 0 || previous.start+len(previous.inserted) != change.start { @@ -749,10 +907,30 @@ func (editor *Editor) merge(change textChange, before, after editorSelection, ki default: return false } + if owned { + capacity := cap(previous.primitives) + previous.primitives = append(previous.primitives, primitive) + editor.historyRunes += (cap(previous.primitives) - capacity) * historyPrimitiveRunes + } previous.after = after + if labels != nil { + labels.ops.record(labels, labelKey, lfLabelHistoryKey(previous)) + editor.historyRunes += labels.ops.cost(labels, lfLabelHistoryKey(previous)) - labelRunes + } return true } +func (editor *Editor) historyUnitRunes(edit *historyEdit) int { + cost := edit.retainedRunes() + if labels := editor.lfLabelState(); labels != nil { + cost += labels.ops.cost(labels, lfLabelHistoryKey(edit)) + } + if edit.kind != editSeparate { + cost += (cap(edit.primitives) - len(edit.primitives)) * historyPrimitiveRunes + } + return cost +} + func (editor *Editor) dropRedo() { if editor.historyIndex < len(editor.history) { editor.discardRedo() @@ -764,23 +942,36 @@ func (editor *Editor) discardRedo() { *point = -1 } for index := editor.historyIndex; index < len(editor.history); index++ { - editor.historyRunes -= editor.history[index].retainedRunes() + editor.forgetLineBatch(&editor.history[index]) + editor.historyRunes -= editor.historyUnitRunes(&editor.history[index]) + editor.forgetLineBatch(&editor.history[index]) + if labels := editor.lfLabelState(); labels != nil { + labels.ops.forget(labels, lfLabelHistoryKey(&editor.history[index])) + } } clear(editor.history[editor.historyIndex:]) editor.history = editor.history[:editor.historyIndex] } func (editor *Editor) trimHistory() { + if state := editor.compositionState(); state != nil && state.ops.trim != nil { + state.ops.trim(state) + return + } + if history := editor.historyState(); history != nil { + history.ops.enforce(history) + } // The newest unit is always kept, unless it alone is beyond what is worth // keeping. remove := 0 - for len(editor.history)-remove > 1 && (len(editor.history)-remove > maxHistoryEntries || editor.historyRunes > maxHistoryRunes) { + for len(editor.history)-remove > 1 && (len(editor.history)-remove > maxHistoryEntries || editor.historyCost() > maxHistoryRunes) { edit := editor.history[remove] - editor.historyRunes -= edit.retainedRunes() + editor.forgetLineBatch(&editor.history[remove]) + editor.historyRunes -= editor.historyUnitRunes(&edit) + editor.forgetLineBatch(&editor.history[remove]) + if labels := editor.lfLabelState(); labels != nil { + labels.ops.forget(labels, lfLabelHistoryKey(&edit)) + } remove++ } - if len(editor.history)-remove == 1 && editor.historyRunes > maxSingleEditRunes { - editor.clearHistory() + if len(editor.history)-remove == 1 && editor.historyCost() > maxSingleEditRunes { + editor.clearHistory(false) if point := editor.savePointIndex(); point != nil { *point = -1 } @@ -789,6 +980,7 @@ func (editor *Editor) trimHistory() { if remove == 0 { return } + editor.invalidateHistoryFrom(remove) if point := editor.savePointIndex(); point != nil && *point >= 0 { *point -= remove if *point < 0 { @@ -813,6 +1005,9 @@ func (editor *Editor) replaceExact(start, removed int, replacement []rune) { context = editor.prepareLineContext(start, end, replacement) } } + if lines != nil && lines.labels != nil { + lines.labels.ops.replace(lines.labels, context.line, editor.runes[start:end], replacement) + } delta := len(replacement) - (end - start) if delta > 0 { editor.runes = append(editor.runes, make([]rune, delta)...) diff --git a/text/editor_sidecar.go b/text/editor_sidecar.go new file mode 100644 index 000000000..01c98945e --- /dev/null +++ b/text/editor_sidecar.go @@ -0,0 +1,58 @@ +package text + +import "unsafe" + +// The two opt-in capabilities share one journal slot; ordinary byte/line/save +// clients allocate neither this header nor either capability state. +type editorSidecar struct { + history *historyJournal + composition *compositionState +} + +const editorSidecarRunes = int((unsafe.Sizeof(editorSidecar{}) + unsafe.Sizeof(rune(0)) - 1) / unsafe.Sizeof(rune(0))) + +func (journal *editJournal) historyJournal() *historyJournal { + if journal == nil || journal.optional == nil { + return nil + } + return journal.optional.history +} + +func (journal *editJournal) compositionState() *compositionState { + if journal == nil || journal.optional == nil { + return nil + } + return journal.optional.composition +} + +func (journal *editJournal) setHistoryJournal(history *historyJournal) { + if journal.optional == nil { + journal.optional = &editorSidecar{} + } + journal.optional.history = history +} + +func (journal *editJournal) setCompositionState(state *compositionState) { + if state == nil { + if journal.optional != nil { + journal.optional.composition = nil + if journal.optional.history == nil { + journal.optional = nil + } + } + return + } + if journal.optional == nil { + journal.optional = &editorSidecar{} + } + journal.optional.composition = state +} + +func (editor *Editor) compositionBaseCost() int { + cost := compositionHeaderRunes + // A retained history header owns the shared slot even after invalidation. + if editor.journal.historyJournal() == nil { + cost += editorSidecarRunes + } + return cost +} diff --git a/text/history_frames_bench_test.go b/text/history_frames_bench_test.go new file mode 100644 index 000000000..b4759d1b4 --- /dev/null +++ b/text/history_frames_bench_test.go @@ -0,0 +1,50 @@ +package text + +import "testing" + +var historyFramesEditorSink *Editor +var historyFramesReadSink []HistoryFrame + +func BenchmarkHistoryFramesClient(b *testing.B) { + for _, tracked := range []bool{false, true} { + mode := "default" + if tracked { + mode = "enabled" + } + b.Run(mode, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + editor := NewEditor("") + if tracked { + editor.TrackHistory() + } + for _, value := range []string{"h", "e", "\n", "l", "l", "o"} { + editor.Insert(value) + } + editor.SetSavePoint() + editor.Undo() + editor.Redo() + historyFramesEditorSink = editor + } + }) + } +} + +func BenchmarkHistoryFramesReadPending(b *testing.B) { + editor := NewEditor("") + from, _, ok := editor.TrackHistory() + if !ok { + b.Fatal("producer unavailable") + } + for range 16 { + editor.Insert("x") + } + b.ReportAllocs() + for b.Loop() { + frames, _, ok := editor.HistorySince(from) + if !ok { + b.Fatal("retained prefix unavailable") + } + historyFramesReadSink = frames + } +} diff --git a/text/history_frames_test.go b/text/history_frames_test.go new file mode 100644 index 000000000..1d2c41455 --- /dev/null +++ b/text/history_frames_test.go @@ -0,0 +1,570 @@ +package text + +import ( + "fmt" + "reflect" + "strings" + "testing" +) + +func mustTrackHistory(t *testing.T, editor *Editor) HistoryCursor { + t.Helper() + cursor, size, ok := editor.TrackHistory() + if !ok || cursor == (HistoryCursor{}) || size != len(editor.String()) { + t.Fatalf("TrackHistory = %+v, %d, %t", cursor, size, ok) + } + return cursor +} + +func historySample(current, save, detach, tail int) HistoryContext { + return HistoryContext{Current: current, Save: save, Detach: detach, RetainedTo: tail, Collecting: true} +} + +func expectHistoryFrames(t *testing.T, editor *Editor, from HistoryCursor, want ...[]HistoryStep) HistoryCursor { + t.Helper() + frames, latest, ok := editor.HistorySince(from) + if !ok || len(frames) != len(want) { + t.Fatalf("HistorySince = %d frames, %t; want %d: %+v", len(frames), ok, len(want), frames) + } + for index, frame := range frames { + if frame.From != from || frame.To == from || !reflect.DeepEqual(frame.Steps, want[index]) { + t.Fatalf("frame %d = %+v; want steps %+v", index, frame, want[index]) + } + if len(frame.Steps) == 0 || frame.BeforeBytes != frame.Steps[0].BeforeBytes || frame.AfterBytes != frame.Steps[len(frame.Steps)-1].AfterBytes { + t.Fatalf("frame %d has inconsistent byte boundaries", index) + } + from = frame.To + } + if latest != from { + t.Fatalf("latest cursor %+v does not end the chain %+v", latest, from) + } + return latest +} + +func TestHistoryFramesPreservePrimitivesAcrossCoalescingSaveAndReplay(t *testing.T) { + editor := NewEditor("a\u00e9") + from := mustTrackHistory(t, editor) + if editor.AtSavePoint() { + t.Fatal("producer unexpectedly enabled save-point tracking") + } + editor.MoveTo(0, false) + editor.Insert("\U0001f600") + editor.Insert("z") + editor.SetSavePoint() + from = expectHistoryFrames(t, editor, from, + []HistoryStep{{HistoryForward, HistoryInsert, 0, 4, 3, 7, historySample(1, 0, -1, 1)}}, + []HistoryStep{{HistoryForward, HistoryInsert, 4, 1, 7, 8, historySample(2, 0, -1, 2)}}, + []HistoryStep{{Operation: HistorySave, BeforeBytes: 8, AfterBytes: 8, Context: historySample(2, 2, -1, 2)}}, + ) + if !editor.Undo() || editor.String() != "a\u00e9" || editor.CanUndo() { + t.Fatal("producer changed ordinary coalesced Undo") + } + from = expectHistoryFrames(t, editor, from, []HistoryStep{ + {HistoryUndo, HistoryDelete, 4, 1, 8, 7, historySample(2, 2, -1, 2)}, + {HistoryUndo, HistoryDelete, 0, 4, 7, 3, historySample(1, 2, -1, 2)}, + }) + if !editor.Redo() || editor.String() != "\U0001f600za\u00e9" || !editor.AtSavePoint() { + t.Fatal("producer changed ordinary Redo or save point") + } + from = expectHistoryFrames(t, editor, from, []HistoryStep{ + {HistoryRedo, HistoryInsert, 0, 4, 3, 7, historySample(0, 2, -1, 2)}, + {HistoryRedo, HistoryInsert, 4, 1, 7, 8, historySample(1, 2, -1, 2)}, + }) + if frames, latest, ok := editor.HistorySince(from); !ok || frames != nil || latest != from { + t.Fatal("empty read is not distinct from a saved operation") + } +} + +func TestHistoryFramesSaveOnlyOwnedReadsAndCursorRefusal(t *testing.T) { + editor := NewEditor("abc") + from := mustTrackHistory(t, editor) + for range 3 { + editor.SetSavePoint() + } + want := []HistoryStep{{Operation: HistorySave, BeforeBytes: 3, AfterBytes: 3, Context: historySample(0, 0, -1, 0)}} + latest := expectHistoryFrames(t, editor, from, want, want, want) + frames, _, _ := editor.HistorySince(from) + frames[0].Steps[0].Context.Save = 99 + frames[0].Steps[0].Position = 99 + frames[0].From = HistoryCursor{} + expectHistoryFrames(t, editor, from, want, want, want) + foreign := mustTrackHistory(t, NewEditor("abc")) + future, generation := latest, latest + future.sequence++ + generation.generation++ + for _, cursor := range []HistoryCursor{{}, foreign, future, generation} { + if got, _, ok := editor.HistorySince(cursor); ok || got != nil { + t.Fatalf("unproven cursor %+v returned partial frames", cursor) + } + } + var absent *Editor + if cursor, size, ok := absent.TrackHistory(); ok || size != 0 || cursor != (HistoryCursor{}) { + t.Fatal("nil producer accepted") + } + if got, _, ok := absent.HistorySince(from); ok || got != nil { + t.Fatal("nil producer returned history") + } + editor.ClearHistory() + if got, _, ok := editor.HistorySince(latest); ok || got != nil { + t.Fatal("reset retained a stale generation") + } + reset := mustTrackHistory(t, editor) + if reset == from || reset == latest { + t.Fatal("reset reused an earlier cursor") + } + expectHistoryFrames(t, editor, reset) +} + +func TestHistoryFramesSaveAndDetachArePrimitivePositions(t *testing.T) { + editor := NewEditor("abc") + from := mustTrackHistory(t, editor) + editor.Insert("1") + editor.BreakUndoGroup() + editor.Insert("2") + editor.SetSavePoint() + editor.Undo() + editor.Insert("X") + frames, latest, ok := editor.HistorySince(from) + if !ok || len(frames) != 5 || editor.String() != "abc1X" || editor.AtSavePoint() { + t.Fatal("saved-branch fixture did not execute") + } + want := HistoryStep{HistoryForward, HistoryInsert, 4, 1, 4, 5, historySample(2, -1, 1, 2)} + if !reflect.DeepEqual(frames[4].Steps, []HistoryStep{want}) { + t.Fatalf("saved branch context = %+v", frames[4].Steps) + } + editor.Undo() + editor.Undo() + editor.Insert("Y") + frames, latest, ok = editor.HistorySince(latest) + if !ok || len(frames) != 3 || editor.String() != "abcY" || frames[2].Steps[0].Context != historySample(1, -1, 0, 1) { + t.Fatalf("earlier detach = %+v", frames) + } + editor.SetSavePoint() + expectHistoryFrames(t, editor, latest, []HistoryStep{{Operation: HistorySave, BeforeBytes: 4, AfterBytes: 4, Context: historySample(1, 1, -1, 1)}}) +} + +func TestHistoryFramesAtomicActionExceedsByteJournalWindow(t *testing.T) { + editor := NewEditor(strings.Repeat("x", 2049)) + byteCursor := editor.TrackEdits() + from := mustTrackHistory(t, editor) + edits := make([]Replacement, 2049) + for index := range edits { + edits[index] = Replacement{Range: Range{Start: index, End: index}, Text: "q"} + } + if err := editor.ReplaceRanges(edits); err != nil { + t.Fatal(err) + } + if _, _, ok := editor.EditsSince(byteCursor, nil); ok { + t.Fatal("ordinary byte window unexpectedly retains the whole large action") + } + for _, operation := range []HistoryOperation{HistoryForward, HistoryUndo, HistoryRedo} { + frames, latest, ok := editor.HistorySince(from) + if !ok || len(frames) != 1 || len(frames[0].Steps) != 2049 { + t.Fatalf("atomic %v delivered a partial action: %d frames, %t", operation, len(frames), ok) + } + first, last := frames[0].Steps[0], frames[0].Steps[2048] + if first.Operation != operation || last.Operation != operation || frames[0].AfterBytes != len(editor.String()) { + t.Fatal("atomic operation is not tied to the accepted editor state") + } + if operation == HistoryUndo { + if first.Primitive != HistoryDelete || first.Position != 0 || first.BeforeBytes != 4098 || last.Position != 2048 || last.AfterBytes != 2049 { + t.Fatalf("inverse order = %+v ... %+v", first, last) + } + } else if first.Primitive != HistoryInsert || first.Position != 2048 || first.BeforeBytes != 2049 || last.Position != 0 || last.AfterBytes != 4098 { + t.Fatalf("forward order = %+v ... %+v", first, last) + } + from = latest + if operation == HistoryForward && !editor.Undo() || operation == HistoryUndo && !editor.Redo() { + t.Fatal("atomic action lost physical Undo/Redo") + } + } +} + +func TestHistoryFramesKeepEqualNetTransactionsAndPrivateDrafts(t *testing.T) { + editor := NewEditor("abc") + from := mustTrackHistory(t, editor) + if err := editor.Transact(func(draft *Editor) error { + if cursor, _, ok := draft.TrackHistory(); ok || cursor != (HistoryCursor{}) { + t.Fatal("private transaction draft accepted a public producer") + } + draft.ReplaceRange(Range{Start: 0, End: 1}, "x") + draft.ReplaceRange(Range{Start: 0, End: 1}, "a") + return nil + }); err != nil { + t.Fatal(err) + } + if editor.String() != "abc" || !editor.CanUndo() { + t.Fatal("equal-net accepted primitives were discarded") + } + frames, latest, ok := editor.HistorySince(from) + if !ok || len(frames) != 1 || len(frames[0].Steps) != 4 || frames[0].BeforeBytes != 3 || frames[0].AfterBytes != 3 { + t.Fatalf("equal-net frame = %+v, %t", frames, ok) + } + for index, step := range frames[0].Steps { + primitive, before, after := HistoryDelete, 3, 2 + if index%2 != 0 { + primitive, before, after = HistoryInsert, 2, 3 + } + want := HistoryStep{HistoryForward, primitive, 0, 1, before, after, historySample(index+1, 0, -1, index+1)} + if step != want { + t.Fatalf("equal-net step %d = %+v, want %+v", index, step, want) + } + } + if err := editor.Transact(func(draft *Editor) error { + draft.Insert("refused") + return fmt.Errorf("cancel transaction") + }); err == nil || editor.String() != "abc" { + t.Fatal("failed draft changed the source") + } + expectHistoryFrames(t, editor, latest) + if !editor.Undo() || editor.String() != "abc" || !editor.Redo() || editor.String() != "abc" { + t.Fatal("equal-net physical history did not replay") + } +} + +func TestHistoryFramesDeliveryExpiryDiffersFromHistoryLoss(t *testing.T) { + editor := NewEditor("abc") + old := mustTrackHistory(t, editor) + for range 50 { + editor.SetSavePoint() + } + _, retained, ok := editor.HistorySince(old) + if !ok { + t.Fatal("early delivery expired") + } + for range 250 { + editor.SetSavePoint() + } + if got, _, ok := editor.HistorySince(old); ok || got != nil { + t.Fatal("expired prefix returned a suffix") + } + if _, _, ok := editor.TrackHistory(); ok { + t.Fatal("expired bootstrap was recreated from current text") + } + if got, _, ok := editor.HistorySince(retained); !ok || len(got) != 250 { + t.Fatal("bootstrap expiry invalidated a retained consumer") + } + trimmed := NewEditor("") + cursor := mustTrackHistory(t, trimmed) + for range 257 { + trimmed.BreakUndoGroup() + trimmed.Insert("x") + } + if got, _, ok := trimmed.HistorySince(cursor); ok || got != nil || !trimmed.Undo() || trimmed.RuneCount() != 256 { + t.Fatal("unprovable trim either invented history or broke physical Undo") + } + trimmed.ClearHistory() + if _, _, ok := trimmed.TrackHistory(); ok { + t.Fatal("unavailable history silently rebootstrapped") + } +} + +func TestHistoryFramesNoOpBatchKeepsSelectionAndRedo(t *testing.T) { + editor := NewEditor("abc") + from := mustTrackHistory(t, editor) + editor.Insert("x") + if !editor.Undo() { + t.Fatal("fixture did not establish Redo") + } + _, from, ok := editor.HistorySince(from) + if !ok { + t.Fatal("fixture lost its cursor") + } + editor.SetSelection(Range{Start: 2, End: 0}) + selection, caret := editor.Selection(), editor.Caret() + if err := editor.ReplaceRanges([]Replacement{{Range: Range{Start: 1, End: 1}}}); err != nil { + t.Fatal(err) + } + if editor.String() != "abc" || editor.Selection() != selection || editor.Caret() != caret || !editor.CanRedo() || editor.CanUndo() { + t.Fatal("empty replacement changed selection, text or history") + } + expectHistoryFrames(t, editor, from) +} + +func TestHistoryFramesLateAttachAndLegacyCompositionRefuse(t *testing.T) { + late := NewEditor("abc") + late.Insert("x") + late.Undo() + if _, _, ok := late.TrackHistory(); ok || !late.CanRedo() { + t.Fatal("redo-only source attached or was mutated") + } + plain, tracked := NewEditor("abc"), NewEditor("abc") + cursor := mustTrackHistory(t, tracked) + for _, editor := range []*Editor{plain, tracked} { + editor.Insert("X") + editor.SetSelection(Range{Start: 1, End: 2}) + editor.SetMarkedText("q", Range{}) + if !editor.CancelComposition() { + t.Fatal("ordinary native cancellation was changed") + } + } + if plain.String() != tracked.String() || plain.Selection() != tracked.Selection() || plain.CanUndo() != tracked.CanUndo() { + t.Fatal("history tracking changed upstream marked-composition behavior") + } + if got, _, ok := tracked.HistorySince(cursor); ok || got != nil { + t.Fatal("legacy composition guessed metadata frames") + } + if !plain.Undo() || !tracked.Undo() || plain.String() != "abc" || tracked.String() != "abc" { + t.Fatal("metadata invalidation destroyed ordinary Undo") + } +} + +func TestHistoryFramesClearPreservesSavedTruth(t *testing.T) { + for _, dirty := range []bool{false, true} { + t.Run(fmt.Sprint(dirty), func(t *testing.T) { + editor := NewEditor("abc") + editor.SetSavePoint() + old := mustTrackHistory(t, editor) + if dirty { + editor.ReplaceRange(Range{Start: 0, End: 1}, "a") + } + editor.ClearChangeHistory() + if editor.String() != "abc" || editor.AtSavePoint() == dirty || editor.CanUndo() || editor.CanRedo() { + t.Fatal("history clear changed text or laundered an unsaved boundary") + } + if got, _, ok := editor.HistorySince(old); ok || got != nil { + t.Fatal("change-history clear retained the prior generation") + } + from := mustTrackHistory(t, editor) + editor.Insert("!") + frames, _, ok := editor.HistorySince(from) + wantSave := 0 + if dirty { + wantSave = -1 + } + if !ok || len(frames) != 1 || frames[0].Steps[0].Context.Save != wantSave { + t.Fatal("clear bootstrap invented a reachable saved boundary") + } + }) + } +} + +func TestHistoryFramesSparseBatchRetainedCapacity(t *testing.T) { + for _, lines := range []bool{false, true} { + t.Run(fmt.Sprint(lines), func(t *testing.T) { + value := strings.Repeat("x\n", 2048) + editor := NewEditor(value) + from := mustTrackHistory(t, editor) + var lineCursor uint64 + if lines { + lineCursor = editor.TrackLineEdits() + } + edits := make([]Replacement, len(value)) + edits[0] = Replacement{Range: Range{End: 1}, Text: "x"} + for index := 1; index < len(edits); index++ { + edits[index].Range = Range{Start: index, End: index} + } + if err := editor.ReplaceRanges(edits); err != nil { + t.Fatal(err) + } + if editor.String() != value || !editor.CanUndo() || len(editor.history) != 1 { + t.Fatal("equal sparse batch did not retain its accepted action") + } + unit := &editor.history[0] + minimum := len(unit.removed) + len(unit.inserted) + cap(unit.primitives)*historyPrimitiveRunes + if lines { + contexts := editor.lineBatchContexts(unit.primitives) + if len(contexts) != 1 { + t.Fatal("sparse batch lost retained line contexts") + } + minimum += cap(contexts) * lineContextRunes + } + if editor.historyRunes < minimum { + t.Errorf("retained charge %d is below backing lower bound %d (primitive len=%d cap=%d)", editor.historyRunes, minimum, len(unit.primitives), cap(unit.primitives)) + } + from = expectHistoryFrames(t, editor, from, []HistoryStep{ + {HistoryForward, HistoryDelete, 0, 1, 4096, 4095, historySample(1, 0, -1, 1)}, + {HistoryForward, HistoryInsert, 0, 1, 4095, 4096, historySample(2, 0, -1, 2)}, + }) + if lines { + lineCursor = requireLineEdits(t, editor, lineCursor, []LineEdit{{Edit: Edit{Removed: 1, Inserted: 1}, AtLineStart: true}}) + } + if !editor.Undo() || editor.String() != value { + t.Fatal("sparse batch Undo failed") + } + if lines { + lineCursor = requireLineEdits(t, editor, lineCursor, []LineEdit{{Edit: Edit{Removed: 1, Inserted: 1}, AtLineStart: true}}) + } + if !editor.Redo() || editor.String() != value { + t.Fatal("sparse batch Redo failed") + } + if lines { + requireLineEdits(t, editor, lineCursor, []LineEdit{{Edit: Edit{Removed: 1, Inserted: 1}, AtLineStart: true}}) + } + if frames, _, ok := editor.HistorySince(from); !ok || len(frames) != 2 || len(frames[0].Steps) != 2 || len(frames[1].Steps) != 2 { + t.Fatal("sparse batch lost complete inverse frames") + } + editor.Undo() + editor.Insert("z") + if editor.CanRedo() || editor.historyRunes != 1+historyPrimitiveRunes { + t.Fatal("branch retained sparse batch storage or accounting") + } + editor.ClearHistory() + if editor.historyRunes != 0 || editor.historyCost() != historyHeaderRunes { + t.Fatal("clear retained sparse batch storage or accounting") + } + }) + } +} + +func TestHistoryFramesClearWithoutSavePointPreservesBoundary(t *testing.T) { + for _, name := range []string{"initial", "dirty", "undone", "dirty-cleared"} { + t.Run(name, func(t *testing.T) { + editor := NewEditor("abc") + old := mustTrackHistory(t, editor) + wantSave, size := 0, 3 + if name != "initial" { + editor.Insert("x") + if name == "undone" { + editor.Undo() + } else { + wantSave, size = -1, 4 + } + } + if name == "dirty-cleared" { + editor.ClearChangeHistory() + } + editor.ClearChangeHistory() + if editor.CanUndo() || editor.CanRedo() || editor.AtSavePoint() || editor.savePointIndex() != nil { + t.Fatal("clear enabled save-point tracking or retained Undo/Redo") + } + if frames, _, ok := editor.HistorySince(old); ok || frames != nil { + t.Fatal("clear retained the old generation") + } + from := mustTrackHistory(t, editor) + editor.Insert("y") + from = expectHistoryFrames(t, editor, from, []HistoryStep{{HistoryForward, HistoryInsert, size, 1, size, size + 1, historySample(1, wantSave, -1, 1)}}) + if !editor.Undo() { + t.Fatal("post-clear Undo failed") + } + from = expectHistoryFrames(t, editor, from, []HistoryStep{{HistoryUndo, HistoryDelete, size, 1, size + 1, size, historySample(1, wantSave, -1, 1)}}) + if editor.AtSavePoint() || editor.savePointIndex() != nil { + t.Fatal("producer implicitly enabled AtSavePoint") + } + editor.SetSavePoint() + expectHistoryFrames(t, editor, from, []HistoryStep{{Operation: HistorySave, BeforeBytes: size, AfterBytes: size, Context: historySample(0, 0, -1, 1)}}) + if !editor.AtSavePoint() { + t.Fatal("explicit Save did not establish the new saved boundary") + } + }) + } +} + +func TestHistoryFramesPartialBudgetEvictionThenGrowth(t *testing.T) { + editor := NewEditor("") + epoch := mustTrackHistory(t, editor) + from := epoch + known := make(map[uint64]HistoryFrame) + remember := func(steps ...HistoryStep) { + t.Helper() + next := expectHistoryFrames(t, editor, from, steps) + known[next.sequence] = HistoryFrame{From: from, To: next, BeforeBytes: steps[0].BeforeBytes, AfterBytes: steps[len(steps)-1].AfterBytes, Steps: steps} + from = next + } + check := func() { + t.Helper() + history := editor.historyState() + if history == nil { + t.Fatal("delivery eviction invalidated the physical history") + } + backing := history.frames[:cap(history.frames)] + occupied := make([]bool, len(backing)) + cost := historyHeaderRunes + len(backing)*historyFrameRunes + var want []HistoryFrame + for index := range len(history.frames) { + at := (int(history.oldest) + index) % len(backing) + occupied[at] = true + frame := backing[at] + expected := known[history.windowStart+uint64(index)+1] + if !reflect.DeepEqual(frame, expected) { + t.Fatalf("logical slot %d = %+v; want %+v", index, frame, expected) + } + want = append(want, expected) + cost += cap(frame.Steps) * historyStepRunes + } + for index, frame := range backing { + if !occupied[index] && !reflect.DeepEqual(frame, HistoryFrame{}) { + t.Fatalf("evicted slot %d retains a frame: %+v", index, frame) + } + } + if history.cost != cost { + t.Fatalf("ring charge = %d; live backing = %d", history.cost, cost) + } + frames, latest, ok := editor.HistorySince(want[0].From) + if !ok || latest != from || !reflect.DeepEqual(frames, want) { + t.Fatal("wrapped read differs from the complete retained frame chain") + } + frames[0].Steps[0].Length++ + again, _, ok := editor.HistorySince(want[0].From) + if !ok || !reflect.DeepEqual(again, want) { + t.Fatal("wrapped read exposes retained step backing") + } + } + size := maxHistoryRunes - 2500 + editor.Insert(strings.Repeat("x", size)) + remember(HistoryStep{HistoryForward, HistoryInsert, 0, size, 0, size, historySample(1, 0, -1, 1)}) + for range 128 { + editor.SetSavePoint() + remember(HistoryStep{Operation: HistorySave, BeforeBytes: size, AfterBytes: size, Context: historySample(1, 1, -1, 1)}) + check() + history := editor.historyState() + if history.oldest > 0 && len(history.frames) < cap(history.frames) { + break + } + } + history := editor.historyState() + if history.oldest == 0 || len(history.frames) == cap(history.frames) { + t.Fatal("fixture did not reach partial budget eviction") + } + capacity := cap(history.frames) + if frames, _, ok := editor.HistorySince(epoch); ok || frames != nil { + t.Fatal("budget eviction served an incomplete bootstrap") + } + if !editor.Undo() || editor.String() != "" { + t.Fatal("budget eviction broke physical Undo") + } + remember(HistoryStep{HistoryUndo, HistoryDelete, 0, size, size, 0, historySample(1, 1, -1, 1)}) + check() + editor.Insert("z") + remember(HistoryStep{HistoryForward, HistoryInsert, 0, 1, 0, 1, historySample(1, -1, 0, 1)}) + check() + if editor.CanRedo() || editor.historyRunes != 1+historyPrimitiveRunes { + t.Fatal("branch did not release the large redo unit") + } + for range capacity + 1 { + editor.SetSavePoint() + remember(HistoryStep{Operation: HistorySave, BeforeBytes: 1, AfterBytes: 1, Context: historySample(1, 1, -1, 1)}) + check() + } + if cap(history.frames) <= capacity { + t.Fatal("fixture did not grow after freeing retained history") + } + editor.ClearHistory() + if history.frames != nil || history.cost != historyHeaderRunes || editor.historyRunes != 0 { + t.Fatal("clear retained delivery or physical-history storage") + } +} + +func TestHistoryFramesClearResetsDetachedBoundary(t *testing.T) { + editor := NewEditor("abc") + mustTrackHistory(t, editor) + editor.Insert("x") + editor.SetSavePoint() + editor.Insert("y") + editor.Undo() + editor.Undo() + editor.Insert("z") + if history := editor.historyState(); history == nil || history.detach != 0 || history.save != -1 { + t.Fatalf("fixture history = %+v, want save -1 and detach 0", history) + } + editor.ClearChangeHistory() + from := mustTrackHistory(t, editor) + editor.Insert("q") + frames, _, ok := editor.HistorySince(from) + if !ok || len(frames) != 1 || len(frames[0].Steps) != 1 { + t.Fatalf("frames = %+v, ok = %t", frames, ok) + } + if got := frames[0].Steps[0].Context.Detach; got != -1 { + t.Fatalf("post-clear detach = %d, want -1", got) + } +} diff --git a/text/history_journal.go b/text/history_journal.go new file mode 100644 index 000000000..5e1ae4e14 --- /dev/null +++ b/text/history_journal.go @@ -0,0 +1,469 @@ +package text + +import ( + "sync/atomic" + "unsafe" +) + +// HistoryCursor identifies one position in one editor's optional history. +// The zero value is invalid and cursors from other sources cannot be replayed. +type HistoryCursor struct { + source, generation, sequence uint64 +} + +// HistoryOperation is the operation that accepted a history step. +type HistoryOperation uint8 + +const ( + HistoryForward HistoryOperation = iota + 1 + HistoryUndo + HistoryRedo + HistorySave +) + +// HistoryPrimitive is the actual byte insertion/deletion performed by a step. +type HistoryPrimitive uint8 + +const ( + HistoryNoPrimitive HistoryPrimitive = iota + HistoryDelete + HistoryInsert +) + +// HistoryContext samples primitive boundaries, separately from Undo units. +// Save and Detach use -1 for an unreachable or absent boundary. +// Forward steps sample after append; Undo/Redo sample before their completion; +// Save samples after SetSavePoint. Unprovable history trimming invalidates the +// producer instead of rebasing these positions. The editor always collects Undo. +type HistoryContext struct { + Current, Save, Detach int + RetainedFrom, RetainedTo int + Collecting bool +} + +// HistoryStep is an accepted UTF-8 byte primitive or a metadata-only Save. +type HistoryStep struct { + Operation HistoryOperation + Primitive HistoryPrimitive + Position, Length int + BeforeBytes, AfterBytes int + Context HistoryContext +} + +// HistoryFrame is one complete operation, even when its accepted primitives +// overlap or have no net text change. Returned Steps belong to the caller. +type HistoryFrame struct { + From, To HistoryCursor + BeforeBytes, AfterBytes int + Steps []HistoryStep +} + +const ( + historyFrameLimit = 256 + historyStepRunes = int((unsafe.Sizeof(HistoryStep{}) + unsafe.Sizeof(rune(0)) - 1) / unsafe.Sizeof(rune(0))) + historyFrameRunes = int((unsafe.Sizeof(HistoryFrame{}) + unsafe.Sizeof(rune(0)) - 1) / unsafe.Sizeof(rune(0))) +) + +type historyJournal struct { + owner *Editor + ops historyOps + source, generation, sequence uint64 + current, save, detach int + retainedFrom, retainedTo int + frames []HistoryFrame + epoch HistoryCursor + windowStart uint64 + bootstrapBytes, bytes int + cost, frameCapacity int + available bool + oldest uint16 +} + +// A history header owns the shared optional slot even after invalidation. +const historyHeaderRunes = editorSidecarRunes + int((unsafe.Sizeof(historyJournal{})+unsafe.Sizeof(rune(0))-1)/unsafe.Sizeof(rune(0))) + +var nextHistorySource atomic.Uint64 + +// TrackHistory enables immutable primitive-history delivery without enabling +// the byte journal. First enable requires no Undo, Redo or composition. It +// returns the original epoch and UTF-8 length while that prefix is retained; +// expiry refuses a new bootstrap without invalidating a retained consumer. +func (editor *Editor) TrackHistory() (HistoryCursor, int, bool) { + if editor == nil { + return HistoryCursor{}, 0, false + } + journal := editor.journal + if state := journal.compositionState(); state != nil && state.owner != editor { + return HistoryCursor{}, 0, false + } + if journal != nil && journal.historyJournal() != nil { + history := journal.historyJournal() + if history.owner != editor || !history.available || history.epoch.sequence < history.windowStart { + return HistoryCursor{}, 0, false + } + return history.epoch, history.bootstrapBytes, true + } + if journal != nil && journal.private || editor.composing || editor.CanUndo() || editor.CanRedo() { + return HistoryCursor{}, 0, false + } + if journal == nil { + journal = &editJournal{} + editor.journal = journal + } + source := nextHistorySource.Add(1) + for source == 0 { + source = nextHistorySource.Add(1) + } + size := len(editor.String()) + saved := 0 + if point := editor.savePointIndex(); point != nil && *point < 0 { + saved = -1 + } + history := &historyJournal{ + owner: editor, + ops: historyOps{ + record: recordHistoryOwned, + capturePrimitives: captureHistoryPrimitivesOwned, + save: captureHistorySaveOwned, + replay: replayHistoryOwned, + clear: clearHistoryOwned, + invalidateFrom: invalidateHistoryFromOwned, + enforce: enforceHistoryBudgetOwned, + }, + source: source, generation: 1, save: saved, detach: -1, + epoch: HistoryCursor{source: source, generation: 1}, + bootstrapBytes: size, bytes: size, cost: historyHeaderRunes, available: true, + } + journal.setHistoryJournal(history) + editor.chargeCompositionCapacity() + return history.epoch, size, true +} + +// HistorySince copies every complete frame after cursor, including nested +// Steps. Repeated reads are independent. Wrong sources/generations, future +// cursors, unavailable history and missing prefixes return no partial replay. +func (editor *Editor) HistorySince(cursor HistoryCursor) ([]HistoryFrame, HistoryCursor, bool) { + history := editor.historyState() + if history == nil { + return nil, HistoryCursor{}, false + } + latest := history.cursor() + if cursor == (HistoryCursor{}) || cursor.source != history.source || cursor.generation != history.generation || + cursor.sequence > history.sequence || cursor.sequence < history.windowStart { + return nil, latest, false + } + want := int(history.sequence - cursor.sequence) + if want == 0 { + return nil, latest, true + } + frames := make([]HistoryFrame, 0, want) + backing := history.frames[:cap(history.frames)] + for index := range len(history.frames) { + frame := backing[(int(history.oldest)+index)%len(backing)] + if frame.To.sequence <= cursor.sequence { + continue + } + frame.Steps = append([]HistoryStep(nil), frame.Steps...) + frames = append(frames, frame) + } + if len(frames) != want { + return nil, latest, false + } + return frames, latest, true +} + +func (history *historyJournal) cursor() HistoryCursor { + return HistoryCursor{history.source, history.generation, history.sequence} +} + +func (history *historyJournal) context(current, tail int) HistoryContext { + return HistoryContext{Current: current, Save: history.save, Detach: history.detach, + RetainedFrom: history.retainedFrom, RetainedTo: tail, Collecting: true} +} + +func (editor *Editor) historyChangePrimitive(change textChange, kind editKind) (Edit, bool) { + if kind == editComposition { + editor.invalidateHistoryFrom(0) + return Edit{}, false + } + if editor.historyState() == nil { + return Edit{}, false + } + position := editor.offsets.offset + if editor.offsets.index != change.start { + position = editor.ByteOffset(change.start) + } + removed, inserted := historyRuneBytes(change.removed), historyRuneBytes(change.inserted) + return Edit{Start: position, Removed: removed, Inserted: inserted}, removed != 0 || inserted != 0 +} + +func historyRuneBytes(value []rune) int { + bytes := 0 + for _, character := range value { + bytes += runeBytes(character) + } + return bytes +} + +func (editor *Editor) captureHistoryPrimitives(primitives []Edit) { + if event := editor.compositionEvent(); event != nil { + editor.appendEventPrimitives(event, primitives) + return + } + history := editor.historyState() + if history == nil || len(primitives) == 0 { + return + } + before, running := history.bytes, history.bytes + steps := make([]HistoryStep, 0, len(primitives)*2) + for _, primitive := range primitives { + if primitive.Removed > 0 { + steps = editor.appendForwardHistoryStep(history, steps, HistoryDelete, primitive.Start, primitive.Removed, running, running-primitive.Removed) + running -= primitive.Removed + } + if primitive.Inserted > 0 { + steps = editor.appendForwardHistoryStep(history, steps, HistoryInsert, primitive.Start, primitive.Inserted, running, running+primitive.Inserted) + running += primitive.Inserted + } + } + if len(steps) > 0 { + editor.appendHistoryFrame(steps, before, running, steps[len(steps)-1].Context.Current) + } +} + +func (editor *Editor) appendForwardHistoryStep(history *historyJournal, steps []HistoryStep, primitive HistoryPrimitive, position, length, before, after int) []HistoryStep { + boundary := history.current + len(steps) + editor.updateHistoryBranch(boundary) + return append(steps, HistoryStep{HistoryForward, primitive, position, length, before, after, history.context(boundary+1, boundary+1)}) +} + +func (editor *Editor) updateHistoryBranch(boundary int) { + history := editor.historyState() + if history == nil { + return + } + if boundary < history.save { + history.save = -1 + if history.detach == -1 { + history.detach = boundary + } + } else if history.detach != -1 && history.detach > boundary { + history.detach = boundary + } +} + +func (editor *Editor) captureHistorySave() { + history := editor.historyState() + if history == nil { + return + } + history.save, history.detach = history.current, -1 + size := history.bytes + step := HistoryStep{Operation: HistorySave, BeforeBytes: size, AfterBytes: size, Context: history.context(history.current, history.retainedTo)} + editor.appendHistoryFrame([]HistoryStep{step}, size, size, history.current) +} + +func (editor *Editor) appendHistoryFrame(steps []HistoryStep, before, after, current int) { + if len(steps) == 0 { + return + } + editor.appendHistoryFrameWithTail(steps, before, after, current, steps[len(steps)-1].Context.RetainedTo) +} + +func (editor *Editor) appendHistoryFrameWithTail(steps []HistoryStep, before, after, current, tail int) { + history := editor.historyState() + if history == nil || len(steps) == 0 { + return + } + running := before + for _, step := range steps { + valid := step.Position >= 0 && step.Length >= 0 && step.BeforeBytes == running + switch step.Primitive { + case HistoryDelete: + valid = valid && step.AfterBytes == running-step.Length && step.Position <= running-step.Length + case HistoryInsert: + valid = valid && step.AfterBytes == running+step.Length && step.Position <= running + case HistoryNoPrimitive: + valid = valid && step.AfterBytes == running && step.Position == 0 && step.Length == 0 + default: + valid = false + } + if !valid { + editor.invalidateHistoryFrom(0) + return + } + running = step.AfterBytes + } + if running != after || current < history.retainedFrom || current < 0 || current > tail { + editor.invalidateHistoryFrom(0) + return + } + from := history.cursor() + history.sequence++ + if len(history.frames) == historyFrameLimit { + history.dropOldestFrame() + } + if len(history.frames) == cap(history.frames) { + capacity := min(historyFrameLimit, max(1, cap(history.frames)*2)) + next := make([]HistoryFrame, len(history.frames), capacity) + old := history.frames[:cap(history.frames)] + for index := range len(history.frames) { + next[index] = old[(int(history.oldest)+index)%len(old)] + } + history.frames, history.oldest = next, 0 + history.cost += (capacity - history.frameCapacity) * historyFrameRunes + history.frameCapacity = capacity + } + // Logical order can wrap while the slice always starts at its backing base. + backing := history.frames[:cap(history.frames)] + backing[(int(history.oldest)+len(history.frames))%len(backing)] = HistoryFrame{from, history.cursor(), before, after, steps} + history.frames = backing[:len(history.frames)+1] + history.cost += cap(steps) * historyStepRunes + history.current, history.retainedTo, history.bytes = current, tail, after + editor.enforceHistoryBudget() +} + +func (history *historyJournal) dropOldestFrame() { + if len(history.frames) == 0 { + return + } + backing := history.frames[:cap(history.frames)] + frame := backing[history.oldest] + history.cost -= cap(frame.Steps) * historyStepRunes + history.windowStart = frame.To.sequence + backing[history.oldest] = HistoryFrame{} + history.oldest = uint16((int(history.oldest) + 1) % len(backing)) + history.frames = backing[:len(history.frames)-1] +} + +func (editor *Editor) historyCost() int { + cost := editor.historyRunes + if editor.journal != nil && editor.journal.historyJournal() != nil { + cost += editor.journal.historyJournal().cost + } + cost += editor.compositionCost() + return cost +} + +func (editor *Editor) enforceHistoryBudget() { + history := editor.historyState() + if history == nil { + return + } + for len(history.frames) > 1 && editor.historyCost() > maxHistoryRunes { + history.dropOldestFrame() + } + if len(history.frames) == 1 && editor.historyCost() > maxSingleEditRunes { + editor.invalidateHistoryFrom(0) + } +} + +type historyReplayPrimitive struct { + kind HistoryPrimitive + position, length int +} + +func (editor *Editor) historyReplayPrimitives(edit *historyEdit) []historyReplayPrimitive { + primitives := make([]historyReplayPrimitive, 0, len(edit.primitives)*2) + appendPrimitive := func(position, removed, inserted int) { + if removed > 0 { + primitives = append(primitives, historyReplayPrimitive{HistoryDelete, position, removed}) + } + if inserted > 0 { + primitives = append(primitives, historyReplayPrimitive{HistoryInsert, position, inserted}) + } + } + if len(edit.primitives) > 0 { + for _, primitive := range edit.primitives { + appendPrimitive(primitive.Start, primitive.Removed, primitive.Inserted) + } + } else { + appendPrimitive(editor.ByteOffset(edit.start), historyRuneBytes(edit.removed), historyRuneBytes(edit.inserted)) + } + return primitives +} + +func (editor *Editor) captureHistoryReplay(edit *historyEdit, inverse bool) { + if event := editor.compositionEvent(); event != nil { + editor.captureEventReplay(event, edit, inverse) + return + } + history := editor.historyState() + if history == nil { + return + } + primitives := editor.historyReplayPrimitives(edit) + if len(primitives) == 0 { + editor.invalidateHistoryFrom(0) + return + } + operation := HistoryRedo + if inverse { + operation = HistoryUndo + } + before, running, current := history.bytes, history.bytes, history.current + steps := make([]HistoryStep, 0, len(primitives)) + for index := range len(primitives) { + at := index + if inverse { + at = len(primitives) - 1 - index + } + primitive := primitives[at] + if inverse { + if primitive.kind == HistoryInsert { + primitive.kind = HistoryDelete + } else { + primitive.kind = HistoryInsert + } + } + after := running + primitive.length + if primitive.kind == HistoryDelete { + after = running - primitive.length + } + steps = append(steps, HistoryStep{operation, primitive.kind, primitive.position, primitive.length, running, after, history.context(current, history.retainedTo)}) + running = after + if inverse { + current-- + } else { + current++ + } + } + editor.appendHistoryFrame(steps, before, running, current) +} + +func (editor *Editor) resetHistoryAfterClear() { + history := editor.historyState() + if history == nil { + return + } + history.frames, history.oldest = nil, 0 + history.cost, history.frameCapacity = historyHeaderRunes, 0 + history.generation++ + history.sequence++ + history.current, history.save, history.detach = 0, 0, -1 + history.retainedFrom, history.retainedTo = 0, 0 + history.bytes = len(editor.String()) + history.bootstrapBytes = history.bytes + history.epoch = history.cursor() + history.windowStart = history.sequence +} + +func invalidateHistoryFromOwned(history *historyJournal, first int) { + editor := history.owner + for index := first; index < len(editor.history); index++ { + edit := &editor.history[index] + if edit.kind != editSeparate && len(edit.primitives) > 0 { + editor.historyRunes -= cap(edit.primitives) * historyPrimitiveRunes + edit.primitives = nil + } + } + history.available = false + history.frames, history.oldest = nil, 0 + history.cost, history.frameCapacity = historyHeaderRunes, 0 + history.bootstrapBytes, history.bytes = 0, 0 + history.current, history.save, history.detach = 0, 0, -1 + history.retainedFrom, history.retainedTo = 0, 0 + history.generation++ + history.sequence++ + history.epoch = HistoryCursor{} +} diff --git a/text/history_link.go b/text/history_link.go new file mode 100644 index 000000000..da3f1dc2f --- /dev/null +++ b/text/history_link.go @@ -0,0 +1,66 @@ +package text + +// Only TrackHistory installs these functions, so ordinary editor callers do +// not cause the complete producer implementation to be linked. +type historyOps struct { + record func(*historyJournal, textChange, editKind) (Edit, bool) + capturePrimitives func(*historyJournal, []Edit) + save func(*historyJournal) + replay func(*historyJournal, int, bool) + clear func(*historyJournal, bool) + invalidateFrom func(*historyJournal, int) + enforce func(*historyJournal) +} + +func (editor *Editor) historyState() *historyJournal { + if editor == nil || editor.journal == nil { + return nil + } + history := editor.journal.historyJournal() + if history == nil || history.owner != editor || !history.available { + return nil + } + return history +} + +func (editor *Editor) retainEqualEdits() bool { + return editor.savePointIndex() != nil || editor.journal != nil && (editor.journal.retainEqual || editor.historyState() != nil) +} + +func (editor *Editor) invalidateHistoryFrom(first int) { + if history := editor.historyState(); history != nil { + history.ops.invalidateFrom(history, first) + } +} + +func recordHistoryOwned(history *historyJournal, change textChange, kind editKind) (Edit, bool) { + primitive, ok := history.owner.historyChangePrimitive(change, kind) + if ok { + history.owner.captureHistoryPrimitives([]Edit{primitive}) + } + return primitive, ok && history.available +} + +func captureHistoryPrimitivesOwned(history *historyJournal, primitives []Edit) { + history.owner.captureHistoryPrimitives(primitives) +} + +func captureHistorySaveOwned(history *historyJournal) { + history.owner.captureHistorySave() +} + +func replayHistoryOwned(history *historyJournal, index int, inverse bool) { + history.owner.captureHistoryReplay(&history.owner.history[index], inverse) +} + +func clearHistoryOwned(history *historyJournal, manual bool) { + if manual { + history.owner.resetHistoryAfterClear() + } else { + invalidateHistoryFromOwned(history, 0) + } +} + +func enforceHistoryBudgetOwned(history *historyJournal) { + history.owner.enforceHistoryBudget() +} diff --git a/text/lf_labels.go b/text/lf_labels.go new file mode 100644 index 000000000..9f21e940c --- /dev/null +++ b/text/lf_labels.go @@ -0,0 +1,363 @@ +package text + +import "slices" + +// LFLabelReplacement describes one actual forward replacement. Labels belongs +// to the callback and contains the labels of Removed's LF characters. +type LFLabelReplacement struct { + Removed, Inserted string + Labels []byte + Default byte +} + +// LFLabelMapper returns one label for every LF in Inserted. It must not mutate +// or reenter the editor. Returning the wrong number of labels panics before +// text is changed. A nil mapper labels each inserted LF with Default. +type LFLabelMapper func(LFLabelReplacement) []byte + +type lfLabelCell struct{ value byte } + +type lfLabelEdit struct { + line int + removed, inserted []*lfLabelCell +} + +type lfLabelEntry struct { + edits []lfLabelEdit + fragments int +} + +type lfLabelOps struct { + replace func(*lfLabelState, int, []rune, []rune) + record func(*lfLabelState, *rune, *rune) + replay func(*lfLabelState, *rune, bool) + forget func(*lfLabelState, *rune) + clear func(*lfLabelState) + batch func(*lfLabelState, []lfLabelSpan) (*lfLabelPlan, error) + clone func(*lfLabelState, *Editor) *lfLabelState + finish func(*lfLabelState, *lfLabelState) *lfLabelPlan + commit func(*lfLabelState, *lfLabelPlan) + hold func(*lfLabelState, textChange) + cancel func(*lfLabelState) + release func(*lfLabelState) + discard func(*lfLabelState) + cost func(*lfLabelState, *rune) int + extra func(*lfLabelState) int +} + +type lfLabelState struct { + ops lfLabelOps + owner *Editor + current []*lfLabelCell + defaultLabel byte + mapper LFLabelMapper + history map[*rune]lfLabelEntry + pending []lfLabelEdit + replaying bool + mapping bool + staging bool + events []lfLabelEdit + revision uint64 + lastLine int + composition lfLabelComposition +} + +// TrackLFLabels enables optional labels before the editor has Undo/Redo or a +// live composition. It copies labels, requiring one per current logical LF. +// An already tracked editor refuses a second source. Labels have no meaning to +// text; applications define their own replacement policy with mapper. +// Private transaction drafts cannot enable or reconfigure labels. +func (editor *Editor) TrackLFLabels(labels []byte, defaultLabel byte, mapper LFLabelMapper) bool { + if editor == nil || editor.composing || editor.CanUndo() || editor.CanRedo() || editor.lfLabelState() != nil || editor.journal != nil && editor.journal.private { + return false + } + if countLabelLF(editor.runes) != len(labels) { + return false + } + editor.TrackLineEdits() + state := &lfLabelState{ + owner: editor, + ops: lfLabelOps{ + replace: replaceLFLabels, + record: recordLFLabels, + replay: replayLFLabels, + forget: forgetLFLabels, + clear: clearLFLabelHistory, + batch: planLFLabelBatch, + clone: cloneLFLabels, + finish: finishLFLabelPlan, + commit: commitLFLabelPlan, + hold: holdLFLabelComposition, + cancel: cancelLFLabelComposition, + release: releaseLFLabelComposition, + discard: discardLFLabelHeldHistory, + cost: lfLabelHistoryCost, + extra: lfLabelExtraCost, + }, + defaultLabel: defaultLabel, + mapper: mapper, + current: make([]*lfLabelCell, len(labels)), + } + for index, value := range labels { + state.current[index] = &lfLabelCell{value: value} + } + editor.journal.lines.labels = state + return true +} + +// LFLabels copies current labels into dst[:0]. The bool distinguishes an enabled +// tracker with no LF characters from an editor that never enabled labels. +func (editor *Editor) LFLabels(dst []byte) ([]byte, bool) { + dst = dst[:0] + state := editor.lfLabelState() + if state == nil { + return dst, false + } + for _, cell := range state.current { + dst = append(dst, cell.value) + } + return dst, true +} + +// LFLabelRevision identifies the current label state for an enabled editor. +// It changes on label mutations and replay, including equal-text edits. Cache +// keys must include the editor identity; a revision is local to that source. +func (editor *Editor) LFLabelRevision() (uint64, bool) { + state := editor.lfLabelState() + if state == nil { + return 0, false + } + return state.revision, true +} + +// SetLFLabels relabels current LF identities and the insertion default without +// adding text history. Those identities retain the labels through Undo/Redo. +// An invalid count, disabled tracker, active composition or private transaction +// draft leaves state alone. +func (editor *Editor) SetLFLabels(labels []byte, defaultLabel byte) bool { + state := editor.lfLabelState() + if state == nil || editor.composing || state.mapping || editor.journal.private || len(labels) != len(state.current) { + return false + } + for index, value := range labels { + state.current[index].value = value + } + state.defaultLabel = defaultLabel + state.revision++ + return true +} + +// UnifyLFLabels relabels both current and reachable historical LF identities. +// Old text restored by Undo/Redo therefore retains the new uniform policy. +// Active compositions and private transaction drafts refuse the change. +func (editor *Editor) UnifyLFLabels(label byte) bool { + state := editor.lfLabelState() + if state == nil || editor.composing || state.mapping || editor.journal.private { + return false + } + for _, cell := range state.current { + cell.value = label + } + for _, entry := range state.history { + for _, edit := range entry.edits { + for _, cells := range [][]*lfLabelCell{edit.removed, edit.inserted} { + for _, cell := range cells { + cell.value = label + } + } + } + } + state.defaultLabel = label + state.revision++ + return true +} + +func (editor *Editor) lfLabelState() *lfLabelState { + if editor == nil || editor.journal == nil || editor.journal.lines == nil { + return nil + } + return editor.journal.lines.labels +} + +func (editor *Editor) pendingLFLabels() bool { + state := editor.lfLabelState() + return state != nil && len(state.pending) != 0 +} + +func lfLabelHistoryKey(edit *historyEdit) *rune { + if len(edit.removed) != 0 { + return &edit.removed[0] + } + if len(edit.inserted) != 0 { + return &edit.inserted[0] + } + return nil +} + +func countLabelLF(value []rune) int { + count := 0 + for _, character := range value { + if character == '\n' { + count++ + } + } + return count +} + +func replaceLFLabels(state *lfLabelState, line int, removed, inserted []rune) { + if state.mapping { + panic("text: LF label mapper reentered editing") + } + if state.replaying { + return + } + state.lastLine = line + removedLF, insertedLF := countLabelLF(removed), countLabelLF(inserted) + if removedLF == 0 && insertedLF == 0 { + return + } + previous := state.current[line : line+removedLF] + labels := make([]byte, insertedLF) + if state.mapper != nil && insertedLF != 0 { + oldLabels := make([]byte, len(previous)) + for index, cell := range previous { + oldLabels[index] = cell.value + } + labels = mapLFLabels(state, LFLabelReplacement{Removed: string(removed), Inserted: string(inserted), Labels: oldLabels, Default: state.defaultLabel}) + if len(labels) != insertedLF { + panic("text: LF label mapper returned the wrong number of labels") + } + } else { + for index := range labels { + labels[index] = state.defaultLabel + } + } + if state.owner.savePointIndex() == nil && runesEqual(removed, inserted) && len(previous) == len(labels) { + equal := true + for index, cell := range previous { + equal = equal && cell.value == labels[index] + } + if equal { + return + } + } + edit := lfLabelEdit{line: line, removed: slices.Clone(previous), inserted: make([]*lfLabelCell, len(labels))} + for index, value := range labels { + edit.inserted[index] = &lfLabelCell{value: value} + } + spliceLFLabels(state, line, len(edit.removed), edit.inserted) + if state.composition.active { + state.composition.currentLF = insertedLF + } + state.pending = append(state.pending, edit) + if state.staging { + state.events = append(state.events, edit) + } +} + +func mapLFLabels(state *lfLabelState, change LFLabelReplacement) []byte { + state.mapping = true + defer func() { state.mapping = false }() + return state.mapper(change) +} + +func spliceLFLabels(state *lfLabelState, line, removed int, inserted []*lfLabelCell) { + before := len(state.current) + delta := len(inserted) - removed + if delta > 0 { + state.current = append(state.current, make([]*lfLabelCell, delta)...) + } + copy(state.current[line+len(inserted):], state.current[line+removed:before]) + if delta < 0 { + clear(state.current[before+delta:]) + state.current = state.current[:before+delta] + } + copy(state.current[line:], inserted) + if len(state.current) == 0 { + state.current = nil + } else if cap(state.current) > 64 && len(state.current) < cap(state.current)/4 { + current := make([]*lfLabelCell, len(state.current)) + copy(current, state.current) + state.current = current + } + state.revision++ +} + +func recordLFLabels(state *lfLabelState, previous, current *rune) { + var edits []lfLabelEdit + if previous != nil { + edits = state.history[previous].edits + if previous != current { + if _, exists := state.history[previous]; exists { + ensureLFLabelHistoryOwned(state) + delete(state.history, previous) + } + } + } + if state.composition.active { + edits = compositionLFLabelEdits(state, previous) + } else { + edits = append(edits, state.pending...) + } + state.pending = nil + if len(edits) != 0 { + ensureLFLabelHistoryOwned(state) + if state.history == nil { + state.history = make(map[*rune]lfLabelEntry) + } + fragments := 0 + for _, edit := range edits { + fragments += cap(edit.removed) + cap(edit.inserted) + } + state.history[current] = lfLabelEntry{edits: edits, fragments: fragments} + } else if _, exists := state.history[current]; exists { + ensureLFLabelHistoryOwned(state) + delete(state.history, current) + state.history = cloneLFLabelHistory(state.history) + } +} + +func replayLFLabels(state *lfLabelState, key *rune, inverse bool) { + if state.mapping { + panic("text: LF label mapper reentered history") + } + edits := state.history[key].edits + if inverse { + for index := len(edits) - 1; index >= 0; index-- { + edit := edits[index] + spliceLFLabels(state, edit.line, len(edit.inserted), edit.removed) + if state.staging { + state.events = append(state.events, lfLabelEdit{line: edit.line, removed: edit.inserted, inserted: edit.removed}) + } + } + return + } + for _, edit := range edits { + spliceLFLabels(state, edit.line, len(edit.removed), edit.inserted) + if state.staging { + state.events = append(state.events, edit) + } + } +} + +func forgetLFLabels(state *lfLabelState, key *rune) { + if _, exists := state.history[key]; !exists { + return + } + ensureLFLabelHistoryOwned(state) + delete(state.history, key) + state.history = cloneLFLabelHistory(state.history) +} + +func clearLFLabelHistory(state *lfLabelState) { + state.history = nil + state.pending = nil + if state.composition.active { + state.composition.sharedHistory = false + state.composition.recorded = false + state.composition.unitOriginal = nil + state.composition.prefix = nil + syncLFLabelExtraCost(state) + } + state.revision++ +} diff --git a/text/lf_labels_batch.go b/text/lf_labels_batch.go new file mode 100644 index 000000000..90d836cb2 --- /dev/null +++ b/text/lf_labels_batch.go @@ -0,0 +1,70 @@ +package text + +import ( + "fmt" + "slices" +) + +type lfLabelSpan struct { + line int + removed, inserted []rune +} + +type lfLabelPlan struct { + staged *lfLabelState + changed bool +} + +func cloneLFLabels(source *lfLabelState, owner *Editor) *lfLabelState { + return &lfLabelState{ + ops: source.ops, + owner: owner, + current: slices.Clone(source.current), + defaultLabel: source.defaultLabel, + mapper: source.mapper, + staging: true, + } +} + +func planLFLabelBatch(source *lfLabelState, spans []lfLabelSpan) (*lfLabelPlan, error) { + if source.mapping { + panic("text: LF label mapper reentered a batch") + } + before, selection, revision := source.owner.String(), source.owner.selectionState(), source.revision + secondary := slices.Clone(source.owner.secondary) + staged := cloneLFLabels(source, source.owner) + source.mapping = true + defer func() { source.mapping = false }() + for _, span := range spans { + replaceLFLabels(staged, span.line, span.removed, span.inserted) + } + if source.owner.String() != before || source.owner.selectionState() != selection || !slices.Equal(source.owner.secondary, secondary) || source.revision != revision { + return nil, fmt.Errorf("LF label mapper changed the source during a batch") + } + return finishLFLabelPlan(source, staged), nil +} + +func finishLFLabelPlan(source, staged *lfLabelState) *lfLabelPlan { + if staged == nil || len(staged.events) == 0 { + return nil + } + changed := len(source.current) != len(staged.current) + if !changed { + for index, cell := range source.current { + if cell.value != staged.current[index].value { + changed = true + break + } + } + } + return &lfLabelPlan{staged: staged, changed: changed} +} + +func commitLFLabelPlan(source *lfLabelState, plan *lfLabelPlan) { + source.current = plan.staged.current + source.pending = append(source.pending, plan.staged.events...) + if source.staging { + source.events = append(source.events, plan.staged.events...) + } + source.revision++ +} diff --git a/text/lf_labels_batch_test.go b/text/lf_labels_batch_test.go new file mode 100644 index 000000000..49db8e84b --- /dev/null +++ b/text/lf_labels_batch_test.go @@ -0,0 +1,578 @@ +package text + +import ( + "errors" + "fmt" + "slices" + "strings" + "testing" +) + +func TestLFLabelMultipleSelectionsUseActualSpans(t *testing.T) { + for _, operation := range []string{"replace", "insert", "delete-backward", "delete-forward"} { + t.Run(operation, func(t *testing.T) { + editor := NewEditor("a\nb\nc\nd") + if !editor.TrackLFLabels([]byte{'W', 'L', 'M'}, 'D', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + selections := []Range{{Start: 1, End: 2}, {Start: 5, End: 6}} + wantText, wantLabels := "ax\nb\ncx\nd", []byte{'W', 'L', 'M'} + switch operation { + case "insert": + selections = []Range{{}, {Start: 4, End: 4}} + wantText, wantLabels = "\na\nb\n\nc\nd", []byte{'D', 'W', 'L', 'D', 'M'} + case "delete-backward": + selections = []Range{{Start: 2, End: 2}, {Start: 6, End: 6}} + wantText, wantLabels = "ab\ncd", []byte{'L'} + case "delete-forward": + selections = []Range{{Start: 1, End: 1}, {Start: 5, End: 5}} + wantText, wantLabels = "ab\ncd", []byte{'L'} + } + if !editor.SetSelections(selections, 1) { + t.Fatal("multiple-selection setup failed") + } + switch operation { + case "replace": + editor.Insert("x\n") + case "insert": + editor.Insert("\n") + case "delete-backward": + if !editor.DeleteBackward() { + t.Fatal("multiple deletion failed") + } + case "delete-forward": + if !editor.DeleteForward() { + t.Fatal("multiple deletion failed") + } + } + if editor.String() != wantText || editor.SelectionCount() != 2 { + t.Fatalf("multiple-selection text/count: %q, %d", editor.String(), editor.SelectionCount()) + } + assertLFLabels(t, editor, wantLabels) + if !editor.Undo() || editor.String() != "a\nb\nc\nd" || editor.CanUndo() { + t.Fatal("multiple selections did not retain one matching Undo unit") + } + assertLFLabels(t, editor, []byte{'W', 'L', 'M'}) + if !editor.Redo() || editor.String() != wantText { + t.Fatal("multiple selections lost matching Redo") + } + assertLFLabels(t, editor, wantLabels) + }) + } +} + +func TestLFLabelInvalidMapperPreservesMultipleSelections(t *testing.T) { + for _, command := range []string{"insert", "marked", "range", "block"} { + t.Run(command, func(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'D', func(LFLabelReplacement) []byte { return nil }) { + t.Fatal("label setup failed") + } + if !editor.SetSelections([]Range{{Start: 1, End: 1}, {Start: 3, End: 3}}, 1) { + t.Fatal("multiple-selection setup failed") + } + selections := editor.Selections() + panicked := false + func() { + defer func() { panicked = recover() != nil }() + switch command { + case "marked": + editor.SetMarkedText("new\n", Range{Start: 4, End: 4}) + case "range": + editor.ReplaceRange(Range{}, "new\n") + case "block": + editor.DuplicateLines(false) + default: + editor.Insert("new\n") + } + }() + if !panicked || editor.String() != "a\nb\nc" || !slices.Equal(editor.Selections(), selections) || editor.CanUndo() || editor.CanRedo() || editor.historyRunes != 0 { + t.Fatal("invalid mapper changed the source selection set or history") + } + if _, composing := editor.Composition(); composing { + t.Fatal("invalid mapper started composition") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + }) + } +} + +func TestLFLabelTransactionRejectsSourceSecondarySelectionChanges(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'M', nil) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{}) + selections := []Range{{}, {Start: 3, End: 3}} + err := editor.Transact(func(draft *Editor) error { + editor.SetSelections(selections, 0) + draft.Insert("x\n") + return nil + }) + if err == nil || editor.String() != "a\nb\nc" || !slices.Equal(editor.Selections(), selections) || editor.CanUndo() || editor.historyRunes != 0 { + t.Fatal("transaction committed over a source secondary selection change") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) +} + +func TestLFLabelBatchRejectsSourceSecondarySelectionChanges(t *testing.T) { + editor := NewEditor("a\nb\nc") + selections := []Range{{}, {Start: 3, End: 3}} + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'M', func(change LFLabelReplacement) []byte { + editor.SetSelections(selections, 0) + return lfLabelPreserveReplacement(change) + }) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{}) + err := editor.ReplaceRanges([]Replacement{{Range: Range{}, Text: "x\n"}}) + if err == nil || editor.String() != "a\nb\nc" || !slices.Equal(editor.Selections(), selections) || editor.CanUndo() || editor.historyRunes != 0 { + t.Fatal("batch committed over a source secondary selection change") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) +} + +func TestLFLabelBatchOrderAndReplay(t *testing.T) { + for _, forward := range []bool{false, true} { + t.Run(fmt.Sprintf("forward-%t", forward), func(t *testing.T) { + editor := NewEditor("a\nb\nc\nd\ne") + editor.SetSavePoint() + if !editor.TrackLFLabels([]byte{'W', 'L', 'M', 'W'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{Start: 3, End: 0}) + selection, caret := editor.Selection(), editor.Caret() + after := Range{Start: 5, End: 1} + err := editor.ReplaceRangesWith([]Replacement{ + {Range: Range{Start: 3, End: 4}}, + {Range: Range{Start: 6, End: 6}, Text: "new\n"}, + }, ReplaceRangesOptions{Forward: forward, AfterSelection: &after}) + if err != nil || editor.String() != "a\nbc\nnew\nd\ne" || editor.Caret() != 1 { + t.Fatalf("batch text/selection = %q, %d, %v", editor.String(), editor.Caret(), err) + } + assertLFLabels(t, editor, []byte{'W', 'M', 'W', 'W'}) + for range 2 { + if !editor.Undo() || editor.String() != "a\nb\nc\nd\ne" || editor.Selection() != selection || editor.Caret() != caret || editor.CanUndo() || !editor.AtSavePoint() { + t.Fatal("batch Undo lost its source or history boundary") + } + assertLFLabels(t, editor, []byte{'W', 'L', 'M', 'W'}) + if !editor.Redo() || editor.String() != "a\nbc\nnew\nd\ne" || editor.Caret() != 1 { + t.Fatal("batch Redo failed") + } + assertLFLabels(t, editor, []byte{'W', 'M', 'W', 'W'}) + } + }) + } +} + +func TestLFLabelBatchMapperReceivesActualDisjointSpans(t *testing.T) { + for _, forward := range []bool{false, true} { + t.Run(fmt.Sprintf("forward-%t", forward), func(t *testing.T) { + editor := NewEditor("a\nkeep\nz\n") + calls := 0 + mapper := func(change LFLabelReplacement) []byte { + calls++ + want := byte('W') + switch change.Removed { + case "a\n": + if change.Inserted != "A\n" { + t.Fatalf("first replacement inserted %q", change.Inserted) + } + case "z\n": + want = 'M' + if change.Inserted != "Z\n" { + t.Fatalf("last replacement inserted %q", change.Inserted) + } + default: + t.Fatalf("mapper received aggregate or unchanged gap %q", change.Removed) + } + if !slices.Equal(change.Labels, []byte{want}) { + t.Fatalf("mapper received labels %q for %q", change.Labels, change.Removed) + } + return change.Labels + } + if !editor.TrackLFLabels([]byte{'W', 'L', 'M'}, 'W', mapper) { + t.Fatal("label setup failed") + } + if err := editor.ReplaceRangesWith([]Replacement{ + {Range: Range{Start: 0, End: 2}, Text: "A\n"}, + {Range: Range{Start: 7, End: 9}, Text: "Z\n"}, + }, ReplaceRangesOptions{Forward: forward}); err != nil { + t.Fatal(err) + } + assertLFLabels(t, editor, []byte{'W', 'L', 'M'}) + if !editor.Undo() || !editor.Redo() || editor.String() != "A\nkeep\nZ\n" || calls != 2 { + t.Fatalf("batch replay changed policy calls or text: calls=%d text=%q", calls, editor.String()) + } + assertLFLabels(t, editor, []byte{'W', 'L', 'M'}) + }) + } +} + +func TestLFLabelBatchEqualTextPhysicalChange(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'W', func(LFLabelReplacement) []byte { return []byte{'M'} }) { + t.Fatal("label setup failed") + } + if err := editor.ReplaceRanges([]Replacement{{Range: Range{End: editor.RuneCount()}, Text: "a\nb"}}); err != nil { + t.Fatal(err) + } + assertLFLabels(t, editor, []byte{'M'}) + if !editor.Undo() || editor.String() != "a\nb" { + t.Fatal("equal-text label change was not undoable") + } + assertLFLabels(t, editor, []byte{'W'}) + if !editor.Redo() { + t.Fatal("equal-text label change lost Redo") + } + assertLFLabels(t, editor, []byte{'M'}) +} + +func TestLFLabelBatchInvalidMapperIsAtomic(t *testing.T) { + editor := NewEditor("a\nb\n") + calls := 0 + mapper := func(change LFLabelReplacement) []byte { + calls++ + if calls == 2 { + return nil + } + return []byte{'W'} + } + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', mapper) { + t.Fatal("label setup failed") + } + cursor := editor.TrackEdits() + panicked := false + func() { + defer func() { panicked = recover() != nil }() + _ = editor.ReplaceRangesWith([]Replacement{ + {Range: Range{Start: 0, End: 0}, Text: "x\n"}, + {Range: Range{Start: 4, End: 4}, Text: "y\n"}, + }, ReplaceRangesOptions{Forward: true}) + }() + if !panicked || calls != 2 || editor.String() != "a\nb\n" || editor.CanUndo() || editor.CanRedo() { + t.Fatalf("late invalid mapper partially committed: panic=%t calls=%d text=%q", panicked, calls, editor.String()) + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if edits, _, ok := editor.EditsSince(cursor, nil); !ok || len(edits) != 0 { + t.Fatal("late invalid mapper published source edits") + } +} + +func TestLFLabelBatchRejectedTargetDoesNotRunPolicy(t *testing.T) { + editor := NewEditor("a\nb\n") + calls := 0 + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', func(change LFLabelReplacement) []byte { + calls++ + return lfLabelPreserveReplacement(change) + }) { + t.Fatal("label setup failed") + } + if err := editor.ReplaceRanges([]Replacement{ + {Range: Range{Start: 0, End: 0}, Text: "new\n"}, + {Range: Range{Start: 99, End: 99}, Text: "bad\n"}, + }); err == nil || calls != 0 || editor.String() != "a\nb\n" || editor.CanUndo() { + t.Fatal("invalid target reached policy or changed the source") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) +} + +func TestLFLabelTransactionCommitAndDraftReplay(t *testing.T) { + editor := NewEditor("a\nb\nc") + editor.SetSavePoint() + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + err := editor.Transact(func(draft *Editor) error { + draft.ReplaceRange(Range{Start: 2, End: 2}, "new\n") + assertLFLabels(t, draft, []byte{'W', 'W', 'L'}) + if !draft.Undo() { + t.Fatal("draft Undo failed") + } + assertLFLabels(t, draft, []byte{'W', 'L'}) + if !draft.Redo() { + t.Fatal("draft Redo failed") + } + draft.ReplaceRange(Range{Start: 7, End: 8}, "") + assertLFLabels(t, draft, []byte{'W', 'W'}) + if editor.String() != "a\nb\nc" { + t.Fatal("draft changed source text before commit") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + return nil + }) + if err != nil || editor.String() != "a\nnew\nbc" { + t.Fatalf("transaction commit = %q, %v", editor.String(), err) + } + assertLFLabels(t, editor, []byte{'W', 'W'}) + if !editor.Undo() || editor.String() != "a\nb\nc" || editor.CanUndo() || !editor.AtSavePoint() { + t.Fatal("transaction did not retain one source Undo action") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Redo() { + t.Fatal("transaction Redo failed") + } + assertLFLabels(t, editor, []byte{'W', 'W'}) +} + +func TestLFLabelTransactionFailureAndRetry(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + wantErr := errors.New("stop staged edits") + err := editor.Transact(func(draft *Editor) error { + draft.ReplaceRange(Range{Start: 3, End: 4}, "") + draft.MoveTo(draft.RuneCount(), false) + draft.Insert("new\n") + return wantErr + }) + if !errors.Is(err, wantErr) || editor.String() != "a\nb\nc" || editor.CanUndo() { + t.Fatal("failed transaction changed the source") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if err := editor.Transact(func(draft *Editor) error { + draft.MoveTo(draft.RuneCount(), false) + draft.Insert("\n") + return nil + }); err != nil { + t.Fatal(err) + } + assertLFLabels(t, editor, []byte{'W', 'L', 'W'}) + if !editor.Undo() { + t.Fatal("retry lost Undo") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) +} + +func TestLFLabelTransactionPrivateConfigurationRefused(t *testing.T) { + for _, tracked := range []bool{false, true} { + t.Run(fmt.Sprintf("tracked-%t", tracked), func(t *testing.T) { + editor := NewEditor("a\nb") + if tracked && !editor.TrackLFLabels([]byte{'W'}, 'W', nil) { + t.Fatal("label setup failed") + } + if err := editor.Transact(func(draft *Editor) error { + if draft.TrackLFLabels([]byte{'M'}, 'M', nil) || draft.SetLFLabels([]byte{'M'}, 'M') || draft.UnifyLFLabels('M') { + t.Fatal("private draft changed label configuration") + } + if tracked { + assertLFLabels(t, draft, []byte{'W'}) + } + return nil + }); err != nil { + t.Fatal(err) + } + if tracked { + assertLFLabels(t, editor, []byte{'W'}) + } else if _, ok := editor.LFLabels(nil); ok { + t.Fatal("private tracking leaked into source") + } + }) + } +} + +func TestLFLabelTransactionRejectsSourceRelabel(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'W', nil) { + t.Fatal("label setup failed") + } + err := editor.Transact(func(draft *Editor) error { + if !editor.SetLFLabels([]byte{'M'}, 'M') { + t.Fatal("fixture source relabel failed") + } + draft.MoveTo(draft.RuneCount(), false) + draft.Insert("\n") + return nil + }) + if err == nil || editor.String() != "a\nb" || editor.CanUndo() { + t.Fatal("transaction committed over a source metadata change") + } + assertLFLabels(t, editor, []byte{'M'}) +} + +func TestLFLabelTransactionEqualTextPhysicalChange(t *testing.T) { + for _, saved := range []bool{false, true} { + t.Run(fmt.Sprintf("saved-%t", saved), func(t *testing.T) { + editor := NewEditor("a\nb\nc") + if saved { + editor.SetSavePoint() + } + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + if err := editor.Transact(func(draft *Editor) error { + draft.ReplaceRange(Range{Start: 3, End: 4}, "") + draft.ReplaceRange(Range{Start: 3, End: 3}, "\n") + return nil + }); err != nil || editor.String() != "a\nb\nc" { + t.Fatalf("zero-net transaction = %q, %v", editor.String(), err) + } + assertLFLabels(t, editor, []byte{'W', 'W'}) + if !editor.Undo() { + t.Fatal("equal-text physical transaction lost Undo") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Redo() { + t.Fatal("equal-text physical transaction lost Redo") + } + assertLFLabels(t, editor, []byte{'W', 'W'}) + }) + } +} + +func TestLFLabelLargeBatchAndTransaction(t *testing.T) { + t.Run("batch", func(t *testing.T) { + const count = 2050 + editor := NewEditor(strings.Repeat("x\n", count)) + seed := make([]byte, count) + for index := range seed { + seed[index] = []byte{'W', 'L', 'M'}[index%3] + } + if !editor.TrackLFLabels(seed, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + edits := make([]Replacement, count-1) + for index := range edits { + edits[index] = Replacement{Range: Range{Start: index*2 + 1, End: index*2 + 2}} + } + if err := editor.ReplaceRanges(edits); err != nil { + t.Fatal(err) + } + assertLFLabels(t, editor, []byte{'W'}) + if !editor.Undo() { + t.Fatal("large batch lost Undo") + } + assertLFLabels(t, editor, seed) + if !editor.Redo() { + t.Fatal("large batch lost Redo") + } + assertLFLabels(t, editor, []byte{'W'}) + }) + t.Run("transaction", func(t *testing.T) { + editor := NewEditor("a\n") + if !editor.TrackLFLabels([]byte{'L'}, 'W', nil) { + t.Fatal("label setup failed") + } + if err := editor.Transact(func(draft *Editor) error { + draft.MoveTo(draft.RuneCount(), false) + for range 2050 { + draft.Insert("n\n") + } + return nil + }); err != nil { + t.Fatal(err) + } + want := append([]byte{'L'}, bytesOfLabel('W', 2050)...) + assertLFLabels(t, editor, want) + if !editor.Undo() || editor.String() != "a\n" || editor.CanUndo() { + t.Fatal("large transaction lost its source Undo boundary") + } + assertLFLabels(t, editor, []byte{'L'}) + if !editor.Redo() { + t.Fatal("large transaction lost Redo") + } + assertLFLabels(t, editor, want) + }) +} + +func TestLFLabelBatchMapperCannotConsumeSourceUndo(t *testing.T) { + editor := NewEditor("a\nb") + reenter := false + mapper := func(change LFLabelReplacement) []byte { + if reenter { + editor.Undo() + } + return lfLabelPreserveReplacement(change) + } + if !editor.TrackLFLabels([]byte{'W'}, 'W', mapper) { + t.Fatal("label setup failed") + } + editor.MoveTo(editor.RuneCount(), false) + editor.Insert("\n") + editor.SetSavePoint() + reenter = true + panicked := false + func() { + defer func() { panicked = recover() != nil }() + _ = editor.ReplaceRanges([]Replacement{{Range: Range{}, Text: "new\n"}}) + }() + if !panicked || editor.String() != "a\nb\n" || !editor.CanUndo() || editor.CanRedo() || !editor.AtSavePoint() { + t.Fatal("reentrant mapper consumed source history before being refused") + } + assertLFLabels(t, editor, []byte{'W', 'W'}) + reenter = false + if err := editor.ReplaceRanges([]Replacement{{Range: Range{}, Text: "new\n"}}); err != nil { + t.Fatal(err) + } + assertLFLabels(t, editor, []byte{'W', 'W', 'W'}) + if !editor.Undo() || !editor.AtSavePoint() || !editor.CanUndo() { + t.Fatal("safe retry lost the preexisting history") + } + assertLFLabels(t, editor, []byte{'W', 'W'}) +} + +func TestLFLabelBatchNoOpKeepsExistingRedo(t *testing.T) { + for _, applyUnchanged := range []bool{false, true} { + t.Run(fmt.Sprintf("apply-unchanged-%t", applyUnchanged), func(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.MoveTo(editor.RuneCount(), false) + editor.Insert("!") + if !editor.Undo() { + t.Fatal("fixture Undo failed") + } + if err := editor.ReplaceRangesWith([]Replacement{{Range: Range{End: editor.RuneCount()}, Text: "a\nb"}}, ReplaceRangesOptions{ApplyUnchanged: applyUnchanged}); err != nil { + t.Fatal(err) + } + if editor.CanUndo() || !editor.CanRedo() { + t.Fatal("equal-text label-preserving batch changed existing history") + } + if !editor.SetLFLabels([]byte{'L'}, 'L') || !editor.Redo() || editor.String() != "a\nb!" { + t.Fatal("no-op batch lost the original LF identity or Redo") + } + assertLFLabels(t, editor, []byte{'L'}) + }) + } +} + +func TestLFLabelNestedTransactionAndBatch(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + err := editor.Transact(func(draft *Editor) error { + if err := draft.Transact(func(inner *Editor) error { + return inner.ReplaceRangesWith([]Replacement{ + {Range: Range{Start: 3, End: 4}}, + {Range: Range{Start: 5, End: 5}, Text: "new\n"}, + }, ReplaceRangesOptions{Forward: true}) + }); err != nil { + return err + } + assertLFLabels(t, draft, []byte{'W', 'W'}) + return nil + }) + if err != nil || editor.String() != "a\nbcnew\n" { + t.Fatalf("nested transaction = %q, %v", editor.String(), err) + } + assertLFLabels(t, editor, []byte{'W', 'W'}) + if !editor.Undo() || editor.String() != "a\nb\nc" || editor.CanUndo() { + t.Fatal("nested transaction did not commit as one source action") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Redo() { + t.Fatal("nested transaction lost Redo") + } + assertLFLabels(t, editor, []byte{'W', 'W'}) +} + +func bytesOfLabel(label byte, count int) []byte { + labels := make([]byte, count) + for index := range labels { + labels[index] = label + } + return labels +} diff --git a/text/lf_labels_budget.go b/text/lf_labels_budget.go new file mode 100644 index 000000000..c83705fb1 --- /dev/null +++ b/text/lf_labels_budget.go @@ -0,0 +1,57 @@ +package text + +import "unsafe" + +// History budgets use rune units. The entry reserve covers map capacity and +// allocator overhead; cells are conservatively charged per retained reference, +// including references also present in current text or another history unit. +const ( + lfLabelEntryBytes = 512 + lfLabelCellBytes = 16 + lfLabelPointerBytes = int(unsafe.Sizeof((*lfLabelCell)(nil))) + lfLabelEditBytes = int(unsafe.Sizeof(lfLabelEdit{})) + lfLabelRuneBytes = int(unsafe.Sizeof(rune(0))) +) + +func lfLabelFragmentBytes(capacity int) int { + return capacity * (lfLabelPointerBytes + lfLabelCellBytes) +} + +func (entry lfLabelEntry) retainedRunes() int { + if len(entry.edits) == 0 { + return 0 + } + bytes := lfLabelEntryBytes + cap(entry.edits)*lfLabelEditBytes + lfLabelFragmentBytes(entry.fragments) + return (bytes + lfLabelRuneBytes - 1) / lfLabelRuneBytes +} + +func lfLabelHistoryCost(state *lfLabelState, key *rune) int { + return state.history[key].retainedRunes() +} + +func lfLabelExtraCost(state *lfLabelState) int { + return state.composition.extraRunes +} + +func syncLFLabelExtraCost(state *lfLabelState) { + composition := &state.composition + cost := (lfLabelFragmentBytes(cap(composition.original)) + lfLabelRuneBytes - 1) / lfLabelRuneBytes + if !composition.sharedHistory { + cost += composition.heldRunes + } + state.owner.historyRunes += cost - composition.extraRunes + composition.extraRunes = cost +} + +// Rebuild after deletions so a small live history cannot retain an old map's +// oversized backing without paying for it. Rekeying an entry keeps its size. +func cloneLFLabelHistory(source map[*rune]lfLabelEntry) map[*rune]lfLabelEntry { + if len(source) == 0 { + return nil + } + result := make(map[*rune]lfLabelEntry, len(source)) + for key, entry := range source { + result[key] = entry + } + return result +} diff --git a/text/lf_labels_composition.go b/text/lf_labels_composition.go new file mode 100644 index 000000000..c6e153613 --- /dev/null +++ b/text/lf_labels_composition.go @@ -0,0 +1,99 @@ +package text + +import "slices" + +type lfLabelComposition struct { + active, sharedHistory, recorded bool + line, currentLF int + original, unitOriginal []*lfLabelCell + prefix []lfLabelEdit + history map[*rune]lfLabelEntry + heldRunes, extraRunes int +} + +func holdLFLabelComposition(state *lfLabelState, change textChange) { + composition := lfLabelComposition{ + active: true, + sharedHistory: true, + line: state.lastLine, + currentLF: countLabelLF(change.inserted), + history: state.history, + } + for _, entry := range composition.history { + composition.heldRunes += entry.retainedRunes() + } + if len(state.pending) != 0 { + composition.original = state.pending[0].removed + } else if count := countLabelLF(change.removed); count != 0 { + composition.original = slices.Clone(state.current[composition.line : composition.line+count]) + } + state.composition = composition + syncLFLabelExtraCost(state) +} + +func ensureLFLabelHistoryOwned(state *lfLabelState) { + if state.composition.active && state.composition.sharedHistory { + state.history = cloneLFLabelHistory(state.history) + state.composition.sharedHistory = false + syncLFLabelExtraCost(state) + } +} + +func compositionLFLabelEdits(state *lfLabelState, previous *rune) []lfLabelEdit { + composition := &state.composition + if !composition.recorded { + composition.prefix = composition.history[previous].edits + if len(state.pending) != 0 { + composition.unitOriginal = state.pending[0].removed + } else if composition.currentLF != 0 { + composition.unitOriginal = slices.Clone(state.current[composition.line : composition.line+composition.currentLF]) + } + composition.recorded = true + } + edits := slices.Clone(composition.prefix) + if len(composition.unitOriginal) != 0 || composition.currentLF != 0 { + edits = append(edits, lfLabelEdit{ + line: composition.line, + removed: composition.unitOriginal, + inserted: slices.Clone(state.current[composition.line : composition.line+composition.currentLF]), + }) + } + return edits +} + +func cancelLFLabelComposition(state *lfLabelState) { + composition := state.composition + if !composition.active { + return + } + if state.staging && (composition.currentLF != 0 || len(composition.original) != 0) { + state.events = append(state.events, lfLabelEdit{ + line: composition.line, + removed: slices.Clone(state.current[composition.line : composition.line+composition.currentLF]), + inserted: composition.original, + }) + } + spliceLFLabels(state, composition.line, composition.currentLF, composition.original) + state.history = composition.history + state.pending = nil + state.composition = lfLabelComposition{} +} + +func releaseLFLabelComposition(state *lfLabelState) { + if !state.owner.composing { + state.owner.historyRunes -= state.composition.extraRunes + state.composition = lfLabelComposition{} + } +} + +func discardLFLabelHeldHistory(state *lfLabelState) { + if state.composition.active { + state.composition.history = nil + state.composition.heldRunes = 0 + state.composition.sharedHistory = false + state.composition.recorded = false + state.composition.unitOriginal = nil + state.composition.prefix = nil + syncLFLabelExtraCost(state) + } +} diff --git a/text/lf_labels_lifecycle_test.go b/text/lf_labels_lifecycle_test.go new file mode 100644 index 000000000..77a940792 --- /dev/null +++ b/text/lf_labels_lifecycle_test.go @@ -0,0 +1,444 @@ +package text + +import ( + "errors" + "fmt" + "strings" + "testing" +) + +func TestLFLabelCompositionCancelRestoresOriginalIdentity(t *testing.T) { + editor := NewEditor("a\nb\nc") + calls := 0 + mapper := func(change LFLabelReplacement) []byte { + calls++ + return lfLabelPreserveReplacement(change) + } + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'M', mapper) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{Start: 4, End: 1}) + selection, caret := editor.Selection(), editor.Caret() + editor.SetMarkedText("p\n", Range{Start: 2, End: 2}) + assertLFLabels(t, editor, []byte{'L'}) + editor.SetMarkedText("q\nr\n", Range{Start: 4, End: 4}) + assertLFLabels(t, editor, []byte{'M', 'L'}) + _ = editor.CommittedString() + if !editor.CancelComposition() || editor.String() != "a\nb\nc" || editor.Selection() != selection || editor.Caret() != caret || editor.CanUndo() || editor.CanRedo() || calls != 2 { + t.Fatalf("cancel changed text/selection/history or reran mapping: text=%q calls=%d", editor.String(), calls) + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if editor.historyRunes != 0 || len(editor.lfLabelState().history) != 0 || len(editor.lfLabelState().pending) != 0 { + t.Fatal("cancel retained provisional label history") + } + if editor.CancelComposition() { + t.Fatal("second cancel reported a composition") + } +} + +func TestLFLabelCompositionCancelPreservesUndoAndRedo(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'M', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.MoveTo(editor.RuneCount(), false) + editor.Paste("\n") + editor.SetSavePoint() + editor.Paste("tail\n") + if !editor.Undo() || !editor.CanUndo() || !editor.CanRedo() { + t.Fatal("fixture did not establish both history directions") + } + beforeRunes := editor.historyRunes + editor.SetSelection(Range{Start: 2, End: 0}) + editor.SetMarkedText("x\n", Range{Start: 2, End: 2}) + editor.SetMarkedText("\n\n", Range{Start: 2, End: 2}) + if !editor.CancelComposition() || editor.String() != "a\nb\n" || !editor.AtSavePoint() || editor.historyRunes != beforeRunes { + t.Fatal("cancel did not restore the original saved history") + } + assertLFLabels(t, editor, []byte{'W', 'M'}) + if !editor.Redo() || editor.String() != "a\nb\ntail\n" { + t.Fatal("cancel lost the old Redo branch") + } + assertLFLabels(t, editor, []byte{'W', 'M', 'M'}) + if !editor.Undo() || !editor.Undo() || editor.String() != "a\nb" { + t.Fatal("cancel lost the original Undo unit") + } + assertLFLabels(t, editor, []byte{'W'}) +} + +func TestLFLabelCompositionCommitReplaysOneUnit(t *testing.T) { + for _, insertResult := range []bool{false, true} { + t.Run(fmt.Sprintf("insert-result-%t", insertResult), func(t *testing.T) { + editor := NewEditor("a\nb\nc") + calls := 0 + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'M', func(change LFLabelReplacement) []byte { + calls++ + return lfLabelPreserveReplacement(change) + }) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{Start: 1, End: 4}) + editor.SetMarkedText("p\n", Range{Start: 2, End: 2}) + editor.SetMarkedText("q\nr\n", Range{Start: 4, End: 4}) + want := []byte{'M', 'L'} + value := "aq\nr\nc" + if insertResult { + editor.Insert("z\n") + want, value = []byte{'L'}, "az\nc" + } else { + editor.Unmark() + } + beforeReplay := calls + assertLFLabels(t, editor, want) + if editor.String() != value || editor.CancelComposition() || !editor.Undo() || editor.String() != "a\nb\nc" || editor.CanUndo() { + t.Fatal("composition commit did not retain one matching history unit") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Redo() || editor.String() != value || calls != beforeReplay { + t.Fatal("composition replay reran policy or lost text") + } + assertLFLabels(t, editor, want) + }) + } +} + +func TestLFLabelCompositionClearHistoryKeepsOnlyCancellationData(t *testing.T) { + for _, cancel := range []bool{false, true} { + t.Run(fmt.Sprintf("cancel-%t", cancel), func(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'M', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.MoveTo(editor.RuneCount(), false) + editor.Paste("X\n") + editor.SetSelection(Range{Start: 1, End: 4}) + editor.SetMarkedText("p\n", Range{Start: 2, End: 2}) + editor.ClearHistory() + if editor.CanUndo() || editor.CanRedo() { + t.Fatal("ClearHistory retained source history") + } + editor.SetMarkedText("q\nr\n", Range{Start: 4, End: 4}) + if cancel { + if !editor.CancelComposition() || editor.String() != "a\nb\ncX\n" || editor.CanUndo() || editor.CanRedo() { + t.Fatal("cancel after ClearHistory restored forgotten history or lost text") + } + assertLFLabels(t, editor, []byte{'W', 'L', 'M'}) + if editor.historyRunes != 0 || len(editor.lfLabelState().history) != 0 { + t.Fatal("cancel after ClearHistory retained old label ownership") + } + } else { + editor.Unmark() + assertLFLabels(t, editor, []byte{'M', 'L', 'M'}) + if !editor.Undo() || editor.String() != "ap\ncX\n" || editor.CanUndo() { + t.Fatal("post-clear commit did not start its history at the cleared text") + } + assertLFLabels(t, editor, []byte{'L', 'M'}) + if !editor.Redo() { + t.Fatal("post-clear commit lost Redo") + } + assertLFLabels(t, editor, []byte{'M', 'L', 'M'}) + } + }) + } +} + +func TestLFLabelCompositionRetainedCostDoesNotGrowPerUpdate(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'M', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{End: editor.RuneCount()}) + for index := range 10 { + editor.SetMarkedText(fmt.Sprintf("v%04d\n", index), Range{Start: 6, End: 6}) + } + before := editor.historyRunes + for index := 10; index < 1000; index++ { + editor.SetMarkedText(fmt.Sprintf("v%04d\n", index), Range{Start: 6, End: 6}) + } + if editor.historyRunes != before || !editor.CanUndo() { + t.Fatalf("composition retained per-update metadata: before=%d after=%d", before, editor.historyRunes) + } + if !editor.CancelComposition() { + t.Fatal("cancel failed") + } + assertLFLabels(t, editor, []byte{'W'}) +} + +func TestLFLabelCompositionRestoresTrimmedAndClearedHistory(t *testing.T) { + for _, clear := range []bool{false, true} { + t.Run(fmt.Sprintf("automatic-clear-%t", clear), func(t *testing.T) { + editor := NewEditor("a\n") + if !editor.TrackLFLabels([]byte{'L'}, 'M', nil) { + t.Fatal("label setup failed") + } + editor.MoveTo(editor.RuneCount(), false) + for range 8 { + editor.Paste("x\n") + } + before, beforeRunes := editor.String(), editor.historyRunes + count := maxHistoryRunes/2 + 1024 + if clear { + count = maxSingleEditRunes/8 + 1024 + } + editor.SetMarkedText(strings.Repeat("p\n", count), Range{Start: count * 2, End: count * 2}) + if clear && editor.CanUndo() { + t.Fatal("oversized label history was not included in automatic-clear budget") + } + if !editor.CancelComposition() || editor.String() != before || editor.historyRunes != beforeRunes { + t.Fatal("cancel did not restore held history after budget pruning") + } + assertLFLabels(t, editor, append([]byte{'L'}, bytesOfLabel('M', 8)...)) + for remaining := 7; remaining >= 0; remaining-- { + if !editor.Undo() { + t.Fatalf("cancel lost original unit %d", remaining) + } + assertLFLabels(t, editor, append([]byte{'L'}, bytesOfLabel('M', remaining)...)) + } + }) + } +} + +func TestLFLabelHistoryBudgetCountsMetadataAndReleasesIt(t *testing.T) { + editor := NewEditor("a\n") + if !editor.TrackLFLabels([]byte{'W'}, 'M', nil) { + t.Fatal("label setup failed") + } + editor.ReplaceRange(Range{End: editor.RuneCount()}, "b\n") + textCost := editor.history[0].retainedRunes() + if editor.historyRunes <= textCost { + t.Fatalf("label metadata is uncharged: history=%d text=%d", editor.historyRunes, textCost) + } + editor.ClearHistory() + if editor.historyRunes != 0 || len(editor.lfLabelState().history) != 0 || len(editor.lfLabelState().pending) != 0 { + t.Fatal("ClearHistory retained label metadata") + } + assertLFLabels(t, editor, []byte{'M'}) +} + +func TestLFLabelMetadataCanPruneALargeUnit(t *testing.T) { + const count = 30000 + editor := NewEditor(strings.Repeat("x\n", count)) + if !editor.TrackLFLabels(bytesOfLabel('L', count), 'M', nil) { + t.Fatal("label setup failed") + } + editor.ReplaceRange(Range{End: editor.RuneCount()}, strings.Repeat("y\n", count)) + if !editor.CanUndo() { + t.Fatal("a single affordable large unit was not retained") + } + editor.MoveTo(editor.RuneCount(), false) + editor.Insert("!") + if !editor.Undo() || editor.CanUndo() { + t.Fatal("label cost did not participate in pruning the large older unit") + } + assertLFLabels(t, editor, bytesOfLabel('M', count)) +} + +func TestLFLabelLargeShrinkReleasesCurrentBacking(t *testing.T) { + for _, keep := range []bool{false, true} { + t.Run(fmt.Sprintf("keep-one-%t", keep), func(t *testing.T) { + editor := NewEditor(strings.Repeat("x\n", 4096)) + if !editor.TrackLFLabels(bytesOfLabel('L', 4096), 'M', nil) { + t.Fatal("label setup failed") + } + state := editor.lfLabelState() + previousBacking := &state.current[0] + start := 0 + if keep { + start = 2 + } + editor.ReplaceRange(Range{Start: start, End: editor.RuneCount()}, "flat") + editor.ClearHistory() + if keep { + assertLFLabels(t, editor, []byte{'L'}) + if cap(state.current) > 64 || &state.current[0] == previousBacking { + t.Fatal("large shrink retained the previous pointer backing") + } + } else if len(state.current) != 0 || cap(state.current) != 0 { + t.Fatal("empty current labels retained the old pointer backing") + } + }) + } +} + +func TestLFLabelWindowExpiryAndPrefixTrimDoNotLoseCurrentData(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'M', nil) { + t.Fatal("label setup failed") + } + cursor := editor.TrackLineEdits() + editor.MoveTo(editor.RuneCount(), false) + for range 2000 { + editor.Paste("x\n") + } + if _, _, ok := editor.LineEditsSince(cursor, nil); ok { + t.Fatal("fixture did not expire the delivery window") + } + assertLFLabels(t, editor, append([]byte{'W'}, bytesOfLabel('M', 2000)...)) + undone := 0 + for editor.CanUndo() { + if !editor.Undo() { + t.Fatal("Undo failed") + } + undone++ + } + if undone == 0 || undone >= 2000 { + t.Fatal("fixture did not prune the history prefix") + } + assertLFLabels(t, editor, append([]byte{'W'}, bytesOfLabel('M', 2000-undone)...)) + editor.MoveTo(editor.RuneCount(), false) + editor.Paste("\n") + if editor.CanRedo() { + t.Fatal("branch retained the discarded Redo tail") + } + editor.ClearHistory() + if editor.historyRunes != 0 || len(editor.lfLabelState().history) != 0 { + t.Fatal("branch/Clear retained unreachable label ownership") + } + assertLFLabels(t, editor, append([]byte{'W'}, bytesOfLabel('M', 2001-undone)...)) +} + +func TestLFLabelCompositionRejectedUpdateKeepsCancellationAndBudget(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'M', func(change LFLabelReplacement) []byte { + if strings.HasPrefix(change.Inserted, "bad") { + return nil + } + return lfLabelPreserveReplacement(change) + }) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{Start: 1, End: 4}) + editor.SetMarkedText("p\n", Range{Start: 2, End: 2}) + before, selection, cost := editor.String(), editor.Selection(), editor.historyRunes + panicked := false + func() { + defer func() { panicked = recover() != nil }() + editor.SetMarkedText("bad\n\n", Range{Start: 5, End: 5}) + }() + if !panicked || editor.String() != before || editor.Selection() != selection || editor.historyRunes != cost { + t.Fatal("rejected marked update changed text, selection or retained budget") + } + assertLFLabels(t, editor, []byte{'L'}) + if !editor.CancelComposition() || editor.String() != "a\nb\nc" || editor.historyRunes != 0 || editor.CanUndo() { + t.Fatal("rejected update damaged the cancellation snapshot") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) +} + +func TestLFLabelReplaceRangeCommitsCompositionBeforeIndependentHistory(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'M', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{Start: 1, End: 2}) + editor.SetMarkedText("x\n", Range{Start: 2, End: 2}) + editor.ReplaceRange(Range{Start: 4, End: 5}, "") + if editor.String() != "ax\nbc" || editor.CancelComposition() { + t.Fatal("ReplaceRange did not end composition") + } + assertLFLabels(t, editor, []byte{'W'}) + if !editor.Undo() || editor.String() != "ax\nb\nc" { + t.Fatal("independent replacement lost its source text") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Undo() || editor.String() != "a\nb\nc" || editor.CanUndo() { + t.Fatal("composition did not retain its independent Undo unit") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Redo() || !editor.Redo() || editor.String() != "ax\nbc" { + t.Fatal("composition and independent edit lost Redo") + } + assertLFLabels(t, editor, []byte{'W'}) + editor.ClearHistory() + if editor.historyRunes != 0 { + t.Fatal("ReplaceRange retained abandoned composition history") + } +} + +func TestLFLabelTransactionCompositionLifecycle(t *testing.T) { + for _, ending := range []string{"cancel", "commit", "error", "unfinished"} { + t.Run(ending, func(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'M', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + failure := errors.New("reject composition transaction") + err := editor.Transact(func(draft *Editor) error { + draft.SetSelection(Range{Start: 1, End: 4}) + draft.SetMarkedText("p\n", Range{Start: 2, End: 2}) + draft.SetMarkedText("q\nr\n", Range{Start: 4, End: 4}) + assertLFLabels(t, draft, []byte{'M', 'L'}) + assertLFLabels(t, editor, []byte{'W', 'L'}) + switch ending { + case "cancel": + if !draft.CancelComposition() { + t.Fatal("draft cancellation failed") + } + assertLFLabels(t, draft, []byte{'W', 'L'}) + draft.MoveTo(draft.RuneCount(), false) + draft.Insert("\n") + case "commit": + draft.Unmark() + case "error": + return failure + } + return nil + }) + if ending == "error" || ending == "unfinished" { + if err == nil || ending == "error" && !errors.Is(err, failure) || editor.String() != "a\nb\nc" || editor.CanUndo() || editor.historyRunes != 0 { + t.Fatal("rejected private composition changed source ownership") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + return + } + wantText, wantLabels := "a\nb\nc\n", []byte{'W', 'L', 'M'} + if ending == "commit" { + wantText, wantLabels = "aq\nr\nc", []byte{'M', 'L'} + } + if err != nil || editor.String() != wantText { + t.Fatalf("composition transaction: %q, %v", editor.String(), err) + } + assertLFLabels(t, editor, wantLabels) + if !editor.Undo() || editor.String() != "a\nb\nc" || editor.CanUndo() { + t.Fatal("composition transaction did not retain one source Undo unit") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Redo() || editor.String() != wantText { + t.Fatal("composition transaction lost Redo") + } + assertLFLabels(t, editor, wantLabels) + editor.ClearHistory() + if editor.historyRunes != 0 { + t.Fatal("composition transaction retained forgotten label history") + } + }) + } +} + +func TestLFLabelLFFreeTypingDoesNotAllocateFragments(t *testing.T) { + makeEditor := func(tracked bool) *Editor { + editor := NewEditor("a\nb") + editor.TrackLineEdits() + if tracked && !editor.TrackLFLabels([]byte{'W'}, 'M', nil) { + t.Fatal("label setup failed") + } + editor.MoveTo(editor.RuneCount(), false) + return editor + } + measure := func(editor *Editor) float64 { + return testing.AllocsPerRun(100, func() { + editor.Insert("x") + editor.DeleteBackward() + editor.ClearHistory() + }) + } + baseline, tracked := makeEditor(false), makeEditor(true) + baselineAllocs, trackedAllocs := measure(baseline), measure(tracked) + if trackedAllocs != baselineAllocs { + t.Fatalf("LF-free typing allocated label fragments: baseline=%g tracked=%g", baselineAllocs, trackedAllocs) + } + assertLFLabels(t, tracked, []byte{'W'}) + if len(tracked.lfLabelState().history) != 0 || len(tracked.lfLabelState().pending) != 0 || tracked.historyRunes != 0 { + t.Fatal("LF-free typing retained label fragments") + } +} diff --git a/text/lf_labels_revision_test.go b/text/lf_labels_revision_test.go new file mode 100644 index 000000000..cd4d47429 --- /dev/null +++ b/text/lf_labels_revision_test.go @@ -0,0 +1,75 @@ +package text + +import "testing" + +func TestLFLabelRevisionTracksReplayAndMetadata(t *testing.T) { + editor := NewEditor("a\nb") + source, ok := any(editor).(interface{ LFLabelRevision() (uint64, bool) }) + if !ok { + t.Fatal("LF labels have no source revision query") + } + if _, enabled := source.LFLabelRevision(); enabled { + t.Fatal("disabled tracker has a revision") + } + if !editor.TrackLFLabels([]byte{'M'}, 'M', nil) { + t.Fatal("tracker setup failed") + } + previous, enabled := source.LFLabelRevision() + if !enabled { + t.Fatal("enabled tracker has no revision") + } + checkChange := func() { + t.Helper() + next, enabled := source.LFLabelRevision() + if !enabled || next == previous { + t.Fatal("accepted LF state change did not advance its revision") + } + previous = next + } + editor.SetSavePoint() + editor.ReplaceRange(Range{End: editor.RuneCount()}, editor.String()) + checkChange() + if !editor.SetLFLabels([]byte{'W'}, 'M') { + t.Fatal("metadata update refused") + } + checkChange() + if !editor.Undo() { + t.Fatal("equal replacement lost Undo") + } + checkChange() + assertLFLabels(t, editor, []byte{'M'}) + if !editor.Redo() { + t.Fatal("equal replacement lost Redo") + } + checkChange() + assertLFLabels(t, editor, []byte{'W'}) + if !editor.UnifyLFLabels('L') { + t.Fatal("conversion refused") + } + checkChange() + editor.SetSavePoint() + editor.LFLabels(nil) + if after, _ := source.LFLabelRevision(); after != previous { + t.Fatal("Save or read changed the LF revision") + } + if err := editor.ReplaceRanges([]Replacement{{Range: Range{Start: 1, End: 2}, Text: "\n"}}); err != nil { + t.Fatal(err) + } + checkChange() + if err := editor.Transact(func(draft *Editor) error { + draft.ReplaceRange(Range{Start: 1, End: 2}, "") + draft.ReplaceRange(Range{Start: 1, End: 1}, "\n") + return nil + }); err != nil { + t.Fatal(err) + } + checkChange() + editor.SetSelection(Range{Start: 1, End: 2}) + editor.SetMarkedText("x\n", Range{}) + checkChange() + if !editor.CancelComposition() { + t.Fatal("legacy Cancel refused") + } + checkChange() + assertLFLabels(t, editor, []byte{'L'}) +} diff --git a/text/lf_labels_test.go b/text/lf_labels_test.go new file mode 100644 index 000000000..054b31fe0 --- /dev/null +++ b/text/lf_labels_test.go @@ -0,0 +1,259 @@ +package text + +import ( + "slices" + "strings" + "testing" +) + +func lfLabelPreserveReplacement(change LFLabelReplacement) []byte { + count := strings.Count(change.Inserted, "\n") + labels := make([]byte, count) + for index := range labels { + previous := len(change.Labels) - count + index + if previous >= 0 { + labels[index] = change.Labels[previous] + } else { + labels[index] = change.Default + } + } + return labels +} + +func assertLFLabels(t *testing.T, editor *Editor, want []byte) { + t.Helper() + got, ok := editor.LFLabels(nil) + if !ok || !slices.Equal(got, want) { + t.Fatalf("LF labels = %q, %t; want %q", got, ok, want) + } +} + +func TestLFLabelSeedOwnershipAndValidation(t *testing.T) { + editor := NewEditor("a\nb\n") + if labels, ok := editor.LFLabels(nil); ok || len(labels) != 0 { + t.Fatal("untracked editor reported LF labels") + } + if editor.TrackLFLabels([]byte{'W'}, 'W', nil) { + t.Fatal("wrong seed cardinality accepted") + } + seed := []byte{'W', 'L'} + if !editor.TrackLFLabels(seed, 'W', lfLabelPreserveReplacement) { + t.Fatal("valid LF labels refused") + } + seed[0] = 'M' + assertLFLabels(t, editor, []byte{'W', 'L'}) + got, _ := editor.LFLabels(nil) + got[0] = 'M' + assertLFLabels(t, editor, []byte{'W', 'L'}) + if editor.TrackLFLabels([]byte{'M', 'M'}, 'M', nil) { + t.Fatal("tracking replaced an existing label source") + } + if editor.SetLFLabels([]byte{'L'}, 'L') { + t.Fatal("wrong relabel cardinality accepted") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if editor.String() != "a\nb\n" || editor.CanUndo() || editor.CanRedo() { + t.Fatal("label setup changed text or history") + } + late := NewEditor("a\n") + late.Insert("!") + if late.TrackLFLabels([]byte{'L'}, 'L', nil) { + t.Fatal("tracking attached after untracked history already existed") + } + var absent *Editor + if _, ok := absent.LFLabels(nil); ok || absent.TrackLFLabels(nil, 0, nil) || absent.SetLFLabels(nil, 0) || absent.UnifyLFLabels(0) { + t.Fatal("nil editor accepted LF label state") + } +} + +func TestLFLabelSaveUndoAndIndependentInsertion(t *testing.T) { + editor := NewEditor("a\nb\nc\nd") + editor.SetSavePoint() + if !editor.TrackLFLabels([]byte{'W', 'L', 'M'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.ReplaceRange(Range{Start: 3, End: 4}, "") + assertLFLabels(t, editor, []byte{'W', 'M'}) + editor.SetSavePoint() + editor.ReplaceRange(Range{Start: 2, End: 2}, "new\n") + assertLFLabels(t, editor, []byte{'W', 'W', 'M'}) + editor.SetSavePoint() + if !editor.Undo() || editor.String() != "a\nbc\nd" { + t.Fatal("Undo insertion failed") + } + assertLFLabels(t, editor, []byte{'W', 'M'}) + if !editor.Undo() || editor.String() != "a\nb\nc\nd" { + t.Fatal("Undo deletion failed") + } + assertLFLabels(t, editor, []byte{'W', 'L', 'M'}) + if !editor.Redo() || !editor.Redo() || !editor.AtSavePoint() { + t.Fatal("Redo failed to recover the latest saved boundary") + } + assertLFLabels(t, editor, []byte{'W', 'W', 'M'}) +} + +func TestLFLabelEqualTextKeepsDistinctNewlineIdentity(t *testing.T) { + editor := NewEditor("a\nb\nc") + editor.SetSavePoint() + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.ReplaceRange(Range{End: editor.RuneCount()}, "a\nb\nc") + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Undo() || !editor.Redo() { + t.Fatal("equal-text replacement lost history") + } + editor.ReplaceRange(Range{Start: 3, End: 4}, "") + editor.ReplaceRange(Range{Start: 3, End: 3}, "\n") + if editor.String() != "a\nb\nc" { + t.Fatal("fixture no longer has equal visible text") + } + assertLFLabels(t, editor, []byte{'W', 'W'}) + if !editor.Undo() || !editor.Undo() { + t.Fatal("Undo separate deletion/insertion failed") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) +} + +func TestLFLabelMapperRunsOnlyOnActualForwardReplacement(t *testing.T) { + editor := NewEditor("a\nkeep\nc") + calls := 0 + mapper := func(change LFLabelReplacement) []byte { + calls++ + if change.Removed != "a\nkeep\nc" || change.Inserted != "a\nkeep\nz" || !slices.Equal(change.Labels, []byte{'W', 'L'}) || change.Default != 'W' { + t.Fatalf("mapper received wrong actual span: %+v", change) + } + return []byte{'W', 'L'} + } + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', mapper) { + t.Fatal("label setup failed") + } + editor.ReplaceRange(Range{End: editor.RuneCount()}, "a\nkeep\nz") + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Undo() || !editor.Redo() || calls != 1 { + t.Fatalf("history replay reran policy or lost the edit: mapper calls=%d", calls) + } + assertLFLabels(t, editor, []byte{'W', 'L'}) +} + +func TestLFLabelCurrentRelabelFollowsExistingRedoIdentity(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'L'}, 'L', nil) { + t.Fatal("label setup failed") + } + editor.MoveTo(editor.RuneCount(), false) + editor.Insert("\n") + if !editor.SetLFLabels([]byte{'W', 'M'}, 'W') { + t.Fatal("valid relabel refused") + } + assertLFLabels(t, editor, []byte{'W', 'M'}) + if !editor.Undo() || editor.CanUndo() { + t.Fatal("metadata relabel created another text Undo action") + } + assertLFLabels(t, editor, []byte{'W'}) + if !editor.Redo() { + t.Fatal("Redo failed") + } + assertLFLabels(t, editor, []byte{'W', 'M'}) + editor.MoveTo(editor.RuneCount(), false) + editor.Insert("\n") + assertLFLabels(t, editor, []byte{'W', 'M', 'W'}) +} + +func TestLFLabelUnifyIncludesReachableHistory(t *testing.T) { + editor := NewEditor("a\nb\nc\nd") + if !editor.TrackLFLabels([]byte{'W', 'L', 'M'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.ReplaceRange(Range{Start: 3, End: 4}, "") + if !editor.UnifyLFLabels('L') { + t.Fatal("uniform label request refused") + } + assertLFLabels(t, editor, []byte{'L', 'L'}) + if !editor.Undo() || editor.CanUndo() { + t.Fatal("uniform labels changed the text history boundary") + } + assertLFLabels(t, editor, []byte{'L', 'L', 'L'}) + if !editor.Redo() { + t.Fatal("Redo failed") + } + assertLFLabels(t, editor, []byte{'L', 'L'}) +} + +func TestLFLabelCoalescedDeletionKeepsMovedHistoryBacking(t *testing.T) { + editor := NewEditor("a\nb\nc") + if !editor.TrackLFLabels([]byte{'W', 'L'}, 'W', nil) { + t.Fatal("label setup failed") + } + editor.MoveTo(editor.RuneCount(), false) + for range 4 { + if !editor.DeleteBackward() { + t.Fatal("coalesced deletion failed") + } + } + assertLFLabels(t, editor, nil) + if !editor.Undo() || editor.String() != "a\nb\nc" || editor.CanUndo() { + t.Fatal("coalesced Undo did not restore its original unit") + } + assertLFLabels(t, editor, []byte{'W', 'L'}) + if !editor.Redo() || editor.String() != "a" { + t.Fatal("coalesced Redo failed") + } + assertLFLabels(t, editor, nil) +} + +func TestLFLabelPhysicalChangeRetainsEqualTextHistory(t *testing.T) { + editor := NewEditor("a\nb") + mapper := func(change LFLabelReplacement) []byte { return []byte{'L'} } + if !editor.TrackLFLabels([]byte{'W'}, 'W', mapper) { + t.Fatal("label setup failed") + } + editor.ReplaceRange(Range{End: editor.RuneCount()}, "a\nb") + assertLFLabels(t, editor, []byte{'L'}) + if !editor.Undo() || editor.String() != "a\nb" { + t.Fatal("physical change with equal text was not undoable") + } + assertLFLabels(t, editor, []byte{'W'}) + if !editor.Redo() { + t.Fatal("equal-text physical change lost Redo") + } + assertLFLabels(t, editor, []byte{'L'}) +} + +func TestLFLabelInvalidMapperPanicsBeforeMutation(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'W', func(LFLabelReplacement) []byte { return nil }) { + t.Fatal("label setup failed") + } + editor.SetSelection(Range{Start: 2, End: 0}) + selection, caret := editor.Selection(), editor.Caret() + panicked := false + func() { + defer func() { panicked = recover() != nil }() + editor.ReplaceRange(Range{Start: 2, End: 2}, "new\n") + }() + if !panicked || editor.String() != "a\nb" || editor.Selection() != selection || editor.Caret() != caret || editor.CanUndo() || editor.CanRedo() { + t.Fatal("invalid mapper changed the source before its contract was checked") + } + assertLFLabels(t, editor, []byte{'W'}) +} + +func TestLFLabelEqualReplacementRelabelKeepsPriorState(t *testing.T) { + editor := NewEditor("a\nb") + editor.SetSavePoint() + if !editor.TrackLFLabels([]byte{'W'}, 'W', lfLabelPreserveReplacement) { + t.Fatal("label setup failed") + } + editor.ReplaceRange(Range{End: editor.RuneCount()}, "a\nb") + if !editor.SetLFLabels([]byte{'L'}, 'L') { + t.Fatal("current relabel failed") + } + if !editor.Undo() { + t.Fatal("equal-text replacement lost Undo") + } + assertLFLabels(t, editor, []byte{'W'}) + if !editor.Redo() { + t.Fatal("equal-text replacement lost Redo") + } + assertLFLabels(t, editor, []byte{'L'}) +} diff --git a/text/line_journal.go b/text/line_journal.go index 4ca2a42f0..bbb9b425a 100644 --- a/text/line_journal.go +++ b/text/line_journal.go @@ -39,6 +39,7 @@ type lineJournal struct { batches map[*Edit][]lineContext position, line int delivery *lineDelivery + labels *lfLabelState } // TrackLineEdits enables optional LF context on the existing byte journal and @@ -73,7 +74,7 @@ func (editor *Editor) LineEditsSince(cursor uint64, dst []LineEdit) ([]LineEdit, } first := len(journal.entries) - int(journal.revision-cursor) for index := first; index < len(journal.entries); index++ { - position := (journal.oldest + index) % len(journal.entries) + position := (int(journal.oldest) + index) % len(journal.entries) context := journal.lines.entries[position] if context.flags&lineKnown == 0 { return dst[:0], journal.revision, false @@ -168,7 +169,7 @@ func (editor *Editor) recordLineContext(edit Edit, context lineContext) { journal := editor.journal lines := journal.lines lines.delivery = nil - position := (journal.oldest + len(journal.entries) - 1) % len(journal.entries) + position := (int(journal.oldest) + len(journal.entries) - 1) % len(journal.entries) if position == len(lines.entries) { lines.entries = append(lines.entries, context) } else { diff --git a/text/multi_replace.go b/text/multi_replace.go index 2646be7ac..05739afe6 100644 --- a/text/multi_replace.go +++ b/text/multi_replace.go @@ -22,8 +22,9 @@ type ReplaceRangesOptions struct { // retained by Undo/Redo. Nil keeps the default caret after the last target. AfterSelection *Range // ApplyUnchanged reports target primitives even when final text is equal. - // Without save-point mode equal text adds no Undo unit and preserves Redo. - // SetSavePoint opts into retaining those actual replacements in history. + // Without save-point or complete-history tracking, equal text and LF labels + // add no Undo unit and preserve Redo. Save points, complete history and + // pending LF labels retain actual replacements in history. ApplyUnchanged bool } @@ -70,8 +71,10 @@ func (editor *Editor) ValidateReplaceRanges(edits []Replacement, options Replace } // ReplaceRangesWith validates and applies a batch with optional primitive order -// and final selection. An empty batch is a no-op. Unchanged text is also a no-op -// unless ApplyUnchanged or save-point mode is enabled; otherwise final selection is unchanged. +// and final selection. An empty batch is a no-op. Unchanged text and LF labels +// are also a no-op unless ApplyUnchanged, save-point mode or complete history +// is enabled; +// otherwise final selection is unchanged. func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRangesOptions) error { if err := editor.ValidateReplaceRanges(edits, options); err != nil { return err @@ -89,6 +92,8 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang position := start runePosition, bytePosition := 0, 0 linePosition, lineShift := 0, 0 + labels := editor.lfLabelState() + var labelSpans []lfLabelSpan for _, edit := range edits { for runePosition < edit.Range.Start { if contexts != nil && editor.runes[runePosition] == '\n' { @@ -130,13 +135,29 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang context := makeLineContext(line, atLineStart, editor.runes[edit.Range.Start:edit.Range.End], inserted) contexts = append(contexts, context) lineShift += context.inserted - context.removed + if labels != nil && (context.removed != 0 || context.inserted != 0) { + labelSpans = append(labelSpans, lfLabelSpan{line: line, removed: editor.runes[edit.Range.Start:edit.Range.End], inserted: inserted}) + } } } replacement = append(replacement, inserted...) position = edit.Range.End } changed := !slices.Equal(replacement, editor.runes[start:end]) - if !changed && !options.ApplyUnchanged && editor.savePointIndex() == nil { + if !options.Forward { + slices.Reverse(labelSpans) + } + var labelPlan *lfLabelPlan + if len(labelSpans) != 0 { + var err error + labelPlan, err = labels.ops.batch(labels, labelSpans) + if err != nil { + return err + } + } + retained := len(primitives) > 0 && editor.retainEqualEdits() + if !changed && !options.ApplyUnchanged && !retained && editor.savePointIndex() == nil && (labelPlan == nil || !labelPlan.changed) { + labelPlan = nil return nil } if options.Forward { @@ -149,17 +170,38 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang slices.Reverse(primitives) slices.Reverse(contexts) } - editor.commitBatch(Range{Start: start, End: end}, string(replacement), primitives, contexts, options.AfterSelection) + editor.commitBatch(Range{Start: start, End: end}, string(replacement), primitives, contexts, options.AfterSelection, labelPlan) return nil } -func (editor *Editor) commitBatch(target Range, replacement string, primitives []Edit, contexts []lineContext, after *Range) { +func (editor *Editor) commitBatch(target Range, replacement string, primitives []Edit, contexts []lineContext, after *Range, labelPlan *lfLabelPlan) { target = normalizeRange(target, len(editor.runes)) + // Empty targets do not become primitives. Retain only the accepted backing + // in producer mode, including the line contexts keyed by that same slice. + if editor.historyState() != nil { + if cap(primitives) > len(primitives) { + retained := make([]Edit, len(primitives)) + copy(retained, primitives) + primitives = retained + } + if cap(contexts) > len(contexts) { + retained := make([]lineContext, len(contexts)) + copy(retained, contexts) + contexts = retained + } + } + // A batch leaves the one selection it names; the multi-selection paths + // reinstall their set after the call. + editor.clearSecondary() before := editor.selectionState() journal := editor.journal editor.journal = nil change := editor.replace(target, replacement, false) editor.journal = journal + if labelPlan != nil { + labels := editor.lfLabelState() + labels.ops.commit(labels, labelPlan) + } editor.collapse(target.Start + len(change.inserted)) editor.composing = false if after != nil { diff --git a/text/multiselection.go b/text/multiselection.go new file mode 100644 index 000000000..191f02120 --- /dev/null +++ b/text/multiselection.go @@ -0,0 +1,427 @@ +package text + +import ( + "sort" + "unicode/utf8" +) + +// Multi-selection, the model CodeMirror uses: one primary selection, which +// Selection and Caret report and every single-selection method acts on, plus +// any number of secondary ones. Selections never overlap: adding or setting a +// range that overlaps another merges the two, so an edit can be applied to +// every selection back to front without the ranges crossing. +// +// The secondary selections are editing state, not history. Typing or deleting +// keeps them, each becoming a caret after what it replaced, as in CodeMirror; +// moving the primary or editing the text another way ends with the primary +// alone, and Undo and Redo restore one selection. An editor that never calls +// AddSelection or SetSelections behaves exactly as it did before they existed. + +// SelectionCount returns how many selections there are, the primary included, +// so an editor without secondary selections reports one. +func (editor *Editor) SelectionCount() int { + return 1 + len(editor.secondary) +} + +// SelectionsInto copies every selection, the primary included, into dst, +// ordered by start and then by end, and returns the result. Pass a reused slice +// as dst to avoid an allocation: a paint calls it every frame. Selection +// reports which range is the primary one. +func (editor *Editor) SelectionsInto(dst []Range) []Range { + total := 1 + len(editor.secondary) + dst = dst[:0] + if cap(dst) < total { + dst = make([]Range, 0, total) + } + dst = append(dst, ordered(Range{Start: editor.anchor, End: editor.caret})) + for _, selection := range editor.secondary { + dst = append(dst, selection.rangeValue()) + } + // A handful of ranges: an insertion sort beats sort.Slice, and the common + // one-selection call only runs the outer loop once. + for i := 1; i < len(dst); i++ { + for j := i; j > 0; j-- { + left, right := dst[j-1], dst[j] + if left.Start < right.Start || left.Start == right.Start && left.End <= right.End { + break + } + dst[j-1], dst[j] = right, left + } + } + return dst +} + +// Selections returns every selection, the primary included, ordered by +// position. Selection reports the primary. It allocates; a paint uses +// SelectionsInto with its own scratch. +func (editor *Editor) Selections() []Range { + return editor.SelectionsInto(make([]Range, 0, 1+len(editor.secondary))) +} + +// SelectionSpansInto is SelectionsInto in the byte offsets String and +// components.CodeEditorSnapshot.SelectionRanges use, so a view paints every +// selection without converting them itself. The spans are ordered; a collapsed +// selection contributes an empty span, which paints nothing. The editor never +// lets selections overlap, so painting them in order is enough. Pass a reused +// dst to avoid an allocation. +func (editor *Editor) SelectionSpansInto(dst []Span) []Span { + dst = dst[:0] + if cap(dst) < 1+len(editor.secondary) { + dst = make([]Span, 0, 1+len(editor.secondary)) + } + dst = append(dst, editor.byteSpan(editor.Selection())) + for _, selection := range editor.secondary { + dst = append(dst, editor.byteSpan(selection.rangeValue())) + } + // Selections() is already ordered; keep its order, which byte offsets share. + for i := 1; i < len(dst); i++ { + for j := i; j > 0 && dst[j-1].Start > dst[j].Start; j-- { + dst[j-1], dst[j] = dst[j], dst[j-1] + } + } + return dst +} + +// SelectionSpans returns SelectionSpansInto's slice in a new allocation. +func (editor *Editor) SelectionSpans() []Span { + return editor.SelectionSpansInto(nil) +} + +func (editor *Editor) byteSpan(selection Range) Span { + return Span{Start: editor.ByteOffset(selection.Start), End: editor.ByteOffset(selection.End)} +} + +// AddSelection adds a selection and makes it the primary, as CodeMirror's add +// selection does, so the caret and the next movement are on the range just +// added. A range that overlaps an existing one merges with it and with every +// range it touches, and adding the selection the editor already has changes +// nothing. It reports whether the selection set changed. It ends an active +// composition, and does nothing while one is active: the input method owns the +// text until it commits. +func (editor *Editor) AddSelection(selection Range) bool { + if editor.composing { + return false + } + states := editor.selectionStates() + states = append(states, editorSelection{ + anchor: clamp(selection.Start, 0, len(editor.runes)), + caret: clamp(selection.End, 0, len(editor.runes)), + }) + merged, main := normalizeSelections(states, len(states)-1) + previous, _ := normalizeSelections(editor.selectionStates(), 0) + if sameRangeSet(merged, previous) { + return false + } + editor.installSelections(merged, main, true) + return true +} + +// ClearSecondarySelections drops every selection but the primary and reports +// whether there was one. It is what Escape does, and what anything that moves +// the primary or edits the text as one selection does implicitly. +func (editor *Editor) ClearSecondarySelections() bool { + if len(editor.secondary) == 0 { + return false + } + editor.clearSecondary() + editor.BreakUndoGroup() + return true +} + +// SetSelections replaces every selection. selections are ranges in any order +// and direction, and main is the index in that slice of the one that becomes +// primary; overlapping ranges merge, and the primary is the merged range its +// own became. Two identical ranges become one. An empty selections clears the +// secondary selections and leaves the primary where it is; a main outside +// selections changes nothing. Both report false. It ends an active composition, +// and does nothing while one is active. +func (editor *Editor) SetSelections(selections []Range, main int) bool { + if len(selections) == 0 { + editor.ClearSecondarySelections() + return false + } + if editor.composing || main < 0 || main >= len(selections) { + return false + } + states := make([]editorSelection, len(selections)) + for index, selection := range selections { + states[index] = editorSelection{ + anchor: clamp(selection.Start, 0, len(editor.runes)), + caret: clamp(selection.End, 0, len(editor.runes)), + } + } + merged, mergedMain := normalizeSelections(states, main) + editor.installSelections(merged, mergedMain, true) + return true +} + +// selectionStates is the whole selection set, primary first, as the editor +// keeps it: ordered and disjoint. +func (editor *Editor) selectionStates() []editorSelection { + states := make([]editorSelection, 0, 1+len(editor.secondary)) + states = append(states, editor.selectionState()) + return append(states, editor.secondary...) +} + +// installSelections installs a normalized set: states[main] is the primary and +// the rest are secondary, in the order normalizeSelections left them, which is +// by position. +func (editor *Editor) installSelections(states []editorSelection, main int, breakUndo bool) { + secondary := make([]editorSelection, 0, len(states)-1) + primary := states[main] + for index, selection := range states { + if index != main { + secondary = append(secondary, selection) + } + } + changed := editor.anchor != primary.anchor || editor.caret != primary.caret || !sameSelectionStates(editor.secondary, secondary) + if changed && breakUndo { + editor.BreakUndoGroup() + } + editor.anchor, editor.caret = primary.anchor, primary.caret + editor.secondary = append(editor.secondary[:0], secondary...) + editor.composing = false + editor.releaseCompositionHistory() +} + +// clearSecondary is the hot path's ClearSecondarySelections: no undo boundary, +// for the movements and edits that already break the group. +func (editor *Editor) clearSecondary() { + if len(editor.secondary) > 0 { + clear(editor.secondary) + editor.secondary = editor.secondary[:0] + } +} + +func (selection editorSelection) from() int { + if selection.anchor < selection.caret { + return selection.anchor + } + return selection.caret +} + +func (selection editorSelection) to() int { + if selection.anchor > selection.caret { + return selection.anchor + } + return selection.caret +} + +func (selection editorSelection) rangeValue() Range { + return Range{Start: selection.from(), End: selection.to()} +} + +func sameSelectionStates(left, right []editorSelection) bool { + if len(left) != len(right) { + return false + } + for index := range left { + if left[index] != right[index] { + return false + } + } + return true +} + +// sameRangeSet reports whether two normalized sets cover the same ranges, +// whatever their order in the slice and whichever is primary. +func sameRangeSet(left, right []editorSelection) bool { + if len(left) != len(right) { + return false + } + for index := range left { + if left[index].from() != right[index].from() || left[index].to() != right[index].to() { + return false + } + } + return true +} + +// normalizeSelections orders and merges states, and reports where the main +// selection ended up in the returned slice. Ranges that overlap or start at the +// same place become one union; a range that merged with nothing keeps the +// direction it was given, while a union is ordered. states is reused as the +// output's storage. +func normalizeSelections(states []editorSelection, main int) ([]editorSelection, int) { + type entry struct { + selection editorSelection + main bool + } + entries := make([]entry, len(states)) + for index, selection := range states { + entries[index] = entry{selection: selection, main: index == main} + } + sort.SliceStable(entries, func(i, j int) bool { + if entries[i].selection.from() != entries[j].selection.from() { + return entries[i].selection.from() < entries[j].selection.from() + } + return entries[i].selection.to() < entries[j].selection.to() + }) + merged := entries[:0] + mergedMain := 0 + for _, current := range entries { + if count := len(merged); count > 0 { + last := &merged[count-1] + if current.selection.from() < last.selection.to() || current.selection.from() == last.selection.from() { + if current.selection.to() > last.selection.to() { + last.selection.anchor, last.selection.caret = last.selection.from(), current.selection.to() + } else { + last.selection.anchor, last.selection.caret = last.selection.from(), last.selection.to() + } + last.main = last.main || current.main + if last.main { + mergedMain = count - 1 + } + continue + } + } + merged = append(merged, current) + if current.main { + mergedMain = len(merged) - 1 + } + } + out := states[:0] + for _, current := range merged { + out = append(out, current.selection) + } + return out, mergedMain +} + +// multiEdit is one replacement at one selection, in the original text's rune +// indices. +type multiEdit struct { + start, end int + text string +} + +// commitMultiEdits applies edits, sorted and disjoint, as one undo unit and +// leaves a caret after each inserted text, with edits[main] the primary. Going +// through ReplaceRangesWith means the text changes in one buffer replacement: +// no selection's offset is ever read after an earlier selection moved it. +func (editor *Editor) commitMultiEdits(edits []multiEdit, main int) bool { + replacements := make([]Replacement, len(edits)) + carets := make([]editorSelection, len(edits)) + shift := 0 + for index, edit := range edits { + inserted := utf8.RuneCountInString(edit.text) + replacements[index] = Replacement{Range: Range{Start: edit.start, End: edit.end}, Text: edit.text} + at := edit.start + shift + inserted + carets[index] = editorSelection{anchor: at, caret: at} + shift += inserted - (edit.end - edit.start) + } + after := carets[main].rangeValue() + if err := editor.ReplaceRangesWith(replacements, ReplaceRangesOptions{AfterSelection: &after}); err != nil { + return false + } + // ReplaceRangesWith is not a multi-selection caller: the secondary selection + // the batch cleared is restored here, normalized for merged carets. + states, main := normalizeSelections(carets, main) + editor.installSelections(states, main, false) + return true +} + +// multiInsert replaces every selection with value as one undo unit and leaves a +// caret after each copy of it. It reports whether it handled the edit: an +// overwriting or restricted editor keeps the primary alone, and a composition +// owns the text. +func (editor *Editor) multiInsert(value string) bool { + if len(editor.secondary) == 0 || editor.composing || editor.overwrite || editor.accept != nil || editor.maxRunes > 0 { + return false + } + ordered, main := orderedSelections(editor) + edits := make([]multiEdit, len(ordered)) + for index, selection := range ordered { + edits[index] = multiEdit{start: selection.from(), end: selection.to(), text: value} + } + return editor.commitMultiEdits(edits, main) +} + +// multiDelete removes what every selection covers, or the grapheme cluster +// before or after each collapsed selection, as one undo unit, and leaves one +// caret where each selection began. A caret never deletes through its +// neighbour. It reports whether it handled the edit. +func (editor *Editor) multiDelete(forward bool) bool { + // A restricted editor (a one-time code, a port) is single-line by + // construction and ReplaceRangesWith refuses it; the primary path deletes. + if len(editor.secondary) == 0 || editor.composing || editor.accept != nil || editor.maxRunes > 0 { + return false + } + ordered, main := orderedSelections(editor) + edits := make([]multiEdit, len(ordered)) + positions := make([]int, len(ordered)) + for index, selection := range ordered { + start, end := selection.from(), selection.to() + if start == end { + if forward { + limit := len(editor.runes) + if index+1 < len(ordered) { + limit = ordered[index+1].from() + } + end = min(nextBoundary(editor.runes, end), limit) + } else { + limit := 0 + if index > 0 { + limit = ordered[index-1].to() + } + start = max(previousBoundary(editor.runes, start), limit) + } + } + edits[index] = multiEdit{start: start, end: end} + positions[index] = start + } + // A caret with nothing left to delete keeps its place; ReplaceRangesWith + // takes only the real, ordered changes. positions maps every selection's + // start to where it lands once the deletions before it are applied. + kept := make([]multiEdit, 0, len(edits)) + caretPositions := make([]int, len(positions)) + shift := 0 + for index, edit := range edits { + caretPositions[index] = edit.start + shift + if edit.end > edit.start { + kept = append(kept, edit) + shift -= edit.end - edit.start + } + } + if len(kept) == 0 { + return false + } + replacements := make([]Replacement, len(kept)) + for index, edit := range kept { + replacements[index] = Replacement{Range: Range{Start: edit.start, End: edit.end}} + } + after := caretPositions[main] + selection := Range{Start: after, End: after} + if err := editor.ReplaceRangesWith(replacements, ReplaceRangesOptions{AfterSelection: &selection}); err != nil { + return false + } + carets := make([]editorSelection, len(caretPositions)) + for index, position := range caretPositions { + carets[index] = editorSelection{anchor: position, caret: position} + } + carets, main = normalizeSelections(carets, main) + editor.installSelections(carets, main, false) + return true +} + +// orderedSelections is the selection set ordered by position, with the index +// the primary ends up at. +func orderedSelections(editor *Editor) ([]editorSelection, int) { + states := editor.selectionStates() + primary := editor.selectionState() + ordered := make([]editorSelection, len(states)) + copy(ordered, states) + sort.SliceStable(ordered, func(i, j int) bool { + if ordered[i].from() != ordered[j].from() { + return ordered[i].from() < ordered[j].from() + } + return ordered[i].to() < ordered[j].to() + }) + main := 0 + for index, selection := range ordered { + if selection == primary { + main = index + break + } + } + return ordered, main +} diff --git a/text/multiselection_test.go b/text/multiselection_test.go new file mode 100644 index 000000000..0301eff8b --- /dev/null +++ b/text/multiselection_test.go @@ -0,0 +1,206 @@ +package text + +import "testing" + +func TestSelectionsStartAsThePrimaryAndAreOrdered(t *testing.T) { + editor := NewEditor("abcdef") + editor.SetSelection(Range{Start: 4, End: 5}) + if got := editor.SelectionCount(); got != 1 { + t.Fatalf("plain editor has %d selections, want 1", got) + } + if got := editor.Selections(); len(got) != 1 || got[0] != (Range{Start: 4, End: 5}) { + t.Fatalf("selections = %+v", got) + } + // Added ranges are ordered by position, wherever the primary is. + editor.AddSelection(Range{Start: 0, End: 1}) + editor.AddSelection(Range{Start: 3, End: 3}) + got := editor.Selections() + want := []Range{{Start: 0, End: 1}, {Start: 3, End: 3}, {Start: 4, End: 5}} + if len(got) != len(want) { + t.Fatalf("selections = %+v", got) + } + for index := range want { + if got[index] != want[index] { + t.Fatalf("selections = %+v, want %+v", got, want) + } + } + // The last one added is the primary: the caret and the next movement are on it. + if selection := editor.Selection(); selection != (Range{Start: 3, End: 3}) || editor.Caret() != 3 { + t.Fatalf("primary = %+v caret %d", selection, editor.Caret()) + } +} + +func TestAddSelectionMergesOverlapsAndIsIdempotent(t *testing.T) { + editor := NewEditor("abcdefgh") + editor.SetSelection(Range{Start: 0, End: 2}) + editor.AddSelection(Range{Start: 3, End: 5}) + // Overlapping the middle of nothing new: merges both into one union. + if !editor.AddSelection(Range{Start: 1, End: 4}) { + t.Fatal("an overlapping selection reported no change") + } + if got := editor.Selections(); len(got) != 1 || got[0] != (Range{Start: 0, End: 5}) { + t.Fatalf("merged selections = %+v", got) + } + if selection := editor.Selection(); selection != (Range{Start: 0, End: 5}) { + t.Fatalf("merged primary = %+v", selection) + } + if editor.AddSelection(Range{Start: 0, End: 5}) { + t.Fatal("adding the selection the editor has reported a change") + } + // Identical ranges on different boundaries stay separate. + editor.AddSelection(Range{Start: 7, End: 8}) + if got := editor.SelectionCount(); got != 2 { + t.Fatalf("selections = %+v", editor.Selections()) + } +} + +func TestSetSelectionsPicksThePrimaryAndClamps(t *testing.T) { + editor := NewEditor("abcdef") + if !editor.SetSelections([]Range{{Start: 5, End: 6}, {Start: 0, End: 1}, {Start: 2, End: 3}}, 0) { + t.Fatal("SetSelections reported no change") + } + if got := editor.Selections(); len(got) != 3 || got[0] != (Range{Start: 0, End: 1}) || got[2] != (Range{Start: 5, End: 6}) { + t.Fatalf("selections = %+v", got) + } + if selection := editor.Selection(); selection != (Range{Start: 5, End: 6}) { + t.Fatalf("primary = %+v, want the one main indexed", selection) + } + // Out of the text and out of order: clamped and ordered. + editor.SetSelections([]Range{{Start: 9, End: 99}, {Start: 3, End: 4}, {Start: 4, End: 9}}, 2) + if got := editor.Selections(); len(got) != 3 || got[0] != (Range{Start: 3, End: 4}) || got[2] != (Range{Start: 6, End: 6}) { + t.Fatalf("clamped selections = %+v", got) + } + // An overlap merges into the union, and the primary is that union. + editor.SetSelections([]Range{{Start: 2, End: 5}, {Start: 4, End: 6}, {Start: 0, End: 1}}, 1) + if got := editor.Selections(); len(got) != 2 || got[0] != (Range{Start: 0, End: 1}) || got[1] != (Range{Start: 2, End: 6}) { + t.Fatalf("merged selections = %+v", got) + } + if selection := editor.Selection(); selection != (Range{Start: 2, End: 6}) { + t.Fatalf("merged primary = %+v", selection) + } + // A bad main or an empty set changes nothing about the text and reports false. + if editor.SetSelections([]Range{{Start: 0, End: 1}}, 3) { + t.Fatal("an out-of-range main was accepted") + } + if editor.SetSelections(nil, 0) { + t.Fatal("an empty set reported a change") + } + if got := editor.SelectionCount(); got != 1 { + t.Fatalf("empty set left %d selections", got) + } +} + +func TestInsertAppliesToEverySelectionBackToFront(t *testing.T) { + // Three selections, deliberately given out of order, all get the text and the + // text stays consistent: the shifts of the later ones never move the earlier. + editor := NewEditor("0123456789") + editor.SetSelections([]Range{{Start: 7, End: 8}, {Start: 0, End: 1}, {Start: 3, End: 4}}, 2) + editor.Insert("X") + if got := editor.String(); got != "X12X456X89" { + t.Fatalf("text = %q", got) + } + if got := editor.Selections(); len(got) != 3 || got[0] != (Range{Start: 1, End: 1}) || got[1] != (Range{Start: 4, End: 4}) || got[2] != (Range{Start: 8, End: 8}) { + t.Fatalf("carets after insert = %+v", got) + } + // The primary was given as the third range, 3..4: its caret is the one at 4. + if editor.Caret() != 4 { + t.Fatalf("primary caret = %d, want 4", editor.Caret()) + } + // One undo unit restores all of it and leaves one selection. + if !editor.Undo() || editor.String() != "0123456789" || editor.SelectionCount() != 1 { + t.Fatalf("undo = %q, %d selections", editor.String(), editor.SelectionCount()) + } +} + +func TestInsertAtCollapsedCaretsAndRelativePositions(t *testing.T) { + editor := NewEditor("ab") + editor.SetSelections([]Range{{Start: 0, End: 0}, {Start: 1, End: 1}, {Start: 2, End: 2}}, 2) + editor.Insert("|") + if got := editor.String(); got != "|a|b|" { + t.Fatalf("text = %q", got) + } + if got := editor.Selections(); len(got) != 3 || got[0].Start != 1 || got[1].Start != 3 || got[2].Start != 5 { + t.Fatalf("carets = %+v", got) + } +} + +func TestMultiDeleteRemovesAtEverySelection(t *testing.T) { + editor := NewEditor("0123456789") + editor.SetSelections([]Range{{Start: 0, End: 1}, {Start: 4, End: 5}, {Start: 8, End: 9}}, 0) + if !editor.DeleteForward() { + t.Fatal("DeleteForward reported nothing to delete") + } + if got := editor.String(); got != "1235679" { + t.Fatalf("text = %q", got) + } + // The carets are where each deletion began, then in order. + if got := editor.Selections(); len(got) != 3 || got[0].Start != 0 || got[1].Start != 3 || got[2].Start != 6 { + t.Fatalf("carets = %+v", got) + } + // Backspace at carets removes the cluster before each, capped by its neighbour. + editor = NewEditor("abc") + editor.SetSelections([]Range{{Start: 1, End: 1}, {Start: 2, End: 2}, {Start: 3, End: 3}}, 2) + if !editor.DeleteBackward() || editor.String() != "" { + t.Fatalf("backspace at carets = %q", editor.String()) + } + if got := editor.SelectionCount(); got != 1 { + t.Fatalf("carets all collapsed to one: %d selections", got) + } + if !editor.Undo() || editor.String() != "abc" { + t.Fatalf("undo = %q", editor.String()) + } +} + +func TestMultiDeleteDeletesOncePerCaretWithoutCrossing(t *testing.T) { + // Two carets one apart: the first deletes only the rune between them. + editor := NewEditor("abc") + editor.SetSelections([]Range{{Start: 0, End: 0}, {Start: 1, End: 1}}, 0) + if !editor.DeleteForward() || editor.String() != "c" { + t.Fatalf("text = %q", editor.String()) + } + // Backspace stops at the previous caret rather than deleting through it. + editor = NewEditor("abc") + editor.SetSelections([]Range{{Start: 1, End: 1}, {Start: 2, End: 2}}, 0) + if !editor.DeleteBackward() || editor.String() != "c" { + t.Fatalf("backspace text = %q", editor.String()) + } + // Two carets a rune apart at either end delete the two outer runes, once each. + editor = NewEditor("abc") + editor.SetSelections([]Range{{Start: 1, End: 1}, {Start: 3, End: 3}}, 1) + if !editor.DeleteBackward() || editor.String() != "b" { + t.Fatalf("spaced backspace text = %q", editor.String()) + } +} + +func TestMovementsAndClearSecondaryReturnToOneSelection(t *testing.T) { + editor := NewEditor("abcdef") + editor.SetSelections([]Range{{Start: 0, End: 1}, {Start: 3, End: 2}}, 1) + if !editor.ClearSecondarySelections() { + t.Fatal("ClearSecondarySelections reported nothing to clear") + } + if editor.SelectionCount() != 1 || editor.Selection() != (Range{Start: 2, End: 3}) { + t.Fatalf("after clear: %+v", editor.Selections()) + } + editor.SetSelections([]Range{{Start: 0, End: 1}, {Start: 4, End: 4}}, 1) + editor.MoveLeft(false) + if editor.SelectionCount() != 1 { + t.Fatalf("a movement kept %d selections", editor.SelectionCount()) + } + editor.SetSelections([]Range{{Start: 0, End: 1}, {Start: 4, End: 4}}, 1) + editor.SetSelection(Range{Start: 2, End: 2}) + if editor.SelectionCount() != 1 { + t.Fatalf("SetSelection kept %d selections", editor.SelectionCount()) + } +} + +func TestSelectionsIntoReusesItsScratch(t *testing.T) { + editor := NewEditor("abcd") + editor.SetSelections([]Range{{Start: 0, End: 1}, {Start: 3, End: 4}}, 1) + dst := make([]Range, 0, 4) + if allocations := testing.AllocsPerRun(100, func() { dst = editor.SelectionsInto(dst) }); allocations != 0 { + t.Fatalf("SelectionsInto allocated %v times with a reused scratch", allocations) + } + if len(dst) != 2 { + t.Fatalf("selections = %+v", dst) + } +} diff --git a/text/multiselection_verbs_test.go b/text/multiselection_verbs_test.go new file mode 100644 index 000000000..3349bf090 --- /dev/null +++ b/text/multiselection_verbs_test.go @@ -0,0 +1,116 @@ +package text + +import "testing" + +// CodeMirror's add-next-occurrence and select-all-occurrences are built from +// SetSelections and the word range: this is the shape DBX's two commands take. + +// occurrenceWord is the word around the primary selection, or the selection +// itself when it already reaches beyond a word. +func occurrenceWord(editor *Editor) (Range, bool) { + selection := editor.Selection() + if selection.Start != selection.End { + return selection, true + } + word := WordRange(editor.String(), selection.Start) + if editor.ByteOffset(word.Start) == editor.ByteOffset(word.End) { + return Range{}, false + } + return word, true +} + +// selectNextOccurrence adds the next occurrence after the last selection, +// wrapping to the first, without overlapping an existing one. +func selectNextOccurrence(editor *Editor) bool { + word, ok := occurrenceWord(editor) + if !ok { + return false + } + value := editor.String() + start := editor.ByteOffset(word.End) + seen := make(map[int]bool) + for _, selection := range editor.Selections() { + seen[editor.ByteOffset(selection.Start)] = true + } + for attempts := 0; attempts <= len(value)+1; attempts++ { + from := start + if from >= len(value) { + from = 0 + } + index := indexOf(value, editor.String()[editor.ByteOffset(word.Start):editor.ByteOffset(word.End)], from) + if index < 0 { + if from == 0 { + return false + } + start = 0 + continue + } + candidate := Range{ + Start: editor.RuneIndex(index), + End: editor.RuneIndex(index + editor.ByteOffset(word.End) - editor.ByteOffset(word.Start)), + } + start = index + 1 + if seen[index] { + continue + } + selections := editor.Selections() + return editor.SetSelections(append(selections, candidate), len(selections)) + } + return false +} + +func indexOf(value, needle string, from int) int { + if from > len(value) { + return -1 + } + for at := from; at+len(needle) <= len(value); at++ { + if value[at:at+len(needle)] == needle { + return at + } + } + return -1 +} + +func TestSelectNextOccurrenceAddsEveryCopyOfTheWord(t *testing.T) { + editor := NewEditor("name name other name") + editor.SetSelection(Range{Start: 0, End: 4}) + if !selectNextOccurrence(editor) { + t.Fatal("the second occurrence was not found") + } + if got := editor.Selections(); len(got) != 2 || got[1] != (Range{Start: 5, End: 9}) { + t.Fatalf("selections = %+v", got) + } + if editor.Selection() != (Range{Start: 5, End: 9}) { + t.Fatalf("the new occurrence is not primary: %+v", editor.Selection()) + } + if !selectNextOccurrence(editor) { + t.Fatal("the third occurrence was not found") + } + if got := editor.Selections(); len(got) != 3 || got[2] != (Range{Start: 16, End: 20}) { + t.Fatalf("selections = %+v", got) + } + // Typing replaces all three and leaves three carets, as CodeMirror does. + editor.Insert("X") + if got := editor.String(); got != "X X other X" { + t.Fatalf("text = %q", got) + } + if got := editor.SelectionCount(); got != 3 { + t.Fatalf("carets after typing = %d", got) + } + if !editor.Undo() || editor.String() != "name name other name" { + t.Fatalf("undo = %q", editor.String()) + } +} + +func TestOccurrenceWordFallsBackToTheCaretWord(t *testing.T) { + editor := NewEditor("host.example.com") + editor.SetSelection(Range{Start: 5, End: 5}) + word, ok := occurrenceWord(editor) + if !ok || word != (Range{Start: 5, End: 12}) { + t.Fatalf("word = %+v, %v", word, ok) + } + editor.SetSelection(Range{Start: 0, End: 4}) + if word, _ := occurrenceWord(editor); word != (Range{Start: 0, End: 4}) { + t.Fatalf("an existing selection was not used: %+v", word) + } +} diff --git a/text/savepoint.go b/text/savepoint.go index 12f8f1e07..dc90c04fd 100644 --- a/text/savepoint.go +++ b/text/savepoint.go @@ -11,6 +11,9 @@ func (editor *Editor) SetSavePoint() { editor.journal.savePoint = new(int) } *editor.journal.savePoint = editor.historyIndex + if history := editor.historyState(); history != nil { + history.ops.save(history) + } editor.BreakUndoGroup() } @@ -27,3 +30,22 @@ func (editor *Editor) savePointIndex() *int { } return editor.journal.savePoint } + +// ClearChangeHistory drops Undo/Redo without making unsaved data clean. Unlike +// ClearHistory, a previously unsaved save boundary remains unreachable. +func (editor *Editor) ClearChangeHistory() { + point := editor.savePointIndex() + dirty := point != nil && !editor.AtSavePoint() + if history := editor.historyState(); history != nil { + dirty = dirty || history.save < 0 || history.current != history.save + } + editor.ClearHistory() + if dirty { + if point != nil { + *point = -1 + } + if history := editor.historyState(); history != nil { + history.save = -1 + } + } +} diff --git a/text/tentative_core_bench_test.go b/text/tentative_core_bench_test.go new file mode 100644 index 000000000..6b91736ae --- /dev/null +++ b/text/tentative_core_bench_test.go @@ -0,0 +1,53 @@ +package text + +import ( + "strings" + "testing" +) + +var tentativeCoreEditorSink *Editor +var tentativeCoreFramesSink []HistoryFrame + +func BenchmarkTentativeCoreWorkflow(b *testing.B) { + for _, history := range []bool{false, true} { + name := "physical" + if history { + name = "with-history" + } + b.Run(name, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + editor := NewEditor("abc") + var cursor HistoryCursor + if history { + cursor, _, _ = editor.TrackHistory() + } + editor.EnableTentativeComposition() + editor.MoveTo(1, false) + editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: "x"}) + editor.ApplyComposition(CompositionEvent{Phase: CompositionResult, Text: "yz"}) + editor.Undo() + editor.Redo() + if history { + tentativeCoreFramesSink, _, _ = editor.HistorySince(cursor) + } + tentativeCoreEditorSink = editor + } + }) + } +} + +func BenchmarkTentativeCoreLargeOverwrite(b *testing.B) { + value, marked := strings.Repeat("a", 2049), strings.Repeat("z", 2049) + b.ReportAllocs() + for b.Loop() { + editor := NewEditor(value) + editor.TrackHistory() + editor.SetOverwrite(true) + editor.MoveTo(0, false) + editor.EnableTentativeComposition() + editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: marked}) + editor.ApplyComposition(CompositionEvent{Phase: CompositionCancel}) + tentativeCoreEditorSink = editor + } +} diff --git a/text/tentative_core_test.go b/text/tentative_core_test.go new file mode 100644 index 000000000..b8f3f3aea --- /dev/null +++ b/text/tentative_core_test.go @@ -0,0 +1,655 @@ +package text + +import ( + "reflect" + "runtime" + "strings" + "testing" + "unsafe" +) + +func enableTentativeCore(t *testing.T, editor *Editor) { + t.Helper() + if !editor.EnableTentativeComposition() || !editor.TentativeCompositionEnabled() { + t.Fatal("fresh editor refused tentative composition") + } +} + +func applyTentativeCore(t *testing.T, editor *Editor, event CompositionEvent) { + t.Helper() + if !editor.ApplyComposition(event) { + t.Fatalf("event refused: %+v", event) + } +} + +func TestTentativeCoreSelectedCancelKeepsOrdinaryDeletion(t *testing.T) { + editor := NewEditor("abc") + from := mustTrackHistory(t, editor) + enableTentativeCore(t, editor) + editor.SetSelection(Range{Start: 1, End: 2}) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "x", Selected: Range{End: 1}}) + if editor.String() != "axc" || editor.CommittedString() != "ac" || !editor.CompositionActive() { + t.Fatal("selected tentative lost its ordinary deletion or committed view") + } + from = expectHistoryFrames(t, editor, from, []HistoryStep{ + {HistoryForward, HistoryDelete, 1, 1, 3, 2, historySample(1, 0, -1, 1)}, + {HistoryForward, HistoryInsert, 1, 1, 2, 3, historySample(2, 0, -1, 2)}, + }) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCancel}) + if editor.String() != "ac" || editor.CompositionActive() || editor.CanRedo() { + t.Fatal("Cancel restored ordinary selected text or retained tentative Redo") + } + from = expectHistoryFrames(t, editor, from, []HistoryStep{{HistoryUndo, HistoryDelete, 1, 1, 3, 2, historySample(2, 0, -1, 2)}}) + if !editor.Undo() || editor.String() != "abc" || editor.CanUndo() { + t.Fatal("ordinary deletion is not the one remaining Undo unit") + } + expectHistoryFrames(t, editor, from, []HistoryStep{{HistoryUndo, HistoryInsert, 1, 1, 2, 3, historySample(1, 0, -1, 1)}}) +} + +func TestTentativeCoreUTF16ReplacementAfterRollback(t *testing.T) { + editor := NewEditor("\U0001f600bc") + from := mustTrackHistory(t, editor) + enableTentativeCore(t, editor) + editor.SetSelection(Range{Start: 1, End: 2}) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "x"}) + from = expectHistoryFrames(t, editor, from, []HistoryStep{ + {HistoryForward, HistoryDelete, 4, 1, 6, 5, historySample(1, 0, -1, 1)}, + {HistoryForward, HistoryInsert, 4, 1, 5, 6, historySample(2, 0, -1, 2)}, + }) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionResult, Text: "r", HasReplacementUTF16: true, ReplacementUTF16: UTF16Range{Start: 0, Length: 2}}) + if editor.String() != "rc" || editor.CompositionActive() { + t.Fatal("raw UTF16 replacement was not applied to the rolled-back buffer") + } + expectHistoryFrames(t, editor, from, []HistoryStep{ + {HistoryUndo, HistoryDelete, 4, 1, 6, 5, historySample(2, 0, -1, 2)}, + {HistoryForward, HistoryDelete, 0, 4, 5, 1, historySample(2, 0, -1, 2)}, + {HistoryForward, HistoryInsert, 0, 1, 1, 2, historySample(3, 0, -1, 3)}, + }) + for _, want := range []string{"c", "\U0001f600c", "\U0001f600bc"} { + if !editor.Undo() || editor.String() != want { + t.Fatalf("Result Undo = %q; want %q", editor.String(), want) + } + } +} + +func TestTentativeCoreOverwriteUnitsAndLiveModeToggle(t *testing.T) { + editor := NewEditor("a\u00e9b\nc") + from := mustTrackHistory(t, editor) + editor.SetOverwrite(true) + enableTentativeCore(t, editor) + editor.MoveTo(1, false) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionResult, Text: "XY"}) + if editor.String() != "aXY\nc" { + t.Fatal("overwrite did not consume one code point per scalar") + } + expectHistoryFrames(t, editor, from, []HistoryStep{ + {HistoryForward, HistoryDelete, 1, 2, 6, 4, historySample(1, 0, -1, 1)}, + {HistoryForward, HistoryInsert, 1, 1, 4, 5, historySample(2, 0, -1, 2)}, + {HistoryForward, HistoryDelete, 2, 1, 5, 4, historySample(3, 0, -1, 3)}, + {HistoryForward, HistoryInsert, 2, 1, 4, 5, historySample(4, 0, -1, 4)}, + }) + for _, want := range []string{"aXb\nc", "a\u00e9b\nc"} { + if !editor.Undo() || editor.String() != want { + t.Fatalf("scalar Undo = %q; want %q", editor.String(), want) + } + } + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "x"}) + if editor.CommittedString() != "a\u00e9b\nc" { + t.Fatal("committed view lost overwritten source text") + } + editor.SetOverwrite(false) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "yz"}) + if editor.String() != "ayz\u00e9b\nc" || editor.CommittedString() != "a\u00e9b\nc" { + t.Fatal("mode toggle changed rollback or the next insertion-mode update") + } + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCancel}) + if editor.String() != "a\u00e9b\nc" || editor.CanUndo() || editor.CanRedo() { + t.Fatal("Cancel retained tentative or discarded old Redo incorrectly") + } +} + +func TestTentativeCoreCommitAndEmptyCommit(t *testing.T) { + for _, phase := range []CompositionPhase{CompositionCommit, CompositionCancel, CompositionEmptyCommit} { + t.Run(string(rune('0'+phase)), func(t *testing.T) { + editor := NewEditor("abc") + from := mustTrackHistory(t, editor) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "x"}) + _, from, _ = editor.HistorySince(from) + applyTentativeCore(t, editor, CompositionEvent{Phase: phase}) + if editor.CompositionActive() { + t.Fatal("terminal event left live rollback ownership") + } + if phase == CompositionCommit { + if editor.String() != "abcx" || !editor.CanUndo() { + t.Fatal("Commit lost its visible ordinary unit") + } + expectHistoryFrames(t, editor, from) + if !editor.Undo() || editor.String() != "abc" { + t.Fatal("committed tentative was not Undoable") + } + } else if editor.String() != "abc" || editor.CanUndo() || editor.CanRedo() { + t.Fatal("rollback terminal event retained tentative units") + } + }) + } + editor := NewEditor("abc") + enableTentativeCore(t, editor) + editor.SetSelection(Range{Start: 1, End: 2}) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionResult}) + if editor.String() != "abc" || editor.Selection() != (Range{Start: 1, End: 2}) || editor.CanUndo() { + t.Fatal("empty implicit Result deleted its selection") + } + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionEmptyCommit}) + if editor.String() != "ac" || !editor.Undo() || editor.String() != "abc" { + t.Fatal("inactive EmptyCommit did not retain ordinary selection deletion") + } +} + +func TestTentativeCoreRefusalPreservesLiveSource(t *testing.T) { + editor := NewEditor("abc") + from := mustTrackHistory(t, editor) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "x", Selected: Range{End: 1}}) + before, _, _ := editor.HistorySince(from) + selection, caret := editor.Selection(), editor.Caret() + for _, event := range []CompositionEvent{ + {Phase: CompositionNone}, + {Phase: CompositionResult, Text: "\xff"}, + {Phase: CompositionResult, Text: "q", HasReplacementUTF16: true, ReplacementUTF16: UTF16Range{Start: -1}}, + {Phase: CompositionUpdate, Text: "q", HasReplacement: true, Replacement: Range{End: 1}}, + } { + if editor.ApplyComposition(event) { + t.Fatalf("invalid event handled: %+v", event) + } + after, _, ok := editor.HistorySince(from) + if !ok || editor.String() != "abcx" || editor.Selection() != selection || editor.Caret() != caret || !editor.CompositionActive() || !reflect.DeepEqual(before, after) { + t.Fatal("refusal partially changed live text, selection, ownership or frames") + } + } + if editor.DisableTentativeComposition() { + t.Fatal("active Disable stranded rollback ownership") + } + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCancel}) + if !editor.DisableTentativeComposition() || editor.TentativeCompositionEnabled() || !editor.DisableTentativeComposition() { + t.Fatal("inactive Disable is not idempotent") + } +} + +func TestTentativeCoreCopiedReceiverCannotMutateOwner(t *testing.T) { + editor := NewEditor("abc") + enableTentativeCore(t, editor) + copy := *editor + if copy.EnableTentativeComposition() || copy.TentativeCompositionEnabled() || copy.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: "x"}) || copy.DisableTentativeComposition() { + t.Fatal("copied receiver borrowed another editor's capability") + } + if editor.String() != "abc" || editor.CompositionActive() || !editor.TentativeCompositionEnabled() { + t.Fatal("foreign capability operation changed its actual owner") + } +} + +func TestTentativeCoreNewUpdateAfterUndoOwnsCurrentBoundary(t *testing.T) { + editor := NewEditor("abc") + from := mustTrackHistory(t, editor) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionResult, Text: "x"}) + if !editor.Undo() || editor.String() != "abc" || !editor.CanRedo() { + t.Fatal("fixture did not create a Redo suffix") + } + _, from, _ = editor.HistorySince(from) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "y"}) + if editor.String() != "abcy" || editor.CommittedString() != "abc" || editor.CanRedo() { + t.Fatalf("new tentative after Undo = %q, committed %q, Redo %t", editor.String(), editor.CommittedString(), editor.CanRedo()) + } + from = expectHistoryFrames(t, editor, from, []HistoryStep{{HistoryForward, HistoryInsert, 3, 1, 3, 4, historySample(1, 0, -1, 1)}}) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCancel}) + if editor.String() != "abc" || editor.CanUndo() || editor.CanRedo() || editor.CompositionActive() { + t.Fatal("Cancel did not remove the new suffix from its actual current boundary") + } + expectHistoryFrames(t, editor, from, []HistoryStep{{HistoryUndo, HistoryDelete, 3, 1, 4, 3, historySample(1, 0, -1, 1)}}) +} + +func TestTentativeCoreSharedHeaderChargedOnce(t *testing.T) { + for _, historyFirst := range []bool{false, true} { + t.Run(map[bool]string{false: "composition-first", true: "history-first"}[historyFirst], func(t *testing.T) { + editor := NewEditor("abc") + if historyFirst { + mustTrackHistory(t, editor) + } + enableTentativeCore(t, editor) + shared := int(unsafe.Sizeof(editorSidecar{})) / 4 + composition := int(unsafe.Sizeof(compositionState{})) / 4 + history := int(unsafe.Sizeof(historyJournal{})) / 4 + want := shared + composition + if historyFirst { + want += history + } + if editor.historyCost() != want { + t.Fatalf("first capability headers charged %d; retained headers %d", editor.historyCost(), want) + } + if !historyFirst { + mustTrackHistory(t, editor) + } + want = shared + composition + history + if editor.historyCost() != want { + t.Fatalf("joint headers charged %d; retained headers %d", editor.historyCost(), want) + } + editor.ClearHistory() + if editor.historyCost() != want { + t.Fatal("idle Clear duplicated or lost a retained header charge") + } + if !editor.DisableTentativeComposition() || editor.historyCost() != shared+history { + t.Fatal("Disable did not release only composition-owned storage") + } + }) + } +} + +func TestTentativeCorePhysicalPreflightIncludesSharedHeader(t *testing.T) { + editor := NewEditor("") + enableTentativeCore(t, editor) + state := editor.compositionState() + unitAndOwner := int(unsafe.Sizeof(historyEdit{})+unsafe.Sizeof(compositionState{})) / 4 + plan := compositionPlan{units: 1, payload: maxSingleEditRunes - unitAndOwner} + if editor.compositionPlanFits(state, plan) { + t.Fatal("physical preflight accepted a plan whose shared header exceeds the bound") + } + plan.payload -= int(unsafe.Sizeof(editorSidecar{})) / 4 + if !editor.compositionPlanFits(state, plan) { + t.Fatal("physical preflight refused the exact retained-capacity bound") + } +} + +func TestTentativeCoreLargeOverwriteFrameAndPassiveRetention(t *testing.T) { + const count = 2049 + editor := NewEditor(strings.Repeat("a", count)) + from := mustTrackHistory(t, editor) + editor.SetOverwrite(true) + editor.MoveTo(0, false) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: strings.Repeat("z", count)}) + frames, latest, ok := editor.HistorySince(from) + if !ok || len(frames) != 1 || len(frames[0].Steps) != 2*count || len(editor.history) != count { + t.Fatal("large overwrite lost complete frame delivery or scalar units") + } + for index := range count { + wantDelete := HistoryStep{HistoryForward, HistoryDelete, index, 1, count, count - 1, historySample(2*index+1, 0, -1, 2*index+1)} + wantInsert := HistoryStep{HistoryForward, HistoryInsert, index, 1, count - 1, count, historySample(2*index+2, 0, -1, 2*index+2)} + if frames[0].Steps[2*index] != wantDelete || frames[0].Steps[2*index+1] != wantInsert { + t.Fatalf("scalar %d does not preserve its delete/insert sample timing", index) + } + unit := &editor.history[index] + if cap(unit.removed) != 1 || cap(unit.inserted) != 1 { + t.Fatal("scalar unit retains uncharged source-buffer or allocator slack") + } + } + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCommit}) + if !editor.DisableTentativeComposition() || editor.TentativeCompositionEnabled() { + t.Fatal("completed Disable failed") + } + editor.SetSelection(Range{}) + editor.Insert("") + if len(editor.history) != count || !editor.DisableTentativeComposition() { + t.Fatal("selection/no-op/repeated Disable retired complete physical work") + } + expectHistoryFrames(t, editor, latest) + if !editor.Undo() || editor.String() != strings.Repeat("z", count-1)+"a" || !editor.Redo() { + t.Fatal("passive completed action lost ordinary Undo/Redo") + } + state := editor.compositionState() + minimum := (cap(editor.history) - maxHistoryEntries) * int(unsafe.Sizeof(historyEdit{})) / 4 + minimum += int(unsafe.Sizeof(compositionState{})) / 4 + if state == nil || state.cost < minimum { + t.Fatal("retiring protection dropped ownership of retained extra capacity") + } + editor.Insert("q") + if len(editor.history) != maxHistoryEntries || cap(editor.history) != maxHistoryEntries || editor.compositionState() != nil { + t.Fatal("ordinary mutation did not settle and release retired composition storage") + } + if frames, _, ok := editor.HistorySince(from); ok || frames != nil { + t.Fatal("unprovable ordinary trim served a complete-looking suffix") + } +} + +func TestTentativeCoreMetadataLossKeepsPhysicalCancel(t *testing.T) { + const count = 60000 + value := strings.Repeat("a", count) + editor := NewEditor(value) + from := mustTrackHistory(t, editor) + editor.SetOverwrite(true) + editor.MoveTo(0, false) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "z"}) + before, _, _ := editor.HistorySince(from) + selection, caret := editor.Selection(), editor.Caret() + text := editor.String() + if editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: strings.Repeat("q", 140000)}) { + t.Fatal("over-budget physical event was accepted") + } + after, _, ok := editor.HistorySince(from) + if !ok || editor.String() != text || editor.Selection() != selection || editor.Caret() != caret || !reflect.DeepEqual(before, after) { + t.Fatal("hard preflight refusal rolled back or changed the old live event") + } + var allocatedBefore, allocatedAfter runtime.MemStats + runtime.ReadMemStats(&allocatedBefore) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: strings.Repeat("z", count)}) + runtime.ReadMemStats(&allocatedAfter) + allocated := allocatedAfter.TotalAlloc - allocatedBefore.TotalAlloc + t.Logf("60000-unit replacement allocated %d bytes", allocated) + if allocated > 256<<20 { + t.Fatalf("metadata-only exhaustion allocated %d bytes for a linear-size event", allocated) + } + if editor.String() != strings.Repeat("z", count) || editor.CommittedString() != value || len(editor.history) != count { + t.Fatal("metadata exhaustion destroyed accepted physical work") + } + if frames, _, ok := editor.HistorySince(from); ok || frames != nil { + t.Fatal("metadata exhaustion served a partial atomic frame") + } + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCancel}) + if editor.String() != value || editor.CanUndo() || editor.CanRedo() || editor.CompositionActive() { + t.Fatal("metadata loss stranded the physical rollback boundary") + } +} + +func TestTentativeCoreOverwriteCodePointsAndLineEnds(t *testing.T) { + for _, test := range []struct { + name, initial, inserted, want string + caret int + }{ + {"base-before-combining", "a\u0301b", "X", "X\u0301b", 0}, + {"combining-code-point", "a\u0301b", "X", "aXb", 1}, + {"astral-code-point", "a\U0001f600b", "X", "aXb", 1}, + {"crlf", "ab\r\ncd", "XY", "abXY\r\ncd", 2}, + {"lf", "ab\ncd", "XY", "abXY\ncd", 2}, + {"end", "ab", "XY", "abXY", 2}, + } { + t.Run(test.name, func(t *testing.T) { + editor := NewEditor(test.initial) + editor.SetOverwrite(true) + editor.MoveTo(test.caret, false) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: test.inserted}) + if editor.String() != test.want || editor.CommittedString() != test.initial { + t.Fatalf("overwrite = %q, committed %q; want %q/%q", editor.String(), editor.CommittedString(), test.want, test.initial) + } + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCancel}) + if editor.String() != test.initial || editor.CanUndo() { + t.Fatal("code-point/line-end rollback did not restore source") + } + }) + } +} + +func TestTentativeCoreRawUTF16BoundaryPolicy(t *testing.T) { + for _, test := range []struct { + name string + raw UTF16Range + want string + }{ + {"split-start", UTF16Range{Start: 1}, "\U0001f600aX"}, + {"split-end", UTF16Range{Length: 1}, "X"}, + {"huge-relative-length", UTF16Range{Start: 2, Length: int(^uint(0) >> 1)}, "\U0001f600X"}, + {"huge-start", UTF16Range{Start: int(^uint(0) >> 1), Length: int(^uint(0) >> 1)}, "\U0001f600aX"}, + } { + t.Run(test.name, func(t *testing.T) { + editor := NewEditor("\U0001f600a") + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionResult, Text: "X", HasReplacementUTF16: true, ReplacementUTF16: test.raw}) + if editor.String() != test.want { + t.Fatalf("UTF16 replacement = %q; want %q", editor.String(), test.want) + } + for editor.Undo() { + } + if editor.String() != "\U0001f600a" { + t.Fatal("UTF16 replacement lost ordinary Undo units") + } + }) + } +} + +func TestTentativeCoreLegacyCommandsRetireRollback(t *testing.T) { + for _, test := range []struct { + name string + apply func(*Editor) + }{ + {"replace-range", func(editor *Editor) { editor.ReplaceRange(Range{End: 1}, "q") }}, + {"selection", func(editor *Editor) { editor.SetSelection(Range{}) }}, + {"move", func(editor *Editor) { editor.MoveTo(0, false) }}, + {"unmark", func(editor *Editor) { editor.Unmark() }}, + {"insert", func(editor *Editor) { editor.Insert("r") }}, + {"paste", func(editor *Editor) { editor.Paste("r") }}, + {"backspace", func(editor *Editor) { editor.DeleteBackward() }}, + {"delete", func(editor *Editor) { editor.DeleteForward() }}, + {"word", func(editor *Editor) { editor.DeleteWord(false) }}, + {"line", func(editor *Editor) { editor.DeleteToLineBoundary(false) }}, + } { + t.Run(test.name, func(t *testing.T) { + editor, legacy := NewEditor("abc"), NewEditor("abc") + from := mustTrackHistory(t, editor) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: "x"}) + legacy.SetMarkedText("x", Range{}) + test.apply(editor) + test.apply(legacy) + if editor.String() != legacy.String() || editor.Selection() != legacy.Selection() || editor.CanUndo() != legacy.CanUndo() || editor.CanRedo() != legacy.CanRedo() { + t.Fatal("direct legacy command changed the established visible or ordinary history behavior") + } + if editor.CompositionActive() || editor.CancelComposition() { + t.Fatal("direct legacy command left a stale owned rollback boundary") + } + if frames, _, ok := editor.HistorySince(from); ok || frames != nil { + t.Fatal("direct legacy escape served unproven metadata") + } + }) + } +} + +func TestTentativeCoreLegacyInsertReleasesLiveProtection(t *testing.T) { + const count = 2049 + editor := NewEditor(strings.Repeat("a", count)) + editor.SetOverwrite(true) + editor.MoveTo(0, false) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: strings.Repeat("z", count)}) + editor.Insert("r") + if editor.String() != "r" || editor.CompositionActive() || len(editor.history) > maxHistoryEntries { + t.Fatalf("legacy Insert kept %d units after ending composition", len(editor.history)) + } + if state := editor.compositionState(); state != nil && (state.live || state.active) { + t.Fatal("legacy Insert retained the former tentative's physical protection") + } + for range 300 { + editor.BreakUndoGroup() + editor.Insert("q") + } + if len(editor.history) != maxHistoryEntries || cap(editor.history) != maxHistoryEntries || editor.historyCost() > maxHistoryRunes { + t.Fatal("ordinary edits after legacy Insert retained unbounded or uncharged storage") + } +} + +func TestTentativeCoreNewResultRetiresPreviousLargeEvent(t *testing.T) { + const count = 80000 + editor := NewEditor(strings.Repeat("a", count)) + from := mustTrackHistory(t, editor) + editor.SetOverwrite(true) + editor.MoveTo(0, false) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: strings.Repeat("z", count)}) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCommit}) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionResult, Text: strings.Repeat("q", count)}) + if editor.String() != strings.Repeat("q", count) || len(editor.history) != count || editor.historyCost() > maxSingleEditRunes { + t.Fatalf("new event retained previous protection: units=%d cost=%d", len(editor.history), editor.historyCost()) + } + if frames, _, ok := editor.HistorySince(from); ok || frames != nil { + t.Fatal("over-budget metadata presented an incomplete event suffix") + } + if !editor.Undo() || editor.String() != strings.Repeat("q", count-1)+"z" { + t.Fatal("retiring the previous event removed the new event's ordinary units") + } +} + +func TestTentativeCoreResultRetainsPlannedCapacity(t *testing.T) { + for _, mode := range []string{"physical-only", "invalidated-history"} { + t.Run(mode, func(t *testing.T) { + editor := NewEditor(strings.Repeat("a", 80000)) + var from HistoryCursor + if mode == "invalidated-history" { + from = mustTrackHistory(t, editor) + } + editor.SetOverwrite(true) + editor.MoveTo(0, false) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: strings.Repeat("z", 80000)}) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCommit}) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionResult, Text: strings.Repeat("q", 130000)}) + runtime.ReadMemStats(&after) + allocated := after.TotalAlloc - before.TotalAlloc + t.Logf("Result allocated %d bytes", allocated) + if allocated > 256<<20 { + t.Fatal("accepted event repeatedly grew/compacted its planned history backing") + } + if editor.String() != strings.Repeat("q", 130000) || len(editor.history) != 130000 || cap(editor.history) != 130000 || editor.historyCost() > maxSingleEditRunes { + t.Fatalf("new event lost physical units or retained old backing: units=%d capacity=%d cost=%d", len(editor.history), cap(editor.history), editor.historyCost()) + } + if mode != "physical-only" { + if frames, _, ok := editor.HistorySince(from); ok || frames != nil { + t.Fatal("over-budget optional metadata exposed a partial event") + } + } + if !editor.Undo() || editor.String() != strings.Repeat("q", 129999) || !editor.Redo() || editor.String() != strings.Repeat("q", 130000) { + t.Fatal("new event lost ordinary Undo/Redo after evicting the old prefix") + } + }) + } +} + +func coalescedTentativeResult(mode string, caret int, value string) CompositionEvent { + event := CompositionEvent{Phase: CompositionResult, Text: value} + switch mode { + case "rune-empty": + event.HasReplacement = true + event.Replacement = Range{Start: caret, End: caret} + case "utf16-empty": + event.HasReplacementUTF16 = true + event.ReplacementUTF16 = UTF16Range{Start: caret} + } + return event +} + +func TestTentativeCoreResultOwnsCoalescedOrdinaryUnit(t *testing.T) { + for _, mode := range []string{"implicit", "rune-empty", "utf16-empty"} { + t.Run(mode, func(t *testing.T) { + editor := NewEditor("") + editor.Insert("a") + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, coalescedTentativeResult(mode, editor.Caret(), "bc")) + if editor.String() != "abc" || len(editor.history) != 1 { + t.Fatal("inactive Result changed ordinary insertion coalescing") + } + state := editor.compositionState() + unit := editor.history[0] + if state == nil || !state.completed || state.completedStart != 0 || cap(unit.inserted) != len(unit.inserted) { + t.Fatal("coalesced Result did not own its complete retained unit and exact text capacity") + } + if !editor.Undo() || editor.String() != "" || !editor.Redo() || editor.String() != "abc" { + t.Fatal("coalesced Result lost its source Undo grouping") + } + }) + } +} + +func TestTentativeCoreCoalescedResultFrameContainsOnlyNewScalars(t *testing.T) { + for _, mode := range []string{"implicit", "rune-empty", "utf16-empty"} { + t.Run(mode, func(t *testing.T) { + editor := NewEditor("") + from := mustTrackHistory(t, editor) + editor.Insert("a") + from = expectHistoryFrames(t, editor, from, []HistoryStep{{HistoryForward, HistoryInsert, 0, 1, 0, 1, historySample(1, 0, -1, 1)}}) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, coalescedTentativeResult(mode, editor.Caret(), "bc")) + expectHistoryFrames(t, editor, from, []HistoryStep{ + {HistoryForward, HistoryInsert, 1, 1, 1, 2, historySample(2, 0, -1, 2)}, + {HistoryForward, HistoryInsert, 2, 1, 2, 3, historySample(3, 0, -1, 3)}, + }) + if !editor.Undo() || editor.String() != "" || !editor.Redo() || editor.String() != "abc" { + t.Fatal("metadata tracking changed the coalesced ordinary unit") + } + }) + } +} + +func TestTentativeCoreCoalescedResultPreflightIncludesPreviousText(t *testing.T) { + for _, mode := range []string{"implicit", "rune-empty", "utf16-empty"} { + t.Run(mode, func(t *testing.T) { + editor := NewEditor("") + editor.Insert(strings.Repeat("a", maxSingleEditRunes-128)) + enableTentativeCore(t, editor) + before, selection := editor.String(), editor.Selection() + if editor.ApplyComposition(coalescedTentativeResult(mode, editor.Caret(), strings.Repeat("b", 512))) { + t.Fatalf("oversized coalesced Result accepted: retained cost=%d", editor.historyCost()) + } + if editor.String() != before || editor.Selection() != selection || len(editor.history) != 1 || editor.CompositionActive() { + t.Fatal("refused coalesced Result partially changed source or history") + } + applyTentativeCore(t, editor, coalescedTentativeResult(mode, editor.Caret(), strings.Repeat("b", 32))) + if editor.String() != before+strings.Repeat("b", 32) || len(editor.history) != 1 || editor.historyCost() > maxSingleEditRunes { + t.Fatal("fitting coalesced Result lost its complete physically bounded unit") + } + if !editor.Undo() || editor.String() != "" || editor.CanUndo() { + t.Fatal("coalesced Result broke ordinary Undo grouping") + } + }) + } +} + +func TestTentativeCoreDisableKeepsRetiredStorageOwner(t *testing.T) { + const count = 2049 + for _, history := range []bool{false, true} { + for _, redo := range []bool{false, true} { + name := map[bool]string{false: "physical", true: "history"}[history] + map[bool]string{false: "-undo", true: "-redo"}[redo] + t.Run(name, func(t *testing.T) { + editor := NewEditor(strings.Repeat("a", count)) + var from HistoryCursor + if history { + from = mustTrackHistory(t, editor) + } + editor.SetOverwrite(true) + editor.MoveTo(0, false) + enableTentativeCore(t, editor) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionUpdate, Text: strings.Repeat("z", count)}) + applyTentativeCore(t, editor, CompositionEvent{Phase: CompositionCommit}) + if !editor.Undo() || redo && !editor.Redo() { + t.Fatal("fixture could not retire completed protection through replay") + } + before, latest, available := editor.HistorySince(from) + if !editor.DisableTentativeComposition() || editor.TentativeCompositionEnabled() { + t.Fatal("inactive Disable failed") + } + if len(editor.history) != count || editor.compositionState() == nil { + t.Fatal("Disable released the remaining owner of oversized ordinary storage") + } + minimum := (cap(editor.history) - maxHistoryEntries) * int(unsafe.Sizeof(historyEdit{})) / 4 + for _, unit := range editor.history { + minimum += cap(unit.removed) + cap(unit.inserted) + } + if editor.historyCost() < minimum || !editor.DisableTentativeComposition() { + t.Fatal("disabled nonprotecting owner lost accounting or idempotence") + } + after, next, ok := editor.HistorySince(from) + if available != ok || latest != next || !reflect.DeepEqual(before, after) { + t.Fatal("Disable changed existing metadata frames or cursors") + } + editor.Insert("q") + if len(editor.history) != maxHistoryEntries || cap(editor.history) != maxHistoryEntries || editor.compositionState() != nil || editor.CanRedo() { + t.Fatal("next ordinary mutation did not settle and release disabled storage") + } + editor.ClearHistory() + if len(editor.history) != 0 || editor.historyRunes != 0 || editor.compositionState() != nil { + t.Fatal("Clear retained retired physical storage") + } + }) + } + } +} diff --git a/text/transaction.go b/text/transaction.go index a003da02f..2f5bf89e6 100644 --- a/text/transaction.go +++ b/text/transaction.go @@ -11,6 +11,7 @@ import ( // through its methods; it must not copy/replace it or mutate the source. Editors // remain single-threaded. Callback errors leave the source unchanged. Temporary // storage grows with staged edits; the source keeps its usual history/journal limits. +// Enabled LF labels follow the draft and commit with the same source undo unit. func (editor *Editor) Transact(apply func(*Editor) error) error { if editor == nil || apply == nil { return fmt.Errorf("transaction source and callback are required") @@ -22,14 +23,21 @@ func (editor *Editor) Transact(apply func(*Editor) error) error { return fmt.Errorf("cannot transact in a restricted editor") } before, selection := editor.String(), editor.selectionState() + secondary := slices.Clone(editor.secondary) draft := NewEditor(before) draft.anchor, draft.caret = selection.anchor, selection.caret draft.code, draft.codeSet, draft.overwrite = editor.code, editor.codeSet, editor.overwrite - recorder := &editJournal{unlimited: true, tracking: true} + recorder := &editJournal{unlimited: true, tracking: true, retainEqual: editor.retainEqualEdits(), private: true} if editor.journal != nil && editor.journal.lines != nil { recorder.lines = &lineJournal{} } draft.journal = recorder + labels := editor.lfLabelState() + var labelRevision uint64 + if labels != nil { + labelRevision = labels.revision + recorder.lines.labels = labels.ops.clone(labels, draft) + } if editor.savePointIndex() != nil { draft.SetSavePoint() } @@ -40,9 +48,12 @@ func (editor *Editor) Transact(apply func(*Editor) error) error { if draft.journal != recorder || draft.composing { return fmt.Errorf("transaction draft lost its recorder or has unfinished composition") } - if editor.String() != before || editor.selectionState() != selection { + if editor.String() != before || editor.selectionState() != selection || !slices.Equal(editor.secondary, secondary) { return fmt.Errorf("transaction source changed during callback") } + if editor.lfLabelState() != labels || labels != nil && labels.revision != labelRevision { + return fmt.Errorf("transaction source LF labels changed during callback") + } value := draft.String() after := Range{Start: draft.anchor, End: draft.caret} target := Range{End: len(editor.runes)} @@ -54,10 +65,20 @@ func (editor *Editor) Transact(apply func(*Editor) error) error { if recorder.lines != nil { contexts = slices.Clone(recorder.lines.entries) } + // The transaction restores one selection, so a multi-selection ends when the + // batch commits (and after a failed callback the source keeps it). + editor.clearSecondary() if len(primitives) == 0 && value == before { editor.SetSelection(after) return nil } - editor.commitBatch(target, value, primitives, contexts, &after) + var labelPlan *lfLabelPlan + if labels != nil { + labelPlan = labels.ops.finish(labels, recorder.lines.labels) + if value == before && editor.savePointIndex() == nil && labelPlan != nil && !labelPlan.changed { + labelPlan = nil + } + } + editor.commitBatch(target, value, primitives, contexts, &after, labelPlan) return nil } diff --git a/tools/apicheck/allow.txt b/tools/apicheck/allow.txt new file mode 100644 index 000000000..a5aea7f14 --- /dev/null +++ b/tools/apicheck/allow.txt @@ -0,0 +1,8 @@ +# Exported symbols allowed to name a dynamic type, one per line. +# +# A line is the symbol apicheck printed, such as app.Something or +# ui.Type.Method; the reason belongs beside it as a comment on the same line. +# Keep this list shrinking: a new symbol that needs a dynamic type usually +# needs a typed one instead. + +ui.Textf # a format and its arguments, as fmt.Print takes them diff --git a/tools/apicheck/apicheck_test.go b/tools/apicheck/apicheck_test.go new file mode 100644 index 000000000..50ae4d118 --- /dev/null +++ b/tools/apicheck/apicheck_test.go @@ -0,0 +1,97 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func writePackage(t *testing.T, source string) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "pkg.go"), []byte(source), 0o600); err != nil { + t.Fatal(err) + } + return dir +} + +func TestCheckFindsDynamicTypesInExportedAPI(t *testing.T) { + dir := writePackage(t, `package sample + +import "reflect" + +func Exported(value any) {} + +func Variadic(values ...any) {} + +func Results() map[string]interface{} { return nil } + +func Fine(value string, values []int) *Widget { return nil } + +func hidden(value any) {} + +func Generic[T any](value T) {} + +type Widget struct { + Name string + Values map[string]any + private any +} + +type Bag = map[string]any + +type Handler interface { + Handle(value any) +} + +var Anything any +`) + findings, err := check([]string{dir}) + if err != nil { + t.Fatal(err) + } + found := make(map[string]bool) + for _, finding := range findings { + found[finding.symbol] = true + } + for _, want := range []string{ + "sample/reflect", + "sample.Exported", + "sample.Variadic", + "sample.Results", + "sample.Widget.Values", + "sample.Bag", + "sample.Handler.Handle", + "sample.Anything", + } { + if !found[want] { + t.Errorf("no finding for %s in %+v", want, findings) + } + } + for _, unwanted := range []string{"sample.Fine", "sample.hidden", "sample.Generic", "sample.Widget.private"} { + if found[unwanted] { + t.Errorf("unexpected finding for %s", unwanted) + } + } +} + +func TestAllowListExemptsASymbol(t *testing.T) { + dir := writePackage(t, `package sample + +func Kept(value any) {} +`) + allowed := map[string]bool{"sample.Kept": true} + findings, err := check([]string{dir}) + if err != nil { + t.Fatal(err) + } + kept := findings[:0] + for _, finding := range findings { + if !allowed[finding.symbol] { + kept = append(kept, finding) + } + } + if len(kept) != 0 { + t.Fatalf("kept = %+v, want none", kept) + } +} diff --git a/tools/apicheck/main.go b/tools/apicheck/main.go new file mode 100644 index 000000000..cd2eae40a --- /dev/null +++ b/tools/apicheck/main.go @@ -0,0 +1,275 @@ +// Command apicheck rejects dynamic types in the exported API of the packages a +// page is written with. Reflection, 'any' and map[string]any are what the +// engine's layout, input, scene and render paths must not see; this makes a +// new exported symbol that introduces one a build failure instead of a review +// catch. +// +// It reads the packages named on the command line (ui, components and app by +// default), and a file of allowed symbols, one per line, for the cases that +// already exist. Run it with: +// +// go run ./tools/apicheck ./ui ./components ./app +package main + +import ( + "flag" + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "sort" + "strings" +) + +type finding struct { + position string + symbol string + reason string +} + +func main() { + allowPath := flag.String("allow", "tools/apicheck/allow.txt", "file of symbols allowed to use a dynamic type, one per line") + flag.Parse() + dirs := flag.Args() + if len(dirs) == 0 { + dirs = []string{"ui", "components", "app", "gfx"} + } + findings, err := check(dirs) + if err != nil { + fmt.Fprintln(os.Stderr, "apicheck:", err) + os.Exit(2) + } + allowed, err := loadAllow(*allowPath) + if err != nil { + fmt.Fprintln(os.Stderr, "apicheck:", err) + os.Exit(2) + } + kept := findings[:0] + for _, finding := range findings { + if !allowed[finding.symbol] { + kept = append(kept, finding) + } + } + for _, finding := range kept { + fmt.Fprintf(os.Stderr, "%s: %s: %s\n", finding.position, finding.symbol, finding.reason) + } + if len(kept) > 0 { + fmt.Fprintf(os.Stderr, "apicheck: %d exported symbol(s) use a dynamic type; use a typed one, or add the symbol to %s\n", len(kept), *allowPath) + os.Exit(1) + } +} + +// loadAllow reads the allowed symbols; a missing file allows nothing. +func loadAllow(path string) (map[string]bool, error) { + allowed := make(map[string]bool) + data, err := os.ReadFile(path) + if os.IsNotExist(err) { + return allowed, nil + } + if err != nil { + return nil, err + } + for _, line := range strings.Split(string(data), "\n") { + line = strings.TrimSpace(line) + if index := strings.IndexByte(line, '#'); index >= 0 { + line = strings.TrimSpace(line[:index]) + } + if line == "" { + continue + } + allowed[line] = true + } + return allowed, nil +} + +// check reports the exported declarations in dirs that name a dynamic type. +func check(dirs []string) ([]finding, error) { + var findings []finding + for _, dir := range dirs { + paths, err := filepath.Glob(filepath.Join(dir, "*.go")) + if err != nil { + return nil, err + } + fset := token.NewFileSet() + var files []*ast.File + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + file, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) + if err != nil { + return nil, err + } + files = append(files, file) + } + if len(files) == 0 { + continue + } + pkg := files[0].Name.Name + for _, file := range files { + findings = append(findings, checkFile(fset, pkg, file)...) + } + } + sort.Slice(findings, func(i, j int) bool { + if findings[i].position != findings[j].position { + return findings[i].position < findings[j].position + } + return findings[i].symbol < findings[j].symbol + }) + return findings, nil +} + +func checkFile(fset *token.FileSet, pkg string, file *ast.File) []finding { + var findings []finding + add := func(node ast.Node, symbol, reason string) { + findings = append(findings, finding{position: fset.Position(node.Pos()).String(), symbol: symbol, reason: reason}) + } + for _, spec := range file.Imports { + if spec.Path.Value == `"reflect"` { + add(spec, pkg+"/reflect", "imports reflect") + } + } + for _, decl := range file.Decls { + switch decl := decl.(type) { + case *ast.FuncDecl: + if !decl.Name.IsExported() { + continue + } + symbol := pkg + "." + decl.Name.Name + if decl.Recv != nil && len(decl.Recv.List) > 0 { + if receiver := receiverName(decl.Recv.List[0].Type); receiver != "" { + symbol = pkg + "." + receiver + "." + decl.Name.Name + } + } + if fieldListUsesAny(decl.Type.Params) || fieldListUsesAny(decl.Type.Results) { + add(decl, symbol, "a parameter or result names any") + } + case *ast.GenDecl: + for _, raw := range decl.Specs { + switch spec := raw.(type) { + case *ast.TypeSpec: + if !spec.Name.IsExported() { + continue + } + symbol := pkg + "." + spec.Name.Name + switch typ := spec.Type.(type) { + case *ast.StructType: + for _, field := range typ.Fields.List { + for _, name := range field.Names { + if !name.IsExported() { + continue + } + if usesAny(field.Type) { + add(field, symbol+"."+name.Name, "an exported field names any") + } + } + } + case *ast.InterfaceType: + for _, method := range typ.Methods.List { + funcType, ok := method.Type.(*ast.FuncType) + if !ok { + continue // an embedded interface is checked where it is declared + } + for _, name := range method.Names { + if !name.IsExported() { + continue + } + if fieldListUsesAny(funcType.Params) || fieldListUsesAny(funcType.Results) { + add(method, symbol+"."+name.Name, "an exported interface method names any") + } + } + } + default: + if usesAny(spec.Type) { + add(spec, symbol, "an exported type names any") + } + } + case *ast.ValueSpec: + for _, name := range spec.Names { + if !name.IsExported() || spec.Type == nil { + continue + } + if usesAny(spec.Type) { + add(spec, pkg+"."+name.Name, "an exported value names any") + } + } + } + } + } + } + return findings +} + +func receiverName(expr ast.Expr) string { + for { + switch e := expr.(type) { + case *ast.StarExpr: + expr = e.X + case *ast.IndexExpr: + expr = e.X + case *ast.IndexListExpr: + expr = e.X + case *ast.Ident: + return e.Name + default: + return "" + } + } +} + +func fieldListUsesAny(fields *ast.FieldList) bool { + if fields == nil { + return false + } + for _, field := range fields.List { + if usesAny(field.Type) { + return true + } + } + return false +} + +// usesAny reports whether a type expression names `any`, `interface{}`, or +// holds one inside a container. +func usesAny(expr ast.Expr) bool { + switch e := expr.(type) { + case *ast.Ident: + return e.Name == "any" + case *ast.InterfaceType: + if e.Methods == nil || len(e.Methods.List) == 0 { + return true + } + for _, method := range e.Methods.List { + funcType, ok := method.Type.(*ast.FuncType) + if !ok { + continue // an embedded interface is checked where it is declared + } + if fieldListUsesAny(funcType.Params) || fieldListUsesAny(funcType.Results) { + return true + } + } + return false + case *ast.MapType: + return usesAny(e.Key) || usesAny(e.Value) + case *ast.ArrayType: + return usesAny(e.Elt) + case *ast.StarExpr: + return usesAny(e.X) + case *ast.ChanType: + return usesAny(e.Value) + case *ast.Ellipsis: + return usesAny(e.Elt) + case *ast.FuncType: + return fieldListUsesAny(e.Params) || fieldListUsesAny(e.Results) + case *ast.StructType: + for _, field := range e.Fields.List { + if usesAny(field.Type) { + return true + } + } + return false + } + return false +} diff --git a/tools/iconcompile/compile.go b/tools/iconcompile/compile.go index 07975216e..2cd784382 100644 --- a/tools/iconcompile/compile.go +++ b/tools/iconcompile/compile.go @@ -91,6 +91,8 @@ func Compile(name string, source []byte) (gfx.Icon, error) { state = state.inherit(root) state.gradients = map[string]*svgNode{} collectGradients(root, state.gradients) + state.ids = map[string]*svgNode{} + collectIDs(root, state.ids) state.walk(root, origin, sink) if sink.err != nil { return gfx.Icon{}, fmt.Errorf("%s: %w", name, sink.err) @@ -334,6 +336,12 @@ type iconState struct { fillRule gfx.PathFillRule // gradients are the document's gradient elements by id. gradients map[string]*svgNode + // ids are the document's id-bearing drawable elements (paths, groups, + // markers) by id, for and marker references. + ids map[string]*svgNode + // useStack holds the ids of the elements being expanded, plus the + // referenced target id, to reject circular references. + useStack []string } // inherit applies a node's own paint attributes over its parent's. @@ -421,78 +429,183 @@ func parseHexColor(raw string) (gfx.Color, error) { return color, nil } +// walk draws node's children: groups recurse with their transform, use +// elements expand their referenced target, and drawable elements paint. func (state iconState) walk(node *svgNode, at transform, sink *iconSink) { - emit := sink.add - for _, child := range node.Children { + for index := range node.Children { + child := &node.Children[index] name := child.XMLName.Local - childState := state.inherit(&child) if name == "g" { next := at if raw := child.Attr("transform"); raw != "" { next = at.then(parseTransform(raw)) } - childState.walk(&child, next, sink) + state.inherit(child).walk(child, next, sink) continue } - elementAt := at - if raw := child.Attr("transform"); raw != "" { - elementAt = at.then(parseTransform(raw)) - } - var ( - fill gfx.Color - colored bool - gradient *gfx.LinearGradient - box *boxGradient - err error - ) - if strings.HasPrefix(childState.fill, "url(") { - gradient, box, err = childState.linearGradient(elementAt) - if gradient != nil { - fill, colored = gradient.From, true - } - } else { - fill, colored, err = childState.color() + if name == "use" { + state.expandUse(child, at, sink) + continue } - if err != nil && sink.err == nil { - sink.err = err + state.emitOne(child, at, sink) + } +} + +// emitOne paints one drawable element in its parent's coordinate system: its +// own transform and paint compose onto the incoming state, colored shapes open +// a layer, and the flag icon sets' vertex markers follow their path. +func (state iconState) emitOne(node *svgNode, at transform, sink *iconSink) { + childState := state.inherit(node) + name := node.XMLName.Local + elementAt := at + if raw := node.Attr("transform"); raw != "" { + elementAt = at.then(parseTransform(raw)) + } + switch name { + case "g", "use", "defs", "title", "desc", "metadata", "style", "linearGradient", "radialGradient", "clipPath", "mask", "filter", "marker": + // Handled by walk or not drawn by themselves. + return + } + var ( + fill gfx.Color + colored bool + gradient *gfx.LinearGradient + box *boxGradient + err error + ) + if strings.HasPrefix(childState.fill, "url(") { + gradient, box, err = childState.linearGradient(elementAt) + if gradient != nil { + fill, colored = gradient.From, true } - if !colored && childState.invisible() { - continue + } else { + fill, colored, err = childState.color() + } + if err != nil && sink.err == nil { + sink.err = err + } + if !colored && childState.invisible() { + // An unpainted path still places its markers: that is exactly how the + // US star field is drawn — a fill-none outline whose vertices carry + // the stars. + state.emitMarkers(node, at, sink) + return + } + if colored { + sink.begin(fill, childState.fillRule, gradient) + } + emit := sink.add + switch name { + case "path": + state.emitPathData(node.Attr("d"), elementAt, emit) + // Star fields of flag icons place a marker at every intermediate + // vertex of the outline (US-SVG's marker-mid). + state.emitMarkers(node, at, sink) + case "line": + state.emitLine(node, elementAt, emit) + case "polyline", "polygon": + state.emitPoly(node, elementAt, name == "polygon", emit) + case "rect": + state.emitRect(node, elementAt, emit) + case "circle": + state.emitCircle(node, elementAt, emit) + case "ellipse": + state.emitEllipse(node, elementAt, emit) + default: + // An element the compiler does not know is never skipped silently: a + // dropped once left half of Lucide's cylinder on screen. + if sink.err == nil { + sink.err = fmt.Errorf("unsupported element <%s>", name) } - if colored { - sink.begin(fill, childState.fillRule, gradient) + } + if box != nil { + sink.fitBoxGradient(box) + } + if colored { + sink.end() + } +} + +// expandUse draws one element: the referenced target is expanded as if +// deeply cloned here, so its shapes inherit paint from the use site unless +// they carry their own, and the use element's transform and x/y offset place +// the clone. A target that is itself a dereferences again, up to a +// bounded depth: a cycle is a compile error, not an infinite icon. +func (state iconState) expandUse(use *svgNode, at transform, sink *iconSink) { + id := referencedID(use) + if id == "" { + if sink.err == nil { + sink.err = fmt.Errorf(" without a target") } - switch name { - case "path": - state.emitPathData(child.Attr("d"), elementAt, emit) - case "line": - state.emitLine(&child, elementAt, emit) - case "polyline", "polygon": - state.emitPoly(&child, elementAt, name == "polygon", emit) - case "rect": - state.emitRect(&child, elementAt, emit) - case "circle": - state.emitCircle(&child, elementAt, emit) - case "ellipse": - state.emitEllipse(&child, elementAt, emit) - case "defs", "title", "desc", "metadata", "style", "linearGradient", "radialGradient", "clipPath", "mask", "filter": - // Structure and metadata: not drawn by themselves. - default: - // An element the compiler does not know is never skipped silently: a - // dropped once left half of Lucide's cylinder on screen. + return + } + target := state.ids[id] + if target == nil { + // An invalid reference draws nothing, as in SVG 1.1. + return + } + for _, active := range state.useStack { + if active == id { if sink.err == nil { - sink.err = fmt.Errorf("unsupported element <%s>", name) + sink.err = fmt.Errorf(" cycle through #%s", id) } + return } - if box != nil { - sink.fitBoxGradient(box) + } + if len(state.useStack) >= maxUseDepth { + if sink.err == nil { + sink.err = fmt.Errorf(" nested more than %d deep through #%s", maxUseDepth, id) } - if colored { - sink.end() + return + } + next := at + if raw := use.Attr("transform"); raw != "" { + next = next.then(parseTransform(raw)) + } + if raw := use.Attr("x"); raw != "" { + if x, err := strconv.ParseFloat(raw, 64); err == nil { + next = next.then(transform{1, 0, 0, 1, x, 0}) + } + } + if raw := use.Attr("y"); raw != "" { + // y="44" on a use of the Korean flag is a plain shift of the bars. + if y, err := strconv.ParseFloat(raw, 64); err == nil { + next = next.then(transform{1, 0, 0, 1, 0, y}) } } + // width/height would scale the target of a , but SVG only applies + // them to and targets; on shapes and groups (every real + // icon source, including the flag sets) they are inert. + useState := state.inherit(use) + useState.useStack = append(state.useStack, id) + switch target.XMLName.Local { + case "g": + nextG := next + if raw := target.Attr("transform"); raw != "" { + nextG = next.then(parseTransform(raw)) + } + // A group target is cloned: its own paint and transform compose like + // a in flow at the use site, then its children walk underneath. + useState.inherit(target).walk(target, nextG, sink) + case "use": + // A use pointing at a use dereferences through the same rules. + useState.expandUse(target, next, sink) + default: + // A single shape target paints like the same node sitting in flow + // where the use is; x/y and transform above carried it so far. + useState.emitOne(target, next, sink) + } +} + +// referencedID reads the href (or xlink:href, whose parsed name is also +// href) attribute of a reference and strips the leading #. +func referencedID(node *svgNode) string { + return strings.TrimPrefix(strings.TrimSpace(node.Attr("href")), "#") } +// maxUseDepth bounds use dereferences, including through nested groups. +const maxUseDepth = 32 + func (state iconState) point(at transform, x, y float64) (float32, float32) { px, py := at.apply(x, y) return float32(px), float32(py) @@ -812,6 +925,25 @@ func collectGradients(node *svgNode, into map[string]*svgNode) { } } +// collectIDs indexes every id-bearing element that and marker +// references can point at: shapes, groups and markers, wherever they are +// defined, including inside . Flag icon sets reference a shared path or +// group from several elements, each with its own transform. +func collectIDs(node *svgNode, into map[string]*svgNode) { + for index := range node.Children { + child := &node.Children[index] + switch child.XMLName.Local { + case "path", "line", "polyline", "polygon", "rect", "circle", "ellipse", "g", "marker", "use": + if id := child.Attr("id"); id != "" { + if _, taken := into[id]; !taken { + into[id] = child + } + } + } + collectIDs(child, into) + } +} + // boxGradient is a gradient given in objectBoundingBox units, SVG's default: its // endpoints are fractions of the bounding box of the shape it fills, which is only // known once the shape has been drawn. fitBoxGradient finishes it. @@ -977,3 +1109,307 @@ func parseStop(stop *svgNode) (float64, gfx.Color, error) { } return offset, color, nil } + +// emitMarkers draws the markers a path element names at its vertices. Only the +// star fields of the flag icon sets use markers today, all through marker-mid, +// which places a marker at every vertex apart from the first of each subpath +// (a closed outline's last vertex keeps its marker, as browsers draw it). +// marker-start and marker-end are placed by the same machinery, one at a +// subpath's first, respectively last, vertex, but no yielded source exercises +// them yet. A marker with no orient attribute — every real source — stays at +// angle 0, matching the browsers (SVG's default; the US star is drawn upright +// at every vertex). orient="auto" turns the content to the bisector of the +// two segments at the vertex. +func (state iconState) emitMarkers(path *svgNode, at transform, sink *iconSink) { + mid := path.Attr("marker-mid") + start, end := path.Attr("marker-start"), path.Attr("marker-end") + if mid == "" && start == "" && end == "" { + return + } + // markerUnits defaults to strokeWidth, so the marker content scales with + // the path's stroke (1 in the flag sets, where paths carry no stroke). + scale := 1.0 + if raw := strings.TrimSpace(path.Attr("stroke-width")); raw != "" { + if width, err := strconv.ParseFloat(raw, 64); err == nil && width > 0 { + scale = width + } + } + for _, subpath := range skeletonVertices(path.Attr("d")) { + for index, vertex := range subpath.vertices { + switch { + case index == 0 && start != "": + state.placeMarker(start, vertex, at, scale, sink) + case index == len(subpath.vertices)-1 && end != "": + // An end marker belongs to the last vertex; on a closed + // subpath that vertex is also where the closepath lands. + state.placeMarker(end, vertex, at, scale, sink) + case index == 0 || index == len(subpath.vertices)-1 && !subpath.closed: + // The first vertex, and the last of an open subpath, are the + // start and end property's, not marker-mid's. + continue + case mid != "": + state.placeMarker(mid, vertex, at, scale, sink) + } + } + } +} + +// placeMarker expands one marker element at a vertex. The content is cloned +// at the vertex, shifted by negated refX/refY, scaled by the path's stroke +// width under the default markerUnits, and turned per orient: a fixed angle +// (absent is 0) or the bisector of the vertex's two directions for auto. +func (state iconState) placeMarker(reference string, vertex pathVertex, at transform, scale float64, sink *iconSink) { + id := strings.Trim(strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(reference), "url("), ")"), " '\"") + id = strings.TrimPrefix(id, "#") + marker := state.ids[id] + if marker == nil || marker.XMLName.Local != "marker" { + return // An invalid reference draws nothing, as in the browsers. + } + if strings.TrimSpace(marker.Attr("markerUnits")) == "userSpaceOnUse" { + scale = 1 + } + placed := transform{scale, 0, 0, scale, 0, 0} + angle := 0.0 + if orient := strings.TrimSpace(marker.Attr("orient")); orient == "auto" { + // Weighted with the segment lengths normalized: the bisector of the + // unit tangents, as SVG specifies. + inX, inY := vertex.in[0], vertex.in[1] + outX, outY := vertex.out[0], vertex.out[1] + lengthIn := math.Hypot(inX, inY) + lengthOut := math.Hypot(outX, outY) + if lengthIn > 0 && lengthOut > 0 { + bisX, bisY := inX/lengthIn+outX/lengthOut, inY/lengthIn+outY/lengthOut + angle = math.Atan2(bisY, bisX) + } else if lengthOut > 0 { + angle = math.Atan2(outY, outX) + } else if lengthIn > 0 { + angle = math.Atan2(inY, inX) + } + } else if orient != "" && orient != "0" { + if parsed, err := strconv.ParseFloat(orient, 64); err == nil { + angle = parsed * math.Pi / 180 + } + } + cos, sin := math.Cos(angle), math.Sin(angle) + rotation := transform{cos, sin, -sin, cos, 0, 0} + view := markerToView(marker) + translate := transform{1, 0, 0, 1, vertex.point[0], vertex.point[1]} + ref := transform{1, 0, 0, 1, -markerNumber(marker.Attr("refX")) * view, -markerNumber(marker.Attr("refY")) * view} + place := at.then(translate).then(rotation).then(placed).then(ref) + // The marker's children are cloned with the paint in scope here. + state.walk(marker, place, sink) +} + +// markerToView converts marker content coordinates into marker viewport units +// when the marker declares a viewBox; without one — the flag sets' case — the +// content is already in viewport units. +func markerToView(marker *svgNode) float64 { + raw := marker.Attr("viewBox") + if raw == "" { + return 1 + } + fields := strings.Fields(raw) + if len(fields) != 4 { + return 1 + } + width, err := strconv.ParseFloat(fields[2], 64) + viewport := markerNumber(marker.Attr("markerWidth")) + if err != nil || width <= 0 || viewport <= 0 { + return 1 + } + return viewport / width +} + +// markerNumber reads a marker geometry attribute, treating SVG's bare-value +// form; anything unparsable is SVG's zero default. +func markerNumber(raw string) float64 { + value, err := strconv.ParseFloat(strings.TrimSpace(raw), 64) + if err != nil { + return 0 + } + return value +} + +// pathVertex is one vertex of a path's straight-line skeleton: the point plus +// the directions of the segments entering and leaving it (a curve flattens to +// its chord). +type pathVertex struct { + point [2]float64 + in [2]float64 // the incoming segment direction; zero at a subpath's first vertex + out [2]float64 // the outgoing segment direction; set by the next vertex or closepath +} + +// pathSkeleton is one subpath of the vertex skeleton. +type pathSkeleton struct { + vertices []pathVertex + closed bool +} + +// skeletonVertices parses path data into per-subpath vertex lists with segment +// directions: every move and every explicit endpoint (line, curve or arc) is a +// vertex; the direction of a curve is its chord. Marker sources are polyline +// outlines, where both are exact. +func skeletonVertices(data string) []pathSkeleton { + parser := &pathParser{input: data} + var currentX, currentY, startX, startY float64 + var subpaths []pathSkeleton + var current []pathVertex + closed := false + var inX, inY float64 // direction of the segment ending at the current point + flush := func() { + if len(current) > 0 { + subpaths = append(subpaths, pathSkeleton{vertices: current, closed: closed}) + current = nil + } + closed = false + } + appendVertex := func(x, y, iX, iY float64) { + if len(current) > 0 { + previous := ¤t[len(current)-1] + previous.out = [2]float64{x - previous.point[0], y - previous.point[1]} + } + current = append(current, pathVertex{point: [2]float64{x, y}, in: [2]float64{iX, iY}}) + } + for { + command, relative, ok := parser.nextCommand() + if !ok { + break + } + switch command { + case 'M': + first := true + for { + x, y, ok := parser.coords() + if !ok { + break + } + if relative && !first { + // Coordinate pairs after the first of an 'm' are implicit + // relative linetos of the same subpath. + x, y = x+currentX, y+currentY + inX, inY = x-currentX, y-currentY + currentX, currentY = x, y + appendVertex(x, y, inX, inY) + } else { + flush() + currentX, currentY = x, y + startX, startY = x, y + appendVertex(x, y, 0, 0) + } + first = false + if !parser.moreNumbers() { + break + } + } + case 'L': + for { + x, y, ok := parser.coords() + if !ok { + break + } + if relative { + x, y = x+currentX, y+currentY + } + inX, inY = x-currentX, y-currentY + currentX, currentY = x, y + appendVertex(x, y, inX, inY) + if !parser.moreNumbers() { + break + } + } + case 'H': + for { + x, ok := parser.number() + if !ok { + break + } + if relative { + x += currentX + } + inX, inY = x-currentX, 0 + currentX = x + appendVertex(x, currentY, inX, inY) + if !parser.moreNumbers() { + break + } + } + case 'V': + for { + y, ok := parser.number() + if !ok { + break + } + if relative { + y += currentY + } + inX, inY = 0, y-currentY + currentY = y + appendVertex(currentX, y, inX, inY) + if !parser.moreNumbers() { + break + } + } + case 'C', 'S', 'Q', 'T': + var pairs int + if command == 'C' || command == 'S' { + pairs = 3 + } else { + pairs = 2 + } + for { + var last [2]float64 + ok := true + for pair := 0; pair < pairs; pair++ { + x, y, got := parser.coords() + if !got { + ok = false + break + } + last = [2]float64{x, y} + } + if !ok { + break + } + if relative { + last = [2]float64{last[0] + currentX, last[1] + currentY} + } + inX, inY = last[0]-currentX, last[1]-currentY + currentX, currentY = last[0], last[1] + appendVertex(last[0], last[1], inX, inY) + if !parser.moreNumbers() { + break + } + } + case 'A': + for { + args, ok := parser.seven() + if !ok { + break + } + x, y := args[5], args[6] + if relative { + x, y = x+currentX, y+currentY + } + inX, inY = x-currentX, y-currentY + currentX, currentY = x, y + appendVertex(x, y, inX, inY) + if !parser.moreNumbers() { + break + } + } + case 'Z': + // A close emits no vertex; the closing line's direction is stored + // as the last vertex's outgoing segment, and the subpath is marked + // closed: its initial vertex is this vertex too, which browsers + // honour by drawing the mid marker on the word's last vertex. + closed = true + if len(current) > 0 { + last := ¤t[len(current)-1] + last.out = [2]float64{startX - last.point[0], startY - last.point[1]} + } + currentX, currentY = startX, startY + } + } + flush() + return subpaths +} diff --git a/tools/iconcompile/compile_test.go b/tools/iconcompile/compile_test.go index c002c0d0a..2f537fedc 100644 --- a/tools/iconcompile/compile_test.go +++ b/tools/iconcompile/compile_test.go @@ -705,3 +705,234 @@ func TestAnUnknownElementIsAnError(t *testing.T) { t.Fatalf("compiling an gave %v, want an unsupported-element error", err) } } + +// The flag fixtures are the three flag-icons sources that needed and +// support: the CN flag references one shared star path from five +// elements with matrix transforms (adjusted by the Chinese flag's +// 4x3 design cell), the KR flag references both a path and a group (whose +// own shifts bars by y=44), and the US flag places its 50 stars with +// marker-mid on the vertices of an invisible closed outline. +// Unmodified copies from lipis/flag-icons v7.5.0, commit 7aa5b2b, MIT license. + +// starPoints lists the anchor vertices of every star layer of the compiled +// US flag: the first drawn point of the star shape, which sits at the outline +// vertex the marker is placed on (the shape draws from its content origin). +func TestUSFlagStarsSitAtEveryMidVertex(t *testing.T) { + mustCompile := func(name string) gfx.Icon { + source, err := testIcons.ReadFile("testdata/flag-" + name + ".svg") + if err != nil { + t.Fatal(err) + } + icon, err := Compile(name, source) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + return icon + } + US := mustCompile("us") + // Red field, blue canton, then one layer per star. + if len(US.Layers) != 52 { + t.Fatalf("US flag has %d layers, want 2 fields + 50 stars", len(US.Layers)) + } + anchors := map[[2]float32]bool{} + for _, layer := range US.Layers[2:] { + first := layer.Commands[0] + // The star content starts at its top tip, 14 units right of the vertex. + anchors[[2]float32{first.Point.X - 14, first.Point.Y}] = true + } + if len(anchors) != 50 { + t.Fatalf("%d distinct star anchors, want 50", len(anchors)) + } + // The star outline's vertices: 51 of them, starting (and, via closepath, + // ending) at (0,0). Browsers draw marker-mid on every vertex but the + // first; the last vertex of the closed subpath keeps its star, which is + // how the 50th star of the bottom row comes to sit at (320,218). + if anchors[[2]float32{0, 0}] { + t.Fatal("a star sits at the first vertex; marker-mid must not") + } + for _, vertex := range [][2]float32{ + {16, 11}, {320, 11}, // first and last of a six-star row + {47, 37}, {290, 37}, // the five-star rows + {320, 218}, // the closed outline's last vertex keeps its star + } { + if !anchors[vertex] { + t.Errorf("no star anchored at vertex %v", vertex) + } + } + // Every star is the same upright shape: the marker carries no orient + // attribute, so SVG's default angle 0 applies and the stars stay upright + // the way browsers render the flag. + reference := US.Layers[2].Commands + tolerant := func(a, b float32) bool { return math.Abs(float64(a-b)) < 1e-3 } + for index, layer := range US.Layers[2:] { + if len(layer.Commands) != len(reference) { + t.Fatalf("star %d has %d commands, want %d", index, len(layer.Commands), len(reference)) + } + dx := layer.Commands[0].Point.X - reference[0].Point.X + dy := layer.Commands[0].Point.Y - reference[0].Point.Y + for command, want := range reference { + got := layer.Commands[command] + if got.Kind == gfx.PathCommandClose { + continue // a close carries no point of its own + } + offX, offY := got.Point.X-want.Point.X-dx, got.Point.Y-want.Point.Y-dy + if got.Kind != want.Kind || !tolerant(offX, 0) || !tolerant(offY, 0) || + !tolerant(got.Control1.X-want.Control1.X, 0) || !tolerant(got.Control1.Y-want.Control1.Y, 0) || + !tolerant(got.Control2.X-want.Control2.X, 0) || !tolerant(got.Control2.Y-want.Control2.Y, 0) { + t.Fatalf("star %d is not the upright shape translated by (%v, %v)", index, dx, dy) + } + } + } +} + +// TestCNFlagExpandsUseMatrices: five elements reference one shared star +// path, each with a matrix transform; the compiled bounding boxes must land +// where the matrices in the source put the star glyphs. +func TestCNFlagExpandsUseMatrices(t *testing.T) { + source, err := testIcons.ReadFile("testdata/flag-cn.svg") + if err != nil { + t.Fatal(err) + } + icon, err := Compile("cn", source) + if err != nil { + t.Fatal(err) + } + if len(icon.Layers) != 6 { + t.Fatalf("CN flag has %d layers, want the field and five stars", len(icon.Layers)) + } + near := func(got, want float64) bool { diff := got - want; return diff > -2e-2 && diff < 2e-2 } + // Matrix(71.9991 0 0 72 120 120) over the star path's points + // (-.6,.8), (0,-1), (.6,.8), (-1,-.3), (1,-.3): the large star. + expected := []struct{ minX, minY, maxX, maxY float64 }{ + {48, 48, 192, 177.6}, // large star + {219.71, 25.78, 264.18, 72.30}, // small stars, in document order + {264.24, 73.06, 309.05, 120.59}, + {264.93, 142.95, 310.43, 189.11}, + {219.37, 192.76, 264.00, 239.25}, + } + for index, want := range expected { + layer := icon.Layers[index+1] + minX, minY, maxX, maxY := starBounds(layer.Commands) + if !near(minX, want.minX) || !near(minY, want.minY) || !near(maxX, want.maxX) || !near(maxY, want.maxY) { + t.Errorf("star %d bounds (%.2f,%.2f)..(%.2f,%.2f), want (%.2f,%.2f)..(%.2f,%.2f)", + index, minX, minY, maxX, maxY, want.minX, want.minY, want.maxX, want.maxY) + } + } +} + +// starBounds is the plain vertex bound of the five-point star path: no curves, +// so control points would only repeat endpoints. +func starBounds(commands []gfx.PathCommand) (float64, float64, float64, float64) { + minX, minY, maxX, maxY := 1e9, 1e9, -1e9, -1e9 + for _, command := range commands { + if command.Kind == gfx.PathCommandClose { + continue + } + x, y := float64(command.Point.X), float64(command.Point.Y) + minX, minY = min(minX, x), min(minY, y) + maxX, maxY = max(maxX, x), max(maxY, y) + } + return minX, minY, maxX, maxY +} + +// TestKRFlagExpandsGroupsAndBars: one targets a plain path shifted by +// y="44", another a group that itself contains that same path and a nested use +// — so the taegeuk bars come out twice per corner group — and four trigram +// bar groups land rotated into the four corners. The pinned corner bboxes are +// the ones measured off the browser-rendered flag. +func TestKRFlagExpandsGroupsAndBars(t *testing.T) { + source, err := testIcons.ReadFile("testdata/flag-kr.svg") + if err != nil { + t.Fatal(err) + } + icon, err := Compile("kr", source) + if err != nil { + t.Fatal(err) + } + // Fields and taegeuk: white background, then the black bar layers come in + // document order: the defined group's own drawing first, then the use. + if len(icon.Layers) != 8 { + t.Fatalf("KR flag has %d layers, want 8", len(icon.Layers)) + } + near := func(got, want float64) bool { diff := got - want; return diff > -2e-2 && diff < 2e-2 } + corners := []struct{ minX, minY, maxX, maxY float64 }{ + {70.12, 45.98, 203.26, 190.20}, // upper-left trigram bars + {436.18, 290.11, 569.32, 434.33}, + {70.39, 290.15, 203.53, 434.37}, + {436.45, 46.02, 569.59, 190.24}, + } + for index, want := range corners { + var layer int + switch index { + case 0: + layer = 1 + case 1: + layer = 2 + case 2: + layer = 6 + default: + layer = 7 + } + bars := icon.Layers[layer] + minX, minY, maxX, maxY := starBounds(bars.Commands) + if !near(minX, want.minX) || !near(minY, want.minY) || !near(maxX, want.maxX) || !near(maxY, want.maxY) { + t.Errorf("trigram %d bounds (%.2f,%.2f)..(%.2f,%.2f), want (%.2f,%.2f)..(%.2f,%.2f)", + index, minX, minY, maxX, maxY, want.minX, want.minY, want.maxX, want.maxY) + } + // Each bar group is three bars; the groups' path draws each bar plus + // the y=44 use of itself: 15 commands of bars in one layer. + if len(bars.Commands) != 15 { + t.Errorf("trigram %d has %d commands, want the bar path drawn twice (15)", index, len(bars.Commands)) + } + } +} + +// TestUseCycleIsRejected: a use that (through a group) references itself must +// fail the compile instead of looping or dropping geometry silently. +func TestUseCycleIsRejected(t *testing.T) { + for name, svg := range map[string]string{ + "self": ``, + "pair": ``, + "deep": ``, + } { + if _, err := Compile("cycle", []byte(svg)); err == nil || !strings.Contains(err.Error(), "cycle") { + t.Errorf("%s: compiling a circular use gave %v, want a cycle error", name, err) + } + } +} + +// TestUseOfShapeAndGroupGeometry: a use shifts its target by x/y and inherits +// the use site's paint where the target carries none; a use of a group composes +// the group's own transform; width/height on a use do not scale a shape or +// group target (SVG applies them only to svg/symbol targets). +func TestUseOfShapeAndGroupGeometry(t *testing.T) { + svg := ` + + + +` + icon, err := Compile("use", []byte(svg)) + if err != nil { + t.Fatal(err) + } + if len(icon.Layers) != 2 { + t.Fatalf("two uses compiled to %d layers", len(icon.Layers)) + } + rectMinX, rectMinY, rectMaxX, rectMaxY := starBounds(icon.Layers[0].Commands) + groupMinX, groupMinY, groupMaxX, groupMaxY := starBounds(icon.Layers[1].Commands) + if rectMinX != 20 || rectMinY != 10 || rectMaxX != 30 || rectMaxY != 20 { + t.Errorf("use of a shape at (20,10) with inert width/height drew (%v,%v)..(%v,%v)", + rectMinX, rectMinY, rectMaxX, rectMaxY) + } + // The group's inner rect spans x 1..9, y 0..8 under translate(5,5) and y+30. + if groupMinX != 6 || groupMinY != 35 || groupMaxX != 14 || groupMaxY != 43 { + t.Errorf("use of a group under translate(5,5) y+30 drew (%v,%v)..(%v,%v)", + groupMinX, groupMinY, groupMaxX, groupMaxY) + } + // The bare rect in defs has no fill, so the use site's #00f paints both. + for index, layer := range icon.Layers { + if layer.Fill.Blue != 1 || layer.Fill.Red != 0 || layer.Fill.Green != 0 { + t.Errorf("layer %d fill %v, want the use site's blue", index, layer.Fill) + } + } +} diff --git a/tools/iconcompile/testdata/flag-cn.svg b/tools/iconcompile/testdata/flag-cn.svg new file mode 100644 index 000000000..10d3489a0 --- /dev/null +++ b/tools/iconcompile/testdata/flag-cn.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/tools/iconcompile/testdata/flag-kr.svg b/tools/iconcompile/testdata/flag-kr.svg new file mode 100644 index 000000000..6947eab2b --- /dev/null +++ b/tools/iconcompile/testdata/flag-kr.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/iconcompile/testdata/flag-us.svg b/tools/iconcompile/testdata/flag-us.svg new file mode 100644 index 000000000..9cfd0c927 --- /dev/null +++ b/tools/iconcompile/testdata/flag-us.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tools/patchgen/patchgen.go b/tools/patchgen/patchgen.go index f42168570..f0a5d5636 100644 --- a/tools/patchgen/patchgen.go +++ b/tools/patchgen/patchgen.go @@ -1,5 +1,6 @@ // Package patchgen writes a delta update between two released payloads: the -// installed .app bundle on macOS, or the executable a Linux tar.gz installs. +// installed .app bundle on macOS, the executable a Linux tar.gz installs, or +// the directory the Windows portable zip holds. // // It is a release tool: it imports the bsdiff encoder, which needs a suffix // array and the whole payload in memory. The update package, which runs in the @@ -40,6 +41,10 @@ type Request struct { // Executable is the program's file name in a Linux archive. Empty finds // the only executable in it. Executable string + // Exclude lists paths, relative to the payload root, left out of the + // patch. A Windows portable zip keeps the application's data folder beside + // the program; a patch must not carry it to an installed copy. + Exclude []string // Output receives the gzip tar patch. Output io.Writer } @@ -49,8 +54,8 @@ func Write(request Request) (update.PatchManifest, error) { if request.App == "" || request.FromVersion == "" || request.ToVersion == "" { return update.PatchManifest{}, fmt.Errorf("patchgen: the application and both versions are required") } - if request.OS != "darwin" && request.OS != "linux" { - return update.PatchManifest{}, fmt.Errorf("patchgen: patches are made for darwin and linux, not %q", request.OS) + if request.OS != "darwin" && request.OS != "linux" && request.OS != "windows" { + return update.PatchManifest{}, fmt.Errorf("patchgen: patches are made for darwin, linux and windows, not %q", request.OS) } if request.Arch != "amd64" && request.Arch != "arm64" { return update.PatchManifest{}, fmt.Errorf("patchgen: architecture %q must be amd64 or arm64", request.Arch) @@ -74,11 +79,11 @@ func Write(request Request) (update.PatchManifest, error) { OS: request.OS, Arch: request.Arch, Payload: newKind, } - oldFiles, err := readFiles(oldPayload) + oldFiles, err := readFiles(oldPayload, request.Exclude) if err != nil { return update.PatchManifest{}, err } - newFiles, err := readFiles(newPayload) + newFiles, err := readFiles(newPayload, request.Exclude) if err != nil { return update.PatchManifest{}, err } @@ -138,8 +143,20 @@ func digest(data []byte) string { return hex.EncodeToString(sum[:]) } -func readFiles(root string) (map[string]fileData, error) { +func readFiles(root string, exclude []string) (map[string]fileData, error) { files := make(map[string]fileData) + excluded := func(relative string) bool { + for _, prefix := range exclude { + prefix = strings.Trim(strings.ReplaceAll(prefix, "\\", "/"), "/") + if prefix == "" { + continue + } + if relative == prefix || strings.HasPrefix(relative, prefix+"/") { + return true + } + } + return false + } err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { if err != nil { return err @@ -158,6 +175,10 @@ func readFiles(root string) (map[string]fileData, error) { if err != nil { return err } + relative = filepath.ToSlash(relative) + if excluded(relative) { + return nil + } data, err := os.ReadFile(path) if err != nil { return err @@ -227,6 +248,16 @@ func extractPayload(archive, goos, arch, executable string) (root, kind string, return "", "", nil, fmt.Errorf("patchgen: %s is not a macOS bundle", filepath.Base(archive)) } return bundles[0], "app", removeTree, nil + case "windows": + if !strings.HasSuffix(strings.ToLower(archive), ".zip") { + removeTree() + return "", "", nil, fmt.Errorf("patchgen: Windows payloads come from the portable .zip, not %s", filepath.Base(archive)) + } + if err := extractZip(archive, directory); err != nil { + removeTree() + return "", "", nil, err + } + return directory, "dir", removeTree, nil default: if !strings.HasSuffix(strings.ToLower(archive), ".tar.gz") { removeTree() diff --git a/tools/patchgen/patchgen_test.go b/tools/patchgen/patchgen_test.go index 452793a86..750d46990 100644 --- a/tools/patchgen/patchgen_test.go +++ b/tools/patchgen/patchgen_test.go @@ -176,3 +176,64 @@ func TestWriteRefusesUnsupportedTargets(t *testing.T) { } } } + +func TestWriteWindowsPortablePatch(t *testing.T) { + dir := t.TempDir() + oldArchive := filepath.Join(dir, "app-1.0.0-windows-amd64.zip") + newArchive := filepath.Join(dir, "app-1.1.0-windows-amd64.zip") + writeZip(t, oldArchive, map[string][]byte{ + "app.exe": []byte("old program"), + "conpty/x64/conpty.dll": []byte("dll"), + "motty-data/README.txt": []byte("data"), + }) + writeZip(t, newArchive, map[string][]byte{ + "app.exe": []byte("new program with more"), + "conpty/x64/conpty.dll": []byte("dll"), + "motty-data/README.txt": []byte("changed data"), + }) + patchPath := filepath.Join(dir, "app.patch") + file, err := os.Create(patchPath) + if err != nil { + t.Fatal(err) + } + manifest, err := Write(Request{ + App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "windows", Arch: "amd64", OldArchive: oldArchive, NewArchive: newArchive, + Exclude: []string{"motty-data"}, Output: file, + }) + file.Close() + if err != nil { + t.Fatal(err) + } + if manifest.Payload != "dir" || len(manifest.Files) != 2 { + t.Fatalf("manifest = %+v", manifest) + } + for _, file := range manifest.Files { + if file.Path == "motty-data/README.txt" { + t.Fatal("the data folder reached the patch") + } + } + patch, err := update.ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + defer patch.Close() + oldRoot := t.TempDir() + if err := os.MkdirAll(filepath.Join(oldRoot, "conpty", "x64"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(oldRoot, "app.exe"), []byte("old program"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(oldRoot, "conpty", "x64", "conpty.dll"), []byte("dll"), 0o644); err != nil { + t.Fatal(err) + } + staging := filepath.Join(dir, "staged") + if err := patch.Apply(oldRoot, staging); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(staging, "app.exe")) + if err != nil || string(got) != "new program with more" { + t.Fatalf("app.exe = %q, %v", got, err) + } +} diff --git a/tools/rpmpkg/rpmpkg.go b/tools/rpmpkg/rpmpkg.go new file mode 100644 index 000000000..b40652b4d --- /dev/null +++ b/tools/rpmpkg/rpmpkg.go @@ -0,0 +1,530 @@ +// Package rpmpkg writes RPM binary packages (.rpm) for a desktop application: +// the program in /usr/bin, a menu entry, the MIME type and the hicolor icons. +// The file list is the one debpkg makes, so a .deb and an .rpm of the same +// application install the same files. +// +// An RPM is a lead, a signature header holding digests of what follows, the +// header (tags describing the package and its files) and a gzip-compressed cpio +// payload. The writer makes unsigned packages: it fills in the digests rpm +// verifies, so rpm -K --nosignature reports them intact. A full rpm -K also +// reports the missing signature, which is expected for an unsigned package. The output is +// deterministic: files are sorted, owners are root and the build time is +// tarball.SourceDate. +package rpmpkg + +import ( + "bytes" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "path" + "regexp" + "sort" + "strings" + "time" + + "github.com/vivaui/viva/tools/debpkg" + "github.com/vivaui/viva/tools/tarball" +) + +// Package describes one RPM. +type Package struct { + // App is the application: the same description the .deb is written from. + // Its Depends are Debian names and are not used; see Requires. + App debpkg.Package + // Release is the release number, 1 when empty. + Release string + // 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). + Requires []string +} + +var ( + rpmVersionPattern = regexp.MustCompile(`^[0-9][A-Za-z0-9._+~^]*$`) + rpmReleasePattern = regexp.MustCompile(`^[0-9][A-Za-z0-9._+~^]*$`) +) + +// rpmArch is the architecture name rpm uses for a Viva architecture. +func rpmArch(arch string) (string, error) { + switch arch { + case "amd64": + return "x86_64", nil + case "arm64": + return "aarch64", nil + } + return "", fmt.Errorf("rpmpkg: architecture %q must be amd64 or arm64", arch) +} + +func (pkg Package) release() string { + if pkg.Release == "" { + return "1" + } + return pkg.Release +} + +func (pkg Package) license() string { + if pkg.License == "" { + return "Unspecified" + } + return pkg.License +} + +func (pkg Package) check() error { + if _, err := debpkg.PackageName(pkg.App.Executable); err != nil { + return err + } + if !rpmVersionPattern.MatchString(pkg.App.Version) { + return fmt.Errorf("rpmpkg: %q is not an RPM version (it starts with a digit and has no hyphen)", pkg.App.Version) + } + if !rpmReleasePattern.MatchString(pkg.release()) { + return fmt.Errorf("rpmpkg: %q is not an RPM release", pkg.release()) + } + if _, err := rpmArch(pkg.App.Arch); err != nil { + return err + } + if pkg.App.Name == "" { + return errors.New("rpmpkg: the application needs a display name") + } + if len(pkg.App.Program) == 0 { + return errors.New("rpmpkg: the program is empty") + } + if strings.ContainsAny(pkg.App.Comment, "\r\n") { + return errors.New("rpmpkg: the comment must be one line") + } + if pkg.App.Maintainer == "" || strings.ContainsAny(pkg.App.Maintainer, "\r\n") { + return errors.New("rpmpkg: the maintainer must be one line") + } + for _, requirement := range pkg.Requires { + if requirement == "" || strings.ContainsAny(requirement, " ,\r\n\t") { + return fmt.Errorf("rpmpkg: %q is not one capability name", requirement) + } + } + return nil +} + +// Name is the RPM name: the executable's package name as debpkg derives it. +func (pkg Package) Name() (string, error) { + return debpkg.PackageName(pkg.App.Executable) +} + +// FileName is the conventional file name, --..rpm. +func (pkg Package) FileName() (string, error) { + if err := pkg.check(); err != nil { + return "", err + } + name, _ := pkg.Name() + arch, _ := rpmArch(pkg.App.Arch) + return fmt.Sprintf("%s-%s-%s.%s.rpm", name, pkg.App.Version, pkg.release(), arch), nil +} + +// Write writes the .rpm. +func (pkg Package) Write(output io.Writer) error { + if err := pkg.check(); err != nil { + return err + } + name, _ := pkg.Name() + arch, _ := rpmArch(pkg.App.Arch) + files, err := pkg.App.Files() + if err != nil { + return err + } + modified := tarball.SourceDate() + installed := installedFiles(files) + nevr := name + "-" + pkg.App.Version + "-" + pkg.release() + + cpio := cpioArchive(installed, uint32(modified.Unix())) + payload, err := tarball.Gzip(cpio) + if err != nil { + return err + } + // rpm checks the payload digest over the payload bytes as stored, that is + // the compressed stream (rpm 6 reports a mismatch for the uncompressed cpio). + payloadSum := sha256.Sum256(payload) + header := encodeHeader(regionHeader, pkg.headerEntries(name, nevr, arch, installed, modified, hex.EncodeToString(payloadSum[:]))) + + // The signature header covers the header and the compressed payload, as + // rpm's own digests do. + covered := append(append([]byte(nil), header...), payload...) + sha1Sum := sha1.Sum(header) + sha256Sum := sha256.Sum256(header) + md5Sum := md5.Sum(covered) + signature := padTo(encodeHeader(regionSignature, []entry{ + int32Tag(tagSigSize, []uint32{uint32(len(covered))}), + int32Tag(tagSigPayloadSize, []uint32{uint32(len(cpio))}), + binTag(tagSigMD5, md5Sum[:]), + stringTag(tagSigSHA1, hex.EncodeToString(sha1Sum[:])), + stringTag(tagSigSHA256, hex.EncodeToString(sha256Sum[:])), + }), 8) + + for _, part := range [][]byte{leadBytes(nevr), signature, header, payload} { + if _, err := output.Write(part); err != nil { + return err + } + } + return nil +} + +// installedFile is one file of the payload with the values the header needs. +type installedFile struct { + full string // absolute path, starting with / + dir string // the directory with a trailing slash + base string + data []byte + mode uint16 // the regular-file type bits with the permission bits +} + +// installedFiles sorts the files by absolute path. The header's file arrays +// and the payload both use this order, which rpm requires. +func installedFiles(files []tarball.File) []installedFile { + sorted := append([]tarball.File(nil), files...) + sort.Slice(sorted, func(i, j int) bool { return sorted[i].Path < sorted[j].Path }) + out := make([]installedFile, 0, len(sorted)) + for _, file := range sorted { + full := "/" + file.Path + out = append(out, installedFile{ + full: full, + dir: path.Dir(full) + "/", + base: path.Base(full), + data: file.Data, + mode: uint16(0o100000 | (file.Mode & 0o7777)), + }) + } + return out +} + +// headerEntries are the tags of the package header, sorted by tag when encoded. +func (pkg Package) headerEntries(name, nevr, arch string, files []installedFile, modified time.Time, payloadDigest string) []entry { + count := len(files) + var installedSize uint32 + sizes := make([]uint32, count) + modes := make([]uint16, count) + rdevs := make([]uint16, count) + mtimes := make([]uint32, count) + digests := make([]string, count) + links := make([]string, count) + flags := make([]uint32, count) + verify := make([]uint32, count) + users := make([]string, count) + inodes := make([]uint32, count) + devices := make([]uint32, count) + langs := make([]string, count) + dirIndexes := make([]uint32, count) + baseNames := make([]string, count) + var dirs []string + dirIndex := map[string]uint32{} + for i, file := range files { + installedSize += uint32(len(file.data)) + sizes[i] = uint32(len(file.data)) + modes[i] = file.mode + mtimes[i] = uint32(modified.Unix()) + sum := sha256.Sum256(file.data) + digests[i] = hex.EncodeToString(sum[:]) + users[i] = "root" + inodes[i] = uint32(i + 1) + devices[i] = 1 + verify[i] = 0xffffffff + if _, ok := dirIndex[file.dir]; !ok { + dirIndex[file.dir] = uint32(len(dirs)) + dirs = append(dirs, file.dir) + } + dirIndexes[i] = dirIndex[file.dir] + baseNames[i] = file.base + } + + entries := []entry{ + stringTag(tagName, name), + stringTag(tagVersion, pkg.App.Version), + stringTag(tagRelease, pkg.release()), + i18nTag(tagSummary, pkg.App.Comment), + i18nTag(tagDescription, descriptionOf(pkg.App)), + int32Tag(tagBuildTime, []uint32{uint32(modified.Unix())}), + stringTag(tagBuildHost, "viva"), + int32Tag(tagSize, []uint32{installedSize}), + stringTag(tagLicense, pkg.license()), + stringTag(tagPackager, pkg.App.Maintainer), + i18nTag(tagGroup, "Applications/System"), + stringTag(tagOS, "linux"), + stringTag(tagArch, arch), + stringTag(tagSourceRPM, nevr+".src.rpm"), + int32Tag(tagFileSizes, sizes), + int16Tag(tagFileModes, modes), + int16Tag(tagFileRDevs, rdevs), + int32Tag(tagFileMTimes, mtimes), + stringArrayTag(tagFileDigests, digests), + stringArrayTag(tagFileLinkTos, links), + int32Tag(tagFileFlags, flags), + int32Tag(tagFileVerifyFlags, verify), + stringArrayTag(tagFileUserName, users), + stringArrayTag(tagFileGroupName, users), + int32Tag(tagFileDevices, devices), + int32Tag(tagFileInodes, inodes), + stringArrayTag(tagFileLangs, langs), + int32Tag(tagDirIndexes, dirIndexes), + stringArrayTag(tagBaseNames, baseNames), + stringArrayTag(tagDirNames, dirs), + stringArrayTag(tagProvideName, []string{name}), + int32Tag(tagProvideFlags, []uint32{rpmSenseEqual}), + stringArrayTag(tagProvideVersion, []string{strings.TrimPrefix(nevr, name+"-")}), + stringTag(tagPayloadFormat, "cpio"), + stringTag(tagPayloadCompressor, "gzip"), + stringTag(tagPayloadFlags, "9"), + int32Tag(tagFileDigestAlgo, []uint32{8}), // PGPHASHALGO_SHA256 + stringArrayTag(tagPayloadDigest, []string{payloadDigest}), + int32Tag(tagPayloadDigestAlgo, []uint32{8}), + } + if pkg.App.Homepage != "" { + entries = append(entries, stringTag(tagURL, pkg.App.Homepage)) + } + if len(pkg.Requires) > 0 { + entries = append(entries, + stringArrayTag(tagRequireName, pkg.Requires), + int32Tag(tagRequireFlags, make([]uint32, len(pkg.Requires))), + stringArrayTag(tagRequireVersion, make([]string, len(pkg.Requires))), + ) + } + return entries +} + +// descriptionOf is the package description: the extended text when there is +// one, otherwise the one-line comment (rpm needs a description). +func descriptionOf(app debpkg.Package) string { + if text := strings.TrimSpace(app.Description); text != "" { + return text + } + if app.Comment != "" { + return app.Comment + } + return app.Name +} + +// rpmSenseEqual is RPMSENSE_EQUAL: the provide's version must equal the one given. +const rpmSenseEqual = 8 + +// cpioArchive writes the payload as a newc cpio archive with rpm's "./" names, +// ending with the TRAILER!!! entry. Every file is owned by root and has one +// time, so the output is reproducible. +func cpioArchive(files []installedFile, mtime uint32) []byte { + var out bytes.Buffer + for i, file := range files { + writeCPIOEntry(&out, uint32(i+1), uint32(file.mode), mtime, file.data, "."+file.full) + } + writeCPIOEntry(&out, 0, 0, mtime, nil, "TRAILER!!!") + return out.Bytes() +} + +// writeCPIOEntry writes one newc entry: "070701", thirteen 8-digit hex fields, +// the name with its NUL padded to 4 bytes from the header start, and the data +// padded to 4 bytes. +func writeCPIOEntry(out *bytes.Buffer, inode, mode, mtime uint32, data []byte, name string) { + nameZ := name + "\x00" + fields := []uint32{ + inode, mode, 0, 0, 1, mtime, uint32(len(data)), + 0, 0, 0, 0, uint32(len(nameZ)), 0, + } + out.WriteString("070701") + for _, field := range fields { + fmt.Fprintf(out, "%08X", field) + } + out.WriteString(nameZ) + out.Write(make([]byte, padLen(110+len(nameZ), 4))) + out.Write(data) + out.Write(make([]byte, padLen(len(data), 4))) +} + +// padLen is how many zero bytes bring n up to a multiple of align. +func padLen(n, align int) int { + return (align - n%align) % align +} + +// padTo appends zeros until the length is a multiple of align. +func padTo(data []byte, align int) []byte { + return append(data, make([]byte, padLen(len(data), align))...) +} + +// leadBytes is the 96-byte lead: the magic, the format version 3.0, a binary +// package, the signature type 5 (a header), Linux, and the name-version-release +// (66 bytes, NUL-terminated). +func leadBytes(nevr string) []byte { + lead := make([]byte, 96) + copy(lead, []byte{0xed, 0xab, 0xee, 0xdb, 3, 0}) + binary.BigEndian.PutUint16(lead[6:], 0) // package type: binary + binary.BigEndian.PutUint16(lead[8:], 1) // archnum: not used by rpm to install + copy(lead[10:76], nevr) // name, NUL-terminated + binary.BigEndian.PutUint16(lead[76:], 1) // osnum: Linux + binary.BigEndian.PutUint16(lead[78:], 5) // signature type: header + return lead +} + +// entry is one header tag: its value's type, element count and encoded bytes. +type entry struct { + tag, typ, count uint32 + data []byte +} + +func stringTag(tag uint32, value string) entry { + return entry{tag, typeString, 1, append([]byte(value), 0)} +} + +func i18nTag(tag uint32, value string) entry { + return entry{tag, typeI18N, 1, append([]byte(value), 0)} +} + +func stringArrayTag(tag uint32, values []string) entry { + var data []byte + for _, value := range values { + data = append(append(data, value...), 0) + } + return entry{tag, typeStringList, uint32(len(values)), data} +} + +func binTag(tag uint32, value []byte) entry { + return entry{tag, typeBin, uint32(len(value)), append([]byte(nil), value...)} +} + +func int16Tag(tag uint32, values []uint16) entry { + data := make([]byte, 2*len(values)) + for i, value := range values { + binary.BigEndian.PutUint16(data[2*i:], value) + } + return entry{tag, typeInt16, uint32(len(values)), data} +} + +func int32Tag(tag uint32, values []uint32) entry { + data := make([]byte, 4*len(values)) + for i, value := range values { + binary.BigEndian.PutUint32(data[4*i:], value) + } + return entry{tag, typeInt32, uint32(len(values)), data} +} + +// alignment is the byte boundary a value of the type must start on in the +// header's data area. +func alignment(typ uint32) int { + switch typ { + case typeInt16: + return 2 + case typeInt32: + return 4 + } + return 1 +} + +// encodeHeader writes a header section: the magic, the index count and the data +// size, the index records, then the data. The last index record is the region +// tag, whose 16-byte data repeats it, so rpm can find where the header ends. +func encodeHeader(region uint32, entries []entry) []byte { + sort.SliceStable(entries, func(i, j int) bool { return entries[i].tag < entries[j].tag }) + var data bytes.Buffer + type record struct{ tag, typ, offset, count uint32 } + records := make([]record, 0, len(entries)+1) + for _, item := range entries { + for data.Len()%alignment(item.typ) != 0 { + data.WriteByte(0) + } + records = append(records, record{item.tag, item.typ, uint32(data.Len()), item.count}) + data.Write(item.data) + } + // The trailer is the last 16 bytes of the data: a copy of the region record + // whose offset is minus the record count, itself included. The region record + // in the index points at that copy. Both match rpm's own headers. + regionCount := len(records) + 1 + trailer := make([]byte, 16) + binary.BigEndian.PutUint32(trailer[0:], region) + binary.BigEndian.PutUint32(trailer[4:], typeBin) + binary.BigEndian.PutUint32(trailer[8:], uint32(int32(-regionCount*16))) + binary.BigEndian.PutUint32(trailer[12:], 16) + records = append(records, record{region, typeBin, uint32(data.Len()), 16}) + // The region record sorts with the others: its tag (62 or 63) is lower than + // every other tag, so rpm finds it first in the index. + sort.SliceStable(records, func(i, j int) bool { return records[i].tag < records[j].tag }) + data.Write(trailer) + + var out bytes.Buffer + out.Write([]byte{0x8e, 0xad, 0xe8, 0x01, 0, 0, 0, 0}) + binary.Write(&out, binary.BigEndian, uint32(len(records))) + binary.Write(&out, binary.BigEndian, uint32(data.Len())) + for _, item := range records { + binary.Write(&out, binary.BigEndian, [4]uint32{item.tag, item.typ, item.offset, item.count}) + } + out.Write(data.Bytes()) + return out.Bytes() +} + +// Region tags: the main header and the signature header each end with one. +const ( + regionHeader = 63 // RPMTAG_HEADERIMMUTABLE + regionSignature = 62 // RPMTAG_HEADERSIGNATURES +) + +// Tags, from rpm's rpmtag.h. Only the ones the writer uses are listed. +const ( + tagName = 1000 + tagVersion = 1001 + tagRelease = 1002 + tagSummary = 1004 + tagDescription = 1005 + tagBuildTime = 1006 + tagBuildHost = 1007 + tagSize = 1009 + tagLicense = 1014 + tagPackager = 1015 + tagGroup = 1016 + tagURL = 1020 + tagOS = 1021 + tagArch = 1022 + tagFileSizes = 1028 + tagProvideName = 1047 + tagFileModes = 1030 + tagFileRDevs = 1033 + tagFileMTimes = 1034 + tagFileDigests = 1035 + tagFileLinkTos = 1036 + tagFileFlags = 1037 + tagFileUserName = 1039 + tagFileGroupName = 1040 + tagSourceRPM = 1044 + tagFileVerifyFlags = 1045 + tagRequireFlags = 1048 + tagRequireName = 1049 + tagRequireVersion = 1050 + tagFileDevices = 1095 + tagFileInodes = 1096 + tagFileLangs = 1097 + tagProvideFlags = 1112 + tagProvideVersion = 1113 + tagDirIndexes = 1116 + tagBaseNames = 1117 + tagDirNames = 1118 + tagPayloadFormat = 1124 + tagPayloadCompressor = 1125 + tagPayloadFlags = 1126 + tagFileDigestAlgo = 5011 + tagPayloadDigest = 5092 + tagPayloadDigestAlgo = 5093 +) + +// Tags of the signature header. +const ( + tagSigSHA1 = 269 + tagSigSHA256 = 273 + tagSigSize = 1000 + tagSigMD5 = 1004 + tagSigPayloadSize = 1007 +) + +// Value types, from rpm's rpmtag.h. +const ( + typeInt16 = 3 + typeInt32 = 4 + typeString = 6 + typeBin = 7 + typeStringList = 8 + typeI18N = 9 +) diff --git a/tools/rpmpkg/rpmpkg_test.go b/tools/rpmpkg/rpmpkg_test.go new file mode 100644 index 000000000..fe87ada41 --- /dev/null +++ b/tools/rpmpkg/rpmpkg_test.go @@ -0,0 +1,147 @@ +package rpmpkg + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/vivaui/viva/tools/debpkg" + "github.com/vivaui/viva/tools/tarball" +) + +// sample is a small application description shared by the tests. +func sample() Package { + return Package{ + App: debpkg.Package{ + Executable: "lithe_desktop", ID: "app.lithe.desktop", Name: "Lithe Desktop", + Version: "0.9.1", Arch: "amd64", Maintainer: "Lithe Maintainers", + Homepage: "https://example.com/lithe", Comment: "A test application", + Description: "First paragraph.\n\nSecond paragraph.", + Category: "Development", Keywords: []string{"ide"}, + Program: []byte("#!/bin/sh\necho hi\n"), + }, + Requires: []string{"vulkan-loader", "libxcb", "cairo"}, + } +} + +func TestFileNameFollowsRPMConvention(t *testing.T) { + pkg := sample() + name, err := pkg.FileName() + if err != nil { + t.Fatal(err) + } + if want := "lithe-desktop-0.9.1-1.x86_64.rpm"; name != want { + t.Fatalf("FileName() = %q, want %q", name, want) + } + pkg.App.Arch = "arm64" + if name, _ = pkg.FileName(); !strings.HasSuffix(name, ".aarch64.rpm") { + t.Fatalf("arm64 FileName() = %q, want aarch64 suffix", name) + } +} + +func TestRejectsVersionsRPMCannotName(t *testing.T) { + pkg := sample() + pkg.App.Version = "0.9.1-preview" + if _, err := pkg.FileName(); err == nil { + t.Fatal("a version with a hyphen must be refused: rpm versions cannot contain '-'") + } +} + +func TestLeadMagicAndNEVR(t *testing.T) { + lead := leadBytes("lithe-desktop-0.9.1-1") + if len(lead) != 96 { + t.Fatalf("lead is %d bytes, want 96", len(lead)) + } + if !bytes.Equal(lead[:4], []byte{0xed, 0xab, 0xee, 0xdb}) { + t.Fatalf("lead magic = % x", lead[:4]) + } + if got := strings.TrimRight(string(lead[10:76]), "\x00"); got != "lithe-desktop-0.9.1-1" { + t.Fatalf("lead name = %q", got) + } +} + +func TestCPIONamesAndTrailer(t *testing.T) { + files := installedFiles(sample().mustFiles(t)) + archive := cpioArchive(files, 0) + if !bytes.HasPrefix(archive, []byte("070701")) { + t.Fatalf("payload does not start with a newc header: %q", archive[:6]) + } + if !bytes.Contains(archive, []byte("./usr/bin/lithe_desktop\x00")) { + t.Fatal("payload does not name the program ./usr/bin/lithe_desktop") + } + if !bytes.Contains(archive, []byte("TRAILER!!!\x00")) { + t.Fatal("payload has no TRAILER!!! entry") + } +} + +func (pkg Package) mustFiles(t *testing.T) []tarball.File { + t.Helper() + files, err := pkg.App.Files() + if err != nil { + t.Fatal(err) + } + return files +} + +// TestWriteVerifiesWithRPMTools builds a package and asks the real rpm tools to +// read it. It is skipped where rpm is not installed (on macOS: brew install rpm). +func TestWriteVerifiesWithRPMTools(t *testing.T) { + rpm, err := exec.LookPath("rpm") + if err != nil { + t.Skip("rpm is not installed") + } + dir := t.TempDir() + pkg := sample() + name, err := pkg.FileName() + if err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, name) + file, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + if err := pkg.Write(file); err != nil { + file.Close() + t.Fatal(err) + } + if err := file.Close(); err != nil { + t.Fatal(err) + } + + run := func(args ...string) string { + t.Helper() + out, err := exec.Command(rpm, args...).CombinedOutput() + if err != nil { + t.Fatalf("rpm %s: %v\n%s", strings.Join(args, " "), err, out) + } + return string(out) + } + fields := run("-qp", "--queryformat", "%{NAME} %{VERSION} %{RELEASE} %{ARCH} %{LICENSE} %{URL}\n", path) + if want := "lithe-desktop 0.9.1 1 x86_64 Unspecified https://example.com/lithe\n"; fields != want { + t.Fatalf("rpm query fields = %q, want %q", fields, want) + } + if summary := run("-qp", "--queryformat", "%{SUMMARY}\n", path); summary != "A test application\n" { + t.Fatalf("rpm summary = %q, want %q", summary, "A test application\n") + } + list := run("-qpl", path) + for _, want := range []string{"/usr/bin/lithe_desktop", "/usr/share/applications/app.lithe.desktop.desktop"} { + if !strings.Contains(list, want) { + t.Fatalf("rpm -qpl lacks %q:\n%s", want, list) + } + } + // The package is unsigned, so the signature check is skipped; the digests + // must all be intact, and the header and payload SHA-256 must be present. + check := run("-K", "--nosignature", "-v", path) + for _, want := range []string{"Header SHA256 digest: OK", "Payload SHA256 digest: OK"} { + if !strings.Contains(check, want) { + t.Fatalf("rpm -K lacks %q:\n%s", want, check) + } + } + if strings.Contains(check, "BAD") || strings.Contains(check, "NOT OK") { + t.Fatalf("rpm -K reports a digest mismatch:\n%s", check) + } +} diff --git a/tools/testenv/README.md b/tools/testenv/README.md index 5f50db3a3..f9eb68750 100644 --- a/tools/testenv/README.md +++ b/tools/testenv/README.md @@ -19,11 +19,11 @@ machine and record what was not automated. | | Linux | | --- | --- | -| System | Debian 12 x86_64, KDE Plasma on X11 (a real StatusNotifier tray), Xvnc 1920x1080 | -| Graphics | software Vulkan only (lavapipe), no GPU | +| System | Debian 12 x86_64 desktop container, Xvnc 1920x1080, `DISPLAY=:1` | +| Graphics | no Vulkan or discrete GPU: software rendering only (the CPU rasterizer; a software Vulkan build may be installed separately) | | API | `${VIVA_LINUX_ENV}` | | Watch the screen | a VNC view served beside the API, self-signed | -| User | an ordinary desktop user with sudo | +| User | an ordinary desktop user with sudo (`user`, password in `local.sh`) | ## HTTP API diff --git a/ui/base_contract_test.go b/ui/base_contract_test.go new file mode 100644 index 000000000..21872c615 --- /dev/null +++ b/ui/base_contract_test.go @@ -0,0 +1,53 @@ +package ui + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// The Bases without a test of their own are still controls without a look: +// they paint no surface, and declare the role and state assistive technology +// needs. ButtonBase, the item Bases, InputBase and TextareaBase have their own +// tests; this table keeps the rest from drifting. +func TestEveryRemainingBaseIsItsControlWithoutALook(t *testing.T) { + theme := gfx.LightTheme() + scope := tree.Sub(page, tree.Name("base-contract")) + type base struct { + name string + role gfx.Role + build func(f *Frame, id gfx.ID) Box + state func(gfx.Hit) bool + } + bases := []base{ + {"checkbox", gfx.RoleCheckbox, func(f *Frame, id gfx.ID) Box { return f.CheckboxBase(id, true) }, + func(h gfx.Hit) bool { return h.Checked }}, + {"switch", gfx.RoleSwitch, func(f *Frame, id gfx.ID) Box { return f.SwitchBase(id, true) }, + func(h gfx.Hit) bool { return h.Checked }}, + {"slider", gfx.RoleSlider, func(f *Frame, id gfx.ID) Box { + return f.SliderBase(id, &SliderState{}).Size(120, 16) + }, func(h gfx.Hit) bool { return h.Range.Set }}, + {"select", gfx.RoleCombobox, func(f *Frame, id gfx.ID) Box { + return f.SelectBase(scope, &SelectState{}, []string{"Small", "Large"}, 0).Size(120, 32) + }, func(h gfx.Hit) bool { return h.Value == "Small" && !h.Expanded }}, + } + for _, b := range bases { + t.Run(b.name, func(t *testing.T) { + var view View + canvas := testCanvas() + view.Draw(canvas, theme, gfx.Rect{Width: 240, Height: 100}, func(f *Frame) { + b.build(f, tree.ID(page, "base-contract-"+b.name)) + }) + if len(canvas.Rectangles()) != 0 || len(canvas.Shadows()) != 0 { + t.Errorf("a Base painted a look: %d rectangles, %d shadows", len(canvas.Rectangles()), len(canvas.Shadows())) + } + hits := canvas.Hits() + if len(hits) != 1 { + t.Fatalf("hits = %+v, want one", hits) + } + if hit := hits[0]; hit.Role != b.role || !hit.Focusable || !b.state(hit) { + t.Errorf("hit = %+v, want a focusable %v in its state", hit, b.role) + } + }) + } +} diff --git a/ui/contextmenu_geometry_test.go b/ui/contextmenu_geometry_test.go new file mode 100644 index 000000000..3ee9d2139 --- /dev/null +++ b/ui/contextmenu_geometry_test.go @@ -0,0 +1,55 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A captured header opens the same context-menu rows as a hit target, at the +// pointer. At a window edge the surface clamps instead of flipping to the row's +// other side, so the rows that stay visible do not reorder their geometry. +func TestContextMenuAtKeepsItsOriginAndDenseRows(t *testing.T) { + m := &contextModel{hosts: []string{"alpha"}} + var menu *ui.MenuItems + at := gfx.Point{X: 45, Y: 267} + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.Button(c, "alpha") + ui.ContextMenuAt(c, ui.Button(c, "Header"), &m.open, at, func(items *ui.MenuItems) { + menu = items + items.RowHeight(24) + menu.Item("One") + menu.Item("Two") + menu.Separator() + if menu.Item("Connect").Clicked() { + m.connected = "alpha" + } + }) + }) + }) + if m.open { + t.Fatal("a closed menu must not declare its rows") + } + m.open = true + d.repaint() + first, second := d.hit("One").Bounds, d.hit("Two").Bounds + if first.X != at.X+4 || first.Y != at.Y+4 || first.Height != 24 || second.Y-first.Y != 24 { + t.Fatalf("dense rows are %v and %v, want origin %v plus the surface inset", first, second, at) + } + if menu == nil { + t.Fatal("the menu did not expose its public per-menu options") + } + d.click("Connect") + if m.connected != "alpha" || m.open { + t.Fatalf("choosing Connect left connected=%q open=%v", m.connected, m.open) + } + + m.open, at = true, gfx.Point{X: 45, Y: 147} + d.repaint() + first, second = d.hit("One").Bounds, d.hit("Two").Bounds + if first.Y != at.Y+4 || second.Y-first.Y != 24 { + t.Fatalf("the menu flipped above the pointer: %v and %v, want %v and 24px apart", first, second, at) + } +} diff --git a/ui/doc.go b/ui/doc.go index 8590c0e26..ce4bd65fc 100644 --- a/ui/doc.go +++ b/ui/doc.go @@ -80,6 +80,18 @@ // (components.TextEntryRecipe), the rest stays, and no variant is needed to make a field // square or thick-framed. See recipe.go, bases.go and draw.go. // +// Restyling a control has four steps, from the cheapest to the most open: the +// theme's tokens (gfx.Theme.Metrics and its colors), the control's Base dressed +// with its own Background, Border, Radius, Shadow, Pad, looks and Draw starting +// from a recipe, the parts a composite control exposes (SelectBase's trigger, +// popup and rows; a strip of TabBase or RadioBase), and Control with Handlers +// for a control the application writes itself. A control that ships with the +// theme's look paints its own surface over the element's, so a Button, Checkbox, +// Switch, Select, Tabs, Segmented, Slider or InputGroup ignores its element's +// Background and Border; give it a look by using its Base. The Bases themselves +// paint no surface: what they declare is the role, the focus, the keyboard, the +// pointer and the state assistive technology reads, and tests hold them to that. +// // A control of the application's own is Control(c, label, handlers): a focusable // empty element painted with Draw, whose Handlers take its keys, pointer and // wheel, and whose regions declared with Canvas.Hit inside Draw reach the same diff --git a/ui/field.go b/ui/field.go index 81b8590b9..d194702d2 100644 --- a/ui/field.go +++ b/ui/field.go @@ -42,6 +42,9 @@ type Field struct { // declaration found it edited since the one before (Box.Changed). seen string changed bool + // spans is the scratch the secondary selections' byte offsets are copied + // into each paint. + spans []text.Span // area lays a field out in rows when it is declared as a FieldArea; nil until it // is. rows is whether the last declaration was one: a field declared as a // FieldArea once and as a Field since keeps its layout but moves by its line. @@ -120,6 +123,7 @@ func (f *frame) FieldArea(field *Field, id gfx.ID, label, placeholder string) Bo ID: input.ID, Label: input.Label, Value: input.Value, DisplayValue: input.Value, Placeholder: placeholder, Focused: input.Focused, HideEditorText: true, ShowCaret: input.ShowCaret, Layout: field.area, Caret: input.Caret, SelectionStart: input.SelectionStart, SelectionEnd: input.SelectionEnd, + SelectionRanges: input.SelectionRanges, CompositionStart: input.CompositionStart, CompositionEnd: input.CompositionEnd, }) } @@ -173,6 +177,14 @@ func (field *Field) snapshot(f *frame, id gfx.ID, label, placeholder string) com snapshot.Caret = editor.ByteOffset(editor.Caret()) snapshot.SelectionStart, snapshot.SelectionEnd = editor.ByteOffset(selection.Start), editor.ByteOffset(selection.End) snapshot.ShowCaret = focused && selection.Start == selection.End + if editor.SelectionCount() > 1 { + // A field bound to a multi-selection editor paints every selection; the + // platform's own editor behind it still sees only the primary one. The + // field is the editor's owner, not a copy: a caller that adds a selection + // sees it without another declaration. + snapshot.SelectionRanges = editor.SelectionSpansInto(field.spans) + field.spans = snapshot.SelectionRanges + } if marked, ok := editor.Composition(); ok { snapshot.CompositionStart, snapshot.CompositionEnd = editor.ByteOffset(marked.Start), editor.ByteOffset(marked.End) } diff --git a/ui/field_multiselection_test.go b/ui/field_multiselection_test.go new file mode 100644 index 000000000..7267fdda8 --- /dev/null +++ b/ui/field_multiselection_test.go @@ -0,0 +1,63 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" +) + +// A Field bound to a multi-selection editor paints every selection: adding one +// to the editor shows up as another band of selection color, without the field +// being told anything but the editor. +func TestFieldPaintsMultipleSelections(t *testing.T) { + editor := text.NewEditor("abcdef") + var field ui.Field + field.Bind(editor) + search := gfx.Item(9) + view := func(c ui.C) { + ui.TextFieldID(c, search, &field, "Search", "").Width(200) + } + d := openPage(t, view) + bands := func() int { + d.repaint() + count := 0 + for _, primitive := range d.driver.Snapshot().Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Color == pageTheme.Selection { + count++ + } + } + return count + } + editor.SetSelection(text.Range{Start: 0, End: 1}) + if got := bands(); got != 1 { + t.Fatalf("one selection painted %d bands", got) + } + editor.AddSelection(text.Range{Start: 3, End: 5}) + if got := bands(); got != 2 { + t.Fatalf("two selections painted %d bands", got) + } + editor.ClearSecondarySelections() + if got := bands(); got != 1 { + t.Fatalf("after clearing: %d bands", got) + } +} + +// The multi-selection paint is allocation-free like the single-selection one: +// the field copies the editor's spans into its own scratch. +func TestFieldMultiSelectionPaintAllocatesNothing(t *testing.T) { + editor := text.NewEditor("abcdef") + editor.SetSelections([]text.Range{{Start: 0, End: 1}, {Start: 3, End: 5}}, 1) + var field ui.Field + field.Bind(editor) + search := gfx.Item(9) + d := openPage(t, func(c ui.C) { + ui.TextFieldID(c, search, &field, "Search", "").Width(200) + }) + d.repaint() + if allocations := testing.AllocsPerRun(100, d.repaint); allocations != 0 { + t.Fatalf("%v allocations a repaint", allocations) + } +} diff --git a/ui/frame.go b/ui/frame.go index 0413ce9b7..bf9e7e836 100644 --- a/ui/frame.go +++ b/ui/frame.go @@ -225,6 +225,7 @@ type extra struct { type frame struct { canvas *gfx.Canvas theme Theme + styles *Styles // the page's recipe overrides; nil keeps the theme's // barStyle is the page's default scrollbar geometry, which every area of the frame // starts from; Box.Bars overrides it for one area. barStyle components.ScrollBarStyle diff --git a/ui/menu.go b/ui/menu.go index 2214894de..03864a30c 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -51,30 +51,7 @@ func Menu(c C, anchor Box, open *bool, body func(*MenuItems)) { scope := p.boundScope(pkMenu, unsafe.Pointer(open)) menu := stateIn[MenuItems](p, scope, "menu") menu.context = false - p.declareMenu(c, menu, scope, open, anchor.i, body) -} - -// MenuAt shows the items body declares at the point x, y of the window while *open, -// as a ContextMenu looks and behaves: for a menu the application opens itself at a -// place no control stands for, such as a mark painted inside a custom-drawn view. -// Choosing an item, Escape or a press outside closes it. -// -// if pressed := m.markAt(event); pressed { -// m.lanes, m.lanesAt = true, ui.Rect{X: event.X, Y: event.Y} -// } -// ui.MenuAt(c, m.lanesAt.X, m.lanesAt.Y, &m.lanes, func(menu *ui.MenuItems) { ... }) -// -// Not inside a Memo. -func MenuAt(c C, x, y float32, open *bool, body func(*MenuItems)) { - p := c.page - p.forbidInMemo("MenuAt") - if !*open { - return - } - scope := p.boundScope(pkMenu, unsafe.Pointer(open)) - menu := stateIn[MenuItems](p, scope, "menu") - menu.context, menu.at = true, Rect{X: x, Y: y} - p.declareMenu(c, menu, scope, open, -1, body) + p.declareMenu(c, menu, scope, open, anchor.i, nil, body) } // ContextMenu shows the items body declares at the pointer when target is pressed @@ -91,6 +68,27 @@ func MenuAt(c C, x, y float32, open *bool, body func(*MenuItems)) { // // Not inside a Memo. func ContextMenu(c C, target Box, body func(*MenuItems)) { + contextMenu(c, target, gfx.Scope(0), nil, body) +} + +// ContextMenuAt shows a context menu at a point the application captured on its +// own surface: a canvas cell, a column header, or a text editor. Unlike Menu, its +// row layout is a ContextMenu's, and a menu that reaches the window edge clamps +// its origin rather than flipping to the other side of the pointer. target names +// the control whose focus and secondary-press token the menu takes; open owns +// dismissal, just as it does for Menu. +// +// Not inside a Memo. +func ContextMenuAt(c C, target Box, open *bool, at gfx.Point, body func(*MenuItems)) { + if !*open { + return + } + contextMenu(c, target, c.page.boundScope(pkMenu, unsafe.Pointer(open)), &menuOrigin{open: open, at: Rect{X: at.X, Y: at.Y}}, body) +} + +func (m *MenuItems) RowHeight(height float32) { m.rowSize = height } + +func contextMenu(c C, target Box, bound gfx.Scope, opened *menuOrigin, body func(*MenuItems)) { p := c.page p.forbidInMemo("ContextMenu") id := target.n().id @@ -98,24 +96,43 @@ func ContextMenu(c C, target Box, body func(*MenuItems)) { panic("ui: ContextMenu needs a target with an identity: a control, or a container given Hit") } scope := p.tree.Sub(id.Scope(), id.Name()) // the target's own: a ContextMenu per target + if !bound.IsZero() { + scope = bound + } menu := stateIn[MenuItems](p, scope, "context") menu.context = true - if canvas := c.f.canvas; canvas != nil { + p.contexts = append(p.contexts, contextTarget{id: id, menu: menu, f: c.f, target: target.i}) + if p.menuRoute == nil { + p.keyRoute, p.menuRoute = (*Page).routeKey, (*Page).menuKey + p.wheelRoute = (*Page).overlayWheel + } + if canvas := c.f.canvas; canvas != nil && opened == nil { if event, ok := canvas.PointerOn(id); ok && event.Kind == gfx.PointerDown && event.Button == gfx.PointerButtonSecondary { menu.shown, menu.at = true, Rect{X: event.X, Y: event.Y} canvas.Consume() } } - p.contexts = append(p.contexts, contextTarget{id: id, menu: menu, f: c.f, target: target.i}) - if p.menuRoute == nil { - p.keyRoute, p.menuRoute = (*Page).routeKey, (*Page).menuKey - p.wheelRoute = (*Page).overlayWheel + if opened != nil { + menu.open, menu.at = opened.open, opened.at } - if menu.shown { - p.declareMenu(c, menu, scope, &menu.shown, -1, body) + if opened != nil || menu.shown { + open := menu.open + if open == nil { + // A context menu the target opened has no *bool of its own: the + // pointer opened it, and the chosen row (or a dismissal) closes it. + open = &menu.shown + } + p.declareMenu(c, menu, scope, open, -1, opened, body) } } +// menuOrigin is the captured open state of a context menu on a custom surface. +// The application owns when it opens; MenuItems owns the rows and dismissal. +type menuOrigin struct { + open *bool + at Rect +} + // contextTarget is a ContextMenu declared in the last paint, which Shift+F10 on its // target opens. type contextTarget struct { @@ -127,14 +144,20 @@ type contextTarget struct { // declareMenu declares an open menu: its rows, its size, and the popup that places // it, under the anchor element or, with anchor -1, at menu.at. -func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, anchor int32, body func(*MenuItems)) { +func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, anchor int32, opened *menuOrigin, body func(*MenuItems)) { p.overlay = true if menu.paint == nil { menu.paint = menu.draw // made once: a method value made in each paint allocates } + if menu.itemPainter == nil { + menu.itemPainter, menu.panelPainter = menu.paintItem, menu.paintPanel + } f := c.f menu.page, menu.f, menu.open, menu.anchor = p, f, open, anchor menu.scope, menu.root, menu.parent = scope, menu, nil + if opened != nil { + menu.at = opened.at + } menu.layer = f.widgetLayer() + 2 // over the page, and over a dialog it is declared in menu.side = menuBelow // unless body says otherwise again in this paint menu.fresh() @@ -156,7 +179,9 @@ func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, an popup.BelowBox(anchorBox, 4, Start) } } else { - popup.At(menu.at.X, menu.at.Y) + height = min(height, max(f.bounds.Height-2*components.DropdownMenuPadding, 0)) + clamped := components.ClampOverlay(gfx.Point{X: menu.at.X, Y: menu.at.Y}, gfx.Size{Width: width, Height: height}, f.bounds, components.DropdownMenuPadding) + popup.At(clamped.X, clamped.Y) } popup.Size(width, height).Within(f.bounds.Inset(gfx.All(components.DropdownMenuPadding))) popup.Draw(menu.paint) @@ -173,6 +198,7 @@ func (m *MenuItems) fresh() { if m.seen+1 != m.page.epoch { m.sub, m.subMenu, m.intent = -1, nil, components.HoverIntent{} } + m.unpainted, m.drawPanel, m.drawItem = false, nil, nil m.seen = m.page.epoch } @@ -236,7 +262,7 @@ func (m *MenuItems) size() (width, height float32) { row := m.row(i) if m.context { context := contextItem(row) - height += components.ContextMenuItemHeight(*theme, context, 0) + height += components.ContextMenuItemHeight(*theme, context, m.rowSize) if f.canvas != nil { width = max(width, components.ContextMenuItemWidth(f.canvas, *theme, context)) } @@ -289,10 +315,10 @@ type MenuItems struct { scope gfx.Scope layer uint16 - context bool // a ContextMenu: its own look, and Tab does not close it - shown bool // a ContextMenu is open - at Rect // where a ContextMenu opened - + context bool // a ContextMenu: its own look, and Tab does not close it + shown bool // a ContextMenu opened from its target + at Rect // where a ContextMenu opened + rowSize float32 side menuSide // the edge of the anchor a Menu opens on widthMin, widthMax float32 // the least and greatest surface width; zero keeps the default @@ -306,6 +332,87 @@ type MenuItems struct { seen uint32 // the page's epoch the menu was last declared in focusSub bool // the keyboard opened the submenu: its first row takes the focus focusFirst bool // this submenu's first row takes the focus as it paints + + // An unpainted menu declares its behavior and rows but paints none of them: + // drawPanel draws the surface and drawItem each row. itemPainter and + // panelPainter are their method values, made once. + unpainted bool + drawPanel func(*gfx.Canvas, gfx.Rect, gfx.Theme) + drawItem func(MenuItemParts) + panelPainter func(*gfx.Canvas, gfx.Rect, gfx.Theme) + itemPainter func(components.MenuItemPaint) +} + +// MenuItemParts is one row of a menu declared Unpainted. The application paints +// it, and the menu keeps the row's hit, its focus and keyboard behavior, and its +// place in a submenu chain. Separator and GroupLabel say the row is not an +// action; Active is the row the pointer or the keyboard is on; Foreground is the +// color the menu's own row would give its label. +type MenuItemParts struct { + Canvas *gfx.Canvas + Theme gfx.Theme + Rect gfx.Rect + Label string + Description string + Shortcut string + Checked bool + Selected bool + Expanded bool + Disabled bool + Active bool + Destructive bool + Separator bool + GroupLabel bool + Foreground gfx.Color +} + +// Unpainted makes the menu declare its behavior, size and rows but paint none +// of them: DrawPanel draws the surface and DrawItem each row, inside the menu's +// layer and clipping. Hits, focus, the keyboard, dismissal and submenu opening +// stay the menu's, so an application's own menu cannot behave differently. A +// menu that is not unpainted keeps the theme's look. +// +// Call it in the body, before the rows, on every paint: the setting lasts one +// paint. +func (m *MenuItems) Unpainted() *MenuItems { + m.unpainted = true + return m +} + +// DrawPanel paints an Unpainted menu's surface, inside the menu's layer and +// clipping and within its entrance. Nil paints no surface. +func (m *MenuItems) DrawPanel(draw func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme)) *MenuItems { + m.drawPanel = draw + return m +} + +// DrawItem paints each row of an Unpainted menu, actions, group labels and +// separators alike, after the menu has declared the row's hit. +func (m *MenuItems) DrawItem(draw func(MenuItemParts)) *MenuItems { + m.drawItem = draw + return m +} + +// paintItem is the unpainted menu's row painter; it is a method value so +// painting a menu allocates nothing. +func (m *MenuItems) paintItem(parts components.MenuItemPaint) { + if m.drawItem == nil { + return + } + m.drawItem(MenuItemParts{ + Canvas: parts.Canvas, Theme: parts.Theme, Rect: parts.Bounds, + Label: parts.Label, Description: parts.Description, Shortcut: parts.Shortcut, + Checked: parts.Checked, Selected: parts.Selected, Expanded: parts.Expanded, + Disabled: parts.Disabled, Active: parts.Active, Destructive: parts.Destructive, + Separator: parts.Separator, GroupLabel: parts.GroupLabel, Foreground: parts.Foreground, + }) +} + +// paintPanel is DrawPanel as the components take it. +func (m *MenuItems) paintPanel(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) { + if m.drawPanel != nil { + m.drawPanel(canvas, bounds, theme) + } } type menuRow struct { @@ -384,7 +491,7 @@ func (m *MenuItems) Sub(label string, body func(*MenuItems)) MenuItem { p := m.page child := stateIn[MenuItems](p, p.tree.Sub(m.scope, gfx.Index(item.i)), "sub") child.page, child.f, child.open, child.anchor = p, m.f, m.open, -1 - child.scope, child.root, child.parent, child.context = p.tree.Sub(m.scope, gfx.Index(item.i)), m.root, m, m.context + child.scope, child.root, child.parent, child.context, child.rowSize = p.tree.Sub(m.scope, gfx.Index(item.i)), m.root, m, m.context, m.rowSize child.fresh() if m.focusSub { m.focusSub, child.focusFirst = false, true @@ -526,7 +633,8 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer if m.context { menu := components.BeginContextMenu(canvas, *theme, bounds, components.ContextMenuOptions{ Layer: layer, Scope: focus, DismissID: dismiss, Viewport: f.bounds, ID: id, - Scroll: &m.scroll, Submenu: m.parent != nil, + Scroll: &m.scroll, Submenu: m.parent != nil, RowHeight: m.rowSize, + Unpainted: m.unpainted, PaintPanel: m.panelPainter, PaintItem: m.itemPainter, }) for i := range m.items { switch row := &m.items[i]; row.kind { @@ -559,6 +667,7 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer menu := components.BeginDropdownMenu(canvas, *theme, bounds, components.DropdownMenuOptions{ Layer: layer, Scope: focus, DismissID: dismiss, Viewport: f.bounds, ID: id, Scroll: &m.scroll, Side: side, Submenu: m.parent != nil, + Unpainted: m.unpainted, PaintPanel: m.panelPainter, PaintItem: m.itemPainter, }) for i := range m.items { switch row := &m.items[i]; row.kind { diff --git a/ui/menu_parts_test.go b/ui/menu_parts_test.go new file mode 100644 index 000000000..711bd1585 --- /dev/null +++ b/ui/menu_parts_test.go @@ -0,0 +1,56 @@ +package ui + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// An unpainted menu keeps its behavior and leaves every visible part to the +// application: the surface, the rows, and the row rectangles the app paints in. +func TestAnUnpaintedMenuDrawsItsOwnPartsAndKeepsItsHits(t *testing.T) { + theme := gfx.LightTheme() + panelColor := gfx.RGB(20, 30, 40) + rowColor := gfx.RGB(50, 60, 70) + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + open := true + var rows []MenuItemParts + page.Draw(canvas, gfx.Rect{Width: 400, Height: 300}, func(c C) { + anchor := Button(c, "Open") + Menu(c, anchor, &open, func(menu *MenuItems) { + menu.Unpainted(). + DrawPanel(func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) { + canvas.Fill(bounds, panelColor) + }). + DrawItem(func(parts MenuItemParts) { + rows = append(rows, parts) + parts.Canvas.Fill(parts.Rect, rowColor) + }) + menu.Item("One") + menu.Item("Two") + }) + }) + if len(rows) != 2 || rows[0].Label != "One" || rows[1].Label != "Two" { + t.Fatalf("rows = %+v, want two actions", rows) + } + if rows[0].Rect.Height <= 0 { + t.Errorf("the first row has no rectangle: %+v", rows[0].Rect) + } + painted := make(map[gfx.Color]bool) + for _, rectangle := range canvas.Rectangles() { + painted[rectangle.Color] = true + } + if !painted[panelColor] || !painted[rowColor] { + t.Fatalf("the menu's parts were not painted: %d rectangles", len(canvas.Rectangles())) + } + items := 0 + for _, hit := range canvas.Hits() { + if hit.Role == gfx.RoleMenuItem { + items++ + } + } + if items != 2 { + t.Fatalf("%d menu item hits, want 2", items) + } +} diff --git a/ui/menu_test.go b/ui/menu_test.go index acec13c5c..777516209 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -166,6 +166,7 @@ type contextModel struct { hosts []string connected string wrap bool + open bool renames, opens int } @@ -508,27 +509,3 @@ func TestMenuAbove(t *testing.T) { t.Fatalf("the menu at %v is not over its anchor at %v", item, anchor) } } - -// MenuAt opens where the application says, closes when an item is chosen, and -// leaves *open false. -func TestMenuAtOpensAtThePointGiven(t *testing.T) { - open, chosen := true, 0 - d := openPage(t, func(c ui.C) { - ui.Column(c).Pad(16).Children(func() { - ui.Button(c, "Below") - ui.MenuAt(c, 120, 90, &open, func(menu *ui.MenuItems) { - if menu.Item("Lane").Clicked() { - chosen++ - } - }) - }) - }) - lane := d.hit("Lane").Bounds - if !d.page.Overlay() || lane.X < 119 || lane.Y < 89 { - t.Fatalf("overlay %v, the menu at %v is not at (120, 90)", d.page.Overlay(), lane) - } - d.click("Lane") - if chosen != 1 || open || d.has("Lane") { - t.Fatalf("chosen %d, open %v, shown %v", chosen, open, d.has("Lane")) - } -} diff --git a/ui/page.go b/ui/page.go index 87de1698c..5b93c5b4c 100644 --- a/ui/page.go +++ b/ui/page.go @@ -207,6 +207,11 @@ type PageConfig struct { // copy of the last paint would have differed, as MemoCheck(true) does for every // page. It is for tests. MemoCheck bool + // Styles replaces the recipes the page's styled controls paint with; nil uses + // the theme's. See Styles. It is for an application with a look of its own + // that keeps using Button, Checkbox, Switch, Input and Textarea rather than + // their Bases, and it does not affect a control given a look of its own. + Styles *Styles // BarStyle is the geometry of the scrollbars every scroll area of this page draws, so // a product whose bars are its own sets it once: IDEA's eleven point track with a five // point thumb. The zero style keeps Viva's, and Box.Bars overrides it for one area. @@ -793,6 +798,7 @@ func (p *Page) paintOnce(canvas *gfx.Canvas, bounds Rect, view func(C)) { } } f := p.view.Begin(canvas, p.currentTheme(), bounds) + f.styles = p.config.Styles f.page = p f.barStyle = p.config.BarStyle p.ctx.page, p.ctx.f, p.ctx.nextSet = p, f, false @@ -1127,6 +1133,13 @@ func (p *Page) Wheel(event gfx.ScrollEvent) gfx.EventResult { return state.Wheel(event) } } + // A TextArea under the pointer scrolls its own rows first; at its end the wheel goes on + // to the page, as in a browser. + for _, entry := range p.fields { + if entry.field.rows && entry.field.area != nil && entry.field.area.Wheel(event) { + return gfx.EventResult{Handled: true, Repaint: true} + } + } if p.wheelRoute != nil { if result, ok := p.wheelRoute(p, event); ok { return result diff --git a/ui/paint.go b/ui/paint.go index 9ec550b01..80b4f3590 100644 --- a/ui/paint.go +++ b/ui/paint.go @@ -179,6 +179,9 @@ func (f *frame) paintControl(n *node, r Rect) { f.captionFn(f, n, bounds) } checkbox := components.BeginCheckbox(canvas, f.theme, n.id, bounds, n.flags&flagChecked != 0) + if f.styles != nil && f.styles.Checkbox != nil { + checkbox = checkbox.Recipe(f.styles.Checkbox) + } if n.label != "" { checkbox = checkbox.Label(n.label) } @@ -214,6 +217,9 @@ func (f *frame) paintControl(n *node, r Rect) { f.captionFn(f, n, bounds) } control := components.BeginSwitch(canvas, f.theme, n.id, bounds, n.flags&flagChecked != 0) + if f.styles != nil && f.styles.Switch != nil { + control = control.Recipe(f.styles.Switch) + } if small { control = control.Small() } @@ -272,6 +278,9 @@ func (f *frame) paintButton(n *node) { extra := &f.exts[n.ext] button := components.BeginButton(f.canvas, f.theme, n.id, Rect{X: r.X, Y: r.Y, Width: r.Width}).Size(n.buttonSize). WithIcon(extra.icon).IconTransform(extra.iconTransform) + if f.styles != nil && f.styles.Button != nil { + button = button.Recipe(f.styles.Button) + } // A button is as tall as its size says unless the element was given more or less // room: a Height, or a Grow along a column. It then fills that room. if h := r.Height; h > 0 && math.Abs(float64(h-button.BoundsHeight())) > 0.01 { diff --git a/ui/recipe.go b/ui/recipe.go index 945214b9c..9d347869c 100644 --- a/ui/recipe.go +++ b/ui/recipe.go @@ -39,6 +39,15 @@ func textEntryInsets(theme *Theme, k kind) (x, y float32) { return x, y } +// textEntryLook is the recipe a themed Input or Textarea is dressed with: the +// page's Styles.TextEntry when it set one, else the theme's. +func (f *frame) textEntryLook(theme *Theme, state gfx.State) components.TextEntryLook { + if f.styles != nil && f.styles.TextEntry != nil { + return f.styles.TextEntry(*theme, state) + } + return components.TextEntryRecipe(*theme, state) +} + // applyRecipes gives every themed element the measurements its recipe has, before the page // is laid out: the corners, the border and the padding of its text. Colors depend on the // state of the frame being painted, so they are filled in by themedDefaults at paint time. @@ -52,11 +61,12 @@ func (f *frame) applyRecipes() { case kindInput, kindTextarea: var scratch Theme theme := f.recipeTheme(n, &scratch) + look := f.textEntryLook(theme, gfx.State{}) if n.flags&flagSetBorder == 0 { - n.borderWidth = components.TextEntryBorderWidth + n.borderWidth = look.BorderWidth } if n.flags&flagHasRadius == 0 { - n.radius = theme.Metrics.RadiusControl + n.radius = look.Radius } if n.flags&flagSetPad == 0 { x, y := textEntryInsets(theme, n.kind) @@ -84,7 +94,7 @@ func (f *frame) themedDefaults(n *node, extra *extra, s *resolved) { return } var scratch Theme - look := components.TextEntryRecipe(*f.recipeTheme(n, &scratch), state) + look := f.textEntryLook(f.recipeTheme(n, &scratch), state) if n.flags&flagSetBackground == 0 { s.background = look.Fill } diff --git a/ui/select.go b/ui/select.go index 2eb3c5723..cc02ee91d 100644 --- a/ui/select.go +++ b/ui/select.go @@ -195,7 +195,8 @@ const ( // per label; scope.At(len(labels)) to At(len(labels)+4) are the trigger, the dismiss // target (a press anywhere outside the list, or Escape), the list's focus scope and // its two scroll arrows, so give the select a scope of its own. A list too long for the -// frame shows a window of options with scroll arrows. selected is the index of the +// frame shows a window of options with scroll arrows, and the list floats over the page: +// inside a scroll area it is not cut by the area's clip. selected is the index of the // current label, negative for none. Placeholder is the text shown then; Small, Disabled // and Label work as for a button. // diff --git a/ui/select_test.go b/ui/select_test.go index 0b3ed30f8..78758de99 100644 --- a/ui/select_test.go +++ b/ui/select_test.go @@ -521,3 +521,105 @@ func TestSelectBasePanelIsAsWideAsItsRowsForANarrowTrigger(t *testing.T) { t.Errorf("row %+v is outside the panel %+v", row, panel) } } + +// A Select in a scroll area shows its list whole: every row is painted and hit +// outside the area's bottom edge, an option scrolled out of the area can be +// clicked, and the area clips its own content again once the list is closed. +func TestSelectInScrollAreaShowsItsListBeyondTheClip(t *testing.T) { + theme := gfx.LightTheme() + labels := []string{"Apple", "Avocado", "Banana", "Blueberry", "Cherry", "Date"} + draw := func(canvas *gfx.Canvas, state *SelectState) Box { + var view View + var box Box + view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Pad(10).Children(func() { + f.ScrollArea(listID).Height(100).Children(func() { + f.Column().Children(func() { + f.Slot().Height(20) + box = f.Select(selScope, state, labels, 0) + }) + }) + }) + }) + return box + } + state := SelectState{Open: true} + canvas := testCanvas() + box := draw(canvas, &state) + area := gfx.Rect{X: 10, Y: 10, Width: 380, Height: 100} + popup, ok := box.Popup() + if !ok { + t.Fatal("the open list has no popup") + } + panel := popup.Rect() + if panel.Y+panel.Height <= area.Y+area.Height { + t.Fatalf("the fixture did not place the list below the scroll area: panel %+v, area %+v", panel, area) + } + // The last row is below the area's bottom edge, painted to the viewport and hit whole. + lastRow := box.Part(len(labels) - 1) + if lastRow.Y+lastRow.Height <= area.Y+area.Height { + t.Fatalf("the last row %+v did not reach below the scroll area %+v", lastRow, area) + } + var last gfx.Hit + found := false + for _, hit := range canvas.Hits() { + if hit.ID == selScope.At(len(labels)-1) { + last, found = hit, true + } + } + if !found || last.Bounds != lastRow { + t.Fatalf("the last row's hit is %+v, want its rectangle %+v", last.Bounds, lastRow) + } + // The surface is painted against the viewport, not the scroll area. + surface := false + for _, r := range canvas.Rectangles() { + if r.Bounds == panel { + surface = true + if !r.HasClip || r.ClipOf != (gfx.Rect{Width: 400, Height: 300}) { + t.Fatalf("the list surface is clipped to the scroll area: %+v", r) + } + } + } + if !surface { + t.Fatal("the list surface was not painted") + } + // A click on an option below the area closes the list and picks it. + canvas = testCanvas() + canvas.BeginEventPass(selScope.At(5), gfx.ClickInfo{}) + var selected int + var picked bool + var view View + view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Pad(10).Children(func() { + f.ScrollArea(listID).Height(100).Children(func() { + f.Column().Children(func() { + f.Slot().Height(20) + if i, ok := f.Select(selScope, &state, labels, 0).Picked(); ok { + selected, picked = i, true + } + }) + }) + }) + }) + canvas.EndEventPass() + if !picked || selected != 5 || state.Open { + t.Fatalf("a click on the option below the area gave picked=%v selected=%d open=%v", picked, selected, state.Open) + } + // Closed, the select declares no list and the area clips its own content again. + canvas = testCanvas() + draw(canvas, &state) + for _, hit := range canvas.Hits() { + if i, ok := hit.ID.In(selScope); ok && i < len(labels) { + t.Fatalf("a closed select still declares option %d", i) + } + } + var slot gfx.Rect + for _, hit := range canvas.Hits() { + if hit.ID == selScope.At(len(labels)) { // the trigger + slot = hit.Bounds + } + } + if slot.Width <= 0 { + t.Fatal("the closed select lost its trigger") + } +} diff --git a/ui/styles.go b/ui/styles.go new file mode 100644 index 000000000..cb5707c33 --- /dev/null +++ b/ui/styles.go @@ -0,0 +1,33 @@ +package ui + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// Styles replaces the recipes a page's styled controls paint with, for an +// application whose look differs from the theme's shadcn recipes but which +// wants the controls themselves rather than a Base at every call site. +// +// A nil field keeps the theme's recipe (components.ButtonRecipe and the rest). +// A recipe is a pure function of the theme and the control's state; it is +// called at every paint, so it must not allocate on the steady path, block, or +// read anything but its arguments. It changes the look, not the measurements: +// a button's height, an input's padding and the controls' hit regions still +// come from the size variant and gfx.Theme.Metrics, so a page can also adjust +// density once in the theme. +// +// A single control with a look of its own is still styled through its Base, +// which also avoids recomputing a recipe for every control. Styles is for the +// page-wide case. +type Styles struct { + // Button dresses Button, and the buttons a component paints. + Button func(theme gfx.Theme, variant components.ButtonVariant, state gfx.State) components.ButtonLook + // Checkbox dresses Checkbox. + Checkbox func(theme gfx.Theme, state gfx.State) components.CheckboxLook + // Switch dresses Switch, progress being how far the thumb has travelled. + Switch func(theme gfx.Theme, state gfx.State, progress float32) components.SwitchLook + // TextEntry dresses Input and Textarea: their fill, border, corners and + // shadow. Their padding, and where the text sits, stay the metrics'. + TextEntry func(theme gfx.Theme, state gfx.State) components.TextEntryLook +} diff --git a/ui/styles_test.go b/ui/styles_test.go new file mode 100644 index 000000000..4d3a97976 --- /dev/null +++ b/ui/styles_test.go @@ -0,0 +1,77 @@ +package ui + +import ( + "testing" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// A page's Styles replace the recipe each styled control paints with, and a +// nil field keeps the theme's: the application keeps using Button, Checkbox, +// Switch and TextField instead of a Base at every call site. +func TestStylesReplaceThePageRecipes(t *testing.T) { + theme := gfx.LightTheme() + buttonColor := gfx.RGB(1, 2, 3) + checkboxColor := gfx.RGB(4, 5, 6) + switchColor := gfx.RGB(7, 8, 9) + entryColor := gfx.RGB(10, 11, 12) + styles := &Styles{ + Button: func(gfx.Theme, components.ButtonVariant, gfx.State) components.ButtonLook { + return components.ButtonLook{Background: buttonColor, Foreground: gfx.RGB(255, 255, 255), Filled: true} + }, + Checkbox: func(gfx.Theme, gfx.State) components.CheckboxLook { + return components.CheckboxLook{Fill: checkboxColor, Border: checkboxColor, Mark: checkboxColor} + }, + Switch: func(gfx.Theme, gfx.State, float32) components.SwitchLook { + return components.SwitchLook{Track: switchColor, Thumb: switchColor} + }, + TextEntry: func(gfx.Theme, gfx.State) components.TextEntryLook { + return components.TextEntryLook{Fill: entryColor, Border: entryColor, BorderWidth: 1, Radius: 3} + }, + } + page := NewPage(PageConfig{Theme: &theme, Styles: styles}) + canvas := testCanvas() + var on bool + var field Field + page.Draw(canvas, gfx.Rect{Width: 320, Height: 200}, func(c C) { + Column(c).Pad(8).Gap(8).Children(func() { + Button(c, "Save") + Checkbox(c, &on, "Remember") + Switch(c, &on, "Sync") + TextFieldID(c, tree.ID(tree.Feature("styles"), "field"), &field, "Name", "") + }) + }) + painted := make(map[gfx.Color]bool) + for _, rectangle := range canvas.Rectangles() { + painted[rectangle.Color] = true + } + for name, color := range map[string]gfx.Color{ + "button": buttonColor, "checkbox": checkboxColor, "switch": switchColor, "text entry": entryColor, + } { + if !painted[color] { + t.Errorf("the %s did not paint its recipe's color; painted %d rectangles", name, len(canvas.Rectangles())) + } + } +} + +// Without Styles the page paints the theme's recipe, not a zero look. +func TestAPageWithoutStylesPaintsTheThemeRecipe(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + page.Draw(canvas, gfx.Rect{Width: 200, Height: 100}, func(c C) { + Column(c).Pad(8).Children(func() { + Button(c, "Save") + }) + }) + found := false + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == theme.Primary { + found = true + } + } + if !found { + t.Fatalf("the default button did not paint the theme's primary color: %d rectangles", len(canvas.Rectangles())) + } +} diff --git a/ui/table.go b/ui/table.go index d3ef258ba..58ea088ec 100644 --- a/ui/table.go +++ b/ui/table.go @@ -115,6 +115,13 @@ type TableState struct { rows, page int32 // as of the last paint: how many rows, how many fit at once rowFirst, rowEnd int32 // the declared source rows: rowFirst <= i < rowEnd scope gfx.Scope // the rows' identities, to tell a key meant for the table + // cellLefts are the painted columns' left edges and the last column's right + // edge, and cellTop and cellRowHeight the first visible row's top and every + // row's height, as of the last paint; see CellRect. They keep their + // capacity across frames, so a warm table records them without allocating. + cellLefts []float32 + cellTop float32 + cellRowHeight float32 } // Selected is the selected row, or -1. @@ -396,10 +403,12 @@ func (f *frame) paintTable(n *node) { // scrolls under the offset. A band with no width, or as wide as the body, // pins nothing — there would be no window left to scroll in. frozenWidth := float32(0) + frozenColumns := 0 if sideways { - frozenWidth = frozenColumnsWidth(t.spec.Columns, frozenColumnCount(t.spec.Columns, t.spec.FrozenColumns)) + frozenColumns = frozenColumnCount(t.spec.Columns, t.spec.FrozenColumns) + frozenWidth = frozenColumnsWidth(t.spec.Columns, frozenColumns) if frozenWidth <= 0 || frozenWidth >= body.Width { - frozenWidth = 0 + frozenWidth, frozenColumns = 0, 0 } } seam := body.X + frozenWidth @@ -430,6 +439,9 @@ func (f *frame) paintTable(n *node) { last = min(max(int(math.Ceil(float64((hi-top)/rowHeight))), first), t.rows) } t.state.rowFirst, t.state.rowEnd = int32(first), int32(last) + // The cells CellRect answers with, laid out once from the same columns and + // the same top the rows are painted from (see recordTableCells). + f.recordTableCells(t, body, left, top, contentWidth, rowHeight, frozenColumns, frozenWidth) if !scrolls && !sticky { // Height: r.Height lets paintTableHeader keep its rule of the header's diff --git a/ui/tablecell.go b/ui/tablecell.go new file mode 100644 index 000000000..adfe77c0d --- /dev/null +++ b/ui/tablecell.go @@ -0,0 +1,71 @@ +package ui + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// CellRect is where source cell (row, column) was painted by the last paint, +// in window coordinates, and false for a cell the table did not paint: a row +// out of view, a column past the ones painted, or any cell before the table's +// first paint. It is the geometry counterpart of RowID, both answers the last +// paint declared, so a caller that puts something over a cell — an editor — +// reads it between frames without repeating the table's arithmetic. +// +// Rows and columns are source indices, as RowID's are: scrolling and sorting do +// not renumber them, and a row keeps its source index as it moves on screen. +// The rectangle is the whole cell and not the part the table's clip leaves +// visible, because an overlay is meant to cover the cell: a row half scrolled +// out at the top of the body still answers with its full height. A frozen +// column answers where that column was pinned; a column scrolling under the +// band keeps its scrolled place, which may lie outside the table. +// +// The header is not a cell and has no source row: it has no rectangle here. +// Declaring the same state in more than one table leaves the calls describing +// only the last table painted. +func (s *TableState) CellRect(row, column int) (gfx.Rect, bool) { + if row < int(s.rowFirst) || row >= int(s.rowEnd) || column < 0 || column+1 >= len(s.cellLefts) { + return gfx.Rect{}, false + } + left, right := s.cellLefts[column], s.cellLefts[column+1] + if right <= left || s.cellRowHeight <= 0 { + return gfx.Rect{}, false + } + return gfx.Rect{ + X: left, Y: s.cellTop + float32(row)*s.cellRowHeight, + Width: right - left, Height: s.cellRowHeight, + }, true +} + +// recordTableCells keeps the cells of the last paint for CellRect: the left +// edge of every painted column, plus the right edge of the last, and the top +// and height of a row. The columns come from components.TableCellBounds, the +// same layout the rows and the header are painted from, so a table pays one +// pass over its columns a frame and no per-cell allocation. A frozen column's +// edge is taken from the body's unscrolled origin, where the band paints it; +// the rest follow the offset the rows were painted at. +func (f *frame) recordTableCells(t *tableDecl, body Rect, left, top, contentWidth, rowHeight float32, frozenColumns int, frozenWidth float32) { + state := t.state + state.cellLefts = state.cellLefts[:0] + state.cellTop, state.cellRowHeight = top, rowHeight + if len(t.spec.Columns) == 0 || rowHeight <= 0 { + return + } + cells := components.TableCellBounds(t.spec.Columns, Rect{Width: contentWidth, Height: rowHeight}, f.widgets.rects[:0]) + f.widgets.rects = cells[:0] + for index, cell := range cells { + x := left + cell.X + if frozenWidth > 0 && index < frozenColumns { + x = body.X + cell.X + } + state.cellLefts = append(state.cellLefts, x) + } + if len(cells) > 0 { + last := cells[len(cells)-1] + x := left + last.X + last.Width + if frozenWidth > 0 && len(cells)-1 < frozenColumns { + x = body.X + last.X + last.Width + } + state.cellLefts = append(state.cellLefts, x) + } +} diff --git a/ui/tablecell_test.go b/ui/tablecell_test.go new file mode 100644 index 000000000..62554935d --- /dev/null +++ b/ui/tablecell_test.go @@ -0,0 +1,230 @@ +package ui + +import ( + "fmt" + "testing" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// cellTable is one table under test: its state, its rows, and a paint that +// draws it into a fresh canvas at the given size. +type cellTable struct { + rows TableRows + state TableState + spec TableSpec + view View +} + +func newCellTable(rows int, spec TableSpec) *cellTable { + t := &cellTable{rows: make(TableRows, rows)} + for i := range t.rows { + t.rows[i] = []string{"a", "b", "c", "d", "e", "f"} + } + spec.Source = &t.rows + t.spec = spec + return t +} + +func (t *cellTable) paint(size gfx.Rect) *gfx.Canvas { + canvas := testCanvas() + t.view.Draw(canvas, gfx.LightTheme(), size, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&t.state, t.spec).Fill() + }) + }) + return canvas +} + +func (t *cellTable) wantCell(t0 *testing.T, row, column int, want gfx.Rect) { + t0.Helper() + got, ok := t.state.CellRect(row, column) + if !ok { + t0.Fatalf("CellRect(%d, %d) reports no cell, want %+v", row, column, want) + } + near(t0, fmt.Sprintf("CellRect(%d, %d)", row, column), got, want) +} + +var cellColumns = []components.TableColumn{{Width: 120}, {Width: 90}, {Width: 100}} + +// The painted cells answer with the geometry the rows were painted at: each +// column where its cell lies, and each row one row height down from the first +// visible one, counted from the body's top under a header. +func TestTableCellsAreWhereTheRowsWerePainted(t *testing.T) { + const width, height = float32(400), float32(300) + table := newCellTable(20, TableSpec{ + Rows: tableScope, Columns: cellColumns, Headers: []string{"A", "B", "C"}, + }) + table.paint(gfx.Rect{Width: width, Height: height}) + rowH := components.TableRowHeight(gfx.LightTheme()) + if rowH != table.state.cellRowHeight { + t.Fatalf("recorded row height %v, want the painted %v", table.state.cellRowHeight, rowH) + } + // The table is taller than it needs and so scrolls; its first row is painted + // under the header, at the top of the body. + headH := components.TableHeaderHeight(gfx.LightTheme()) + top := headH + for _, column := range []int{0, 1, 2} { + x := float32(0) + for c := 0; c < column; c++ { + x += cellColumns[c].Width + } + for _, row := range []int{0, 1, 5} { + table.wantCell(t, row, column, gfx.Rect{X: x, Y: top + float32(row)*rowH, Width: cellColumns[column].Width, Height: rowH}) + } + } +} + +// A table that scrolls its rows keeps the source indices: the same cell moves +// up by the offset, the rows scrolled off answer false, and the rows scrolled +// into view answer. +func TestTableCellsFollowTheScroll(t *testing.T) { + table := newCellTable(100, TableSpec{Rows: tableScope, Columns: cellColumns}) + table.paint(gfx.Rect{Width: 400, Height: 160}) + rowH := components.TableRowHeight(gfx.LightTheme()) + table.wantCell(t, 0, 0, gfx.Rect{X: 0, Y: 0, Width: 120, Height: rowH}) + + table.state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 10 * rowH, Precise: true}) + if table.state.Scroll.Offset != 10*rowH { + t.Fatalf("offset %v, want ten rows of %v", table.state.Scroll.Offset, rowH) + } + table.paint(gfx.Rect{Width: 400, Height: 160}) + table.wantCell(t, 10, 0, gfx.Rect{X: 0, Y: 0, Width: 120, Height: rowH}) + if _, ok := table.state.CellRect(0, 0); ok { + t.Error("a row scrolled above the body still reports a cell") + } + table.state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 1e9}) + table.paint(gfx.Rect{Width: 400, Height: 160}) + if _, ok := table.state.CellRect(99, 2); !ok { + t.Error("the last row, on screen at the end, reports no cell") + } + if _, ok := table.state.CellRect(100, 0); ok { + t.Error("a row past the table's rows reports a cell") + } +} + +// A cell is the whole cell, not the strip its clip leaves visible: a row half +// scrolled out at the top keeps its full height. +func TestTableCellRectIsNotCutByTheClip(t *testing.T) { + table := newCellTable(100, TableSpec{Rows: tableScope, Columns: cellColumns}) + rowH := components.TableRowHeight(gfx.LightTheme()) + table.paint(gfx.Rect{Width: 400, Height: 160}) + table.state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 5*rowH + rowH/2, Precise: true}) + table.paint(gfx.Rect{Width: 400, Height: 160}) + // Rows 5 and 6 straddle the top of the body; both answer their whole height, + // row 5 starting above it. + table.wantCell(t, 5, 0, gfx.Rect{X: 0, Y: -rowH / 2, Width: 120, Height: rowH}) + table.wantCell(t, 6, 0, gfx.Rect{X: 0, Y: rowH / 2, Width: 120, Height: rowH}) +} + +// A column's cell comes back where the column was painted: a fixed width as +// declared, the last one taking what is left. Changing the widths and the row +// height moves the next paint's cells with them. +func TestTableCellsFollowTheColumnAndRowSizes(t *testing.T) { + rowH := components.TableRowHeight(gfx.LightTheme()) + table := newCellTable(10, TableSpec{Rows: tableScope, Columns: cellColumns}) + table.paint(gfx.Rect{Width: 500, Height: 300}) + table.wantCell(t, 1, 1, gfx.Rect{X: 120, Y: rowH, Width: 90, Height: rowH}) + + // The last column has a width of its own, so the table ends at 310. + table.wantCell(t, 1, 2, gfx.Rect{X: 210, Y: rowH, Width: 100, Height: rowH}) + + const wide, tall = float32(160), float32(34) + table.spec.Columns = []components.TableColumn{{Width: wide}, {Width: 90}, {Width: 100}} + table.spec.RowHeight = tall + table.paint(gfx.Rect{Width: 500, Height: 300}) + table.wantCell(t, 2, 1, gfx.Rect{X: wide, Y: 2 * tall, Width: 90, Height: tall}) +} + +// Two tables of one paint keep their own cells: each state answers for the +// table it was declared in, never for the other's. +func TestTableCellsDoNotCrossTables(t *testing.T) { + first := newCellTable(20, TableSpec{Rows: tableScope, Columns: cellColumns}) + second := newCellTable(20, TableSpec{Rows: tableScope, Columns: []components.TableColumn{{Width: 60}, {Width: 60}, {Width: 60}}}) + canvas := testCanvas() + var view View + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 600}, func(f *Frame) { + f.Column().Fill().Gap(8).Children(func() { + f.Table(&first.state, first.spec).Height(200) + f.Table(&second.state, second.spec).Height(200) + }) + }) + if rect, ok := first.state.CellRect(0, 0); !ok || rect.Width != 120 { + t.Errorf("the first table's cell is %+v, %v; want its own 120 wide column", rect, ok) + } + if rect, ok := second.state.CellRect(0, 0); !ok || rect.Width != 60 { + t.Errorf("the second table's cell is %+v, %v; want its own 60 wide column", rect, ok) + } +} + +// A frozen column answers where the band was pinned, and a column scrolling +// under it keeps its scrolled place; the frozen ones do not move with OffsetX. +func TestFrozenColumnCellsStayPinned(t *testing.T) { + table := newCellTable(20, TableSpec{Rows: tableScope, Columns: wideSixColumns, Headers: sixTitles, FrozenColumns: 2}) + table.paint(gfx.Rect{Width: 400, Height: 300}) + frozen, ok := table.state.CellRect(0, 0) + if !ok || frozen.X != 0 || frozen.Width != 120 { + t.Fatalf("frozen cell is %+v, %v; want the first 120 px column at the left edge", frozen, ok) + } + scrolled, ok := table.state.CellRect(0, 2) + if !ok || scrolled.X != 240 { + t.Fatalf("the scrolling column is at %+v, %v; want it at 240", scrolled, ok) + } + table.state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 100, Precise: true}) + table.paint(gfx.Rect{Width: 400, Height: 300}) + if moved, ok := table.state.CellRect(0, 0); !ok || moved != frozen { + t.Errorf("the frozen cell moved to %+v, want it at %+v", moved, frozen) + } + if moved, ok := table.state.CellRect(0, 2); !ok || moved.X != 140 { + t.Errorf("the scrolling column sits at %+v, want it at 140", moved) + } +} + +// A table in a ScrollArea scrolls with the area: its cells are painted where +// the area's last paint put them, which is a window coordinate, and the header +// keeps its height above them. +func TestTableCellsInAScrollAreaFollowTheArea(t *testing.T) { + table := newCellTable(1000, TableSpec{Rows: tableScope, Columns: cellColumns, Headers: []string{"A", "B", "C"}}) + rowH, headH := components.TableRowHeight(gfx.LightTheme()), components.TableHeaderHeight(gfx.LightTheme()) + paint := func() { + canvas := testCanvas() + table.view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 200}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.ScrollArea(listID).Grow(1).Children(func() { + f.Text("above").Height(30) + f.Table(&table.state, table.spec) + }) + }) + }) + } + paint() + table.wantCell(t, 0, 0, gfx.Rect{X: 0, Y: 30 + headH, Width: 120, Height: rowH}) + table.view.ScrollState(listID).Offset = 30 + headH + 10*rowH + paint() + // The header sticks to the area's top; its rows have scrolled under it, and + // row 10 lies behind the sticky header, so the first cell it paints is 11. + if _, ok := table.state.CellRect(10, 0); ok { + t.Error("a row scrolled behind the sticky header reports a cell") + } + table.wantCell(t, 11, 0, gfx.Rect{X: 0, Y: rowH, Width: 120, Height: rowH}) + if _, ok := table.state.CellRect(0, 0); ok { + t.Error("a row scrolled above the area still reports a cell") + } +} + +// Before any paint, and for columns the table does not have, there is no cell. +func TestTableCellsAreUnsetBeforeAPaint(t *testing.T) { + var state TableState + if rect, ok := state.CellRect(0, 0); ok || rect != (gfx.Rect{}) { + t.Fatalf("an unpainted table answers %+v, %v", rect, ok) + } + table := newCellTable(4, TableSpec{Rows: tableScope, Columns: cellColumns}) + table.paint(gfx.Rect{Width: 400, Height: 300}) + if _, ok := table.state.CellRect(0, 3); ok { + t.Error("a column the table does not paint reports a cell") + } + if _, ok := table.state.CellRect(-1, 0); ok { + t.Error("a negative row reports a cell") + } +} diff --git a/update/doc.go b/update/doc.go index 5025c1b61..8860f1a63 100644 --- a/update/doc.go +++ b/update/doc.go @@ -39,9 +39,11 @@ // installed payload and this one. PatchFrom finds one for the running version; // DownloadPatch fetches and verifies it; ApplyPatch applies it to the running // application and returns a staging directory holding the new payload. Install -// accepts that payload in place of an archive. Windows downloads the full -// installer: the NSIS installer owns the installation, so it has no payload to -// patch. +// accepts that payload in place of an archive. On Windows a patch carries a +// directory: the executable and the folders beside it, which is the same file +// set whether the copy was installed by the NSIS setup or unpacked as the +// portable zip. Install replaces those files and starts the new program without +// running the installer, so shortcuts and the uninstall entry stay as they are. // // # Installing // diff --git a/update/install_linux.go b/update/install_linux.go index edbf73e08..59c5d8056 100644 --- a/update/install_linux.go +++ b/update/install_linux.go @@ -49,6 +49,9 @@ func install(options InstallOptions, quit func()) error { if managedByDpkg(executable) { return fmt.Errorf("%w: %s is installed by dpkg", ErrManagedExternally, executable) } + if managedByRPM(executable) { + return fmt.Errorf("%w: %s is installed by rpm", ErrManagedExternally, executable) + } directory := filepath.Dir(executable) if err := checkWritable(directory); err != nil { return fmt.Errorf("%w: %s: %v", ErrNotWritable, directory, err) @@ -221,6 +224,18 @@ func managedByDpkg(executable string) bool { return strings.Contains(string(output), executable) } +// managedByRPM reports whether rpm owns executable. rpm -qf exits zero when a +// package owns the file and non-zero otherwise, and a missing rpm command means +// no package manager owns it. +func managedByRPM(executable string) bool { + query, err := lookPath("rpm") + if err != nil { + return false + } + _, err = runCommand(query, "-qf", executable) + return err == nil +} + // checkWritable reports whether directory accepts a new file, which is the // permission replacing the executable needs. func checkWritable(directory string) error { diff --git a/update/install_linux_test.go b/update/install_linux_test.go index 844b65376..c74b63f4e 100644 --- a/update/install_linux_test.go +++ b/update/install_linux_test.go @@ -120,6 +120,59 @@ func TestLinuxDpkgDetection(t *testing.T) { } } +func TestLinuxRPMDetection(t *testing.T) { + originalLookPath, originalRunCommand := lookPath, runCommand + t.Cleanup(func() { + lookPath, runCommand = originalLookPath, originalRunCommand + }) + const executable = "/usr/bin/lithe-desktop" + notFound := errors.New("executable file not found") + tests := []struct { + name string + lookup func(string) (string, error) + run func(string, ...string) ([]byte, error) + want bool + }{ + { + name: "owned by rpm", + lookup: func(string) (string, error) { return "/usr/bin/rpm", nil }, + run: func(name string, args ...string) ([]byte, error) { + if len(args) != 2 || args[0] != "-qf" || args[1] != executable { + t.Errorf("args = %q, want -qf %s", args, executable) + } + return []byte("lithe-desktop-0.9.1-1.x86_64\n"), nil + }, + want: true, + }, + { + name: "not owned by rpm", + lookup: func(string) (string, error) { return "/usr/bin/rpm", nil }, + run: func(string, ...string) ([]byte, error) { + return []byte("file " + executable + " is not owned by any package\n"), errors.New("exit status 1") + }, + want: false, + }, + { + name: "rpm is missing", + lookup: func(string) (string, error) { return "", notFound }, + run: func(string, ...string) ([]byte, error) { + t.Error("rpm ran although it was not found") + return nil, notFound + }, + want: false, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + lookPath = test.lookup + runCommand = test.run + if got := managedByRPM(executable); got != test.want { + t.Errorf("managedByRPM = %v, want %v", got, test.want) + } + }) + } +} + func TestFindProgramUsesTheOnlyExecutable(t *testing.T) { root := extractFixture(t, []archiveEntry{ {name: "viva-linux-amd64", mode: 0o755, body: "binary"}, diff --git a/update/install_windows.go b/update/install_windows.go index 21159c4b5..dbf6985a1 100644 --- a/update/install_windows.go +++ b/update/install_windows.go @@ -105,7 +105,7 @@ var ( // this process to end before it replaces the running executable. func install(options InstallOptions, quit func()) error { if options.Payload != "" { - return fmt.Errorf("%w: Windows has no installed payload to patch; download the installer", ErrUnsupported) + return installPayload(options, quit) } if options.Asset.Format != FormatNSIS { return fmt.Errorf("%w: windows needs an NSIS installer, not %q", ErrManifest, options.Asset.Format) @@ -148,6 +148,119 @@ func install(options InstallOptions, quit func()) error { return nil } +// installPayload replaces the application's files from a staged payload: the +// executable and the folders beside it that a patch wrote. The installer and +// its uninstaller are not run, so shortcuts, registry entries and anything +// else the installer owns stay as they are. A writable install directory is +// required; a machine-wide installation under Program Files is refused before +// anything changes. +func installPayload(options InstallOptions, quit func()) error { + payload, err := filepath.Abs(options.Payload) + if err != nil { + return fmt.Errorf("update: resolve %s: %w", options.Payload, err) + } + info, err := os.Stat(payload) + if err != nil { + return fmt.Errorf("update: %w", err) + } + if !info.IsDir() { + return fmt.Errorf("%w: %s is not a directory", ErrManifest, options.Payload) + } + executable, err := os.Executable() + if err != nil { + return fmt.Errorf("update: locate the running program: %w", err) + } + if executable, err = filepath.Abs(executable); err != nil { + return fmt.Errorf("update: resolve %s: %w", executable, err) + } + installDir := filepath.Dir(executable) + if _, err := os.Stat(filepath.Join(payload, filepath.Base(executable))); err != nil { + return fmt.Errorf("%w: the payload does not hold %s", ErrManifest, filepath.Base(executable)) + } + options.report("checking install directory") + if err := checkWritable(installDir); err != nil { + return err + } + options.report("replacing") + if err := startPayloadHelper(os.Getpid(), payload, installDir, executable, options.Args); err != nil { + return fmt.Errorf("update: start the update helper: %w", err) + } + quit() + return nil +} + +// 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. +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...) + command.SysProcAttr = helperSysProcAttr() + if err := command.Start(); err != nil { + return err + } + _ = command.Process.Release() + return nil +} + +// payloadHelperScript builds the script the payload helper runs. Every path is +// a PowerShell single-quoted literal. +func payloadHelperScript(parentPID int, payload, installDir, executable string, args []string) string { + var script strings.Builder + script.WriteString("$ErrorActionPreference = 'Stop'\n") + fmt.Fprintf(&script, "$parent = %d\n", parentPID) + fmt.Fprintf(&script, "$payload = %s\n", powerShellQuote(payload)) + fmt.Fprintf(&script, "$dir = %s\n", powerShellQuote(installDir)) + 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("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("function Restore {\n") + 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(" }\n }\n") + script.WriteString(" foreach ($rel in $created) { Remove-Item -LiteralPath (Join-Path $dir $rel) -Force -ErrorAction SilentlyContinue }\n") + script.WriteString("}\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("try {\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(" 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(" } 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(" }\n") + script.WriteString(" $p = Start-Process -FilePath $exe -PassThru") + if len(args) > 0 { + fmt.Fprintf(&script, " -ArgumentList %s", powerShellArgumentList(args)) + } + 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("Remove-Item -Recurse -Force $backup -ErrorAction SilentlyContinue\n") + script.WriteString("Remove-Item -Recurse -Force $payload -ErrorAction SilentlyContinue\n") + script.WriteString("exit 0\n") + return script.String() +} + // verifyAuthenticode reports whether path is signed and trusted, unsigned, or // could not be verified. Only the last case is an error; an unsigned installer // is allowed because the feed's Ed25519 signature authenticated its bytes. diff --git a/update/install_windows_test.go b/update/install_windows_test.go index 81ccf5067..38fc35fd1 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -3,11 +3,14 @@ package update import ( + "bytes" "errors" "io/fs" "os" + "os/exec" "path/filepath" "slices" + "strings" "syscall" "testing" "unsafe" @@ -224,3 +227,169 @@ func TestWinTrustStructLayout(t *testing.T) { } } } + +func TestPayloadHelperScriptKeepsABackupAndRestores(t *testing.T) { + script := payloadHelperScript(1234, `C:\Temp\O'Brien\payload`, `C:\Apps\Motty`, `C:\Apps\Motty\motty.exe`, []string{"--flag", "a b"}) + for _, want := range []string{ + "$parent = 1234", + `$payload = 'C:\Temp\O''Brien\payload'`, + `$dir = 'C:\Apps\Motty'`, + `$exe = 'C:\Apps\Motty\motty.exe'`, + "$backup = Join-Path $env:TEMP", + "function Restore", + "$created = New-Object System.Collections.ArrayList", + "Get-Process -Id $parent", + "Copy-Item -LiteralPath $_.FullName -Destination $dest -Force", + "Start-Process -FilePath $exe -PassThru", + "$p.HasExited -and $p.ExitCode -ne 0", + "Restore; Start-Process -FilePath $exe", + "Remove-Item -Recurse -Force $payload", + "exit 0", + } { + if !strings.Contains(script, want) { + t.Errorf("the helper script lacks %q:\n%s", want, script) + } + } +} + +func TestInstallPayloadNeedsTheProgramInThePayload(t *testing.T) { + payload := t.TempDir() + called := false + err := installPayload(InstallOptions{Payload: payload}, func() { called = true }) + if !errors.Is(err, ErrManifest) { + t.Fatalf("err = %v, want ErrManifest", err) + } + if called { + t.Fatal("installPayload called quit after refusing the payload") + } +} + +func TestInstallPayloadRefusesAFile(t *testing.T) { + file := writeWindowsTestArtifact(t, "payload") + called := false + err := installPayload(InstallOptions{Payload: file}, func() { called = true }) + if !errors.Is(err, ErrManifest) { + t.Fatalf("err = %v, want ErrManifest", err) + } + if called { + t.Fatal("installPayload called quit after refusing the payload") + } +} + +func systemExecutable(t *testing.T, name string) string { + t.Helper() + path := filepath.Join(os.Getenv("SystemRoot"), "System32", name) + if _, err := os.Stat(path); err != nil { + t.Skipf("%s is not available: %v", path, err) + } + return path +} + +func copyWindowsFile(t *testing.T, source, destination string) []byte { + t.Helper() + data, err := os.ReadFile(source) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(destination, data, 0o755); err != nil { + t.Fatal(err) + } + return data +} + +func runPayloadHelper(t *testing.T, script string, wantExit int) { + t.Helper() + path := filepath.Join(t.TempDir(), "helper.ps1") + if err := os.WriteFile(path, []byte(script), 0o600); err != nil { + t.Fatal(err) + } + command := exec.Command("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", path) + output, err := command.CombinedOutput() + if wantExit == 0 { + if err != nil { + t.Fatalf("helper: %v\n%s\n%s", err, output, script) + } + return + } + var exitErr *exec.ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != wantExit { + t.Fatalf("helper exit = %v, want %d\n%s\n%s", err, wantExit, output, script) + } +} + +func TestPayloadHelperReplacesTheApplication(t *testing.T) { + payload := filepath.Join(t.TempDir(), "payload with spaces") + install := filepath.Join(t.TempDir(), "app with spaces") + copyWindowsFile(t, systemExecutable(t, "cmd.exe"), filepath.Join(install, "app.exe")) + copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, "app.exe")) + if err := os.WriteFile(filepath.Join(install, "old.dll"), []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(payload, "new.dll"), []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + 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("app.exe was not replaced") + } + if data, err := os.ReadFile(filepath.Join(install, "new.dll")); err != nil || string(data) != "new" { + t.Errorf("new.dll = %q, %v", data, err) + } + if data, err := os.ReadFile(filepath.Join(install, "old.dll")); err != nil || string(data) != "old" { + t.Errorf("old.dll = %q, %v", data, err) + } +} + +func TestPayloadHelperRollsBackAFailedStart(t *testing.T) { + payload := t.TempDir() + install := t.TempDir() + original := copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(install, "app.exe")) + testExecutable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + copyWindowsFile(t, testExecutable, filepath.Join(payload, "app.exe")) + marker := filepath.Join(t.TempDir(), "started") + t.Setenv("VIVA_UPDATE_START_MARKER", marker) + if err := os.WriteFile(filepath.Join(payload, "new.dll"), []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), []string{"-test.run=^TestPayloadHelperProcess$"}) + runPayloadHelper(t, script, 1) + if data, err := os.ReadFile(marker); err != nil || string(data) != "started" { + t.Fatalf("updated application did not start: marker=%q, %v", data, err) + } + got, err := os.ReadFile(filepath.Join(install, "app.exe")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, original) { + t.Error("app.exe was not restored") + } + if _, err := os.Stat(filepath.Join(install, "new.dll")); !os.IsNotExist(err) { + t.Errorf("new.dll survived the rollback: %v", err) + } +} + +func TestPayloadHelperProcess(t *testing.T) { + marker := os.Getenv("VIVA_UPDATE_START_MARKER") + if marker == "" { + return + } + if err := os.WriteFile(marker, []byte("started"), 0o600); err != nil { + os.Exit(2) + } + os.Exit(1) +} diff --git a/update/patch.go b/update/patch.go index ccadac9ee..edf45e10b 100644 --- a/update/patch.go +++ b/update/patch.go @@ -51,7 +51,9 @@ type PatchManifest struct { ToVersion string `json:"to_version"` OS string `json:"os"` Arch string `json:"arch"` - // Payload is "app" for a macOS bundle and "file" for a Linux executable. + // Payload is "app" for a macOS bundle, "file" for a Linux executable and + // "dir" for the directory of a Windows installation: the program and the + // folders beside it. Payload string `json:"payload"` Files []PatchFile `json:"files"` } @@ -333,14 +335,24 @@ func (manifest PatchManifest) validate() error { if _, err := Compare(manifest.ToVersion, manifest.ToVersion); err != nil { return fmt.Errorf("%w: to_version: %v", ErrManifest, err) } - if manifest.OS != "darwin" && manifest.OS != "linux" { - return fmt.Errorf("%w: os %q has no patch support", ErrManifest, manifest.OS) - } if manifest.Arch != "amd64" && manifest.Arch != "arm64" { return fmt.Errorf("%w: arch %q is not supported", ErrManifest, manifest.Arch) } - if manifest.Payload != "app" && manifest.Payload != "file" { - return fmt.Errorf("%w: payload %q is not app or file", ErrManifest, manifest.Payload) + switch manifest.OS { + case "darwin": + if manifest.Payload != "app" { + return fmt.Errorf("%w: macOS patches carry an app payload, not %q", ErrManifest, manifest.Payload) + } + case "linux": + if manifest.Payload != "file" { + return fmt.Errorf("%w: Linux patches carry a file payload, not %q", ErrManifest, manifest.Payload) + } + case "windows": + if manifest.Payload != "dir" { + return fmt.Errorf("%w: Windows patches carry a dir payload, not %q", ErrManifest, manifest.Payload) + } + default: + return fmt.Errorf("%w: os %q has no patch support", ErrManifest, manifest.OS) } if len(manifest.Files) == 0 { return fmt.Errorf("%w: the patch holds no files", ErrManifest) diff --git a/update/patch_test.go b/update/patch_test.go index f67b3ac55..0b20ce31c 100644 --- a/update/patch_test.go +++ b/update/patch_test.go @@ -112,11 +112,11 @@ func TestPatchApply(t *testing.T) { if err != nil { t.Fatal(err) } + defer patch.Close() staging := filepath.Join(t.TempDir(), "staged") if err := patch.Apply(oldRoot, staging); err != nil { t.Fatal(err) } - patch.Close() for name, want := range map[string][]byte{ "program": newData, "same.txt": sameData, "resource/added.txt": addedData, @@ -133,8 +133,13 @@ func TestPatchApply(t *testing.T) { if _, err := os.Stat(filepath.Join(staging, "dropped.txt")); !os.IsNotExist(err) { t.Errorf("a deleted file was staged: %v", err) } - if info, err := os.Stat(filepath.Join(staging, "program")); err != nil || info.Mode().Perm() != 0o755 { - t.Errorf("program mode = %v, %v", info.Mode(), err) + info, err := os.Stat(filepath.Join(staging, "program")) + if err != nil { + t.Fatal(err) + } + // Windows has no Unix executable bits to preserve. + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o755 { + t.Errorf("program mode = %v, want 0755", info.Mode()) } } @@ -153,6 +158,7 @@ func TestPatchRefusesAChangedBase(t *testing.T) { if err != nil { t.Fatal(err) } + defer patch.Close() if err := os.WriteFile(filepath.Join(oldRoot, "program"), []byte("something else entirely"), 0o755); err != nil { t.Fatal(err) } @@ -226,6 +232,7 @@ func TestPatchRefusesANonEmptyStaging(t *testing.T) { if err != nil { t.Fatal(err) } + defer patch.Close() staging := filepath.Join(t.TempDir(), "staged") if err := os.MkdirAll(staging, 0o755); err != nil { t.Fatal(err) @@ -252,19 +259,43 @@ func TestApplyPatchChecksNameAndVersions(t *testing.T) { if err != nil { t.Fatal(err) } + payload := "file" + switch runtime.GOOS { + case "darwin": + payload = "app" + case "windows": + payload = "dir" + } + supported := runtime.GOOS == "darwin" || runtime.GOOS == "linux" || runtime.GOOS == "windows" + patchOS, patchArch := runtime.GOOS, runtime.GOARCH + if !supported { + // Use a valid patch so rejection exercises the running-platform check. + patchOS, patchArch = "linux", "amd64" + } manifest := PatchManifest{ Schema: PatchSchema, App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", - OS: runtime.GOOS, Arch: runtime.GOARCH, Payload: "file", + OS: patchOS, Arch: patchArch, Payload: payload, Files: []PatchFile{fileManifest("program", newData, "diff", "files/0001", 0o755)}, } patchPath := writePatch(t, manifest, map[string][]byte{"files/0001": diff}) original := locateInstalledPayload defer func() { locateInstalledPayload = original }() - located := "file" - locateInstalledPayload = func() (string, string, error) { return oldRoot, located, nil } + located := payload + locateInstalledPayload = func() (string, string, error) { + if !supported { + t.Error("an unsupported platform reached installed payload lookup") + } + return oldRoot, located, nil + } staging, err := ApplyPatch(patchPath, "dev.example.notes", "1.0.0", "1.1.0") + if !supported { + if staging != "" || !errors.Is(err, ErrManifest) { + t.Fatalf("unsupported platform: staging = %q, err = %v, want empty staging and ErrManifest", staging, err) + } + return + } if err != nil { t.Fatal(err) } @@ -279,6 +310,10 @@ func TestApplyPatchChecksNameAndVersions(t *testing.T) { t.Fatal(err) } + other := "file" + if payload != "app" { + other = "app" + } for name, call := range map[string]func() (string, error){ "wrong app": func() (string, error) { return ApplyPatch(patchPath, "other", "1.0.0", "1.1.0") }, "wrong from": func() (string, error) { return ApplyPatch(patchPath, "dev.example.notes", "0.9.0", "1.1.0") }, @@ -286,11 +321,79 @@ func TestApplyPatchChecksNameAndVersions(t *testing.T) { "wrong platform": func() (string, error) { return ApplyPatch(patchPath, "dev.example.notes", "1.0.0", "1.1.0") }, } { if name == "wrong platform" { - locateInstalledPayload = func() (string, string, error) { return oldRoot, "app", nil } + locateInstalledPayload = func() (string, string, error) { return oldRoot, other, nil } } if _, err := call(); !errors.Is(err, ErrManifest) { t.Errorf("%s: err = %v, want ErrManifest", name, err) } - locateInstalledPayload = func() (string, string, error) { return oldRoot, "file", nil } + locateInstalledPayload = func() (string, string, error) { return oldRoot, payload, nil } + } +} + +func TestPatchApplyWindowsDirectory(t *testing.T) { + oldRoot := t.TempDir() + oldExe := []byte("the old windows program") + newExe := []byte("the new windows program with more") + conpty := []byte("conpty dll bytes") + if err := os.MkdirAll(filepath.Join(oldRoot, "conpty", "x64"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(oldRoot, "app.exe"), oldExe, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(oldRoot, "conpty", "x64", "conpty.dll"), conpty, 0o644); err != nil { + t.Fatal(err) + } + diff, err := bsdiff.Bytes(oldExe, newExe) + if err != nil { + t.Fatal(err) + } + manifest := PatchManifest{ + Schema: PatchSchema, App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "windows", Arch: "amd64", Payload: "dir", + Files: []PatchFile{ + fileManifest("app.exe", newExe, "diff", "files/0001", 0o755), + fileManifest("conpty/x64/conpty.dll", conpty, "same", "", 0o644), + fileManifest("conpty/x64/new.dll", []byte("new"), "new", "files/0002", 0o644), + }, + } + patchPath := writePatch(t, manifest, map[string][]byte{"files/0001": diff, "files/0002": []byte("new")}) + patch, err := ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + defer patch.Close() + staging := filepath.Join(t.TempDir(), "staged") + if err := patch.Apply(oldRoot, staging); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(staging, "app.exe")) + if err != nil || !bytes.Equal(got, newExe) { + t.Fatalf("app.exe = %q, %v", got, err) + } + if got, err := os.ReadFile(filepath.Join(staging, "conpty", "x64", "new.dll")); err != nil || string(got) != "new" { + t.Fatalf("new.dll = %q, %v", got, err) + } +} + +func TestPatchRefusesAMismatchedPayloadKind(t *testing.T) { + base := func() PatchManifest { + return PatchManifest{ + Schema: PatchSchema, App: "app", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "windows", Arch: "amd64", Payload: "dir", + Files: []PatchFile{{Path: "app.exe", Mode: 0o755, Size: 1, SHA256: digest([]byte("x")), Op: "new", Blob: "files/0001"}}, + } + } + for name, change := range map[string]func(*PatchManifest){ + "windows with app": func(m *PatchManifest) { m.Payload = "app" }, + "darwin with dir": func(m *PatchManifest) { m.OS, m.Payload = "darwin", "dir" }, + "linux with dir": func(m *PatchManifest) { m.OS, m.Payload = "linux", "dir" }, + } { + manifest := base() + change(&manifest) + patchPath := writePatch(t, manifest, map[string][]byte{"files/0001": []byte("x")}) + if _, err := ReadPatch(patchPath); !errors.Is(err, ErrManifest) { + t.Errorf("%s: err = %v, want ErrManifest", name, err) + } } } diff --git a/update/payload_windows.go b/update/payload_windows.go index e5bc7a03d..7533d51f5 100644 --- a/update/payload_windows.go +++ b/update/payload_windows.go @@ -2,10 +2,24 @@ package update -import "fmt" +import ( + "fmt" + "os" + "path/filepath" +) -// installedPayload has nothing to describe on Windows: the NSIS installer owns -// the installation and patches are not offered there. +// installedPayload returns the directory holding the running program. Both an +// NSIS installation and a portable copy keep the application's files there: +// the executable and the folders it loads. A patch touches only the files it +// names, so the installer's uninstaller and shortcuts stay as they are. func installedPayload() (root, kind string, err error) { - return "", "", fmt.Errorf("%w: Windows installs updates from an installer, not a payload", ErrUnsupported) + executable, err := os.Executable() + if err != nil { + return "", "", fmt.Errorf("update: locating the running program: %w", err) + } + resolved, err := filepath.Abs(executable) + if err != nil { + return "", "", fmt.Errorf("update: resolving %s: %w", executable, err) + } + return filepath.Dir(resolved), "dir", nil } diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md index be08cb710..bbc5530ca 100644 --- a/website/content/guides/en/getting-started.md +++ b/website/content/guides/en/getting-started.md @@ -22,7 +22,7 @@ go mod init example.com/hello go get github.com/vivaui/viva ``` -`go get` without a version resolves to the latest tagged release, which is `v0.6.3`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.3`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading. +`go get` without a version resolves to the latest tagged release, which is `v0.6.4`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.4`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading. If you are working on Viva itself rather than using it, `replace` it with your checkout instead: diff --git a/website/content/guides/zh/getting-started.md b/website/content/guides/zh/getting-started.md index 5ab36bfc8..cdefa9343 100644 --- a/website/content/guides/zh/getting-started.md +++ b/website/content/guides/zh/getting-started.md @@ -22,7 +22,7 @@ go mod init example.com/hello go get github.com/vivaui/viva ``` -`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.3`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.3`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 +`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.4`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.4`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 如果你是在 Viva 仓库里改框架本身、而不是使用它,改用 `replace` 指向检出目录: