From c2fd6ada707b093ec8669ad330cd5a531483dcc8 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 13 Nov 2026 21:52:29 +0800 Subject: [PATCH 01/86] fix(components): stop menu rows tinting under caller content The runtime now records the hovered hit's role, and a menu row only draws its current-item tint when the pointer is not over a non-row control inside the menu. This removes Motty's paint-time focus workaround for the tab colour row. --- app/painter.go | 8 +++- components/context_menu_test.go | 74 ++++++++++++++++++++++++++++++++ components/dropdown_menu.go | 7 ++- gfx/canvas.go | 17 ++++++++ internal/input/input.go | 10 +++++ internal/interaction/pointer.go | 7 +++ internal/platform/web/painter.go | 8 +++- 7 files changed, 126 insertions(+), 5 deletions(-) diff --git a/app/painter.go b/app/painter.go index be6764c4d..587adda3d 100644 --- a/app/painter.go +++ b/app/painter.go @@ -274,6 +274,7 @@ func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Fram return platform.Frame{}, nil } painter.pointer.SetHovered(gfx.ID{}) + painter.pointer.SetHoveredRole(gfx.Role(0)) return painter.repaintAfterInput() } beforeHovered, beforePressed := painter.pointer.Hovered(), painter.pointer.Pressed() @@ -338,9 +339,11 @@ func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Fram // application answered and whether focus and the pointer's edge state changed. func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.EventResult, focusChanged, edgeChanged bool) { painter.pointer.SetHovered(gfx.ID{}) + painter.pointer.SetHoveredRole(gfx.Role(0)) if event.Kind != platform.PointerExit { - if target, ok := painter.focus.Router().HitTest(event.X, event.Y); ok { - painter.pointer.SetHovered(target) + if target, ok := painter.focus.Router().HitTestRegion(event.X, event.Y); ok { + painter.pointer.SetHovered(target.Target) + painter.pointer.SetHoveredRole(target.Role) } } edgeChanged = painter.trackEdge(event) @@ -848,6 +851,7 @@ func (painter *painter) paintCanvas() { } focused, visible := painter.focus.PaintTarget() painter.canvas.SetInteraction(painter.pointer.Hovered(), painter.pointer.Pressed(), focused, visible) + painter.canvas.SetHoveredRole(painter.pointer.HoveredRole()) painter.canvas.SetScroll(painter.scrollX, painter.scrollY) painter.canvas.BeginFrame() painter.paint(painter.canvas, painter.size) diff --git a/components/context_menu_test.go b/components/context_menu_test.go index b18b3f8c5..6b203148b 100644 --- a/components/context_menu_test.go +++ b/components/context_menu_test.go @@ -4,6 +4,7 @@ import ( "slices" "testing" + "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" ) @@ -197,3 +198,76 @@ func TestContextMenuItemWidthKeepsTheLabelWhole(t *testing.T) { t.Fatalf("12px under the computed width the label still gets %v of %v: the width is not tight", got, need) } } + +func TestMenuContentKeepsTheFocusedRowFromTinting(t *testing.T) { + var tree gfx.Tree + feature := tree.Feature("menu-content") + scope := gfx.Item(64) + rowID := tree.ID(feature, "row") + contentID := tree.ID(feature, "content") + theme := gfx.DarkTheme() + var rowBounds, contentBounds gfx.Rect + driver, err := app.NewDriver(app.Config{ + Width: 320, Height: 240, Tree: &tree, + Paint: func(c *gfx.Canvas, size gfx.Size) { + menu := BeginContextMenu(c, theme, gfx.Rect{X: 20, Y: 20, Width: 220, Height: 160}, ContextMenuOptions{Layer: 7, Scope: scope}) + rowBounds = menu.AddItem(ContextMenuItem{ID: rowID, Label: "Row"}) + menu.BeginContent() + contentBounds = menu.AddItem(ContextMenuItem{}) + c.HitWithOptions(contentID, contentBounds, "Content", gfx.HitOptions{Role: gfx.RoleButton}) + menu.EndContent() + menu.End() + }, + }, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + move := func(x, y float32) { + t.Helper() + must(driver.Move(x, y)) + } + rowTinted := func() bool { + t.Helper() + for _, primitive := range driver.Snapshot().Primitives { + if primitive.Color == theme.Accent && primitive.Bounds == rowBounds { + return true + } + } + return false + } + rowCenter := func() (float32, float32) { + return rowBounds.X + rowBounds.Width/2, rowBounds.Y + rowBounds.Height/2 + } + contentCenter := func() (float32, float32) { + return contentBounds.X + contentBounds.Width/2, contentBounds.Y + contentBounds.Height/2 + } + // Hovering the row makes it the menu's current row. + x, y := rowCenter() + move(x, y) + move(x+1, y) + if !rowTinted() { + t.Fatal("hovering the row did not tint it: the test cannot see the state it checks") + } + // The pointer then rests on caller content inside the menu. The focused row + // must not light up again. + x, y = contentCenter() + move(x, y) + move(x+1, y) + if rowTinted() { + t.Fatal("the row is tinted while the pointer rests on the menu's content") + } + // Returning to the row lights it again. + x, y = rowCenter() + move(x, y) + move(x+1, y) + if !rowTinted() { + t.Fatal("the row is no longer tinted after the pointer returned to it") + } +} diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index c6cc53903..4fd14679b 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -950,6 +950,11 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { // 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 + // switch), no row is the menu's current row: keeping the last focused row + // tinted would fight the control under the pointer. Menu rows themselves + // declare RoleMenuItem. + inContent := !hovered.IsZero() && canvas.HoveredRole() != 0 && canvas.HoveredRole() != gfx.RoleMenuItem if claim && hovered == item.ID { // A disabled row cannot take focus, but the frame is still repainted so // the row that kept focus is tinted again on the next paint. @@ -960,7 +965,7 @@ 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 && (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 } diff --git a/gfx/canvas.go b/gfx/canvas.go index 8f2533530..9d7760091 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -717,6 +717,10 @@ type Canvas struct { // fits remembers the lines FitLine cut; a different measurement empties it. fits []fitEntry hovered ID + // hoveredRole is the role of the hovered hit, when the runtime recorded one. + // Components that draw content inside a menu use it to tell their own rows + // from caller content under the pointer. + hoveredRole Role // prevHovered is the hit the pointer was on at the end of the previous // paint, which is what HoverCrossed compares against. prevHovered ID @@ -1925,6 +1929,7 @@ func (canvas *Canvas) Clips() []Clip { // runtime-facing; application paint code should only read it. func (canvas *Canvas) SetInteraction(hovered, pressed, focused ID, focusVisible bool) { canvas.hovered = hovered + canvas.hoveredRole = 0 canvas.pressed = pressed canvas.focused = focused canvas.focusVisible = focusVisible @@ -1935,6 +1940,18 @@ func (canvas *Canvas) Hovered() ID { return canvas.hovered } +// HoveredRole returns the role of the hovered hit, or the zero role when the +// runtime did not record one. +func (canvas *Canvas) HoveredRole() Role { + return canvas.hoveredRole +} + +// SetHoveredRole records the role of the hovered hit. It is runtime-facing; +// application paint code should only read it. +func (canvas *Canvas) SetHoveredRole(role Role) { + canvas.hoveredRole = role +} + // HoverCrossed reports whether the pointer reached a different hit since the // previous paint. Lists use it to move their current row onto the row the // pointer entered, without letting a pointer that rests in place take the row diff --git a/internal/input/input.go b/internal/input/input.go index e3995c90d..4252c69fc 100644 --- a/internal/input/input.go +++ b/internal/input/input.go @@ -177,6 +177,16 @@ func (router *Router) HitTest(x float32, y float32) (Target, bool) { return router.regions[index].Target, true } +// HitTestRegion returns the front-most enabled region containing the point, +// including the focus scope it was declared in. +func (router *Router) HitTestRegion(x float32, y float32) (Region, bool) { + index, ok := router.hitTestIndex(x, y) + if !ok { + return Region{}, false + } + return router.regions[index], true +} + // PressKind is what a press at a point does in a custom-titlebar window. type PressKind uint8 diff --git a/internal/interaction/pointer.go b/internal/interaction/pointer.go index 33642956b..3c5687cae 100644 --- a/internal/interaction/pointer.go +++ b/internal/interaction/pointer.go @@ -8,6 +8,7 @@ import "github.com/vivaui/viva/gfx" // target and the application did not consume it. type Pointer struct { hovered gfx.ID + hoveredRole gfx.Role pressed gfx.ID target gfx.ID button gfx.PointerButton @@ -17,9 +18,15 @@ type Pointer struct { // SetHovered records the hit under the pointer, or zero when there is none. func (p *Pointer) SetHovered(target gfx.ID) { p.hovered = target } +// SetHoveredRole records the role of the hovered hit. +func (p *Pointer) SetHoveredRole(role gfx.Role) { p.hoveredRole = role } + // Hovered returns the hit under the pointer. func (p *Pointer) Hovered() gfx.ID { return p.hovered } +// HoveredRole returns the role of the hovered hit. +func (p *Pointer) HoveredRole() gfx.Role { return p.hoveredRole } + // Pressed returns the target of the current press, or zero. func (p *Pointer) Pressed() gfx.ID { return p.pressed } diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index 2da21ae2d..8dc66f309 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -418,6 +418,7 @@ func (p *painter) paint() { p.canvas.Reset() focused, visible := p.focus.PaintTarget() p.canvas.SetInteraction(p.pointer.Hovered(), p.pointer.Pressed(), focused, visible) + p.canvas.SetHoveredRole(p.pointer.HoveredRole()) p.canvas.SetScroll(p.scrollX, p.scrollY) p.canvas.BeginFrame() p.config.Paint(p.canvas, gfx.Size{Width: p.width, Height: p.height}) @@ -647,6 +648,7 @@ func (p *painter) pointerEvent(event gfx.PointerEvent) bool { // comes up; only hover is gone. The release is delivered outside. p.pointerOutside = true p.pointer.SetHovered(gfx.ID{}) + p.pointer.SetHoveredRole(gfx.Role(0)) if beforeHovered.IsZero() { return false } @@ -693,9 +695,11 @@ func (p *painter) pointerCancel(event gfx.PointerEvent) bool { // state, the application and the controls' event pass. func (p *painter) pointerStep(event gfx.PointerEvent) (result gfx.EventResult, focusChanged, placed bool) { p.pointer.SetHovered(gfx.ID{}) + p.pointer.SetHoveredRole(gfx.Role(0)) if event.Kind != gfx.PointerExit { - if target, ok := p.focus.Router().HitTest(event.X, event.Y); ok { - p.pointer.SetHovered(target) + if target, ok := p.focus.Router().HitTestRegion(event.X, event.Y); ok { + p.pointer.SetHovered(target.Target) + p.pointer.SetHoveredRole(target.Role) } } if event.Kind == gfx.PointerDown { From 0edcd90182f69da44b1e80511911785d70e8d826 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Fri, 13 Nov 2026 21:59:58 +0800 Subject: [PATCH 02/86] fix(ui): let a tooltip open on a chosen side --- components/tooltip.go | 13 +++++++++--- ui/frame.go | 1 + ui/tooltip.go | 37 +++++++++++++++++++++++++++++++++- ui/tooltip_test.go | 47 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 4 deletions(-) diff --git a/components/tooltip.go b/components/tooltip.go index 92bb497a8..4e2134df9 100644 --- a/components/tooltip.go +++ b/components/tooltip.go @@ -91,6 +91,9 @@ type TooltipOptions struct { SideOffset float32 AlignOffset float32 MaxWidth float32 + // SideOf is the side HoverTooltip opens the tooltip of the hit id on, where + // Side has no say. Nil opens every one below its control. + SideOf func(id gfx.ID) TooltipSide } // Tooltip is one noninteractive Vega tooltip declaration. @@ -308,9 +311,10 @@ func (hover *HoverTooltip) Dismiss() bool { func (hover *HoverTooltip) ShowOnFocus() { hover.focus = true } // Paint draws the tooltip of the hovered hit once it has been hovered for -// delay, and reports whether it did. The tooltip goes below the control, or -// above it when the viewport has no room below (see PlaceOverlay). It stays hidden while a button -// is pressed and for hits without a Hint. +// delay, and reports whether it did. The tooltip goes below the control, or on +// the side options.SideOf names, and on the opposite side when the viewport has +// no room there (see PlaceOverlay). It stays hidden while a button is pressed and +// for hits without a Hint. func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, options TooltipOptions, delay time.Duration) bool { hovered := canvas.Hovered() if !canvas.Pressed().IsZero() { @@ -364,6 +368,9 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g return false } options.Side = TooltipBottom + if options.SideOf != nil { + options.Side = options.SideOf(id) + } options.ID = id BeginTooltip(canvas, theme, viewport, hit.Bounds, options).Paint(hit.Hint) hover.shown = id diff --git a/ui/frame.go b/ui/frame.go index 3e1dc82f8..9b58d5b2b 100644 --- a/ui/frame.go +++ b/ui/frame.go @@ -208,6 +208,7 @@ type extra struct { memo int32 // 1 + the index the element's cache has with whoever declared it (memoFn), or 0 draws int32 // 1 + the index of the element's Draw and DrawOver callbacks in frame.draws, or 0 for none tooltip string // what Tooltip says over the element; empty for none + tooltipSide uint8 // 1 + the TooltipSide TooltipOn opens the element's tip on; 0 is below addons int32 // 1 + the index of the field's icon and button in frame.addons, or 0 focusGroup FocusAxis // FocusGroup: the arrow keys that move the focus between the controls inside; zero is none focusOrder FocusOrder // FocusOrder: how the group chooses the next member; nil is its axis diff --git a/ui/tooltip.go b/ui/tooltip.go index e3f16361a..e7a881b28 100644 --- a/ui/tooltip.go +++ b/ui/tooltip.go @@ -25,6 +25,31 @@ func (b Box) Tooltip(text string) Box { return b } +// TooltipSide is the edge of its element a Tooltip opens beside. +type TooltipSide = components.TooltipSide + +// The sides TooltipOn opens a Tooltip on. +const ( + TooltipTop = components.TooltipTop + TooltipRight = components.TooltipRight + TooltipBottom = components.TooltipBottom + TooltipLeft = components.TooltipLeft +) + +// TooltipOn opens the element's Tooltip beside side rather than below it: an +// information icon at the end of a label shows its tip to its right, where the +// tip covers neither the label nor the rows under it. Without room on side, the +// tip opens on the opposite one. +// +// ui.Button(c, "").Icon(info).Tooltip("Applies to new terminals").TooltipOn(ui.TooltipRight) +func (b Box) TooltipOn(side TooltipSide) Box { + if b.n().id.IsZero() { + panic("ui: TooltipOn needs an element with an identity: a control, or a container given Hit") + } + b.f.extra(b.i).tooltipSide = uint8(side) + 1 + return b +} + // paintTooltip paints the Tooltip of the element the pointer rests on, over // everything the frame painted. func (f *frame) paintTooltip() { @@ -37,10 +62,20 @@ func (f *frame) paintTooltip() { f.tooltip = components.HoverTooltip{} return } - f.tooltip.Paint(f.canvas, f.theme, f.bounds, components.TooltipOptions{Layer: TooltipLayer}, + f.tooltip.Paint(f.canvas, f.theme, f.bounds, components.TooltipOptions{Layer: TooltipLayer, SideOf: f.tooltipSideOf}, components.HoverTooltipDelay) } +// tooltipSideOf is the side TooltipOn gave the element id, or below. +func (f *frame) tooltipSideOf(id gfx.ID) TooltipSide { + for i := range f.nodes { + if n := &f.nodes[i]; n.id == id && n.ext != 0 && f.exts[n.ext].tooltipSide != 0 { + return TooltipSide(f.exts[n.ext].tooltipSide - 1) + } + } + return TooltipBottom +} + // hasTooltip reports whether id names an element of this frame given a Tooltip. // A Memo declares what it holds again while the pointer is on it, so the element // under the pointer is always one the frame declared. diff --git a/ui/tooltip_test.go b/ui/tooltip_test.go index 5d263ef0c..a1bb0e399 100644 --- a/ui/tooltip_test.go +++ b/ui/tooltip_test.go @@ -3,6 +3,7 @@ package ui_test import ( "testing" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -56,3 +57,49 @@ func TestTooltip(t *testing.T) { } } } + +// tooltipLabel is the label of the shown tooltip saying text. +func tooltipLabel(t *testing.T, d *pageDriver, text string) gfx.Rect { + t.Helper() + for _, label := range d.driver.Snapshot().Labels { + if label.Value == text { + return label.Bounds + } + } + t.Fatalf("no tooltip says %q", text) + return gfx.Rect{} +} + +// TooltipOn opens the tip beside the side it names, below the control by +// default, and a Memo's copy keeps the side. +func TestTooltipOn(t *testing.T) { + for _, memo := range []bool{false, true} { + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(40).Gap(40).Children(func() { + row := func() { + ui.Button(c, "Info").Tooltip("Opens to the right").TooltipOn(ui.TooltipRight) + ui.Button(c, "Plain").Tooltip("Opens below") + } + if memo { + ui.Memo(c, 1, row) + } else { + row() + } + }) + }) + info := d.hit("Info").Bounds + if err := d.driver.Move(center(info)); err != nil { + t.Fatal(err) + } + if tip := tooltipLabel(t, d, "Opens to the right"); tip.X < info.X+info.Width || tip.Y >= info.Y+info.Height { + t.Fatalf("memo=%v: the tip %v is not to the right of its control %v", memo, tip, info) + } + plain := d.hit("Plain").Bounds + if err := d.driver.Move(center(plain)); err != nil { + t.Fatal(err) + } + if tip := tooltipLabel(t, d, "Opens below"); tip.Y < plain.Y+plain.Height { + t.Fatalf("memo=%v: the tip %v is not below its control %v", memo, tip, plain) + } + } +} From 9305ef2a89bebd838b9ab0a3d56787f97bf2597b Mon Sep 17 00:00:00 2001 From: t8y2 Date: Fri, 13 Nov 2026 22:00:52 +0800 Subject: [PATCH 03/86] fix(tooltip): regenerate the installer recipe --- cmd/viva/templates/tooltip.go.txt | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/cmd/viva/templates/tooltip.go.txt b/cmd/viva/templates/tooltip.go.txt index edae11d2e..37fc971db 100644 --- a/cmd/viva/templates/tooltip.go.txt +++ b/cmd/viva/templates/tooltip.go.txt @@ -91,6 +91,9 @@ type TooltipOptions struct { SideOffset float32 AlignOffset float32 MaxWidth float32 + // SideOf is the side HoverTooltip opens the tooltip of the hit id on, where + // Side has no say. Nil opens every one below its control. + SideOf func(id gfx.ID) TooltipSide } // Tooltip is one noninteractive Vega tooltip declaration. @@ -308,9 +311,10 @@ func (hover *HoverTooltip) Dismiss() bool { func (hover *HoverTooltip) ShowOnFocus() { hover.focus = true } // Paint draws the tooltip of the hovered hit once it has been hovered for -// delay, and reports whether it did. The tooltip goes below the control, or -// above it when the viewport has no room below (see PlaceOverlay). It stays hidden while a button -// is pressed and for hits without a Hint. +// delay, and reports whether it did. The tooltip goes below the control, or on +// the side options.SideOf names, and on the opposite side when the viewport has +// no room there (see PlaceOverlay). It stays hidden while a button is pressed and +// for hits without a Hint. func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, options TooltipOptions, delay time.Duration) bool { hovered := canvas.Hovered() if !canvas.Pressed().IsZero() { @@ -364,6 +368,9 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g return false } options.Side = TooltipBottom + if options.SideOf != nil { + options.Side = options.SideOf(id) + } options.ID = id BeginTooltip(canvas, theme, viewport, hit.Bounds, options).Paint(hit.Hint) hover.shown = id From 74ddd6535629b3ae5905a4006dc4edd721c363e2 Mon Sep 17 00:00:00 2001 From: jakey <267309453@qq.com> Date: Fri, 13 Nov 2026 22:02:37 +0800 Subject: [PATCH 04/86] feat(web): allow a page to bypass system proxies --- app/web.go | 8 ++++- app/web_test.go | 11 +++++++ docs/web-views.md | 14 +++++--- internal/platform/darwin/web_darwin.go | 13 ++++++-- internal/platform/darwin/web_darwin.h | 3 +- internal/platform/darwin/web_darwin.m | 32 ++++++++++++++++--- internal/platform/linux/gtk_web_linux.go | 28 ++++++++++------ internal/platform/web_host.go | 4 +++ .../windows/web_proxy_windows_test.go | 7 ++++ internal/platform/windows/webview2_windows.go | 5 +++ 10 files changed, 103 insertions(+), 22 deletions(-) diff --git a/app/web.go b/app/web.go index 948a487ff..f428b4356 100644 --- a/app/web.go +++ b/app/web.go @@ -77,6 +77,11 @@ func (host *WebHost) repaintWith(painter *painter) { } } +// WebProxyDirect selects direct networking for a page, bypassing system proxies. +// macOS requires version 14 or newer; unsupported engines return ErrUnsupported. +// On macOS and Linux, direct pages use a nonpersistent data store. +const WebProxyDirect = platform.WebProxyDirect + // WebViewConfig describes a page to open. type WebViewConfig struct { // URL is loaded when the page opens, unless HTML is set. @@ -91,6 +96,7 @@ type WebViewConfig struct { // carries all of the page's traffic, names resolved by the proxy: the page reaches only what the // proxy reaches. Opening fails with ErrUnsupported where the engine cannot be held to it, rather // than opening a page that connects directly. + // Empty follows the system proxy policy. WebProxyDirect bypasses system proxies for this page. Proxy string // OnMessage receives what the page posts with window.viva.postMessage(text). OnMessage func(text string) @@ -206,7 +212,7 @@ func (host *WebHost) Open(config WebViewConfig) (*WebView, error) { if host == nil || host.native == nil || host.native.Open == nil { return nil, fmt.Errorf("%w: web views", ErrUnsupported) } - if config.Proxy != "" && !loopbackAddress(config.Proxy) { + if config.Proxy != "" && config.Proxy != WebProxyDirect && !loopbackAddress(config.Proxy) { return nil, fmt.Errorf("app: web view proxy %q is not a loopback host:port", config.Proxy) } id := gfx.NativeViewID(host.next.Add(1)) diff --git a/app/web_test.go b/app/web_test.go index 181f7c9e0..57990df9a 100644 --- a/app/web_test.go +++ b/app/web_test.go @@ -53,6 +53,17 @@ func TestOpeningAPageWithoutAHostIsUnsupported(t *testing.T) { } } +func TestDirectPageNetworkingReachesPlatform(t *testing.T) { + var proxy string + host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) { + proxy = config.Proxy + return nil, platform.ErrWebViewUnsupported + }}} + if _, err := host.Open(WebViewConfig{Proxy: WebProxyDirect}); !errors.Is(err, ErrUnsupported) || proxy != platform.WebProxyDirect { + t.Fatalf("direct networking was not passed to the platform: proxy=%q err=%v", proxy, err) + } +} + func TestAPageProxyMustBeOnThisMachine(t *testing.T) { var opened []string host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) { diff --git a/docs/web-views.md b/docs/web-views.md index 81965e58d..6bfb1ba69 100644 --- a/docs/web-views.md +++ b/docs/web-views.md @@ -83,10 +83,16 @@ scheme, a message in each direction and a menu that stands over the page. included, goes through it, names are resolved by the proxy, and WebRTC sends no UDP around it, so the page reaches only what the proxy reaches (a tunnel to a remote network, Tor, a test harness). On Windows each proxy has its own WebView2 browser, in a folder of its own under the user data folder; on Linux an ephemeral - WebKit context (WebKitGTK 2.16 or newer). Either ends with its last page. macOS cannot hold a page to a proxy, - and `Open` fails with `ErrUnsupported` rather than open one that connects directly: WKWebView's - `proxyConfigurations` (macOS 14) sends names to the proxy unresolved, but the system exempts loopback - addresses from it, so `http://127.0.0.1:3000/` would reach the user's own machine. + WebKit context (WebKitGTK 2.16 or newer). Either ends with its last page. macOS cannot hold a page to a + SOCKS5 proxy, and `Open` fails with `ErrUnsupported` rather than open one that connects directly: + WKWebView's `proxyConfigurations` (macOS 14) sends names to the proxy unresolved, but the system exempts + loopback addresses from it, so `http://127.0.0.1:3000/` would reach the user's own machine. +- `Proxy: app.WebProxyDirect` bypasses the system proxy for this page alone, which an embedded document or + workspace page needs when the machine's proxy rejects it. macOS needs 14 or newer and returns + `ErrUnsupported` on older versions; Windows passes `--no-proxy-server` to the page's own WebView2 + environment; Linux sets WebKitGTK's no-proxy mode on the page's own context. This selects a route, not a + privacy guarantee. Direct pages also use a nonpersistent store on macOS and Linux even when `Ephemeral` is + false, so cookies and storage do not outlive them; Windows keeps its dedicated persistent WebView2 profile. - `TopCornerRadius` rounds the page's two top corners in logical pixels, for a page that sits inside a rounded window or toolbar; zero keeps it rectangular. macOS cuts the rounded outline out of the page and refuses the pointer in the clipped corners, and Windows cuts the same outline into the child window's region. GTK has no diff --git a/internal/platform/darwin/web_darwin.go b/internal/platform/darwin/web_darwin.go index 03e0a669c..b0c12e2a1 100644 --- a/internal/platform/darwin/web_darwin.go +++ b/internal/platform/darwin/web_darwin.go @@ -3,7 +3,7 @@ package darwin /* -#cgo LDFLAGS: -framework Cocoa -framework WebKit -framework QuartzCore +#cgo LDFLAGS: -framework Cocoa -framework WebKit -framework QuartzCore -framework Network #include #include "web_darwin.h" */ @@ -67,8 +67,15 @@ func newWebState(run *runState, host *platform.WebHost, initial []platform.Nativ // open is WebHost.Open. func (w *webState) open(config platform.WebViewConfig) (platform.WebView, error) { + direct := C.int(0) if config.Proxy != "" { - return nil, platform.ErrWebViewUnsupported + if config.Proxy != platform.WebProxyDirect { + return nil, fmt.Errorf("%w: macOS cannot hold a page to a SOCKS5 proxy", platform.ErrWebViewUnsupported) + } + if C.viva_web_direct_supported() == 0 { + return nil, fmt.Errorf("%w: direct web networking requires macOS 14 or newer", platform.ErrWebViewUnsupported) + } + direct = 1 } if w.run.closed || w.token == nil { return nil, platform.ErrWebViewUnsupported @@ -105,7 +112,7 @@ func (w *webState) open(config platform.WebViewConfig) (platform.WebView, error) ephemeral = 1 } var failure *C.char - native := C.viva_web_open(view, C.uint32_t(config.ID), C.uintptr_t(w.run.callbackHandle), url, html, base, script, mainFrameOnly, scheme, ephemeral, &failure) + native := C.viva_web_open(view, C.uint32_t(config.ID), C.uintptr_t(w.run.callbackHandle), url, html, base, script, mainFrameOnly, scheme, ephemeral, direct, &failure) if native == nil { message := "the page could not be created" if failure != nil { diff --git a/internal/platform/darwin/web_darwin.h b/internal/platform/darwin/web_darwin.h index 5e734ca6e..129d8db0c 100644 --- a/internal/platform/darwin/web_darwin.h +++ b/internal/platform/darwin/web_darwin.h @@ -13,8 +13,9 @@ void *viva_application_window_view(void *token); // bridge script is for the main frame alone (WebKit is also told to inject it there only). An // ephemeral page keeps its data in a store in memory, which goes with the page. void *viva_web_open(void *view, uint32_t id, uintptr_t handle, const char *url, const char *html, - const char *base, const char *script, int main_frame_only, const char *scheme, int ephemeral, + const char *base, const char *script, int main_frame_only, const char *scheme, int ephemeral, int direct, char **error); +int viva_web_direct_supported(void); void viva_web_load(void *web, const char *url); void viva_web_load_html(void *web, const char *html, const char *base); void viva_web_reload(void *web); diff --git a/internal/platform/darwin/web_darwin.m b/internal/platform/darwin/web_darwin.m index 3e450747b..f95366a55 100644 --- a/internal/platform/darwin/web_darwin.m +++ b/internal/platform/darwin/web_darwin.m @@ -1,6 +1,7 @@ #import #import #import +#import #include #include @@ -518,8 +519,17 @@ - (void)mouseExited:(NSEvent *)event { @end +int viva_web_direct_supported(void) { +#if defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 140000 + if (@available(macOS 14.0, *)) { + return 1; + } +#endif + return 0; +} + void *viva_web_open(void *view, uint32_t id, uintptr_t handle, const char *url, const char *html, - const char *base, const char *script, int mainFrameOnly, const char *scheme, int ephemeral, + const char *base, const char *script, int mainFrameOnly, const char *scheme, int ephemeral, int direct, char **error) { __block VivaWebView *web = nil; viva_web_main(^{ @@ -531,11 +541,25 @@ - (void)mouseExited:(NSEvent *)event { bridge->_handle = handle; bridge->_id = id; WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; - if (ephemeral) { - // Nothing the page keeps reaches the disk, and no other page shares it: the store lives - // in this process only and goes with the page. + if (ephemeral || direct) { + // Ephemeral pages keep nothing on disk. Direct pages also need a private store so + // their proxy policy cannot change another page's in-flight requests or data store. configuration.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore]; } + if (direct) { +#if defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 140000 + if (@available(macOS 14.0, *)) { + // An empty proxyConfigurations array restores system proxies. Excluding every + // domain selects direct connections; the excluded endpoint is never contacted. + nw_endpoint_t endpoint = nw_endpoint_create_host("127.0.0.1", "9"); + nw_proxy_config_t policy = nw_proxy_config_create_http_connect(endpoint, NULL); + nw_proxy_config_add_excluded_domain(policy, "*"); + configuration.websiteDataStore.proxyConfigurations = @[policy]; + nw_release(policy); + nw_release(endpoint); + } +#endif + } WKUserContentController *controller = configuration.userContentController; [controller addScriptMessageHandler:bridge name:@"viva"]; WKUserScript *bridgeScript = [[WKUserScript alloc] initWithSource:[NSString stringWithUTF8String:script] diff --git a/internal/platform/linux/gtk_web_linux.go b/internal/platform/linux/gtk_web_linux.go index 7c40a263f..ef395e912 100644 --- a/internal/platform/linux/gtk_web_linux.go +++ b/internal/platform/linux/gtk_web_linux.go @@ -281,7 +281,10 @@ type webContext struct { } // WebKitNetworkProxyMode. -const webProxyCustom = 2 +const ( + webProxyNone = 1 + webProxyCustom = 2 +) // proxyContext is the context for pages held to proxy, shared by the pages behind that proxy and // made the first time. @@ -298,7 +301,7 @@ func proxyContext(g *gtkLibrary, k *webKit, proxy string) (*webContext, error) { return context, nil } -// newProxyContext makes an ephemeral context with every request sent through proxy. It is not +// newProxyContext makes an ephemeral context with the requested network policy. It is not // shared: a page that asked for a proxy and to keep nothing gets one of these, so it shares // nothing with the pages behind the same proxy. func newProxyContext(k *webKit, proxy string) (*webContext, error) { @@ -309,16 +312,23 @@ func newProxyContext(k *webKit, proxy string) (*webContext, error) { if err != nil { return nil, err } - // No hosts are left out: loopback goes through the proxy too, and names are the proxy's to - // resolve. - uri := cString("socks5://" + proxy) - settings := k.proxySettingsNew(&uri[0], 0) + mode := int32(webProxyCustom) + var settings uintptr + if proxy == platform.WebProxyDirect { + mode = webProxyNone + } else { + // No hosts are left out: loopback goes through the proxy too, and names are the proxy's to resolve. + uri := cString("socks5://" + proxy) + settings = k.proxySettingsNew(&uri[0], 0) + } if k.managerSetProxy != nil { - k.managerSetProxy(k.contextDataManager(context.object), webProxyCustom, settings) + k.managerSetProxy(k.contextDataManager(context.object), mode, settings) } else { - k.contextSetProxy(context.object, webProxyCustom, settings) + k.contextSetProxy(context.object, mode, settings) + } + if settings != 0 { + k.proxySettingsFree(settings) } - k.proxySettingsFree(settings) context.proxy = proxy return context, nil } diff --git a/internal/platform/web_host.go b/internal/platform/web_host.go index c18c55899..938565277 100644 --- a/internal/platform/web_host.go +++ b/internal/platform/web_host.go @@ -15,6 +15,9 @@ import ( // window, or the system's web engine is not installed. var ErrWebViewUnsupported = errors.New("platform: this window cannot host web pages") +// WebProxyDirect explicitly bypasses system proxies for one page's network context. +const WebProxyDirect = "direct" + // NativeView is a place in the window that a native view fills. type NativeView struct { // ID is the WebView it belongs to (WebViewConfig.ID). @@ -55,6 +58,7 @@ type WebViewConfig struct { // Proxy, when set, is the loopback host:port of a SOCKS5 proxy that carries all of the page's // traffic, names resolved by the proxy. A platform that cannot hold the page to it returns // ErrWebViewUnsupported rather than opening a page that connects directly. + // WebProxyDirect bypasses system proxies instead. Proxy string // OnMessage receives what the page posts with window.viva.postMessage(text). OnMessage func(text string) diff --git a/internal/platform/windows/web_proxy_windows_test.go b/internal/platform/windows/web_proxy_windows_test.go index 8d8bfeb3e..1268a22e5 100644 --- a/internal/platform/windows/web_proxy_windows_test.go +++ b/internal/platform/windows/web_proxy_windows_test.go @@ -8,6 +8,13 @@ import ( "testing" ) +func TestDirectBrowserArgumentsBypassSystemProxy(t *testing.T) { + got := proxyBrowserArguments("--lang=en", "direct") + if got != "--lang=en --no-proxy-server" { + t.Fatalf("direct browser arguments = %q", got) + } +} + func TestProxyBrowserArgumentsKeepThePageOnTheProxy(t *testing.T) { got := proxyBrowserArguments("", "127.0.0.1:1080") for _, want := range []string{ diff --git a/internal/platform/windows/webview2_windows.go b/internal/platform/windows/webview2_windows.go index eb4580982..8f188896b 100644 --- a/internal/platform/windows/webview2_windows.go +++ b/internal/platform/windows/webview2_windows.go @@ -11,6 +11,8 @@ import ( "sync" "syscall" "unsafe" + + "github.com/vivaui/viva/internal/platform" ) // WebView2 without WebView2Loader.dll: the loader's job is to find the installed runtime and call @@ -329,6 +331,9 @@ func proxyBrowserArguments(existing, proxy string) string { " --proxy-bypass-list=<-loopback>" + ` "--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE ` + proxyHost(proxy) + `"` + " --force-webrtc-ip-handling-policy=disable_non_proxied_udp" + if proxy == platform.WebProxyDirect { + arguments = "--no-proxy-server" + } if existing = strings.TrimSpace(existing); existing != "" { return existing + " " + arguments } From 3c025a1b9ddbdcdfbc78de0849a016d72cc97ae3 Mon Sep 17 00:00:00 2001 From: jakey <267309453@qq.com> Date: Fri, 13 Nov 2026 22:06:16 +0800 Subject: [PATCH 05/86] feat(app): scale macOS traffic lights in a custom titlebar --- app/app.go | 4 ++ app/reload_worker.go | 3 +- app/reload_worker_test.go | 8 ++- app/run.go | 21 +++---- app/run_canvas.go | 9 +-- internal/devreload/supervisor.go | 7 ++- internal/platform/contract.go | 5 +- internal/platform/darwin/native.h | 1 + internal/platform/darwin/native.m | 57 ++++++++++++++++--- internal/platform/darwin/platform.go | 1 + .../platform/darwin/testdata/traffic_lights.m | 49 ++++++++++++++-- internal/reloadwire/codec.go | 34 ++++++----- internal/reloadwire/input_test.go | 2 +- 13 files changed, 149 insertions(+), 52 deletions(-) diff --git a/app/app.go b/app/app.go index f9de5ec32..1118c2284 100644 --- a/app/app.go +++ b/app/app.go @@ -81,6 +81,10 @@ type Config struct { // that. Zero means 28, // the system titlebar's own height. It only applies to WindowCustomTitlebar. TitlebarHeight float32 + // TrafficLightScale scales native macOS traffic lights in a custom titlebar. + // Values in (0, 1] shrink the controls around their original centers; zero + // preserves the system size. Other platforms ignore this setting. + TrafficLightScale float32 // WindowControls styles the minimize, maximize and close buttons Viva draws at // the trailing end of a WindowCustomTitlebar's strip on Windows and Linux, // where the system draws none for a window without a titlebar; macOS has its diff --git a/app/reload_worker.go b/app/reload_worker.go index d4095f11a..c75c8228e 100644 --- a/app/reload_worker.go +++ b/app/reload_worker.go @@ -30,7 +30,8 @@ func newReloadWorkerConfig(config Config, canvas *gfx.Canvas) reloadwire.WorkerC Title: config.Title, Width: config.Width, Height: config.Height, MinWidth: config.MinWidth, MinHeight: config.MinHeight, WindowMode: uint8(config.WindowMode), TitlebarHeight: uint16(max(config.TitlebarHeight+0.5, 0)), - ClearRed: config.ClearColor.Red, ClearGreen: config.ClearColor.Green, + TrafficLightScale: config.TrafficLightScale, + ClearRed: config.ClearColor.Red, ClearGreen: config.ClearColor.Green, ClearBlue: config.ClearColor.Blue, ClearAlpha: config.ClearColor.Alpha, HasClick: config.Paint != nil, HasPointer: config.OnPointer != nil || config.Paint != nil, HasKey: config.OnKey != nil, HasShortcut: config.OnShortcut != nil, HasScroll: config.OnScroll != nil, HasModifierTap: config.OnModifierTap != nil, diff --git a/app/reload_worker_test.go b/app/reload_worker_test.go index fc92e9ba0..c638f4fff 100644 --- a/app/reload_worker_test.go +++ b/app/reload_worker_test.go @@ -67,13 +67,19 @@ func TestReloadWorkerConfigForwardsInputHandlers(t *testing.T) { // A development host opens the window, so the custom titlebar's height has to // reach it from the worker's configuration, rounded to a whole pixel. func TestReloadWorkerCarriesTheTitlebarHeightToTheHost(t *testing.T) { - worker := newReloadWorkerConfig(Config{Title: "bar", Width: 100, Height: 100, MinWidth: 80, MinHeight: 60, WindowMode: WindowCustomTitlebar, TitlebarHeight: 36}, &gfx.Canvas{}) + worker := newReloadWorkerConfig(Config{Title: "bar", Width: 100, Height: 100, MinWidth: 80, MinHeight: 60, WindowMode: WindowCustomTitlebar, TitlebarHeight: 36, TrafficLightScale: 0.9}, &gfx.Canvas{}) if worker.Window.MinWidth != 80 || worker.Window.MinHeight != 60 { t.Fatalf("minimum lost by reload worker: %+v", worker.Window) } if worker.Window.TitlebarHeight != 36 || worker.Window.WindowMode != uint8(WindowCustomTitlebar) { t.Fatalf("window = %+v", worker.Window) } + if worker.Window.TrafficLightScale != 0.9 { + t.Fatalf("traffic light scale lost by reload worker: %+v", worker.Window) + } + if got := newReloadWorkerConfig(Config{}, &gfx.Canvas{}).Window.TrafficLightScale; got != 0 { + t.Fatalf("an unset scale became %v", got) + } if got := newReloadWorkerConfig(Config{TitlebarHeight: 35.6}, &gfx.Canvas{}).Window.TitlebarHeight; got != 36 { t.Fatalf("35.6 became %d", got) } diff --git a/app/run.go b/app/run.go index 5afd83297..93a1b3d08 100644 --- a/app/run.go +++ b/app/run.go @@ -21,16 +21,17 @@ func Run(config Config) error { defer runtime.UnlockOSThread() return runNative(platform.Config{ - Title: normalized.Title, - Class: normalized.Class, - Icon: normalized.Icon.platform(), - Width: normalized.Width, - Height: normalized.Height, - MinWidth: normalized.MinWidth, - MinHeight: normalized.MinHeight, - WindowMode: platform.WindowMode(normalized.WindowMode), - WindowMaterials: normalized.windowMaterials(), - TitlebarHeight: normalized.TitlebarHeight, + Title: normalized.Title, + Class: normalized.Class, + Icon: normalized.Icon.platform(), + Width: normalized.Width, + Height: normalized.Height, + MinWidth: normalized.MinWidth, + MinHeight: normalized.MinHeight, + WindowMode: platform.WindowMode(normalized.WindowMode), + WindowMaterials: normalized.windowMaterials(), + TitlebarHeight: normalized.TitlebarHeight, + TrafficLightScale: normalized.TrafficLightScale, ClearColor: platform.Color{ Red: normalized.ClearColor.Red, Green: normalized.ClearColor.Green, diff --git a/app/run_canvas.go b/app/run_canvas.go index 17e1870f7..8e5831f1b 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -152,10 +152,11 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, Title: normalized.Title, Class: normalized.Class, Icon: normalized.Icon.platform(), Width: normalized.Width, Height: normalized.Height, MinWidth: normalized.MinWidth, MinHeight: normalized.MinHeight, Origin: normalized.originPoint(), HasOrigin: normalized.Origin != nil, - WindowMode: platform.WindowMode(normalized.WindowMode), - WindowMaterials: normalized.windowMaterials(), - TitlebarHeight: normalized.TitlebarHeight, - Anchor: normalized.Anchor.rect, HasAnchor: normalized.Anchor.set, + WindowMode: platform.WindowMode(normalized.WindowMode), + WindowMaterials: normalized.windowMaterials(), + TitlebarHeight: normalized.TitlebarHeight, + TrafficLightScale: normalized.TrafficLightScale, + Anchor: normalized.Anchor.rect, HasAnchor: normalized.Anchor.set, ClearColor: platform.Color{ Red: normalized.ClearColor.Red, Green: normalized.ClearColor.Green, Blue: normalized.ClearColor.Blue, Alpha: normalized.ClearColor.Alpha, diff --git a/internal/devreload/supervisor.go b/internal/devreload/supervisor.go index 62f84930a..c51460a2b 100644 --- a/internal/devreload/supervisor.go +++ b/internal/devreload/supervisor.go @@ -38,8 +38,9 @@ func (value *supervisor) hostConfig() app.Config { Title: value.window.Title, Width: value.window.Width, Height: value.window.Height, MinWidth: value.window.MinWidth, MinHeight: value.window.MinHeight, WindowMode: app.WindowMode(value.window.WindowMode), TitlebarHeight: float32(value.window.TitlebarHeight), - ClearColor: app.Color{Red: value.window.ClearRed, Green: value.window.ClearGreen, Blue: value.window.ClearBlue, Alpha: value.window.ClearAlpha}, - Paint: value.paint, OnPointer: value.pointer, + TrafficLightScale: value.window.TrafficLightScale, + ClearColor: app.Color{Red: value.window.ClearRed, Green: value.window.ClearGreen, Blue: value.window.ClearBlue, Alpha: value.window.ClearAlpha}, + Paint: value.paint, OnPointer: value.pointer, OnKey: value.key, OnShortcut: value.shortcut, OnScroll: value.scroll, OnCloseRequest: value.requestClose, Invalidator: &value.invalidator, } @@ -303,7 +304,7 @@ func (value *supervisor) clearErrorLocked() { value.lastError = "" } func compatibleWindow(current, next reloadwire.WindowConfig) error { if current.Title != next.Title || current.Width != next.Width || current.Height != next.Height || - current.WindowMode != next.WindowMode || current.TitlebarHeight != next.TitlebarHeight || current.ClearRed != next.ClearRed || + current.WindowMode != next.WindowMode || current.TitlebarHeight != next.TitlebarHeight || current.TrafficLightScale != next.TrafficLightScale || current.ClearRed != next.ClearRed || current.ClearGreen != next.ClearGreen || current.ClearBlue != next.ClearBlue || current.ClearAlpha != next.ClearAlpha { return fmt.Errorf("candidate changed immutable window configuration; restart viva dev") } diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 7a63c16a3..35c459978 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -44,8 +44,9 @@ type Config struct { WindowMode WindowMode // TitlebarHeight is the height in logical pixels of the strip a custom // titlebar leaves for the application. Zero means DefaultTitlebarHeight. - TitlebarHeight float32 - ClearColor Color + TitlebarHeight float32 + TrafficLightScale float32 + ClearColor Color WindowMaterials Rectangles []render.Rectangle TextLabels []TextLabel diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 1a8b85edf..7d47034f4 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -334,6 +334,7 @@ typedef struct { int dynamic_text_input; int window_mode; float titlebar_height; + float traffic_light_scale; int close_intercept_enabled; uintptr_t callback_handle; // Where a panel opens: the screen rectangle of its status item, in the diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index d21554693..b6d8a1cb3 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -138,18 +138,20 @@ static CGFloat viva_traffic_light_center(NSWindow *window) { * inside it and clickable, and each button is set that far below the top. * Idempotent. AppKit puts the buttons back at the system's height on every * layout, so callers place them again whenever a button or the container - * reports a frame change (see keepTrafficLightsCentered). A strip no taller - * than the system's, and a full screen window, keep the system's layout. */ -static void viva_place_traffic_lights(NSWindow *window, CGFloat stripHeight) { - if (window == nil || stripHeight <= VIVA_DEFAULT_TITLEBAR_HEIGHT || - (window.styleMask & NSWindowStyleMaskFullScreen) != 0) { + * reports a frame change (see keepTrafficLightsCentered). A scale in (0, 1) + * shrinks the buttons around their original centers whether or not the strip + * is taller; a strip no taller than the system's keeps the system's positions, + * and a full screen window keeps the system's layout. */ +static void viva_place_traffic_lights(NSWindow *window, CGFloat stripHeight, CGFloat scale) { + if (window == nil || (window.styleMask & NSWindowStyleMaskFullScreen) != 0) { return; } + BOOL taller = stripHeight > VIVA_DEFAULT_TITLEBAR_HEIGHT; NSView *container = viva_titlebar_container(window); if (container == nil || container.superview == nil) { return; } - if (fabs(NSHeight(container.frame) - stripHeight) > 0.25) { + if (taller && fabs(NSHeight(container.frame) - stripHeight) > 0.25) { NSRect frame = container.frame; frame.size.height = stripHeight; frame.origin.y = NSHeight(container.superview.bounds) - stripHeight; @@ -160,6 +162,26 @@ static void viva_place_traffic_lights(NSWindow *window, CGFloat stripHeight) { if (button == nil || button.superview == nil) { continue; } + // Keep the original drawing coordinates while shrinking the view frame. + // Using bounds makes repeated AppKit layout notifications idempotent. + if (isfinite(scale) && scale > 0 && scale < 1) { + NSSize originalSize = button.bounds.size; + NSSize targetSize = NSMakeSize(originalSize.width * scale, originalSize.height * scale); + if (fabs(NSWidth(button.frame) - targetSize.width) > 0.01 || + fabs(NSHeight(button.frame) - targetSize.height) > 0.01) { + NSRect frame = button.frame; + frame.origin.x += (frame.size.width - targetSize.width) / 2.0; + // Keep the vertical center too, so the shrink holds in a strip of the + // system's height where the placement below does not run. + frame.origin.y += (frame.size.height - targetSize.height) / 2.0; + frame.size = targetSize; + button.frame = frame; + button.bounds = NSMakeRect(0, 0, originalSize.width, originalSize.height); + } + } + if (!taller) { + continue; + } CGFloat y = NSHeight(button.superview.bounds) - stripHeight / 2.0 - NSHeight(button.frame) / 2.0; if (fabs(button.frame.origin.y - y) > 0.25) { NSPoint origin = button.frame.origin; @@ -6094,6 +6116,8 @@ @interface VivaAppDelegate : NSObject BOOL _scrollEventsEnabled; int _windowMode; CGFloat _titlebarHeight; + CGFloat _trafficLightScale; + BOOL _placingTrafficLights; NSMutableArray *_titlebarWatched; /* views whose frame changes re-center the traffic lights */ BOOL _fullscreenTarget; BOOL _fullscreenTransition; @@ -6205,6 +6229,7 @@ - (instancetype)initWithConfig:(viva_window_config)config _scrollEventsEnabled = scrollEventsEnabled; _windowMode = windowMode; _titlebarHeight = config.titlebar_height > 0 ? config.titlebar_height : VIVA_DEFAULT_TITLEBAR_HEIGHT; + _trafficLightScale = config.traffic_light_scale; _closeInterceptEnabled = closeInterceptEnabled; _callbackHandle = callbackHandle; _hasAnchor = config.has_anchor != 0; @@ -6553,8 +6578,22 @@ - (void)windowWillClose:(NSNotification *)notification { * or the container, so the placement is redone in that very pass and the * buttons are never drawn at the system's height. Entering and leaving full * screen replaces the container, so the watched views are collected again. */ +// Frame notifications may fire synchronously between setting frame and bounds. +// Suppress reentry until the scaled drawing coordinates are fully restored. +- (void)placeTrafficLights { + if (_placingTrafficLights) { + return; + } + _placingTrafficLights = YES; + @try { + viva_place_traffic_lights(_window, _titlebarHeight, _trafficLightScale); + } @finally { + _placingTrafficLights = NO; + } +} + - (void)keepTrafficLightsCentered { - viva_place_traffic_lights(_window, _titlebarHeight); + [self placeTrafficLights]; if (_titlebarWatched == nil) { _titlebarWatched = [[NSMutableArray alloc] init]; } @@ -6581,7 +6620,7 @@ - (void)keepTrafficLightsCentered { - (void)titlebarChanged:(NSNotification *)notification { (void)notification; - viva_place_traffic_lights(_window, _titlebarHeight); + [self placeTrafficLights]; } /* AppKit reports some of the buttons' moves a turn of the run loop late, so the @@ -6589,7 +6628,7 @@ - (void)titlebarChanged:(NSNotification *)notification { - (void)windowDidResize:(NSNotification *)notification { (void)notification; if (_windowMode == VIVA_WINDOW_CUSTOM_TITLEBAR) { - viva_place_traffic_lights(_window, _titlebarHeight); + [self placeTrafficLights]; } [self reportFrameChange]; } diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 138efbd6f..ee9146391 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -443,6 +443,7 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window dynamic_text_input: C.int(boolInt(config.DynamicTextInput)), window_mode: C.int(int(config.WindowMode)), titlebar_height: C.float(config.TitlebarStrip()), + traffic_light_scale: C.float(config.TrafficLightScale), close_intercept_enabled: C.int(boolInt(config.OnCloseRequest != nil)), callback_handle: C.uintptr_t(state.callbackHandle), has_anchor: C.int(boolInt(config.HasAnchor)), diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index 016b1534a..88e7eaf94 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -88,22 +88,50 @@ int main(void) { NSWindow *window = customTitlebarWindow(800, 600); CGFloat system = viva_traffic_light_center(window); assert(system > 0); - viva_place_traffic_lights(window, VIVA_DEFAULT_TITLEBAR_HEIGHT); + viva_place_traffic_lights(window, VIVA_DEFAULT_TITLEBAR_HEIGHT, 0); assertCenter(window, system, "in a strip of the system's height"); - viva_place_traffic_lights(window, 20); + viva_place_traffic_lights(window, 20, 0); assertCenter(window, system, "in a strip shorter than the system's"); // A taller strip centers them in it, and placing again changes nothing. - viva_place_traffic_lights(window, 36); + viva_place_traffic_lights(window, 36, 0); assertCenter(window, 18, "in a 36 point strip"); assertAligned(window, "in a 36 point strip"); assert(fabs(NSHeight(viva_titlebar_container(window).frame) - 36) < 0.01); NSRect container = viva_titlebar_container(window).frame; - viva_place_traffic_lights(window, 36); + viva_place_traffic_lights(window, 36, 0); assert(NSEqualRects(container, viva_titlebar_container(window).frame)); - viva_place_traffic_lights(window, 44); + viva_place_traffic_lights(window, 44, 0); assertCenter(window, 22, "in a 44 point strip"); + // Shrinking preserves centers and drawing bounds, and never compounds. + NSButton *close = [window standardWindowButton:NSWindowCloseButton]; + NSSize originalSize = close.bounds.size; + CGFloat originalCenterX = NSMidX(close.frame); + const CGFloat compactScale = 0.9; + viva_place_traffic_lights(window, 44, compactScale); + assert(fabs(NSWidth(close.frame) - originalSize.width * compactScale) < 0.01); + assert(fabs(NSMidX(close.frame) - originalCenterX) < 0.01); + assert(NSEqualSizes(close.bounds.size, originalSize)); + viva_place_traffic_lights(window, 44, compactScale); + assert(fabs(NSWidth(close.frame) - originalSize.width * compactScale) < 0.01); + assertCenter(window, 22, "after shrinking the native buttons"); + + // A strip of the system's height needs no placement, but the scale + // still shrinks the buttons around their original centers. + window = customTitlebarWindow(800, 600); + NSButton *systemClose = [window standardWindowButton:NSWindowCloseButton]; + NSSize systemSize = systemClose.bounds.size; + CGFloat systemCenterX = NSMidX(systemClose.frame); + CGFloat systemCenterY = NSMidY(systemClose.frame); + viva_place_traffic_lights(window, VIVA_DEFAULT_TITLEBAR_HEIGHT, compactScale); + assert(fabs(NSWidth(systemClose.frame) - systemSize.width * compactScale) < 0.01); + assert(fabs(NSMidX(systemClose.frame) - systemCenterX) < 0.01); + assert(fabs(NSMidY(systemClose.frame) - systemCenterY) < 0.01); + assert(NSEqualSizes(systemClose.bounds.size, systemSize)); + viva_place_traffic_lights(window, VIVA_DEFAULT_TITLEBAR_HEIGHT, compactScale); + assert(fabs(NSWidth(systemClose.frame) - systemSize.width * compactScale) < 0.01); + // AppKit puts the buttons back whenever it lays the titlebar out, a // resize being one; the delegate puts them back in the same pass. window = customTitlebarWindow(800, 600); @@ -114,6 +142,14 @@ int main(void) { window.delegate = delegate; [delegate performSelector:@selector(keepTrafficLightsCentered)]; assertCenter(window, 18, "once the delegate keeps them centered"); + // Changing scale after observers are installed must not reenter while + // frame and drawing bounds are temporarily out of sync. + [delegate setValue:[NSNumber numberWithDouble:compactScale] forKey:@"_trafficLightScale"]; + [delegate performSelector:@selector(keepTrafficLightsCentered)]; + assertCenter(window, 18, "after scaling with active frame observers"); + NSButton *scaledClose = [window standardWindowButton:NSWindowCloseButton]; + assert(fabs(NSWidth(scaledClose.frame) / NSWidth(scaledClose.bounds) - compactScale) < 0.01); + [window setFrame:NSMakeRect(0, 85, 1000, 700) display:NO]; assertCenter(window, 18, "after the window grew"); assertAligned(window, "after the window grew"); @@ -122,6 +158,7 @@ int main(void) { window.titlebarAppearsTransparent = NO; window.titlebarAppearsTransparent = YES; assertCenter(window, 18, "after the titlebar was restyled"); + assert(fabs(NSWidth(scaledClose.frame) / NSWidth(scaledClose.bounds) - compactScale) < 0.01); [delegate setAlwaysOnTop:YES]; assert(window.level == NSFloatingWindowLevel); [delegate setAlwaysOnTop:NO]; @@ -129,7 +166,7 @@ int main(void) { [delegate release]; // A window with no traffic lights to move is left alone. - viva_place_traffic_lights(nil, 36); + viva_place_traffic_lights(nil, 36, 0); printf("traffic lights: ok (system center %.1f, strip 36 -> 18, strip 44 -> 22)\n", system); } return 0; diff --git a/internal/reloadwire/codec.go b/internal/reloadwire/codec.go index 943bbd1b7..a8cebf45f 100644 --- a/internal/reloadwire/codec.go +++ b/internal/reloadwire/codec.go @@ -9,7 +9,7 @@ import ( ) const ( - ProtocolVersion = 27 + ProtocolVersion = 28 MaxFrameBytes = 32 << 20 MaxStateBytes = 8 << 20 maxItems = 200_000 @@ -45,19 +45,21 @@ type WindowConfig struct { WindowMode uint8 // TitlebarHeight is Config.TitlebarHeight rounded to whole logical pixels. TitlebarHeight uint16 - ClearRed float64 - ClearGreen float64 - ClearBlue float64 - ClearAlpha float64 - HasClick bool - HasPointer bool - HasKey bool - HasShortcut bool - HasScroll bool - HasModifierTap bool - HasClose bool - HasSnapshot bool - HasRestore bool + // TrafficLightScale is Config.TrafficLightScale, or zero for the system size. + TrafficLightScale float32 + ClearRed float64 + ClearGreen float64 + ClearBlue float64 + ClearAlpha float64 + HasClick bool + HasPointer bool + HasKey bool + HasShortcut bool + HasScroll bool + HasModifierTap bool + HasClose bool + HasSnapshot bool + HasRestore bool } type Hello struct { @@ -274,6 +276,7 @@ func encodeWindowConfig(result *encoder, value WindowConfig) { result.u32(uint32(value.MinHeight)) result.u8(value.WindowMode) result.u16(value.TitlebarHeight) + result.f32(value.TrafficLightScale) result.f64(value.ClearRed) result.f64(value.ClearGreen) result.f64(value.ClearBlue) @@ -293,7 +296,8 @@ func decodeWindowConfig(value *decoder) WindowConfig { return WindowConfig{ Title: value.string(), Width: int(value.u32()), Height: int(value.u32()), MinWidth: int(value.u32()), MinHeight: int(value.u32()), WindowMode: value.u8(), TitlebarHeight: value.u16(), - ClearRed: value.f64(), ClearGreen: value.f64(), ClearBlue: value.f64(), ClearAlpha: value.f64(), + TrafficLightScale: value.f32(), + ClearRed: value.f64(), ClearGreen: value.f64(), ClearBlue: value.f64(), ClearAlpha: value.f64(), HasClick: value.bool(), HasPointer: value.bool(), HasKey: value.bool(), HasShortcut: value.bool(), HasScroll: value.bool(), HasModifierTap: value.bool(), HasClose: value.bool(), HasSnapshot: value.bool(), HasRestore: value.bool(), } diff --git a/internal/reloadwire/input_test.go b/internal/reloadwire/input_test.go index 9bf17d2a5..fbafab7f0 100644 --- a/internal/reloadwire/input_test.go +++ b/internal/reloadwire/input_test.go @@ -180,7 +180,7 @@ func decodeResultError(data []byte) error { _, err := decodeEventResult(data); func TestWindowConfigCodecPreservesInputCapabilities(t *testing.T) { want := Hello{Token: "capabilities", Config: WindowConfig{ - Title: "input", Width: 640, Height: 480, WindowMode: 2, TitlebarHeight: 36, + Title: "input", Width: 640, Height: 480, WindowMode: 2, TitlebarHeight: 36, TrafficLightScale: 0.9, MinWidth: 480, MinHeight: 320, HasClick: true, HasPointer: true, HasKey: true, HasShortcut: true, HasScroll: true, HasModifierTap: true, HasClose: true, HasSnapshot: true, HasRestore: true, From 50a25e39c47bc8c7c4337873794af84784097f8c Mon Sep 17 00:00:00 2001 From: ezreal <71426102+Ezreal-byte@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:11:40 +0800 Subject: [PATCH 06/86] feat(app): request a native window content size --- app/application.go | 1 + app/content_window.go | 10 ++ app/window_size.go | 37 ++++++++ app/window_size_native_test.go | 58 ++++++++++++ app/window_size_test.go | 79 ++++++++++++++++ headless/application.go | 36 ++++++-- headless/window_size_test.go | 52 +++++++++++ internal/platform/contract.go | 12 +++ internal/platform/darwin/native.h | 2 + internal/platform/darwin/native.m | 34 +++++++ .../platform/darwin/testdata/window_size.m | 92 +++++++++++++++++++ .../platform/darwin/window_size_darwin.go | 21 +++++ .../darwin/window_size_darwin_test.go | 24 +++++ internal/platform/linux/status_item_linux.go | 23 ++++- internal/platform/linux/window_linux.go | 22 ++++- internal/platform/linux/window_size_linux.go | 16 ++++ .../platform/linux/window_size_linux_test.go | 79 ++++++++++++++++ .../platform/windows/window_size_windows.go | 64 +++++++++++++ internal/platform/windows/window_windows.go | 4 + website/content/guides/en/windows.md | 11 +++ website/content/guides/zh/windows.md | 4 + 21 files changed, 672 insertions(+), 9 deletions(-) create mode 100644 app/window_size.go create mode 100644 app/window_size_native_test.go create mode 100644 app/window_size_test.go create mode 100644 headless/window_size_test.go create mode 100644 internal/platform/darwin/testdata/window_size.m create mode 100644 internal/platform/darwin/window_size_darwin.go create mode 100644 internal/platform/darwin/window_size_darwin_test.go create mode 100644 internal/platform/linux/window_size_linux.go create mode 100644 internal/platform/linux/window_size_linux_test.go create mode 100644 internal/platform/windows/window_size_windows.go diff --git a/app/application.go b/app/application.go index 10e77c48b..df70dc9e7 100644 --- a/app/application.go +++ b/app/application.go @@ -20,6 +20,7 @@ var ErrNoWindows = errors.New("app: application opened no windows") // and Fullscreen() bool. It reports transitions through Config.OnFullscreen // before resize/frame callbacks and repaints afterward. // An always-on-top host additionally implements SetAlwaysOnTop(bool) error. +// A size-capable host additionally implements SetSize(int, int) error. type WindowControl interface { Close() Hide() diff --git a/app/content_window.go b/app/content_window.go index 2ec096d25..e574ba442 100644 --- a/app/content_window.go +++ b/app/content_window.go @@ -1,6 +1,7 @@ package app import ( + "fmt" "sync" "github.com/vivaui/viva/gfx" @@ -110,6 +111,15 @@ func (content *ContentWindow) Show() { content.window.Show() } } + +// SetSize asks the window manager for a new content size, as Window.SetSize +// does. Config.OnResize reports the size actually granted. +func (content *ContentWindow) SetSize(width, height int) error { + if content == nil || content.window == nil { + return fmt.Errorf("app: content window is closed") + } + return content.window.SetSize(width, height) +} func (content *ContentWindow) Closed() bool { return content == nil || content.window == nil || content.window.Closed() } diff --git a/app/window_size.go b/app/window_size.go new file mode 100644 index 000000000..bc1a9d9e7 --- /dev/null +++ b/app/window_size.go @@ -0,0 +1,37 @@ +package app + +import ( + "errors" + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +const maximumProgrammaticWindowSize = 65535 + +// SetSize asks the window manager to make this window's content area width by +// height logical pixels. The request is asynchronous: OnResize reports the size +// actually granted. The window manager may adjust a request, and width and +// height must be 1 through 65535. A maximized, minimized or fullscreen window +// ignores it. It is safe to call from any goroutine. +// +// Unsupported hosts return an error wrapping ErrUnsupported. +func (window *Window) SetSize(width, height int) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("app: window is closed") + } + if width < 1 || height < 1 || width > maximumProgrammaticWindowSize || height > maximumProgrammaticWindowSize { + return fmt.Errorf("app: invalid window size %dx%d", width, height) + } + sizer, ok := window.control.(platform.WindowSizer) + if !ok { + return fmt.Errorf("%w: programmatic window size", ErrUnsupported) + } + if err := sizer.SetSize(width, height); err != nil { + if errors.Is(err, platform.ErrWindowSizeUnsupported) { + return fmt.Errorf("%w: programmatic window size", ErrUnsupported) + } + return err + } + return nil +} diff --git a/app/window_size_native_test.go b/app/window_size_native_test.go new file mode 100644 index 000000000..3ec16584b --- /dev/null +++ b/app/window_size_native_test.go @@ -0,0 +1,58 @@ +//go:build windows || linux + +package app + +import ( + "fmt" + "os" + "testing" + "time" + + "github.com/vivaui/viva/gfx" +) + +func TestNativeProgrammaticWindowSize(t *testing.T) { + if os.Getenv("VIVA_NATIVE_WINDOW_SIZE_TEST") != "1" { + t.Skip("requires a native desktop session") + } + for _, test := range []struct { + name string + mode WindowMode + }{ + {name: "titled", mode: WindowTitled}, + {name: "custom_titlebar", mode: WindowCustomTitlebar}, + } { + t.Run(test.name, func(t *testing.T) { + var canvas gfx.Canvas + var got gfx.Size + err := RunApplication(func(application *Application) error { + window, err := application.OpenWindow(Config{ + Title: "Viva content resize test", Width: 320, Height: 240, WindowMode: test.mode, + Paint: func(*gfx.Canvas, gfx.Size) {}, + OnResize: func(size gfx.Size) { + if size.Width >= 419 && size.Width <= 421 && size.Height >= 299 && size.Height <= 301 { + got = size + application.Quit() + } + }, + }, &canvas) + if err != nil { + return err + } + if err := window.SetSize(420, 300); err != nil { + application.Quit() + return fmt.Errorf("request size: %w", err) + } + timer := time.AfterFunc(8*time.Second, application.Quit) + t.Cleanup(func() { timer.Stop() }) + return nil + }) + if err != nil { + t.Fatal(err) + } + if got.Width == 0 { + t.Fatal("native resize never reached OnResize with the requested content size") + } + }) + } +} diff --git a/app/window_size_test.go b/app/window_size_test.go new file mode 100644 index 000000000..b4442bb6a --- /dev/null +++ b/app/window_size_test.go @@ -0,0 +1,79 @@ +package app + +import ( + "errors" + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +type sizingWindow struct { + WindowControl + width, height int + err error +} + +func (window *sizingWindow) SetSize(width, height int) error { + window.width, window.height = width, height + return window.err +} + +func TestWindowSetSizeReachesTheNativeWindow(t *testing.T) { + native := &sizingWindow{} + window := &Window{control: native} + if err := window.SetSize(1440, 900); err != nil { + t.Fatal(err) + } + if native.width != 1440 || native.height != 900 { + t.Fatalf("SetSize = %dx%d", native.width, native.height) + } + if err := window.SetSize(65535, 65535); err != nil { + t.Fatalf("maximum size was rejected: %v", err) + } + for _, size := range [][2]int{{0, 1}, {1, 0}, {65536, 1}, {1, 65536}} { + if err := window.SetSize(size[0], size[1]); err == nil { + t.Fatalf("invalid size %dx%d was accepted", size[0], size[1]) + } + } + window.closed.Store(true) + if err := window.SetSize(800, 600); err == nil || errors.Is(err, ErrUnsupported) { + t.Fatalf("closed window error = %v", err) + } + var nilWindow *Window + if err := nilWindow.SetSize(800, 600); err == nil { + t.Fatal("nil window accepted SetSize") + } +} + +func TestWindowSetSizeReportsUnsupportedHosts(t *testing.T) { + window := &Window{control: struct{ WindowControl }{}} + if err := window.SetSize(800, 600); !errors.Is(err, ErrUnsupported) { + t.Fatalf("unsupported host error = %v", err) + } + + window.control = &sizingWindow{err: platform.ErrWindowSizeUnsupported} + if err := window.SetSize(800, 600); !errors.Is(err, ErrUnsupported) { + t.Fatalf("unsupported native window error = %v", err) + } + + failure := errors.New("native resize failed") + window.control = &sizingWindow{err: failure} + if err := window.SetSize(800, 600); !errors.Is(err, failure) || errors.Is(err, ErrUnsupported) { + t.Fatalf("native resize error = %v", err) + } +} + +func TestContentWindowForwardsSetSize(t *testing.T) { + native := &sizingWindow{} + content := &ContentWindow{window: &Window{control: native}} + if err := content.SetSize(800, 600); err != nil { + t.Fatal(err) + } + if native.width != 800 || native.height != 600 { + t.Fatalf("SetSize = %dx%d", native.width, native.height) + } + var nilContent *ContentWindow + if err := nilContent.SetSize(800, 600); err == nil { + t.Fatal("nil content window accepted SetSize") + } +} diff --git a/headless/application.go b/headless/application.go index 927571479..92133282e 100644 --- a/headless/application.go +++ b/headless/application.go @@ -20,13 +20,15 @@ import ( type applicationWindow struct { fullscreen atomic.Bool fullscreenRequest atomic.Int32 - invalidator *app.Invalidator - id uint64 - title string - panel bool - hidden bool - session *Session - closed func() + // sizeRequest is the content size SetSize queued for the loop, or nil. + sizeRequest atomic.Pointer[[2]int32] + invalidator *app.Invalidator + id uint64 + title string + panel bool + hidden bool + session *Session + closed func() // closeRequest is the application's OnCloseRequest, if it set one. closeRequest func(allow func()) } @@ -93,6 +95,11 @@ func (application *applicationSession) OpenWindow(config app.Config, canvas *gfx panic(err) } } + if size := entry.sizeRequest.Swap(nil); size != nil { + if err := entry.session.Resize(int(size[0]), int(size[1])); err != nil { + panic(err) + } + } if onWake != nil { onWake() } @@ -133,6 +140,21 @@ func (window *headlessWindow) Frame() (gfx.Rect, bool) { } func (window *headlessWindow) Show() { window.application.setHidden(window.id, false) } +// SetSize queues a content-size request for the driver's loop, which reports +// the granted size through OnResize. +func (window *headlessWindow) SetSize(width, height int) error { + window.application.mu.Lock() + entry := window.application.windows[window.id] + window.application.mu.Unlock() + if entry == nil { + return fmt.Errorf("headless: window is closed") + } + request := [2]int32{int32(width), int32(height)} + entry.sizeRequest.Store(&request) + entry.invalidator.Invalidate() + return nil +} + func (window *headlessWindow) SetFullscreen(fullscreen bool) error { window.application.mu.Lock() entry := window.application.windows[window.id] diff --git a/headless/window_size_test.go b/headless/window_size_test.go new file mode 100644 index 000000000..08746f4eb --- /dev/null +++ b/headless/window_size_test.go @@ -0,0 +1,52 @@ +//go:build darwin || windows || linux + +package headless + +import ( + "sync" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +func TestApplicationSizeRequestRunsOnDriver(t *testing.T) { + host := newApplicationSession(Options{ReferenceText: true}) + var window *app.Window + var sizes []gfx.Size + app.UseApplicationRunner(func(start func(app.Host) error) error { return start(host) }) + defer app.UseApplicationRunner(nil) + err := app.RunApplication(func(application *app.Application) error { + var err error + window, err = application.OpenWindow(app.Config{Title: "size", Width: 500, Height: 300, + OnResize: func(size gfx.Size) { sizes = append(sizes, size) }, + }, nil) + return err + }) + if err != nil { + t.Fatal(err) + } + defer host.closeAll() + entry := host.windows[1] + var requests sync.WaitGroup + for range 8 { + requests.Go(func() { + if err := window.SetSize(420, 240); err != nil { + t.Error(err) + } + }) + } + requests.Wait() + if len(sizes) != 0 { + t.Fatal("background request ran OnResize off the driver thread") + } + if err := entry.session.driver.Pump(); err != nil { + t.Fatal(err) + } + if len(sizes) == 0 || sizes[len(sizes)-1].Width != 420 || sizes[len(sizes)-1].Height != 240 { + t.Fatalf("OnResize = %v, want 420x240", sizes) + } + if frame, ok := window.Frame(); !ok || frame.Width != 420 || frame.Height != 240 { + t.Fatalf("Frame = %v, %v", frame, ok) + } +} diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 35c459978..02ee5a0eb 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -189,6 +189,14 @@ type WindowMover interface { MoveTo(origin gfx.Point) } +// WindowSizer is implemented by windows that can change their content size +// without the user dragging a border. Sizes are logical pixels and the window +// manager may clamp them to the display or the window's minimum size. It may be +// called from any goroutine and posts the request to the native event loop. +type WindowSizer interface { + SetSize(width, height int) error +} + // Application creates windows that share one native application event loop. // OpenWindow, AddStatusItem, SetDockBadge and SetProgress are called on that // event-loop thread. @@ -237,6 +245,10 @@ var ErrFullscreenUnsupported = errors.New("platform: fullscreen is unsupported") // above others. var ErrAlwaysOnTopUnsupported = errors.New("platform: always-on-top is unsupported") +// ErrWindowSizeUnsupported means this window kind cannot be resized by the +// application. +var ErrWindowSizeUnsupported = errors.New("platform: programmatic window size is unsupported") + // ErrStatusAreaUnavailable is returned by AddStatusItem when the desktop has no // status area to put an icon in, as a Linux session without a StatusNotifier // host. The application keeps running; it only has no icon. diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 7d47034f4..119d32058 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -391,6 +391,8 @@ void *viva_application_open_window(viva_window_config config); int viva_application_window_frame(void *window, double *out); /* Puts the window's content area at x, y in top-left screen coordinates. */ void viva_application_move_window(void *window, double x, double y); +/* Posts a content resize to the AppKit event loop. */ +void viva_application_set_window_size(void *window, double width, double height); int viva_application_set_fullscreen(void *window, int fullscreen); int viva_application_fullscreen(void *window); int viva_application_set_always_on_top(void *window, int enabled); diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index b6d8a1cb3..e46e2c2d9 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -6132,6 +6132,7 @@ @interface VivaAppDelegate : NSObject } - (void)updateMinimumSize; +- (void)setVivaContentSize:(NSSize)size; - (instancetype)initWithConfig:(viva_window_config)config device:(id)device @@ -6893,6 +6894,32 @@ - (void)moveContentTo:(NSPoint)origin { [_window setFrame:[_window frameRectForContentRect:content] display:NO]; } +/* Changes the content area while keeping its current top-left origin. */ +- (void)setVivaContentSize:(NSSize)size { + if (_window == nil || !_running || _window.miniaturized || _window.zoomed || + (_window.styleMask & NSWindowStyleMaskFullScreen) != 0) { + return; + } + NSRect current = [_window contentRectForFrameRect:_window.frame]; + NSSize minimum = _window.contentMinSize; + size.width = MAX(size.width, minimum.width); + size.height = MAX(size.height, minimum.height); + NSScreen *screen = _window.screen ?: NSScreen.mainScreen ?: NSScreen.screens.firstObject; + if (screen != nil) { + NSRect available = [_window contentRectForFrameRect:screen.visibleFrame]; + size.width = MIN(size.width, available.size.width); + size.height = MIN(size.height, available.size.height); + } + NSRect wanted = NSMakeRect(current.origin.x, NSMaxY(current) - size.height, size.width, size.height); + NSRect frame = [_window frameRectForContentRect:wanted]; + if (screen != nil) { + NSRect work = screen.visibleFrame; + frame.origin.x = MAX(NSMinX(work), MIN(frame.origin.x, NSMaxX(work) - frame.size.width)); + frame.origin.y = MAX(NSMinY(work), MIN(frame.origin.y, NSMaxY(work) - frame.size.height)); + } + [_window setFrame:frame display:YES]; +} + /* The content area in top-left screen coordinates; NO before the window exists. */ - (BOOL)contentFrame:(double *)out { if (_window == nil || !_running) { @@ -7434,6 +7461,13 @@ void viva_application_move_window(void *window, double x, double y) { } } +void viva_application_set_window_size(void *window, double width, double height) { + dispatch_async(dispatch_get_main_queue(), ^{ + VivaAppDelegate *delegate = viva_find_window(window); + [delegate setVivaContentSize:NSMakeSize(width, height)]; + }); +} + void viva_application_hide_window(void *window) { viva_post_window_event(VIVA_HIDE_EVENT, window); } diff --git a/internal/platform/darwin/testdata/window_size.m b/internal/platform/darwin/testdata/window_size.m new file mode 100644 index 000000000..9c9c1facb --- /dev/null +++ b/internal/platform/darwin/testdata/window_size.m @@ -0,0 +1,92 @@ +#include "../native.m" +#include "../main_menu_darwin.m" +#include +#include + +// The callbacks native.m reports to Go; this test listens to none of them. +void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaRedrawRequested(uintptr_t handle, void *view) {} +void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} +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) {} +void vivaWindowActivated(uintptr_t handle) {} +void vivaFocusLost(uintptr_t handle, void *view) {} +int vivaTerminalCells(uint32_t character) { return 1; } +int vivaAccessibilityAction(uintptr_t handle, void *view, uint64_t node, int action, double number, const unsigned char *utf8, size_t utf8Length, int start, int end) { return 0; } +viva_text_line *vivaShapedLine(const unsigned char *utf8, size_t length, double size, double weight) { return viva_text_line_create(utf8, length, size, weight); } +viva_text_line *vivaShapedLineStyle(const unsigned char *utf8, size_t length, double size, double weight, int italic) { return viva_text_line_create_style(utf8, length, size, weight, italic); } +int vivaShortcutEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) { return 0; } +void vivaOpenURL(const char *url) {} +void vivaOpenFile(const char *path) {} +int vivaApplicationQuitRequested(void) { return 0; } +int vivaApplicationReopenRequested(void) { return 0; } +int vivaFileDropEvent(uintptr_t handle, void *view, int phase, double x, double y, const char *paths, size_t length) { return 0; } +void vivaScrollEvent(uintptr_t handle, void *view, double deltaX, double deltaY, double x, double y, int modifiers, int precise) {} +void vivaCloseRequested(uintptr_t handle, void *view) {} +void vivaWindowClosed(uintptr_t handle) {} +void vivaFrameChanged(uintptr_t handle, void *view, double x, double y, double width, double height) {} +void vivaWindowMinimized(uintptr_t handle, void *view, int minimized) {} +void vivaWindowOccluded(uintptr_t handle, void *view, int visible) {} +void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} +int vivaWindowReopenRequested(uintptr_t handle, void *view) { return 0; } +int vivaPressAt(uintptr_t handle, double x, double y) { return 0; } +void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command) {} +unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } + +static BOOL near(CGFloat a, CGFloat b) { return fabs(a - b) < 0.5; } + +// A titled window that is never ordered front, so nothing appears on screen. +static NSWindow *titledWindow(CGFloat width, CGFloat height) { + NSWindowStyleMask style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | + NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable; + return [[NSWindow alloc] initWithContentRect:NSMakeRect(200, 200, width, height) + styleMask:style + backing:NSBackingStoreBuffered + defer:NO]; +} + +int main(void) { + @autoreleasepool { + [NSApplication sharedApplication]; + + NSWindow *window = titledWindow(320, 240); + assert(window != nil); + [window setFrame:NSMakeRect(200, 200, 320, 240) display:NO]; + // The delegate's size path runs only while the window is live; the + // rest of the delegate is not involved in this test. + VivaAppDelegate *delegate = [VivaAppDelegate alloc]; + [delegate setValue:window forKey:@"_window"]; + [delegate setValue:@YES forKey:@"_running"]; + + NSRect before = [window contentRectForFrameRect:window.frame]; + [delegate setVivaContentSize:NSMakeSize(420, 300)]; + NSRect after = [window contentRectForFrameRect:window.frame]; + assert(near(after.size.width, 420) && near(after.size.height, 300)); + // The top-left origin is preserved: same x, same top edge. + assert(near(NSMinX(after), NSMinX(before))); + assert(near(NSMaxY(after), NSMaxY(before))); + + // The minimum content size wins over a smaller request. + window.contentMinSize = NSMakeSize(260, 200); + [delegate setVivaContentSize:NSMakeSize(100, 80)]; + NSRect clamped = [window contentRectForFrameRect:window.frame]; + assert(clamped.size.width >= 260 - 0.5 && clamped.size.height >= 200 - 0.5); + + // A request larger than the screen is clamped to its visible area. + NSScreen *screen = window.screen ?: NSScreen.mainScreen ?: NSScreen.screens.firstObject; + assert(screen != nil); + [delegate setVivaContentSize:NSMakeSize(100000, 100000)]; + NSRect huge = [window contentRectForFrameRect:window.frame]; + assert(huge.size.width <= screen.visibleFrame.size.width + 0.5); + assert(huge.size.height <= screen.visibleFrame.size.height + 0.5); + + printf("window size: content %.0fx%.0f, min clamp %.0fx%.0f, screen clamp %.0fx%.0f\n", + after.size.width, after.size.height, clamped.size.width, clamped.size.height, + huge.size.width, huge.size.height); + [delegate release]; + [window release]; + } + return 0; +} diff --git a/internal/platform/darwin/window_size_darwin.go b/internal/platform/darwin/window_size_darwin.go new file mode 100644 index 000000000..5f16d051a --- /dev/null +++ b/internal/platform/darwin/window_size_darwin.go @@ -0,0 +1,21 @@ +package darwin + +/* +#include "native.h" +*/ +import "C" + +import "fmt" + +// SetSize queues a content size request on the AppKit thread. The +// system may clamp the result to the window minimum or the screen. +func (window *nativeWindow) SetSize(width, height int) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("darwin: window is closed") + } + if width < 1 || height < 1 || width > 65535 || height > 65535 { + return fmt.Errorf("darwin: invalid window size %dx%d", width, height) + } + C.viva_application_set_window_size(window.token, C.double(width), C.double(height)) + return nil +} diff --git a/internal/platform/darwin/window_size_darwin_test.go b/internal/platform/darwin/window_size_darwin_test.go new file mode 100644 index 000000000..c00f05939 --- /dev/null +++ b/internal/platform/darwin/window_size_darwin_test.go @@ -0,0 +1,24 @@ +package darwin + +import ( + "os/exec" + "path/filepath" + "testing" +) + +// The native content-size path runs on a window that is never shown, so the +// test opens nothing on screen. +func TestNativeWindowContentSize(t *testing.T) { + executable := filepath.Join(t.TempDir(), "window-size") + command := exec.Command("xcrun", "clang", "-fno-objc-arc", "-Werror", + "-Wno-deprecated-declarations", "testdata/window_size.m", "-o", executable, + "-framework", "Cocoa", "-framework", "CoreText", "-framework", "Metal", "-framework", "QuartzCore") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native window size test: %v\n%s", err, output) + } + if output, err := exec.Command(executable).CombinedOutput(); err != nil { + t.Fatalf("native window content size: %v\n%s", err, output) + } else { + t.Logf("%s", output) + } +} diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 407be48e4..66af1ef33 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -1,6 +1,7 @@ package linux import ( + "encoding/binary" "errors" "fmt" "math" @@ -141,9 +142,29 @@ func (win *window) markPanel(config platform.Config, x, y int16) error { } // command runs one request another goroutine posted to this window's loop. -func (state *linuxWindowState) command(command uint32) error { +func (state *linuxWindowState) command(command uint32, data []byte) error { win := state.win switch command { + case commandSetSize: + if len(data) < 12 || win.frame.maximized || win.minimized || win.fullscreen.Load() { + return nil + } + width := int(binary.LittleEndian.Uint32(data[4:8])) + height := int(binary.LittleEndian.Uint32(data[8:12])) + margin := uint32(0) + if win.margin > 0 { + margin = frameMargin(win.displayScale()) + } + if width < 1 || height < 1 { + return nil + } + size := [2]uint32{ + min(deviceLength(width, win.displayScale())+2*margin, 65535), + min(deviceLength(height, win.displayScale())+2*margin, 65535), + } + win.api.configureWindow(win.connection, win.id, + xcbConfigWindowWidth|xcbConfigWindowHeight, &size[0]) + win.api.flush(win.connection) case commandEnterFullscreen, commandExitFullscreen: action := uint32(0) // _NET_WM_STATE_REMOVE if command == commandEnterFullscreen { diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 9972ec2c8..7b85b844a 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -193,6 +193,7 @@ const ( commandDesktop commandEnterFullscreen commandExitFullscreen + commandSetSize ) type nativeWindow struct { @@ -852,7 +853,7 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { case message.Format == 32 && message.Window == win.id && message.Type == win.closeAtom: return true, nil case message.Format == 32 && message.Window == win.id && message.Type == win.commandAtom: - return false, state.command(binary.LittleEndian.Uint32(message.Data[:4])) + return false, state.command(binary.LittleEndian.Uint32(message.Data[:4]), message.Data[:]) case message.Format == 32 && message.Window == win.id && message.Type == win.caretAtom: generation := binary.LittleEndian.Uint32(message.Data[:4]) if frame, changed := textInput.blinkCaret(generation); changed { @@ -1466,6 +1467,25 @@ func (win *window) postClientMessage(atom, value uint32) { win.api.flush(win.connection) } +func (win *window) postClientSize(width, height uint32) { + win.mu.Lock() + defer win.mu.Unlock() + if win.connection == 0 || win.commandAtom == 0 { + return + } + event := xcbClientEvent{ + ResponseType: xcbClientMessage, + Format: 32, + Window: win.id, + Type: win.commandAtom, + } + binary.LittleEndian.PutUint32(event.Data[0:4], commandSetSize) + binary.LittleEndian.PutUint32(event.Data[4:8], width) + binary.LittleEndian.PutUint32(event.Data[8:12], height) + win.api.sendEvent(win.connection, 0, win.id, 0, (*byte)(unsafe.Pointer(&event))) + win.api.flush(win.connection) +} + func (win *window) close() { win.mu.Lock() defer win.mu.Unlock() diff --git a/internal/platform/linux/window_size_linux.go b/internal/platform/linux/window_size_linux.go new file mode 100644 index 000000000..3b89aef7e --- /dev/null +++ b/internal/platform/linux/window_size_linux.go @@ -0,0 +1,16 @@ +package linux + +import "fmt" + +// SetSize posts a logical content-size request to the X11 event loop. The +// window manager's later ConfigureNotify reports the size that was granted. +func (window *nativeWindow) SetSize(width, height int) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("linux: window is closed") + } + if width < 1 || height < 1 || width > 65535 || height > 65535 { + return fmt.Errorf("linux: invalid window size %dx%d", width, height) + } + window.state.win.postClientSize(uint32(width), uint32(height)) + return nil +} diff --git a/internal/platform/linux/window_size_linux_test.go b/internal/platform/linux/window_size_linux_test.go new file mode 100644 index 000000000..2aa833790 --- /dev/null +++ b/internal/platform/linux/window_size_linux_test.go @@ -0,0 +1,79 @@ +package linux + +import ( + "encoding/binary" + "testing" + "unsafe" +) + +func TestSetSizeCommandUsesLogicalContentSize(t *testing.T) { + var gotWidth, gotHeight uint32 + var gotMask uint16 + flushed := false + win := &window{ + id: 7, + margin: frameMargin(1.5), + api: &xcbAPI{ + configureWindow: func(_ uintptr, window uint32, mask uint16, values *uint32) xcbVoidCookie { + if window != 7 { + t.Fatalf("configured window = %d, want 7", window) + } + gotMask = mask + size := unsafe.Slice(values, 2) + gotWidth, gotHeight = size[0], size[1] + return xcbVoidCookie{} + }, + flush: func(uintptr) int32 { + flushed = true + return 1 + }, + }, + } + win.storeScale(1.5) + state := &linuxWindowState{win: win} + data := make([]byte, 12) + binary.LittleEndian.PutUint32(data[0:4], commandSetSize) + binary.LittleEndian.PutUint32(data[4:8], 420) + binary.LittleEndian.PutUint32(data[8:12], 300) + if err := state.command(commandSetSize, data); err != nil { + t.Fatal(err) + } + margin := 2 * frameMargin(1.5) + if want := deviceLength(420, 1.5) + margin; gotWidth != want { + t.Fatalf("configured width = %d, want %d", gotWidth, want) + } + if want := deviceLength(300, 1.5) + margin; gotHeight != want { + t.Fatalf("configured height = %d, want %d", gotHeight, want) + } + if want := uint16(xcbConfigWindowWidth | xcbConfigWindowHeight); gotMask != want { + t.Fatalf("configure mask = %#x, want %#x", gotMask, want) + } + if !flushed { + t.Fatal("size request was not flushed") + } +} + +func TestSetSizeCommandIgnoresMinimizedWindows(t *testing.T) { + configured := false + win := &window{ + id: 7, + minimized: true, + api: &xcbAPI{ + configureWindow: func(uintptr, uint32, uint16, *uint32) xcbVoidCookie { + configured = true + return xcbVoidCookie{} + }, + }, + } + state := &linuxWindowState{win: win} + data := make([]byte, 12) + binary.LittleEndian.PutUint32(data[0:4], commandSetSize) + binary.LittleEndian.PutUint32(data[4:8], 420) + binary.LittleEndian.PutUint32(data[8:12], 300) + if err := state.command(commandSetSize, data); err != nil { + t.Fatal(err) + } + if configured { + t.Fatal("minimized window was resized") + } +} diff --git a/internal/platform/windows/window_size_windows.go b/internal/platform/windows/window_size_windows.go new file mode 100644 index 000000000..34588c19e --- /dev/null +++ b/internal/platform/windows/window_size_windows.go @@ -0,0 +1,64 @@ +package windows + +import ( + "fmt" + "math" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// SetSize queues a content-size request on the window thread. It reports only +// whether the request was accepted; the resulting WM_SIZE is authoritative. +func (window *nativeWindow) SetSize(width, height int) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + if width < 1 || height < 1 || width > 65535 || height > 65535 { + return fmt.Errorf("windows: invalid window size %dx%d", width, height) + } + packed := uintptr(uint16(width)) | uintptr(uint16(height))<<16 + if ok, _, err := postMessage.Call(window.state.window, wmSetSize, packed, 0); ok == 0 { + return fmt.Errorf("windows: request window size: %w", err) + } + return nil +} + +func (state *windowState) resizeClient(width, height int) { + if state.window == 0 || width < 1 || height < 1 || state.maximized || state.minimized || state.fullscreen.Load() { + return + } + scale := state.scale + if scale <= 0 { + scale = 1 + } + bounds := rect{ + Right: int32(math.Round(float64(width) * float64(scale))), + Bottom: int32(math.Round(float64(height) * float64(scale))), + } + style := uintptr(wsOverlappedWindow) + if state.config.WindowMode == platform.WindowTitled { + if adjustWindow.Find() == nil { + adjustWindow.Call(uintptr(unsafe.Pointer(&bounds)), style, 0, 0, uintptr(scale*96)) + } else { + adjustWindowLegacy.Call(uintptr(unsafe.Pointer(&bounds)), style, 0, 0) + } + } + minimum := state.minimumTrackSize() + w, h := max(minimum.X, bounds.Right-bounds.Left), max(minimum.Y, bounds.Bottom-bounds.Top) + const noZOrder, noActivate, noMove = 0x4, 0x10, 0x2 + flags := uintptr(noZOrder | noActivate | noMove) + var x, y int32 + monitor, _, _ := monitorFromWindow.Call(state.window, monitorNearest) + info := monitorInfo{Size: uint32(unsafe.Sizeof(monitorInfo{}))} + var current rect + if ok, _, _ := getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))); ok != 0 { + if ok, _, _ := getWindowRect.Call(state.window, uintptr(unsafe.Pointer(¤t))); ok != 0 { + w, h = min(w, info.Work.Right-info.Work.Left), min(h, info.Work.Bottom-info.Work.Top) + x = min(max(current.Left, info.Work.Left), info.Work.Right-w) + y = min(max(current.Top, info.Work.Top), info.Work.Bottom-h) + flags &^= noMove + } + } + setWindowPosition.Call(state.window, 0, uintptr(x), uintptr(y), uintptr(w), uintptr(h), flags) +} diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index a52289f0f..db3a9fb58 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -63,6 +63,7 @@ const ( wmAllowClose = 32769 wmApplyCursor = 32770 wmRedraw = 32771 + wmSetSize = 0x8052 wsOverlappedWindow = 0x00cf0000 ) @@ -442,6 +443,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { return 1 } return 0 + case wmSetSize: + state.resizeClient(int(first&0xffff), int((first>>16)&0xffff)) + return 0 case wmFullscreen: state.setFullscreen(first != 0) return 0 diff --git a/website/content/guides/en/windows.md b/website/content/guides/en/windows.md index e27e9f59a..6e07cb578 100644 --- a/website/content/guides/en/windows.md +++ b/website/content/guides/en/windows.md @@ -65,6 +65,17 @@ The headless application's `Window.SetFullscreen` queues work for the driver's next pump, without a worker or polling. Its command protocol also provides `fullscreen on|off` and `fullscreenmonitor x y width height`. +## Changing the content size + +Call `window.SetSize(width, height)` to ask the window manager for a new content +size in logical pixels. The call is asynchronous and safe from any goroutine; +`Config.OnResize` reports the size that was actually granted, which may be +clamped to the window minimum, the screen's work area or the platform's limit +(width and height must be 1 through 65535). A maximized, minimized or fullscreen +window ignores the request. `ContentWindow` from `OpenContentWindow` forwards the +same call, and the headless application applies it on the driver's next pump. +Hosts without the capability return an error wrapping `app.ErrUnsupported`. + ## A complete example The program below opens a custom-title-bar window with a Settings button that opens a second window, and refuses to close while a note is unsaved. The strip along the top is an ordinary `ui.Row` padded by `app.TitlebarInsets`, so the title never runs under the window buttons, and the confirmation is a `ui.ModalWith` declared only while a close is pending: diff --git a/website/content/guides/zh/windows.md b/website/content/guides/zh/windows.md index 4b10f7da9..419d05048 100644 --- a/website/content/guides/zh/windows.md +++ b/website/content/guides/zh/windows.md @@ -38,6 +38,10 @@ Windows 使用整个显示器而不是任务栏工作区,并保存之前的位 无头应用的 `Window.SetFullscreen` 把工作排进 driver 的下一次 pump,不需要 worker,也不轮询。它的命令协议还提供 `fullscreen on|off` 和 `fullscreenmonitor x y width height`。 +## 改变内容尺寸 + +调用 `window.SetSize(width, height)` 请求窗口管理器把内容区域改成给定的逻辑像素尺寸。调用是异步的,可以从任意 goroutine 发起;`Config.OnResize` 报告实际获得的尺寸,它可能被窗口最小尺寸、屏幕工作区或平台上限(宽高必须在 1 到 65535 之间)夹住。最大化、最小化或全屏的窗口会忽略这个请求。`OpenContentWindow` 返回的 `ContentWindow` 转发同一个调用,无头应用会在 driver 的下一次 pump 应用它。不支持该能力的宿主返回一个包装了 `app.ErrUnsupported` 的错误。 + ## 完整示例 下面的程序打开一个自定义标题栏窗口,其中的“Settings”按钮会打开第二个窗口,并且在有未保存的笔记时拒绝关闭。顶部条带是一个普通的 `ui.Row`,用 `app.TitlebarInsets` 留出内边距,所以标题不会压到窗口按钮下面;确认框是 `ui.ModalWith`,只在有关闭请求挂起时才声明: From fb7300d75fe95c62d70ee3c0413e19e2c9e1539b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 00:14:10 +0800 Subject: [PATCH 07/86] fix(gfx): draw cell glyphs with the font's underline weight The rule a Box Drawing or Block Element stroke is drawn with was a fixed 5 percent of the font size, rounded down to whole device pixels. At a 13 px font on a 2x display that is one device pixel and a heavy stroke two, half of what the font itself draws: opencode's prompt border (U+2503) turned into a hairline, and the stroke got relatively thinner as the display scale rose. The text engines now report the face's underline thickness (MonoCellMetrics.Underline), the source Ghostty takes its box thickness from, and a rule is that thickness at the line's scale rounded up, with a heavy stroke still two rules. Geometry then weighs what the font's own glyphs weigh at any size and scale; a canvas without an engine keeps the reference thickness (internal/textmetrics.MonoUnderline). Refs: t8y2/motty#822 --- gfx/box_drawing.go | 2 + gfx/canvas.go | 43 ++++++----- gfx/cell_glyphs.go | 13 +++- gfx/cell_glyphs_test.go | 50 +++++++++++++ gfx/text_engine.go | 6 ++ internal/platform/darwin/native.h | 5 +- internal/platform/darwin/native.m | 5 +- internal/platform/darwin/text.go | 18 +++-- internal/platform/darwin/text_engine.go | 2 +- internal/platform/darwin/text_test.go | 19 +++++ internal/platform/linux/text_engine_linux.go | 9 ++- internal/platform/linux/text_linux.go | 23 ++++++ internal/platform/linux/text_linux_test.go | 21 ++++++ .../windows/text_underline_windows_test.go | 37 +++++++++ internal/platform/windows/text_windows.go | 75 +++++++++++++++++++ .../platform/windows/textengine_windows.go | 12 +-- internal/textmetrics/textmetrics.go | 6 ++ text/measure.go | 4 + 18 files changed, 306 insertions(+), 44 deletions(-) create mode 100644 internal/platform/windows/text_underline_windows_test.go diff --git a/gfx/box_drawing.go b/gfx/box_drawing.go index a433f295c..b083e5d1f 100644 --- a/gfx/box_drawing.go +++ b/gfx/box_drawing.go @@ -368,3 +368,5 @@ func (g *cellGlyph) strokeDiagonal(rising bool) { } func round32(v float64) int32 { return int32(math.Floor(v + 0.5)) } + +func ceil32(v float64) int32 { return int32(math.Ceil(v)) } diff --git a/gfx/canvas.go b/gfx/canvas.go index 9d7760091..37fc8ed12 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -808,7 +808,7 @@ func (canvas *Canvas) CellSize(size float32) (width, height float32) { // glyph that fills its cell, such as a powerline arrow, ends where the next cell's begins // and no pixel column holds the glyphs of two cells drawn in two colors. func (canvas *Canvas) MonoCellSize(size float32, face MonoFace) (width, height float32) { - width, height, _ = canvas.monoCell(size, face) + width, height, _, _ = canvas.monoCell(size, face) return width, height } @@ -820,25 +820,26 @@ func (canvas *Canvas) MonoCellSize(size float32, face MonoFace) (width, height f // the face, and for a label of no height: the renderers then place the line by their own // rule. func (canvas *Canvas) MonoBaseline(size float32, face MonoFace, height float32) float32 { - _, cell, baseline := canvas.monoCell(size, face) + _, cell, baseline, _ := canvas.monoCell(size, face) if cell <= 0 || baseline <= 0 || height <= 0 { return 0 } return (height-cell)/2 + baseline } -// monoCell is MonoCellSize and the baseline of the cell, measured once per face, size, -// scale and font generation. The baseline is 0 when no engine measured the face. -func (canvas *Canvas) monoCell(size float32, face MonoFace) (width, height, baseline float32) { +// monoCell is MonoCellSize, the baseline of the cell and the face's underline thickness, +// measured once per face, size, scale and font generation. The baseline is 0 and the +// underline the reference thickness when no engine measured the face. +func (canvas *Canvas) monoCell(size float32, face MonoFace) (width, height, baseline, underline float32) { if size <= 0 { - return 0, 0, 0 + return 0, 0, 0, 0 } if !validMonoFace(face) { face = MonoSystem } generation := canvas.FontGeneration() - if width, height, baseline, ok := canvas.cellSizes.find(size, face, canvas.pixelScale, generation); ok { - return width, height, baseline + if width, height, baseline, underline, ok := canvas.cellSizes.find(size, face, canvas.pixelScale, generation); ok { + return width, height, baseline, underline } width, height = size*textmetrics.MonoAdvance, size*textmetrics.MonoLine switch { @@ -849,25 +850,31 @@ func (canvas *Canvas) monoCell(size float32, face MonoFace) (width, height, base case canvas.monoCells != nil: if cell := canvas.monoCells.MonoCell(size, face); cell.Line() > 0 && cell.Advance > 0 { width, height, baseline = cell.Advance, cell.CellHeight(), cell.CellBaseline() + underline = cell.Underline } } + if underline <= 0 { + // No engine measured the face, or its font has no underline: the reference + // thickness stands in, in the font's own units so it follows the size. + underline = size * textmetrics.MonoUnderline + } // A font's own cell is whole already (MonoCellMetrics.CellHeight); the reference cell // and a measurer's answer are rounded up, as they always were. height = float32(int32(height + 0.999)) if canvas.pixelScale > 0 { width = float32(math.Max(math.Floor(float64(width)*float64(canvas.pixelScale)+0.5), 1)) / canvas.pixelScale } - canvas.cellSizes.put(cellSizeMemo{size: size, width: width, height: height, baseline: baseline, face: face, scale: canvas.pixelScale, generation: generation}) - return width, height, baseline + canvas.cellSizes.put(cellSizeMemo{size: size, width: width, height: height, baseline: baseline, underline: underline, face: face, scale: canvas.pixelScale, generation: generation}) + return width, height, baseline, underline } // cellSizeMemo is one remembered MonoCellSize answer. type cellSizeMemo struct { - size, width, height, baseline float32 - face MonoFace - scale float32 // the canvas's pixel scale the width was made whole for - generation uint32 // the font generation it was measured in - filled bool + size, width, height, baseline, underline float32 + face MonoFace + scale float32 // the canvas's pixel scale the width was made whole for + generation uint32 // the font generation it was measured in + filled bool } // cellSizeMemos remembers the last few MonoCellSize answers: a terminal asks every @@ -879,14 +886,14 @@ type cellSizeMemos struct { next int } -func (memos *cellSizeMemos) find(size float32, face MonoFace, scale float32, generation uint32) (width, height, baseline float32, ok bool) { +func (memos *cellSizeMemos) find(size float32, face MonoFace, scale float32, generation uint32) (width, height, baseline, underline float32, ok bool) { for i := range memos.entries { memo := &memos.entries[i] if memo.filled && memo.size == size && memo.face == face && memo.scale == scale && memo.generation == generation { - return memo.width, memo.height, memo.baseline, true + return memo.width, memo.height, memo.baseline, memo.underline, true } } - return 0, 0, 0, false + return 0, 0, 0, 0, false } func (memos *cellSizeMemos) put(memo cellSizeMemo) { diff --git a/gfx/cell_glyphs.go b/gfx/cell_glyphs.go index 18754c10d..0135df606 100644 --- a/gfx/cell_glyphs.go +++ b/gfx/cell_glyphs.go @@ -70,9 +70,13 @@ type cellLine struct { padY int32 // rule is one rule's thickness, in device pixels. // - // ponytail: it is 5% of the font size, the underline a fixed-pitch face draws, because no - // text engine reports its underline thickness yet; an engine that does can hand it over the - // way MonoCell hands the cell, and only the line that computes it changes. + // It is the face's underline thickness (MonoCellMetrics.Underline) at the line's scale, + // rounded up to the whole device pixel a stroke covers: the weight the font itself draws + // an underline with, so a box drawing or block character drawn as geometry weighs what + // the font's own glyphs around it weigh, as in Ghostty (src/font/Metrics.zig). Rounding + // down would make a stroke thinner, relative to the glyphs, at every scale that leaves + // it a fraction of a pixel; the reference thickness stands in when no engine measured + // the face. rule int32 } @@ -280,10 +284,11 @@ func (canvas *Canvas) cellLine(text Text) cellLine { scale := canvas.deviceScale() top := round32(float64(text.Bounds.Y) * scale) height := max(round32(float64(text.Bounds.Y+text.Bounds.Height)*scale)-top, 1) + _, _, _, underline := canvas.monoCell(text.Style.Size, text.Style.MonoFace) return cellLine{ text: text, scale: scale, top: float32(float64(top) / scale), height: height, padY: height / 4, - rule: max(round32(0.05*float64(text.Style.Size)*scale), 1), + rule: max(ceil32(float64(underline)*scale), 1), } } diff --git a/gfx/cell_glyphs_test.go b/gfx/cell_glyphs_test.go index 6656b1ac5..7ea83952c 100644 --- a/gfx/cell_glyphs_test.go +++ b/gfx/cell_glyphs_test.go @@ -269,6 +269,56 @@ func FuzzReplaceCellGlyphs(f *testing.F) { }) } +// A cell glyph's rule is the face's underline thickness (MonoCellMetrics.Underline) at the +// line's scale, rounded up to whole device pixels, and a heavy stroke is two rules wide: a +// box drawing character drawn as geometry then weighs what the font's own glyphs weigh, and +// a fractional device pixel makes the stroke no thinner than the whole one it rounds up to. +func TestCellGlyphRuleFollowsTheFacesUnderline(t *testing.T) { + for _, test := range []struct { + name string + underline float32 + scale float32 + light float32 // device pixels + }{ + {"thinner than a device pixel at 1x", 0.57, 1, 1}, + {"thinner than a device pixel at 2x", 0.57, 2, 2}, + {"thicker than a device pixel", 1.2, 2, 3}, + {"a fraction at 3x", 0.4, 3, 2}, + } { + for _, glyph := range []struct { + value string + rules float32 + }{{"│", 1}, {"┃", 2}} { + var canvas Canvas + canvas.SetPixelScale(test.scale) + canvas.SetTextEngine(&monoCellEngine{MonoCellMetrics: MonoCellMetrics{ + Advance: 0.6, Ascent: 0.8, Descent: 0.2, Underline: test.underline, + }}) + cellWidth, cellHeight := float32(10), float32(20) + canvas.LabelRuns(glyph.value, Rect{Width: cellWidth, Height: cellHeight}, TextStyle{Size: 10}, cellWidth, + []TextRun{{Column: 0, Bytes: int32(len(glyph.value)), Cells: 1, Color: Color{Red: 1, Alpha: 1}}}) + texts := canvas.Texts() + shapes := canvas.CellGlyphGeometry(CellGlyphShapes{}, texts[len(texts)-1]) + want := test.light * glyph.rules + var strokes int + for _, shape := range shapes.Rectangles { + bounds := shape.Bounds + if bounds.Height < cellHeight/2 || bounds.Width >= cellWidth/2 { + continue // not a vertical stroke of the glyph + } + strokes++ + if got := bounds.Width * test.scale; math.Abs(float64(got-want)) > 1e-3 { + t.Errorf("%s at %g x %g: a vertical stroke is %g device pixels, want %g", + test.name, test.scale, test.underline, got, want) + } + } + if strokes == 0 { + t.Errorf("%s: %s draws no vertical stroke", test.name, glyph.value) + } + } + } +} + // runsOver covers value with one run per stretch between the byte offsets the cuts // name, so a cut can fall anywhere, glyphs included. func runsOver(value, cuts string) []TextRun { diff --git a/gfx/text_engine.go b/gfx/text_engine.go index ed18bedc1..307bda64b 100644 --- a/gfx/text_engine.go +++ b/gfx/text_engine.go @@ -84,6 +84,12 @@ type MonoCellMetrics struct { Ascent float32 // baseline to the top of the line box Descent float32 // baseline to the bottom of the line box LineGap float32 // the space the font asks between two line boxes; zero where the engine derives Descent from the font's line height (Windows and Linux), which folds the gap into it + // Underline is the thickness of the stroke the face draws an underline with, in + // logical pixels: the weight a cell glyph's rule takes, so that a box drawing or + // block character drawn as geometry weighs what the font's own glyphs weigh + // (Ghostty's Metrics.box_thickness). Zero when the engine does not report it; the + // canvas then uses the reference thickness (internal/textmetrics.MonoUnderline). + Underline float32 } // Line is the height of the font's line box: its ascent, its descent and the gap it asks diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 119d32058..27189838a 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -556,8 +556,9 @@ int viva_text_line_rasterize( ); // viva_measure_mono reports the system fixed-pitch font's cell at a size: the advance of -// one character and the ascent, descent and leading of its line box. -int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading); +// one character, the ascent, descent and leading of its line box, and the thickness of +// the stroke the font underlines with. +int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading, double *underline); // viva_register_mono_family teaches what a mono_face number (2 and up) stands for: the // installed family it draws in first (empty for a stack over a built-in face), whether // that built-in face is the classic one, and the families that draw the characters the diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index e46e2c2d9..faa667ffd 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -7802,8 +7802,8 @@ int viva_measure_text( } } -int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading) { - if (advance == NULL || ascent == NULL || descent == NULL || leading == NULL || font_size <= 0) { +int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading, double *underline) { + if (advance == NULL || ascent == NULL || descent == NULL || leading == NULL || underline == NULL || font_size <= 0) { return 1; } @autoreleasepool { @@ -7825,6 +7825,7 @@ int viva_measure_mono(double font_size, int mono_face, double *advance, double * *ascent = CTFontGetAscent(font); *descent = CTFontGetDescent(font); *leading = CTFontGetLeading(font); + *underline = CTFontGetUnderlineThickness(font); CFRelease(font); return *advance > 0 ? 0 : 4; } diff --git a/internal/platform/darwin/text.go b/internal/platform/darwin/text.go index f184cf1f9..601b94fdd 100644 --- a/internal/platform/darwin/text.go +++ b/internal/platform/darwin/text.go @@ -40,22 +40,24 @@ func MeasureText(value string, fontSize, weight float32) (text.Metrics, error) { } // measureMonoMetrics reports the system fixed-pitch font's character cell at a size: the -// advance of one character and the line box around its baseline. +// advance of one character, the line box around its baseline, and the thickness of the +// stroke the font underlines with. func measureMonoMetrics(fontSize float32, face gfx.MonoFace) (text.Metrics, error) { if fontSize <= 0 { return text.Metrics{}, fmt.Errorf("darwin: font size must be positive") } syncMonoFamilies() - var advance, ascent, descent, leading C.double - if status := C.viva_measure_mono(C.double(fontSize), C.int(face), &advance, &ascent, &descent, &leading); status != 0 { + var advance, ascent, descent, leading, underline C.double + if status := C.viva_measure_mono(C.double(fontSize), C.int(face), &advance, &ascent, &descent, &leading, &underline); status != 0 { return text.Metrics{}, fmt.Errorf("darwin: CoreText fixed-pitch measurement failed with status %d", status) } return text.Metrics{ - Width: float32(advance), - Height: float32(ascent + descent + leading), - Ascent: float32(ascent), - Descent: float32(descent), - Leading: float32(leading), + Width: float32(advance), + Height: float32(ascent + descent + leading), + Ascent: float32(ascent), + Descent: float32(descent), + Leading: float32(leading), + Underline: float32(underline), }, nil } diff --git a/internal/platform/darwin/text_engine.go b/internal/platform/darwin/text_engine.go index 5f69820c5..17cc20628 100644 --- a/internal/platform/darwin/text_engine.go +++ b/internal/platform/darwin/text_engine.go @@ -112,7 +112,7 @@ func (engine *TextEngine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCell if err != nil { return gfx.MonoCellMetrics{} } - return gfx.MonoCellMetrics{Advance: metrics.Width, Ascent: metrics.Ascent, Descent: metrics.Descent, LineGap: metrics.Leading} + return gfx.MonoCellMetrics{Advance: metrics.Width, Ascent: metrics.Ascent, Descent: metrics.Descent, LineGap: metrics.Leading, Underline: metrics.Underline} } // FontGeneration implements gfx.FontFamilyAware. diff --git a/internal/platform/darwin/text_test.go b/internal/platform/darwin/text_test.go index e0e1712c9..17541065b 100644 --- a/internal/platform/darwin/text_test.go +++ b/internal/platform/darwin/text_test.go @@ -599,3 +599,22 @@ func TestACanvasOnTheEngineSizesTheTerminalCellByTheFont(t *testing.T) { } } } + +// The engine reports the thickness the font underlines with, in logical pixels at the size +// asked: that is the rule a cell glyph is drawn with, so box drawing geometry is as thick as +// the font's own glyphs. +func TestTheEngineReportsTheFontsUnderline(t *testing.T) { + engine := SharedTextEngine() + for _, face := range []gfx.MonoFace{gfx.MonoSystem, gfx.MonoFamily("Courier New")} { + cell := engine.MonoCell(13, face) + if cell.Advance <= 0 { + t.Fatalf("face %v: no cell", face) + } + if cell.Underline <= 0 || cell.Underline >= cell.Advance { + t.Errorf("face %v: underline %v of a cell %v wide, want a positive stroke narrower than the cell", face, cell.Underline, cell.Advance) + } + if at26 := engine.MonoCell(26, face); at26.Underline <= cell.Underline { + t.Errorf("face %v: underline %v at 26, %v at 13, want it to follow the size", face, at26.Underline, cell.Underline) + } + } +} diff --git a/internal/platform/linux/text_engine_linux.go b/internal/platform/linux/text_engine_linux.go index bb8c92254..d0a765258 100644 --- a/internal/platform/linux/text_engine_linux.go +++ b/internal/platform/linux/text_engine_linux.go @@ -143,10 +143,11 @@ func (engine *textEngine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCell return gfx.MonoCellMetrics{} } return gfx.MonoCellMetrics{ - Advance: metrics.Width, - Ascent: metrics.Ascent, - Descent: metrics.Descent, - LineGap: max(metrics.Height-metrics.Ascent-metrics.Descent, 0), + Advance: metrics.Width, + Ascent: metrics.Ascent, + Descent: metrics.Descent, + LineGap: max(metrics.Height-metrics.Ascent-metrics.Descent, 0), + Underline: metrics.Underline, } } diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go index f714ce34a..7eee8b1ca 100644 --- a/internal/platform/linux/text_linux.go +++ b/internal/platform/linux/text_linux.go @@ -53,6 +53,9 @@ type textServices struct { fontSetWeight func(uintptr, int32) fontSetStyle func(uintptr, int32) objectUnref func(uintptr) + contextGetMetrics func(uintptr, uintptr, uintptr) uintptr + fontMetricsUnderline func(uintptr) int32 + fontMetricsUnref func(uintptr) imageSurfaceCreateForData func(*byte, int32, int32, int32, int32) uintptr surfaceStatus func(uintptr) int32 @@ -137,6 +140,9 @@ func loadTextAPI() (*textServices, error) { purego.RegisterLibFunc(&services.fontSetWeight, services.pango, "pango_font_description_set_weight") purego.RegisterLibFunc(&services.fontSetStyle, services.pango, "pango_font_description_set_style") purego.RegisterLibFunc(&services.objectUnref, services.gobject, "g_object_unref") + purego.RegisterLibFunc(&services.contextGetMetrics, services.pango, "pango_context_get_metrics") + purego.RegisterLibFunc(&services.fontMetricsUnderline, services.pango, "pango_font_metrics_get_underline_thickness") + purego.RegisterLibFunc(&services.fontMetricsUnref, services.pango, "pango_font_metrics_unref") purego.RegisterLibFunc(&services.imageSurfaceCreateForData, services.cairo, "cairo_image_surface_create_for_data") purego.RegisterLibFunc(&services.surfaceStatus, services.cairo, "cairo_surface_status") @@ -323,10 +329,27 @@ func (services *textServices) configureLayout(value, family string, size, weight Height: float32(logical.Height) / pangoScale, Ascent: float32(baseline) / pangoScale, Descent: float32(logical.Height-baseline) / pangoScale, + // The stroke the face underlines with, at the description's absolute size: + // the weight a fixed-pitch cell glyph's rule takes. + Underline: services.underline(description), } return metrics, nil } +// underline is the thickness of the stroke description's face underlines with, in logical +// pixels, or 0 when Pango cannot report it. +func (services *textServices) underline(description uintptr) float32 { + if services.contextGetMetrics == nil || services.fontMetricsUnderline == nil || services.fontMetricsUnref == nil { + return 0 + } + metrics := services.contextGetMetrics(services.context, description, 0) + if metrics == 0 { + return 0 + } + defer services.fontMetricsUnref(metrics) + return float32(services.fontMetricsUnderline(metrics)) / pangoScale +} + func (services *textServices) measure(value string, size, weight float32) (text.Metrics, error) { return services.configureLayout(value, proportionalFamily, size, weight, false) } diff --git a/internal/platform/linux/text_linux_test.go b/internal/platform/linux/text_linux_test.go index 6dc18a5c9..d2c361c47 100644 --- a/internal/platform/linux/text_linux_test.go +++ b/internal/platform/linux/text_linux_test.go @@ -311,3 +311,24 @@ func TestMeasureTextIsWiderAtAHeavierWeight(t *testing.T) { t.Fatalf("bold %.2f is not wider than regular %.2f", bold.Width, regular.Width) } } + +// The engine reports the thickness the font underlines with, in logical pixels at the size +// asked: that is the rule a cell glyph is drawn with, so box drawing geometry weighs what +// the font's own glyphs weigh. Pango reads it from the face; a face that files no underline +// thickness answers 0, and the canvas then uses the reference thickness. +func TestTheEngineReportsTheFontsUnderline(t *testing.T) { + engine := sharedTextEngine() + cell := engine.MonoCell(13, gfx.MonoSystem) + if cell.Advance <= 0 { + t.Fatal("no fixed-pitch cell on this runner") + } + if cell.Underline == 0 { + t.Skip("the runner's fixed-pitch face reports no underline thickness") + } + if cell.Underline < 0 || cell.Underline >= cell.Advance { + t.Fatalf("underline %v of a cell %v wide, want a positive stroke narrower than the cell", cell.Underline, cell.Advance) + } + if at26 := engine.MonoCell(26, gfx.MonoSystem); at26.Underline <= cell.Underline { + t.Errorf("underline %v at size 26, %v at size 13, want it to follow the size", at26.Underline, cell.Underline) + } +} diff --git a/internal/platform/windows/text_underline_windows_test.go b/internal/platform/windows/text_underline_windows_test.go new file mode 100644 index 000000000..12fbecd66 --- /dev/null +++ b/internal/platform/windows/text_underline_windows_test.go @@ -0,0 +1,37 @@ +package windows + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// The cell of a fixed-pitch face carries the thickness the font underlines with: the rule +// a cell glyph draws with (gfx.MonoCellMetrics.Underline), so a box drawing border drawn +// as geometry weighs what the font's own glyphs weigh. DirectWrite reports the thickness +// in design units; the engine scales it to the logical size asked. +func TestTheEngineReportsTheFontsUnderline(t *testing.T) { + engine, err := theTextEngine() + if err != nil { + t.Skipf("no DirectWrite text engine: %v", err) + } + reported := 0 + for _, name := range []string{"Consolas", "Cascadia Mono", "Courier New"} { + face := gfx.MonoFamily(name) + cell := engine.MonoCell(13, face) + if cell.Advance <= 0 { + continue // the runner does not have this family + } + if cell.Underline <= 0 || cell.Underline >= cell.Advance { + t.Errorf("%s: underline %v of a cell %v wide, want a positive stroke narrower than the cell", name, cell.Underline, cell.Advance) + continue + } + reported++ + if at26 := engine.MonoCell(26, face); at26.Underline <= cell.Underline { + t.Errorf("%s: underline %v at size 26, %v at size 13, want it to follow the size", name, at26.Underline, cell.Underline) + } + } + if reported == 0 { + t.Fatal("no installed fixed-pitch face reported its underline thickness") + } +} diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index 606a9455e..a25219a7e 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -472,3 +472,78 @@ func (services *textServices) measureIn(typeface, value string, size, weight flo line := lines[0] return text.Metrics{Width: metrics.WidthTrailing, Height: metrics.Height, Ascent: line.Baseline, Descent: line.Height - line.Baseline}, nil } + +// Method slots of IDWriteFactory, IDWriteFontCollection, IDWriteFontFamily and +// IDWriteFont (checked against dwrite.h). +const ( + writeFactoryGetSystemFontCollection = 3 + writeCollectionGetFontFamily = 4 + writeCollectionFindFamilyName = 5 + writeFontFamilyGetFirstMatchingFont = 7 + writeFontGetMetrics = 11 +) + +// writeFontMetrics is DWRITE_FONT_METRICS: the face's design units per em and the +// thicknesses and positions the font draws its rules with. +type writeFontMetrics struct { + DesignUnitsPerEm, Ascent, Descent uint16 + LineGap int16 + CapHeight, XHeight uint16 + UnderlinePosition int16 + UnderlineThickness uint16 + StrikethroughPosition int16 + StrikethroughThickness uint16 +} + +// underline is the thickness of the stroke typeface's face at weight underlines with, in +// logical pixels, or 0 when DirectWrite cannot report it: the weight a fixed-pitch cell +// glyph's rule takes. +func (services *textServices) underline(typeface string, size, weight float32) float32 { + if size <= 0 || typeface == "" { + return 0 + } + familyName, err := syscall.UTF16PtrFromString(typeface) + if err != nil { + return 0 + } + // The collection every text format is made from: the application's fonts and the + // system's, or the system's alone. A registered collection is held by the process + // and must outlive the use; its read lock keeps it from being released meanwhile. + customFonts.RLock() + collection, owned := customFonts.collection, false + if collection == 0 { + customFonts.RUnlock() + status := comCall(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&collection)), 0) + if err = hresult(status); err != nil || collection == 0 { + return 0 + } + owned = true + } else { + defer customFonts.RUnlock() + } + if owned { + defer release(&collection) + } + var index, exists uint32 + if err := hresult(comCall(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(familyName)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil || exists == 0 { + return 0 + } + var family, font uintptr + if err := hresult(comCall(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&family)))); err != nil { + return 0 + } + defer release(&family) + const ( + stretchNormal = 5 + styleNormal = 0 + ) + if err := hresult(comCall(family, writeFontFamilyGetFirstMatchingFont, uintptr(nativeFontWeight(weight)), stretchNormal, styleNormal, uintptr(unsafe.Pointer(&font)))); err != nil { + return 0 + } + defer release(&font) + var metrics writeFontMetrics + if err := hresult(comCall(font, writeFontGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil || metrics.DesignUnitsPerEm == 0 { + return 0 + } + return float32(metrics.UnderlineThickness) / float32(metrics.DesignUnitsPerEm) * size +} diff --git a/internal/platform/windows/textengine_windows.go b/internal/platform/windows/textengine_windows.go index f82fb6fc6..9f0ce0d6f 100644 --- a/internal/platform/windows/textengine_windows.go +++ b/internal/platform/windows/textengine_windows.go @@ -181,15 +181,17 @@ func (engine *textEngine) SetFontFamily(family string) { func (engine *textEngine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCellMetrics { engine.mu.Lock() defer engine.mu.Unlock() - metrics, err := engine.services.measureIn(monoFamily(face), "M", size, 0) + family := monoFamily(face) + metrics, err := engine.services.measureIn(family, "M", size, 0) if err != nil { return gfx.MonoCellMetrics{} } return gfx.MonoCellMetrics{ - Advance: metrics.Width, - Ascent: metrics.Ascent, - Descent: metrics.Descent, - LineGap: max(metrics.Height-metrics.Ascent-metrics.Descent, 0), + Advance: metrics.Width, + Ascent: metrics.Ascent, + Descent: metrics.Descent, + LineGap: max(metrics.Height-metrics.Ascent-metrics.Descent, 0), + Underline: engine.services.underline(family, size, 0), } } diff --git a/internal/textmetrics/textmetrics.go b/internal/textmetrics/textmetrics.go index a5a8e866c..80bec0677 100644 --- a/internal/textmetrics/textmetrics.go +++ b/internal/textmetrics/textmetrics.go @@ -53,6 +53,12 @@ const ( const ( MonoAdvance = 0.6 MonoLine = 1.18 + // MonoUnderline is the reference thickness of the stroke an underline draws, + // in units of the font size: the rule a cell glyph is drawn with when the text + // engine does not report the face's own underline thickness. A fixed-pitch face + // draws its underline at 5 to 10 percent of the size, and its heavy box drawing + // strokes at twice that, which is what the reference cell stands for. + MonoUnderline = 0.05 ) // weightIndex selects the table for a Viva weight (gfx.TextStyle.Weight: 0 regular, diff --git a/text/measure.go b/text/measure.go index 5cbc64b7e..689dcb657 100644 --- a/text/measure.go +++ b/text/measure.go @@ -7,6 +7,10 @@ type Metrics struct { Ascent float32 Descent float32 Leading float32 + // Underline is the thickness of the stroke the font underlines with, in logical + // pixels: the weight a fixed-pitch cell glyph's rule takes. Zero where the + // platform's measurement does not include it. + Underline float32 } // MeasureFunc shapes and measures one line at a logical font size and weight From 30a91db045bcff4f714778dd2755bf3ca5d5df1b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 00:18:45 +0800 Subject: [PATCH 08/86] ci: run the underline metric test on Windows The test reads the thickness DirectWrite reports for a fixed-pitch face, which only a Windows runner can execute: the hosted job's name filter must list it or the COM path is compiled and never run. Refs: t8y2/motty#822 --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 35b7e2552..93c2254a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -284,7 +284,7 @@ jobs: # native structure ABI tests are here for the same reason: they build only # on Windows. - name: Material contracts and controls (WARP) - run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI)' -count=1 -v + run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI)' -count=1 -v - name: Terminal keyboard routing run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v - name: Native Windows global shortcut From d1252da43e9c72c046ea5329ae2bfdbbb3c386be Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 01:29:10 +0800 Subject: [PATCH 09/86] feat(table): expose last-painted row identities Co-Authored-By: Kimi --- ui/rowidentity.go | 25 +++++ ui/rowidentity_test.go | 204 +++++++++++++++++++++++++++++++++++++++++ ui/table.go | 16 ++-- 3 files changed, 238 insertions(+), 7 deletions(-) create mode 100644 ui/rowidentity.go create mode 100644 ui/rowidentity_test.go diff --git a/ui/rowidentity.go b/ui/rowidentity.go new file mode 100644 index 000000000..895a4f3ea --- /dev/null +++ b/ui/rowidentity.go @@ -0,0 +1,25 @@ +package ui + +import "github.com/vivaui/viva/gfx" + +// RowID is the identity of source row i as declared by the last paint, and false +// for a row the table did not declare (offscreen, out of range, or not yet +// painted). Scrolling does not renumber source rows: an identity keeps its source +// index when the row moves on screen. When the Source is sorted or reordered, the +// identities follow those indices, not the records the application moved. +func (s *TableState) RowID(i int) (gfx.ID, bool) { + if i < int(s.rowFirst) || i >= int(s.rowEnd) || s.scope.IsZero() { + return gfx.ID{}, false + } + return s.scope.At(i), true +} + +// Rows is the scope the table named its rows in on the last paint, for a handler +// that must recover a source row from a target: +// +// row, ok := event.Target.In(state.Rows()) +// +// It is zero before the first paint, and after a paint that gave the table no row +// scope. Identities from RowID belong to this scope. Declaring the same state in +// more than one table leaves the calls describing only the last table painted. +func (s *TableState) Rows() gfx.Scope { return s.scope } diff --git a/ui/rowidentity_test.go b/ui/rowidentity_test.go new file mode 100644 index 000000000..cff44989d --- /dev/null +++ b/ui/rowidentity_test.go @@ -0,0 +1,204 @@ +package ui_test + +import ( + "fmt" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +type rowIdentityModel struct { + rows ui.TableRows + first ui.TableState + second ui.TableState + target gfx.ID + row int + ok bool +} + +func newRowIdentityModel(rows int) *rowIdentityModel { + m := &rowIdentityModel{rows: make(ui.TableRows, rows), row: -1} + for i := range m.rows { + m.rows[i] = []string{fmt.Sprintf("source-%d", i)} + } + return m +} + +func (m *rowIdentityModel) table(c ui.C, state *ui.TableState) { + ui.Table(c, state, ui.TableSpec{ + Columns: []components.TableColumn{{}}, + Source: &m.rows, + RowHeight: 20, + }).Height(100) +} + +func (m *rowIdentityModel) page(c ui.C) { + m.table(c, &m.first) +} + +func (m *rowIdentityModel) pointer(event gfx.PointerEvent) gfx.EventResult { + if event.Kind != gfx.PointerDown { + return gfx.EventResult{} + } + m.target = event.Target + m.row, m.ok = event.Target.In(m.first.Rows()) + return gfx.EventResult{} +} + +func (m *rowIdentityModel) press(t *testing.T, d *pageDriver, row int) { + t.Helper() + x, y := center(d.hit(fmt.Sprintf("source-%d", row)).Bounds) + m.ok = false + if err := d.driver.Click(x, y); err != nil { + t.Fatal(err) + } + if !m.ok { + t.Fatalf("a press on source row %d did not reach the table's row scope; target: %v", row, m.target) + } + if m.row != row { + t.Fatalf("pointer routed to source row %d, want %d", m.row, row) + } + id, ok := m.first.RowID(row) + if !ok || id != m.target || id.Scope() != m.first.Rows() { + t.Fatalf("RowID(%d) = %v, %v; pointer target = %v, Rows = %v", row, id, ok, m.target, m.first.Rows()) + } +} + +func declaredRowHits(d *pageDriver, scope gfx.Scope) map[int]gfx.ID { + ids := make(map[int]gfx.ID) + for _, hit := range d.driver.Snapshot().Hits { + if row, ok := hit.ID.In(scope); ok && !hit.IsLabel { + ids[row] = hit.ID + } + } + return ids +} + +func TestTableRowIDRoutesRealPointerAcrossScroll(t *testing.T) { + m := newRowIdentityModel(50) + d := openPageWith(t, ui.PageConfig{View: m.page}, app.Config{OnPointer: m.pointer}) + m.press(t, d, 0) + firstRowID := m.target + m.press(t, d, 3) + if _, ok := m.first.RowID(20); ok { + t.Fatal("RowID names an undeclared row below the table's viewport") + } + + at := d.hit("source-3").Bounds + if err := d.driver.Scroll(gfx.ScrollEvent{X: at.X + 1, Y: at.Y + 1, DeltaY: 200, Precise: true}); err != nil { + t.Fatal(err) + } + if _, ok := m.first.RowID(0); ok { + t.Fatal("RowID still names row 0 after the second page replaces the first") + } + m.press(t, d, 10) + m.press(t, d, 14) + if firstRowID == m.target { + t.Fatal("a second-page source row reused the old first-page identity") + } + hits := declaredRowHits(d, m.first.Rows()) + for row, id := range hits { + if got, ok := m.first.RowID(row); !ok || got != id { + t.Fatalf("declared source row %d has RowID %v, %v, hit %v", row, got, ok, id) + } + } + if len(hits) == 0 { + t.Fatal("the second page declares no row hits") + } + for _, row := range []int{-1, 50, 100} { + if id, ok := m.first.RowID(row); ok || !id.IsZero() { + t.Fatalf("RowID(%d) = %v, %v, want zero, false", row, id, ok) + } + } +} + +func TestTableRowsIdentitiesArePerTableAndStableInAnOuterScroll(t *testing.T) { + m := newRowIdentityModel(40) + d := openPage(t, func(c ui.C) { + ui.Column(c).Fill().Children(func() { + ui.Scroll(c).Grow(1).Children(func() { + m.table(c, &m.first) + m.table(c, &m.second) + }) + }) + }) + firstID, firstOK := m.first.RowID(0) + secondID, secondOK := m.second.RowID(0) + if !firstOK || !secondOK || m.first.Rows().IsZero() || m.second.Rows().IsZero() { + t.Fatal("the default scopes do not expose declared rows") + } + if firstID == secondID || m.first.Rows() == m.second.Rows() { + t.Fatal("two tables on one page share row identities") + } + if row, ok := firstID.In(m.second.Rows()); ok || row != 0 { + t.Fatal("the first table's row belongs to the second table's scope") + } + for _, hit := range declaredRowHits(d, m.first.Rows()) { + if hit == secondID { + t.Fatal("the default scope passed to Table changed its row identity") + } + } + + at := d.hit("source-1").Bounds + if err := d.driver.Scroll(gfx.ScrollEvent{X: at.X + 1, Y: at.Y + 1, DeltaY: 20, Precise: true}); err != nil { + t.Fatal(err) + } + movedID, movedOK := m.first.RowID(0) + if !movedOK || movedID != firstID { + t.Fatal("a row's identity changed as an outer scroll moved it on screen") + } + if row, ok := movedID.In(m.second.Rows()); ok || row != 0 { + t.Fatal("a moved row entered another table's scope") + } + + d.repaint() + if next, ok := m.first.RowID(0); !ok || next != firstID { + t.Fatal("the first table's identity changed after a repaint with unchanged layout") + } +} + +func TestTableRowIDLastDeclarationAndZeroState(t *testing.T) { + var zero ui.TableState + if !zero.Rows().IsZero() { + t.Fatal("a zero state has a row scope before its first paint") + } + if id, ok := zero.RowID(0); ok || !id.IsZero() { + t.Fatal("a zero state has a row identity before its first paint") + } + + m := newRowIdentityModel(3) + tree := new(gfx.Tree) + page := tree.Feature("row-identity-test") + rows := tree.Sub(page, tree.Name("rows")) + other := tree.Sub(page, tree.Name("other")) + second := false + var state ui.TableState + d := openPage(t, func(c ui.C) { + ui.Table(c, &state, ui.TableSpec{Rows: rows, Source: &m.rows, RowHeight: 20}) + if second { + ui.Table(c, &state, ui.TableSpec{Rows: other, Source: &m.rows, RowHeight: 20}) + } + }) + firstID, ok := state.RowID(0) + if !ok || state.Rows() != rows { + t.Fatal("an explicitly named table did not publish its declared scope") + } + second = true + d.repaint() + lastID, ok := state.RowID(0) + if !ok || state.Rows() != other || lastID == firstID { + t.Fatal("the accessors do not describe the last table's declaration") + } + + m.rows = m.rows[:1] + d.repaint() + if id, ok := state.RowID(1); ok || !id.IsZero() { + t.Fatal("a row removed from the source retains its old identity") + } + if id, ok := state.RowID(0); !ok || id != lastID { + t.Fatal("the remaining source row's identity was not preserved") + } +} diff --git a/ui/table.go b/ui/table.go index ccd9f7985..23b144da3 100644 --- a/ui/table.go +++ b/ui/table.go @@ -85,13 +85,14 @@ type TableState struct { // Fill or Grow that is less than its rows need). Give config.OnScroll // state.Wheel, or call it for the table under the pointer. A table in a // ScrollArea is as tall as its rows and needs none of it. - Scroll ScrollState - selected int32 // 1 + the row, or 0 - sortColumn int32 // 1 + the column, or 0 - descending bool - reveal bool // scroll the selected row into view at the next paint - rows, page int32 // as of the last paint: how many rows, how many fit at once - scope gfx.Scope // the rows' identities, to tell a key meant for the table + Scroll ScrollState + selected int32 // 1 + the row, or 0 + sortColumn int32 // 1 + the column, or 0 + descending bool + reveal bool // scroll the selected row into view at the next paint + 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 } // Selected is the selected row, or -1. @@ -305,6 +306,7 @@ func (f *frame) paintTable(n *node) { first = min(max(int(math.Floor(float64((lo-top)/rowHeight))), 0), t.rows) last = min(max(int(math.Ceil(float64((hi-top)/rowHeight))), first), t.rows) } + t.state.rowFirst, t.state.rowEnd = int32(first), int32(last) if !scrolls && !sticky { f.paintTableHeader(t, Rect{X: r.X, Y: r.Y, Width: body.Width, Height: r.Height}, headerHeight, rowHeight) From 5bee0d351ce2efaaa0a57e72974c61d33fe4ca1f Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 01:35:33 +0800 Subject: [PATCH 10/86] feat: add editor gutter actions and directory paths Co-Authored-By: Claude Code --- app/driver_system_test.go | 20 +++++++++++ app/open_path.go | 7 ++++ app/painter_test.go | 43 ++++++++++++++++++++++++ cmd/viva/templates/code_editor.go.txt | 45 +++++++++++++++++++++---- components/code_editor.go | 45 +++++++++++++++++++++---- components/code_editor_test.go | 48 +++++++++++++++++++++++++++ 6 files changed, 196 insertions(+), 12 deletions(-) diff --git a/app/driver_system_test.go b/app/driver_system_test.go index 71a3d62df..3f40e132d 100644 --- a/app/driver_system_test.go +++ b/app/driver_system_test.go @@ -379,6 +379,26 @@ func TestDriverRecordsOpenPathAndOpensNothing(t *testing.T) { if opened, ok := driver.LastOpenedPath(); !ok || opened != file { t.Fatalf("LastOpenedPath = %q, %t", opened, ok) } + directory := t.TempDir() + if err := driver.QueueOpenDirectory(directory, nil); err != nil { + t.Fatal(err) + } + path, err := OpenDirectoryPath(OpenDirectoryOptions{Title: "Choose project"}) + if err != nil || path != directory { + t.Fatalf("OpenDirectoryPath = %q, %v; want %q", path, err, directory) + } + if opened, _ := driver.LastOpenedPath(); opened != file { + t.Fatalf("OpenDirectoryPath unexpectedly opened %q", opened) + } + if err := driver.QueueOpenDirectory("", ErrCanceled); err != nil { + t.Fatal(err) + } + if _, err := OpenDirectoryPath(OpenDirectoryOptions{}); !errors.Is(err, ErrCanceled) { + t.Fatalf("canceled OpenDirectoryPath error = %v", err) + } + if opened, ok := driver.LastOpenedPath(); !ok || opened != file { + t.Fatalf("LastOpenedPath = %q, %t", opened, ok) + } program := filepath.Join(t.TempDir(), "run.sh") if err := os.WriteFile(program, []byte("#!/bin/sh\n"), 0o755); err != nil { t.Fatal(err) diff --git a/app/open_path.go b/app/open_path.go index 6e360f175..a440dc5ed 100644 --- a/app/open_path.go +++ b/app/open_path.go @@ -42,6 +42,13 @@ func OpenPath(path string) error { return nativeOpenURL(openPathTarget(runtime.GOOS, path)) } +// OpenDirectoryPath asks the user to choose one existing local directory and +// returns its path through the same integration as OpenDirectory. Cancellation +// is ErrCanceled and the Web target returns ErrUnsupported. +func OpenDirectoryPath(options OpenDirectoryOptions) (string, error) { + return OpenDirectory(options) +} + // openPathTarget is what the platform's opener is given: a file URL where the // opener takes URLs (macOS), the path itself elsewhere. func openPathTarget(goos, path string) string { diff --git a/app/painter_test.go b/app/painter_test.go index aa7dc7c1f..4ada51e45 100644 --- a/app/painter_test.go +++ b/app/painter_test.go @@ -49,6 +49,49 @@ func TestPointerFocusDoesNotFlashKeyboardRing(t *testing.T) { } } +func TestCodeEditorGutterMarkerRoutesRealClicksAndIgnoresLineWhitespace(t *testing.T) { + var canvas gfx.Canvas + var editor components.CodeEditor + var clicks []gfx.ID + config := Config{Title: "gutter markers", Width: 400, Height: 200} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + editor.Paint(canvas, gfx.LightTheme(), gfx.Rect{X: 10, Y: 20, Width: 300, Height: 160}, components.CodeEditorSnapshot{ + ID: gfx.Item(1), Value: "first\n\nthird", GutterMarkers: []components.CodeEditorGutterMarker{ + {Line: 0, ID: gfx.Item(20), Color: gfx.RGB(20, 80, 160), Label: "Toggle breakpoint"}, + }, + }) + } + onClick(&config, func(id gfx.ID) { + if id == gfx.Item(20) { + clicks = append(clicks, id) + } + }) + painter := newTestPainter(t, &canvas, config) + marker, ok := canvas.HitBounds(gfx.Item(20)) + if !ok || marker.Width == 0 || marker.Height == 0 { + t.Fatalf("missing gutter marker hit: %+v, %v", marker, ok) + } + click := func(x, y float32) { + t.Helper() + for _, event := range []platform.PointerEvent{ + {Kind: platform.PointerDown, Button: gfx.PointerButtonPrimary, X: x, Y: y}, + {Kind: platform.PointerUp, Button: gfx.PointerButtonPrimary, X: x, Y: y}, + } { + if _, err := painter.pointerEvent(event); err != nil { + t.Fatal(err) + } + } + } + click(marker.X+1, marker.Y+marker.Height/2) + if len(clicks) != 1 || clicks[0] != gfx.Item(20) { + t.Fatalf("marker-only clicks = %v, want [20]", clicks) + } + click(marker.X+1, marker.Y+marker.Height*1.5) + if len(clicks) != 1 { + t.Fatalf("blank-line whitespace clicked a marker: %v", clicks) + } +} + func TestFocusTrapEscapeDismissesAndRestoresFocus(t *testing.T) { var canvas gfx.Canvas open := false diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index 063598031..5c50a4234 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -35,15 +35,16 @@ type codeExtraCaret struct { } // CodeEditorGutterMarker decorates one zero-based logical line with a dot in the -// gutter. It is purely visual: it is not hit-tested and is not exposed to -// assistive technology, so state it carries must also be available elsewhere. -// Markers are sorted by Line and unique; a wrapped line paints its marker only -// once. They follow logical line numbers, not edits, so the caller updates the -// slice when lines are inserted or removed. Unsorted or repeated lines are not -// painted. +// gutter. A nonzero ID exposes that line's marker lane as a button; the caller +// owns the ID and handles clicks through the canvas. Markers are sorted by Line +// and unique; a wrapped line paints and exposes its marker only once. They follow +// logical line numbers, not edits, so the caller updates the slice when lines are +// inserted or removed. Unsorted or repeated lines are not painted or hit-tested. type CodeEditorGutterMarker struct { Line int + ID gfx.ID Color gfx.Color + Label string } // CodeEditorFoldRange hides logical lines after Header through LastLine, @@ -556,6 +557,38 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. } canvas.HitWithOptions(snapshot.ID, bounds, snapshot.Label, options) } + if markerLane > 0 && len(snapshot.GutterMarkers) != 0 { + markerIndex := 0 + if firstRow < len(editor.rows) { + firstLine := int(editor.rows[firstRow].line) + markerIndex = sort.Search(len(snapshot.GutterMarkers), func(i int) bool { return snapshot.GutterMarkers[i].Line >= firstLine }) + } + for index := firstRow; index < len(editor.rows); index++ { + y := content.Y + float32(index)*lineHeight - editor.scrollY + if y >= content.Y+content.Height { + break + } + if !editor.firstOfLine(index) { + continue + } + row := editor.rows[index] + for markerIndex < len(snapshot.GutterMarkers) && snapshot.GutterMarkers[markerIndex].Line < int(row.line) { + markerIndex++ + } + if markerIndex >= len(snapshot.GutterMarkers) || snapshot.GutterMarkers[markerIndex].Line != int(row.line) { + continue + } + marker := snapshot.GutterMarkers[markerIndex] + markerIndex++ + if !marker.ID.IsZero() { + label := marker.Label + if label == "" { + label = "Gutter marker" + } + canvas.HitWithOptions(marker.ID, gfx.Rect{X: markerX, Y: y, Width: markerLane, Height: lineHeight}, label, gfx.HitOptions{Role: gfx.RoleButton, Disabled: snapshot.Disabled}) + } + } + } if foldLane > 0 && len(snapshot.FoldMarkers) != 0 { canvas.Clip(gfx.Rect{X: foldX, Y: content.Y, Width: foldLane, Height: content.Height}) markerIndex := 0 diff --git a/components/code_editor.go b/components/code_editor.go index 055eb78e9..f6d6a5f0f 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -35,15 +35,16 @@ type codeExtraCaret struct { } // CodeEditorGutterMarker decorates one zero-based logical line with a dot in the -// gutter. It is purely visual: it is not hit-tested and is not exposed to -// assistive technology, so state it carries must also be available elsewhere. -// Markers are sorted by Line and unique; a wrapped line paints its marker only -// once. They follow logical line numbers, not edits, so the caller updates the -// slice when lines are inserted or removed. Unsorted or repeated lines are not -// painted. +// gutter. A nonzero ID exposes that line's marker lane as a button; the caller +// owns the ID and handles clicks through the canvas. Markers are sorted by Line +// and unique; a wrapped line paints and exposes its marker only once. They follow +// logical line numbers, not edits, so the caller updates the slice when lines are +// inserted or removed. Unsorted or repeated lines are not painted or hit-tested. type CodeEditorGutterMarker struct { Line int + ID gfx.ID Color gfx.Color + Label string } // CodeEditorFoldRange hides logical lines after Header through LastLine, @@ -556,6 +557,38 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. } canvas.HitWithOptions(snapshot.ID, bounds, snapshot.Label, options) } + if markerLane > 0 && len(snapshot.GutterMarkers) != 0 { + markerIndex := 0 + if firstRow < len(editor.rows) { + firstLine := int(editor.rows[firstRow].line) + markerIndex = sort.Search(len(snapshot.GutterMarkers), func(i int) bool { return snapshot.GutterMarkers[i].Line >= firstLine }) + } + for index := firstRow; index < len(editor.rows); index++ { + y := content.Y + float32(index)*lineHeight - editor.scrollY + if y >= content.Y+content.Height { + break + } + if !editor.firstOfLine(index) { + continue + } + row := editor.rows[index] + for markerIndex < len(snapshot.GutterMarkers) && snapshot.GutterMarkers[markerIndex].Line < int(row.line) { + markerIndex++ + } + if markerIndex >= len(snapshot.GutterMarkers) || snapshot.GutterMarkers[markerIndex].Line != int(row.line) { + continue + } + marker := snapshot.GutterMarkers[markerIndex] + markerIndex++ + if !marker.ID.IsZero() { + label := marker.Label + if label == "" { + label = "Gutter marker" + } + canvas.HitWithOptions(marker.ID, gfx.Rect{X: markerX, Y: y, Width: markerLane, Height: lineHeight}, label, gfx.HitOptions{Role: gfx.RoleButton, Disabled: snapshot.Disabled}) + } + } + } if foldLane > 0 && len(snapshot.FoldMarkers) != 0 { canvas.Clip(gfx.Rect{X: foldX, Y: content.Y, Width: foldLane, Height: content.Height}) markerIndex := 0 diff --git a/components/code_editor_test.go b/components/code_editor_test.go index 5aac722a3..d84409130 100644 --- a/components/code_editor_test.go +++ b/components/code_editor_test.go @@ -175,6 +175,54 @@ func TestCodeEditorGutterMarkersIgnoreOutOfContractInput(t *testing.T) { } } +func TestCodeEditorGutterMarkersExposeOnlyTheirVisibleLineLanes(t *testing.T) { + fixture := newCodeFixture("first\n\nthird") + fixture.snapshot.Wrap = true + fixture.snapshot.GutterMarkers = []CodeEditorGutterMarker{ + {Line: 0, ID: gfx.Item(20), Color: gfx.RGB(20, 80, 160), Label: "Breakpoint"}, + {Line: 2, Color: gfx.RGB(180, 40, 60)}, + } + fixture.paint() + var hit gfx.Hit + found := false + for _, candidate := range fixture.canvas.Hits() { + if candidate.ID == gfx.Item(20) { + hit, found = candidate, true + } + if candidate.ID == gfx.Item(21) { + t.Fatal("a marker without an ID was hit-testable") + } + } + if !found || hit.Role != gfx.RoleButton || hit.Label != "Breakpoint" || hit.Bounds.Height != fixture.editor.lineHeight { + t.Fatalf("line marker hit = %+v, %v", hit, found) + } + blankY := hit.Bounds.Y + hit.Bounds.Height + 1 + if point := (gfx.Point{X: hit.Bounds.X + hit.Bounds.Width/2, Y: blankY}); point.Y < fixture.editor.content.Y+2*fixture.editor.lineHeight { + for _, candidate := range fixture.canvas.Hits() { + if candidate.ID != gfx.Item(1) && point.X >= candidate.Bounds.X && point.X < candidate.Bounds.X+candidate.Bounds.Width && point.Y >= candidate.Bounds.Y && point.Y < candidate.Bounds.Y+candidate.Bounds.Height { + t.Fatalf("blank line had interactive hit %+v", candidate) + } + } + } + + fixture.snapshot.Disabled = true + fixture.paint() + for _, candidate := range fixture.canvas.Hits() { + if candidate.ID == gfx.Item(20) && !candidate.Disabled { + t.Fatal("a disabled editor exposed an enabled gutter marker") + } + } +} + +func TestCodeEditorGutterMarkerSteadyPaintDoesNotAllocate(t *testing.T) { + fixture := newCodeFixture("first\nsecond") + fixture.snapshot.GutterMarkers = []CodeEditorGutterMarker{{Line: 0, ID: gfx.Item(20), Color: gfx.RGB(20, 80, 160), Label: "Line marker"}} + fixture.paint() + if allocations := testing.AllocsPerRun(50, fixture.paint); allocations != 0 { + t.Fatalf("steady gutter-marker paint allocated %g times", allocations) + } +} + func TestCodeEditorGutterMarkersFadeWhenDisabled(t *testing.T) { fixture := newCodeFixture("one") fixture.bounds.Height = 600 From 8239839dc9266e88c239b1e8d5cb0252c969ad3f Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 02:10:04 +0800 Subject: [PATCH 11/86] feat(table): scroll wide tables left and right under a fixed header A ui.Table whose explicit column widths overflow the room it was given now scrolls horizontally, its header riding along with its rows. TableState.Scroll reports the offsets, geometry and viewports of both axes, the wheel moves the columns horizontally or with Shift held (as a Sideways ScrollArea takes it), and TableSpec.HorizontalScrollbar names a bar below the body that drags like the vertical one. ScrollbarGutter now reserves space for either bar. The default layouts are unchanged: a table whose last column has no width still lets that column take whatever is left and never scrolls across, and a table inside a ScrollArea leaves its width to the area, sideways or not. Bounds are clamped to MaxX/MaxY on every paint, and a warm wide table still paints with zero allocations (BenchmarkWideTable and the existing table benchmarks at 0 allocs/op). Closes the horizontal half of the datagrid gap registered in dbxui: wide grids can now be panned, and reveal/freeze features have a viewport to target. Co-Authored-By: Claude Code --- ui/page.go | 14 +- ui/scroll.go | 2 +- ui/table.go | 161 ++++++++++---- ui/table_scroll_horizontal_test.go | 340 +++++++++++++++++++++++++++++ 4 files changed, 470 insertions(+), 47 deletions(-) create mode 100644 ui/table_scroll_horizontal_test.go diff --git a/ui/page.go b/ui/page.go index 7ac885140..c8bb7c471 100644 --- a/ui/page.go +++ b/ui/page.go @@ -566,7 +566,7 @@ func (p *Page) hoverPlaceAt(x, y float32) gfx.ID { } for i := range p.tables { route := &p.tables[i] - if !route.scrolls || route.bar.IsZero() || !pointInRect(x, y, route.bounds) { + if (!route.scrolls && !route.sideways) || (route.bar.IsZero() && route.horizontal.IsZero()) || !pointInRect(x, y, route.bounds) { continue } if area := route.bounds.Width * route.bounds.Height; best.IsZero() || area < bestArea { @@ -1135,13 +1135,17 @@ func (p *Page) Wheel(event gfx.ScrollEvent) gfx.EventResult { } for i := len(p.tables) - 1; i >= 0; i-- { route := &p.tables[i] - if !route.scrolls || !pointInRect(event.X, event.Y, route.bounds) { + if !route.scrolls && !route.sideways || !pointInRect(event.X, event.Y, route.bounds) { continue } - if result := route.state.Wheel(event); result.Handled { - result.Repaint = result.Repaint || moved - return result + state := &route.state.Scroll + dx, dy := state.wheelSteps(event) + if !state.canScroll(dx, dy) { + continue } + result := state.Wheel(event) + result.Repaint = result.Repaint || moved + return result } if moved { return gfx.EventResult{Handled: true, Repaint: true} diff --git a/ui/scroll.go b/ui/scroll.go index d0c970b11..0d3293b11 100644 --- a/ui/scroll.go +++ b/ui/scroll.go @@ -2,7 +2,7 @@ package ui import "github.com/vivaui/viva/gfx" -// ScrollState is the scroll position of one ScrollArea. It lives in the view, keyed +// ScrollState is a scroll position: one ScrollArea's, or a Table's. It lives in the view, keyed // by the area's identity, so the application keeps nothing: declare the area with an // identity and give the wheel to the view. // diff --git a/ui/table.go b/ui/table.go index 23b144da3..d68917d61 100644 --- a/ui/table.go +++ b/ui/table.go @@ -55,26 +55,33 @@ type TableSpec struct { // Striped shades every second row. Striped bool // Scrollbar is the identity of the vertical bar a table that scrolls itself - // draws under its columns; zero paints the bar without an action. A table - // inside a ScrollArea takes the area's bar instead and ignores this. + // draws under its columns; zero paints the bar without an action. Scrollbar gfx.ID - // ScrollbarLabel names that bar for assistive technology; empty is "Table - // rows". - ScrollbarLabel string - // ScrollbarSize is the bar's thickness; zero keeps the thin hover default. + // HorizontalScrollbar is the identity of the bar below the body when the + // columns overflow their viewport; zero paints that bar without an action. + HorizontalScrollbar gfx.ID + // ScrollbarLabel names the vertical bar for assistive technology; empty is + // "Table rows". HorizontalScrollbarLabel does the same for the horizontal + // bar, whose default is "Table columns". + ScrollbarLabel string + HorizontalScrollbarLabel string + // ScrollbarSize is the bars' thickness; zero keeps the thin hover default. ScrollbarSize float32 - // ScrollbarGutter is the strip reserved beside the columns for the bar; zero - // lets the bar sit over their edge. The columns lose that width. + // ScrollbarGutter is the strip reserved beside or below the cells for an + // overflowing bar; zero lets the bars sit over their edges. The columns lose + // the width of a vertical gutter, and the rows the height of a horizontal one. ScrollbarGutter float32 } // tableRoute is a Table of the last paint that scrolls itself, and where: the // page gives it the wheel and the keys that reach it. type tableRoute struct { - state *TableState - bounds Rect - scrolls bool - bar gfx.ID + state *TableState + bounds Rect + scrolls bool + sideways bool + bar gfx.ID + horizontal gfx.ID } // TableState is what a Table keeps between frames, in the application's state: the @@ -82,9 +89,11 @@ type tableRoute struct { // scrolled. The zero value is a table with nothing selected, unsorted, at the top. type TableState struct { // Scroll is the scroll position of a table with a height of its own (a Height, - // Fill or Grow that is less than its rows need). Give config.OnScroll + // Fill or Grow that is less than its rows need), and, when its explicit column + // widths are wider than it, how far across it is scrolled. Give config.OnScroll // state.Wheel, or call it for the table under the pointer. A table in a - // ScrollArea is as tall as its rows and needs none of it. + // ScrollArea is as tall as its rows, as wide as its area makes it, and needs + // none of it. Scroll ScrollState selected int32 // 1 + the row, or 0 sortColumn int32 // 1 + the column, or 0 @@ -175,6 +184,15 @@ type tableDecl struct { // the rows on screen are read and painted; given a smaller height it scrolls its // rows under a fixed header, by state.Scroll. // +// A table of explicit column widths wider than itself also scrolls left and +// right under its fixed header, the header riding along with its rows: the +// horizontal wheel, Shift with the wheel, or a horizontal scrollbar +// (HorizontalScrollbar) moves the columns, and state.Scroll reports how far +// across it is. A table whose last column has no width keeps the layout it +// always had: the last column takes what is left, however narrow that is. A +// table inside a ScrollArea is never scrolled across by itself; the area owns +// its width, sideways or not. +// // tbl := f.Table(&state, ui.TableSpec{Rows: rows, Header: heads, Columns: cols, Headers: titles, Sortable: sortable, Source: &data}) // if row, ok := tbl.RowClicked(); ok { state.Select(row) } // if col, ok := tbl.HeaderClicked(); ok { state.SortBy(col); data.Sort(state.Sort()) } @@ -236,6 +254,16 @@ func (f *frame) measureTable(n *node) { n.pref = [2]float32{width, t.headerHeight(f.theme) + float32(t.rows)*t.rowHeight(f.theme)} } +// tableColumnsWidth is the total width a table's columns declare: the fixed +// widths of every column, zero for the flexible one that takes what is left. +func tableColumnsWidth(columns []components.TableColumn) float32 { + width := float32(0) + for _, column := range columns { + width += max(column.Width, 0) + } + return width +} + // scrollAncestor is the state and viewport of the ScrollArea nearest around element n. func (f *frame) scrollAncestor(n *node) (*ScrollState, Rect) { for p := n.parent; p >= 0; p = f.nodes[p].parent { @@ -257,29 +285,64 @@ func (f *frame) paintTable(n *node) { canvas := f.canvas body := Rect{X: r.X, Y: r.Y + headerHeight, Width: r.Width, Height: max(r.Height-headerHeight, 0)} content := float32(t.rows) * rowHeight + gutter := max(t.spec.ScrollbarGutter, 0) + // A table whose last column has no width keeps the layout it always had: the + // last column takes what is left, however narrow that is. Only explicit widths + // that do not fit move the whole grid across, with the header riding along — + // and never inside a ScrollArea, whose viewport (sideways or not) owns the + // table's width; such a table is only ever clipped. + declaredWidth := tableColumnsWidth(t.spec.Columns) + flexibleLast := len(t.spec.Columns) == 0 || t.spec.Columns[len(t.spec.Columns)-1].Width <= 0 + selfContained := true + if ancestor, _ := f.scrollAncestor(n); ancestor != nil { + selfContained = false + } + verticalGutter := float32(0) + if body.Height+0.5 < content { + verticalGutter = min(gutter, body.Width) + body.Width -= verticalGutter + } + sideways := selfContained && !flexibleLast && declaredWidth > body.Width+0.5 + horizontalGutter := float32(0) + if sideways { + horizontalGutter = min(gutter, body.Height) + body.Height -= horizontalGutter + } scrolls := body.Height+0.5 < content - gutter := float32(0) - if scrolls { - gutter = min(max(t.spec.ScrollbarGutter, 0), r.Width) - body.Width = r.Width - gutter + contentWidth := body.Width + if !flexibleLast && declaredWidth > contentWidth { + contentWidth = declaredWidth } if f.page != nil { - f.page.tables = append(f.page.tables, tableRoute{state: t.state, bounds: r, scrolls: scrolls, bar: t.spec.Scrollbar}) + f.page.tables = append(f.page.tables, tableRoute{ + state: t.state, bounds: r, scrolls: scrolls, sideways: sideways, + bar: t.spec.Scrollbar, horizontal: t.spec.HorizontalScrollbar, + }) } - var offset float32 + var offset, offsetX float32 s := &t.state.Scroll + s.sideways = true // TableState.Wheel accepts both axes; only the overflows below can move. s.Content, s.Viewport = content, min(body.Height, content) if scrolls { s.Viewport = body.Height } + s.ContentWidth, s.ViewportWidth = contentWidth, body.Width + if !sideways { + s.OffsetX = 0 // an outer ScrollArea owns the table's geometry instead + } t.state.rows, t.state.scope = int32(t.rows), t.spec.Rows if t.state.reveal { f.revealSelected(n, t, body, rowHeight, headerHeight, scrolls) } s.Offset = min(max(s.Offset, 0), s.Max()) + s.OffsetX = min(max(s.OffsetX, 0), s.MaxX()) if scrolls { offset = snapScroll(s.Offset) } + if sideways { + offsetX = snapScroll(s.OffsetX) + } + left := body.X - offsetX // The rows on screen: the table's body, cut by every clip it sits in. top := body.Y - offset @@ -309,20 +372,22 @@ func (f *frame) paintTable(n *node) { t.state.rowFirst, t.state.rowEnd = int32(first), int32(last) if !scrolls && !sticky { - f.paintTableHeader(t, Rect{X: r.X, Y: r.Y, Width: body.Width, Height: r.Height}, headerHeight, rowHeight) + // Height: r.Height lets paintTableHeader keep its rule of the header's + // bottom rule needing room below it. + f.paintTableHeader(t, Rect{X: left, Y: r.Y, Width: contentWidth, Height: r.Height}, body, headerHeight, rowHeight, sideways) } if last > first { extra := float32(0) if top+float32(last)*rowHeight < r.Y+r.Height { extra = 1 // a divider under the last row painted, when something follows or the table is taller } - if scrolls { + if scrolls || sideways { canvas.Clip(body) } else if sticky { below := headerY + headerHeight canvas.Clip(Rect{X: r.X, Y: below, Width: body.Width, Height: max(r.Y+r.Height-below, 0)}) } - table := components.BeginTable(canvas, f.theme, Rect{X: r.X, Y: top + float32(first)*rowHeight, Width: body.Width, Height: float32(last-first)*rowHeight + extra}, t.spec.Columns). + table := components.BeginTable(canvas, f.theme, Rect{X: left, Y: top + float32(first)*rowHeight, Width: contentWidth, Height: float32(last-first)*rowHeight + extra}, t.spec.Columns). RowHeight(rowHeight).FontSize(t.spec.FontSize).CellPadding(t.spec.CellPadding) w := &f.widgets if cap(w.cells) < len(t.spec.Columns) { @@ -336,7 +401,7 @@ func (f *frame) paintTable(n *node) { if t.spec.Striped && row%2 == 1 { stripe := f.theme.Muted stripe.Alpha *= 0.6 - canvas.Fill(Rect{X: r.X, Y: top + float32(row)*rowHeight, Width: body.Width, Height: rowHeight}, stripe) + canvas.Fill(Rect{X: left, Y: top + float32(row)*rowHeight, Width: contentWidth, Height: rowHeight}, stripe) } // A press on the bar owns the pointer: the row under it neither // highlights nor takes a click while the bar is held. @@ -346,7 +411,7 @@ func (f *frame) paintTable(n *node) { } table.RowState(id, cells, components.TableRowState{Selected: row == t.state.Selected()}) } - if scrolls || sticky { + if scrolls || sideways || sticky { canvas.Unclip() } } @@ -354,40 +419,48 @@ func (f *frame) paintTable(n *node) { if headerHeight > 0 { canvas.Fill(Rect{X: r.X, Y: headerY, Width: body.Width, Height: headerHeight}, f.theme.Background) } - f.paintTableHeader(t, Rect{X: r.X, Y: headerY, Width: body.Width, Height: r.Height}, headerHeight, rowHeight) + f.paintTableHeader(t, Rect{X: left, Y: headerY, Width: contentWidth, Height: r.Height}, body, headerHeight, rowHeight, sideways) } - if scrolls { - f.paintTableScrollbar(t, body, content, offset) + if scrolls || sideways { + f.paintTableScrollbars(t, r, body, gfx.Size{Width: contentWidth, Height: content}, offsetX, offset) } } -// paintTableScrollbar paints and drags the bar of a Table that scrolls itself. -// The bar is the hover style announced for the area: the page's pointer reveals -// it, and it sits in the gutter beside the columns when one is asked for. -func (f *frame) paintTableScrollbar(t *tableDecl, body Rect, content, offset float32) { - bounds := Rect{X: body.X, Y: body.Y, Width: body.Width + float32(max(t.spec.ScrollbarGutter, 0)), Height: body.Height} - if t.spec.ScrollbarGutter <= 0 { - bounds.Width = body.Width - } - revealed := f.page == nil || f.page.pointerOver(bounds) || t.state.Scroll.dragging +// paintTableScrollbars paints and drags the bars of a Table that scrolls itself. +// They share the body's content extents and offsets; a bar sits in the gutter the +// spec asked for and over the body's edge when it did not. +func (f *frame) paintTableScrollbars(t *tableDecl, r, body Rect, content gfx.Size, offsetX, offsetY float32) { + revealed := f.page == nil || f.page.pointerOver(r) || t.state.Scroll.dragging label := t.spec.ScrollbarLabel if label == "" { label = "Table rows" } + horizontalLabel := t.spec.HorizontalScrollbarLabel + if horizontalLabel == "" { + horizontalLabel = "Table columns" + } size := t.spec.ScrollbarSize if size <= 0 && f.page != nil { size = f.page.config.ScrollbarSize } - area := components.BeginScrollArea(f.canvas, f.theme, bounds, gfx.Size{Height: content}). - Offset(0, offset). + // The bars sit at the table's own edges, over the body's clips: the component + // places their tracks from these bounds alone, so a gutter only trims what the + // columns and rows paint under them. + areaBounds := Rect{X: r.X, Y: body.Y, Width: r.Width, Height: body.Height} + area := components.BeginScrollArea(f.canvas, f.theme, areaBounds, content). + Offset(offsetX, offsetY). ScrollbarSize(size). HoverScrollbars(revealed). - VerticalScrollbar(t.spec.Scrollbar, label, "") + VerticalScrollbar(t.spec.Scrollbar, label, ""). + HorizontalScrollbar(t.spec.HorizontalScrollbar, horizontalLabel, "") geometry := area.Geometry() area.EndContent() if !t.spec.Scrollbar.IsZero() && geometry.MaxOffsetY > 0 { f.dragScrollbar(&t.state.Scroll, t.spec.Scrollbar, geometry, axisY) } + if !t.spec.HorizontalScrollbar.IsZero() && geometry.MaxOffsetX > 0 { + f.dragScrollbar(&t.state.Scroll, t.spec.HorizontalScrollbar, geometry, axisX) + } } // revealSelected scrolls the selected row into view after a key moved it: the table's @@ -427,11 +500,17 @@ func (f *frame) revealSelected(n *node, t *tableDecl, body Rect, rowHeight, head // paintTableHeader paints the header row and, over it, the hit regions and arrow // of the sortable columns. -func (f *frame) paintTableHeader(t *tableDecl, r Rect, headerHeight, rowHeight float32) { +func (f *frame) paintTableHeader(t *tableDecl, r, viewport Rect, headerHeight, rowHeight float32, sideways bool) { if headerHeight <= 0 { return } canvas := f.canvas + if sideways { + // The header scrolls with the body, clipped to the same columns; without + // an overflow it is laid out over the table, as it always was. + canvas.Clip(Rect{X: viewport.X, Y: r.Y, Width: viewport.Width, Height: headerHeight}) + defer canvas.Unclip() + } bounds := Rect{X: r.X, Y: r.Y, Width: r.Width, Height: headerHeight} cells := components.TableCellBounds(t.spec.Columns, bounds, f.widgets.rects[:0]) f.widgets.rects = cells[:0] diff --git a/ui/table_scroll_horizontal_test.go b/ui/table_scroll_horizontal_test.go new file mode 100644 index 000000000..ce6b2d41b --- /dev/null +++ b/ui/table_scroll_horizontal_test.go @@ -0,0 +1,340 @@ +package ui + +import ( + "testing" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// wideFourColumns is four explicitly 120-wide columns: 480 in a table given +// less, so it scrolls them left and right. Package-level slices, like +// tableColumns, because a slice literal built inside a paint allocates every +// frame. +var wideFourColumns = []components.TableColumn{{Width: 120}, {Width: 120}, {Width: 120}, {Width: 120}} + +var wideSixColumns = []components.TableColumn{{Width: 120}, {Width: 120}, {Width: 120}, {Width: 120}, {Width: 120}, {Width: 120}} + +var fourTitles = []string{"A", "B", "C", "D"} +var sixTitles = []string{"A", "B", "C", "D", "E", "F"} +var allSortableSix = []bool{true, true, true, true, true, true} + +// A table whose explicit columns do not fit the room it was given scrolls them +// left and right, and its header rides along with its rows. +func TestTableScrollsItsColumnsWhenTheyDoNotFit(t *testing.T) { + theme := gfx.LightTheme() + viewport := gfx.Size{Width: 320, Height: 240} + rows := make(TableRows, 50) + for i := range rows { + rows[i] = []string{"aa", "bb", "cc", "dd"} + } + var state TableState + var view View + canvas := testCanvas() + // headerX and rowX are read from cell hits: the header is not sortable + // here, so the header texts are the witnesses of where the header sits. + var headerX, rowX float32 + paint := func() { + view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: wideFourColumns, Headers: fourTitles, Sortable: []bool{true, false, false, false}, Source: &rows}).Size(viewport.Width, viewport.Height) + }) + }) + headerX, rowX = headerAndRowX(canvas) + } + paint() + if max := state.Scroll.MaxX(); max != 160 { // 480 declared in 320 shown + t.Fatalf("MaxX = %v, want 160", max) + } + beforeHeader, beforeRow := headerX, rowX + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 60, Precise: true}) + canvas.Reset() + paint() + if state.Scroll.OffsetX != 60 { + t.Errorf("OffsetX = %v, want 60", state.Scroll.OffsetX) + } + if moved := headerX - beforeHeader; moved != -60 { + t.Errorf("the header moved %v, want it left by 60", moved) + } + if moved := rowX - beforeRow; moved != -60 { + t.Errorf("the body moved %v, want it left by 60 with the header", moved) + } + + // Out of range on either side stays in bounds. + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 1e5, Precise: true}) + canvas.Reset() + paint() + if got := state.Scroll.OffsetX; got != state.Scroll.MaxX() { + t.Errorf("past the end OffsetX = %v, want %v", got, state.Scroll.MaxX()) + } + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: -1e5, Precise: true}) + canvas.Reset() + paint() + if got := state.Scroll.OffsetX; got != 0 { + t.Errorf("before the start OffsetX = %v, want 0", got) + } +} + +func headerAndRowX(canvas *gfx.Canvas) (headerX, rowX float32) { + for _, text := range canvas.Texts() { + if text.Value == "B" { + headerX = text.Bounds.X + } + if text.Value == "bb" { + rowX = text.Bounds.X + } + } + return +} + +// The wheel moves the columns of a wide table and its rows at once: a +// horizontal trackpad delta (or the wheel with Shift held, as for a Sideways +// area) moves the columns while the plain wheel still moves the rows. +func TestTableWheelScrollsBothWays(t *testing.T) { + theme := gfx.LightTheme() + viewport := gfx.Size{Width: 320, Height: 240} + rows := make(TableRows, 200) + for i := range rows { + rows[i] = []string{"aa", "bb", "cc", "dd"} + } + var state TableState + var view View + canvas := testCanvas() + paint := func() { + canvas.Reset() + view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, TableSpec{Rows: tableScope, Columns: wideFourColumns, Headers: fourTitles, Source: &rows}).Size(viewport.Width, viewport.Height) + }) + }) + } + paint() + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 30, Precise: true}) + paint() + if state.Scroll.OffsetX != 30 || state.Scroll.Offset != 0 { + t.Errorf("a horizontal delta left the table at (%v, %v), want (30, 0)", state.Scroll.OffsetX, state.Scroll.Offset) + } + state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 30, Precise: true, Modifiers: gfx.ModifierShift}) + paint() + if state.Scroll.OffsetX != 60 { + t.Errorf("Shift with the wheel moved the columns to %v, want 60", state.Scroll.OffsetX) + } + if state.Scroll.Offset != 0 { + t.Errorf("a horizontal gesture also moved the rows to %v, want 0", state.Scroll.Offset) + } + before := state.Scroll.Offset + state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 40, Precise: true}) + paint() + if state.Scroll.Offset == before { + t.Error("the plain wheel no longer scrolls the rows") + } +} + +// A table whose columns fit (the last flexible, or all of them explicit and +// room still left) keeps the layout it always had: no horizontal offset, and +// the last column takes whatever is left. +func TestTableThatFitsDoesNotScrollAcross(t *testing.T) { + theme := gfx.LightTheme() + viewport := gfx.Size{Width: 320, Height: 240} + rows := make(TableRows, 50) + for i := range rows { + rows[i] = []string{"aa", "bb", "cc"} + } + cases := []struct { + name string + columns []components.TableColumn + }{ + {"flexible last", []components.TableColumn{{Width: 100}, {Width: 100}, {}}}, + {"all explicit", []components.TableColumn{{Width: 60}, {Width: 60}, {Width: 60}}}, + } + for _, c := range cases { + headers := []string{"A", "B", "C"} + var state TableState + var view View + canvas := testCanvas() + paint := func() { + canvas.Reset() + view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, TableSpec{Rows: tableScope, Columns: c.columns, Headers: headers, Source: &rows}).Size(viewport.Width, viewport.Height) + }) + }) + } + paint() + if max := state.Scroll.MaxX(); max != 0 { + t.Errorf("%s: a fitting table scrolls across, MaxX %v", c.name, max) + } + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 30, Precise: true}) + paint() + if state.Scroll.OffsetX != 0 { + t.Errorf("%s: the wheel moved a fitting table to %v", c.name, state.Scroll.OffsetX) + } + if state.Scroll.ContentWidth != state.Scroll.ViewportWidth { + t.Errorf("%s: content is %v wide in a %v viewport, want them equal", c.name, state.Scroll.ContentWidth, state.Scroll.ViewportWidth) + } + } +} + +// A table inside a ScrollArea is as tall as its rows and as wide as the area +// makes it; the area scrolls left and right when it is Sideways, and the table +// leaves the horizontal offset to it. +func TestTableInAScrollAreaLeavesAcrossToTheArea(t *testing.T) { + theme := gfx.LightTheme() + viewport := gfx.Size{Width: 300, Height: 200} + rows := make(TableRows, 50) + for i := range rows { + rows[i] = []string{"aa", "bb", "cc", "dd"} + } + for _, sideways := range []bool{false, true} { + var state TableState + var view View + canvas := testCanvas() + paint := func() { + canvas.Reset() + view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { + f.Column().Fill().Children(func() { + area := f.ScrollArea(listID).Grow(1) + if sideways { + area = area.Sideways() + } + area.Children(func() { + f.Table(&state, TableSpec{Rows: tableScope, Columns: wideFourColumns, Headers: fourTitles, Source: &rows}) + }) + }) + }) + } + paint() + area := view.ScrollState(listID) + want := float32(300) + if sideways { + want = 480 + } + if area.ContentWidth != want { + t.Errorf("sideways %v: the area's content is %v wide, want %v", sideways, area.ContentWidth, want) + } + // However wide its columns are, a table in an area leaves the horizontal + // offset to it: it never moves itself across, sideways area or not. + if state.Scroll.OffsetX != 0 { + t.Errorf("sideways %v: the table moved itself across to %v", sideways, state.Scroll.OffsetX) + } + } +} + +// The horizontal scrollbar drags like the vertical one: a press on the thumb +// holds it, a drag moves the columns with it, and the release lets go. +func TestTableHorizontalScrollbarDrags(t *testing.T) { + theme := gfx.LightTheme() + viewport := gfx.Size{Width: 320, Height: 240} + rows := make(TableRows, 10) + for i := range rows { + rows[i] = []string{"aa", "bb", "cc", "dd"} + } + var state TableState + var view View + canvas := testCanvas() + paint := func(*gfx.Canvas, gfx.Size) { + canvas.Reset() + view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, TableSpec{ + Rows: tableScope, Header: headerScope, Columns: wideFourColumns, + Headers: fourTitles, Sortable: []bool{true, true, true, true}, Source: &rows, + HorizontalScrollbar: gfx.Item(901), + }).Size(viewport.Width, viewport.Height) + }) + }) + } + paint(canvas, gfx.Size{}) + // A 320 viewport shows the first two 120 columns whole and the third cut at + // its right edge; the fourth is off screen and declares no hit. The header + // scissored by the same clip as the body shows three. + if hits := tableHeaderHits(canvas, headerScope); len(hits) != 3 { + t.Fatalf("the header shows %d cells in a 320 viewport showing 320 of 480 px, want the 2 whole and 1 cut", len(hits)) + } + hbar := hitByID(canvas, gfx.Item(901)) + thumb := hbar.Bounds + deliver := func(kind gfx.PointerEventKind, x, y float32) bool { + return canvas.DeliverPointer(gfx.PointerEvent{Kind: kind, Button: gfx.PointerButtonPrimary, Target: gfx.Item(901), Captured: kind != gfx.PointerDown, X: x, Y: y}, gfx.Size{Width: viewport.Width, Height: viewport.Height}, paint) + } + x, y := thumb.X+2, thumb.Y+thumb.Height/2 + if ok := deliver(gfx.PointerDown, x, y); !ok { + t.Fatal("a press on the horizontal bar was not taken") + } + if !deliver(gfx.PointerMove, x+40, y) { + t.Fatal("the drag of the bar was not taken") + } + if got := state.Scroll.OffsetX; got <= 0 || got > 160 { + t.Errorf("dragging the bar left the columns at %v, want some of the 160 px of range", got) + } + deliver(gfx.PointerUp, x+40, y) + paint(canvas, gfx.Size{}) + if state.Scroll.Dragging() { + t.Error("the bar is still dragging after the release") + } +} + +func hitByID(canvas *gfx.Canvas, id gfx.ID) gfx.Hit { + var hit gfx.Hit + for _, h := range canvas.Hits() { + if h.ID == id { + return h + } + } + return hit +} + +func tableHeaderHits(canvas *gfx.Canvas, scope gfx.Scope) []gfx.Hit { + var hits []gfx.Hit + for _, hit := range canvas.Hits() { + if hit.ID.Scope() == scope { + hits = append(hits, hit) + } + } + return hits +} + +// A warm wide table paints without allocating: the horizontal scroll path adds +// no per-frame allocations to the vertical one. +func TestWideTableAllocatesNothingOnceWarm(t *testing.T) { + theme := gfx.LightTheme() + rows := &countingRows{n: 100} + var view View + var state TableState + canvas := testCanvas() + paint := func() { + canvas.Reset() + view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: wideSixColumns, Headers: sixTitles, Sortable: allSortableSix, Striped: true, Source: rows, Scrollbar: gfx.Item(900), HorizontalScrollbar: gfx.Item(901)}).Fill() + }) + }) + } + paint() + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 40, Precise: true}) + state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 90, Precise: true}) + for range 3 { + paint() + } + if allocs := testing.AllocsPerRun(100, paint); allocs != 0 { + t.Fatalf("a warm wide table allocates %v times a frame, want 0", allocs) + } +} + +func BenchmarkWideTable(b *testing.B) { + theme := gfx.LightTheme() + rows := &countingRows{n: 1000} + var view View + var state TableState + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 60, Precise: true}) + state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 3000, Precise: true}) + canvas := testCanvas() + b.ReportAllocs() + for b.Loop() { + canvas.Reset() + view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: wideSixColumns, Headers: sixTitles, Sortable: allSortableSix, Striped: true, Source: rows, Scrollbar: gfx.Item(900), HorizontalScrollbar: gfx.Item(901)}).Fill() + }) + }) + } +} From a6f6e5df36f37da56ee54fe8204c7d3f504b00f6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 02:16:42 +0800 Subject: [PATCH 12/86] feat(gfx): stroke dashed borders through the path pipeline Add PathStyle.Dashed and Canvas.DashedRoundedOutline: shared tessellation splits a flattened contour into a 6:4 dash rhythm along its arc length, fitting a whole number of periods to a closed outline's perimeter so the pattern closes where it began. Translucent dashes go through the seam-free stroke decomposition, and a warm outline allocates nothing. Co-Authored-By: Claude Code --- gfx/canvas.go | 12 ++- gfx/dashed_outline.go | 29 ++++++ gfx/dashed_outline_test.go | 175 +++++++++++++++++++++++++++++++++++++ gfx/path.go | 138 +++++++++++++++++++++++++---- 4 files changed, 334 insertions(+), 20 deletions(-) create mode 100644 gfx/dashed_outline.go create mode 100644 gfx/dashed_outline_test.go diff --git a/gfx/canvas.go b/gfx/canvas.go index 37fc8ed12..c85f9afd5 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -425,6 +425,9 @@ const ( PointerCursorResizeNWSE PointerCursorResizeNESW PointerCursorNotAllowed + // PointerCursorGrabbing is the closed hand shown while dragging something + // that can be grabbed. + PointerCursorGrabbing // PointerCursorHidden removes the pointer entirely: for a surface that // draws its own pointer, such as a remote desktop. PointerCursorHidden @@ -518,6 +521,9 @@ type HitOptions struct { TextSize float32 TextWeight float32 TextColor Color + // TextAlignment is the line's placement within TextBounds. Zero preserves + // an ordinary input's left alignment; the component resolves its default. + TextAlignment Alignment // HideNativeOverlays asks the platform text service to keep its caret and // selection invisible while preserving native editing, IME and clipboard // behavior. Components that paint their own caret and selection set this @@ -569,6 +575,7 @@ type HitText struct { Size float32 Weight float32 Color Color + Alignment Alignment Placement TextPlacement } @@ -669,6 +676,7 @@ type Canvas struct { // the next one (see Rectangle.Order). order uint32 pathPoints []Point + dashPoints []Point // one dash's outline at a time, while pathPoints keeps the source contourEnds []int32 contourClosed []bool // iconPartCenters is where each contour of an icon in motion turns and grows, @@ -1609,10 +1617,10 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H // stretch of hits owns a contiguous stretch of hitTexts (see replay.go). var text int32 if options.TextBounds != (Rect{}) || options.TextSize != 0 || options.TextWeight != 0 || - options.TextColor != (Color{}) || options.Placement != nil { + options.TextColor != (Color{}) || options.TextAlignment != 0 || options.Placement != nil { canvas.hitTexts = append(canvas.hitTexts, HitText{ Bounds: options.TextBounds, Size: options.TextSize, Weight: options.TextWeight, - Color: options.TextColor, Placement: options.Placement, + Color: options.TextColor, Alignment: options.TextAlignment, Placement: options.Placement, }) text = int32(len(canvas.hitTexts)) } diff --git a/gfx/dashed_outline.go b/gfx/dashed_outline.go new file mode 100644 index 000000000..abe1e3f52 --- /dev/null +++ b/gfx/dashed_outline.go @@ -0,0 +1,29 @@ +package gfx + +// DashedRoundedOutline strokes a dashed line inside bounds without painting +// the interior, as RoundedOutline does solid. On the rectangle's whole +// perimeter the repetition is fitted so the pattern closes where it began: the +// dashes are one repeating rhythm around the outline, six parts paint to four +// parts gap, not a fixed pixel length whose remainder lands as a short stub. +func (canvas *Canvas) DashedRoundedOutline(bounds Rect, radius, width float32, color Color) { + if width <= 0 || color.Alpha <= 0 || bounds.Width <= 0 || bounds.Height <= 0 { + return + } + if canvas.pixelScale > 0 { + bounds = canvas.snapBox(bounds, radius) + width = canvas.borderWidth(width) + } + if bounds.Width <= width*2 || bounds.Height <= width*2 { + // Too small to dash: the whole box is the line, as RoundedOutline has it. + canvas.Rounded(bounds, radius, color) + return + } + // The stroke's centerline runs half the width inside the outline, so the + // painted line still sits entirely within bounds. + centerline := Rect{X: bounds.X + width/2, Y: bounds.Y + width/2, Width: bounds.Width - width, Height: bounds.Height - width} + radius = min(max(radius-width/2, 0), min(centerline.Width, centerline.Height)/2) + canvas.pathPoints = appendRoundedRectContour(canvas.pathPoints[:0], centerline, radius) + canvas.contourEnds = append(canvas.contourEnds[:0], int32(len(canvas.pathPoints))) + canvas.contourClosed = append(canvas.contourClosed[:0], true) + canvas.dashStrokeContours(color.Alpha >= 0.999, width/2, CapButt, JoinMiter, color) +} diff --git a/gfx/dashed_outline_test.go b/gfx/dashed_outline_test.go new file mode 100644 index 000000000..47ad61fee --- /dev/null +++ b/gfx/dashed_outline_test.go @@ -0,0 +1,175 @@ +package gfx + +import ( + "math" + "testing" +) + +// pointCovered reports whether triangles paint the point, ignoring their +// feathering: a solid border covers every point of its band, a dashed one +// leaves gaps behind. +func pointCovered(triangles []Triangle, point Point) bool { + for _, triangle := range triangles { + a, b, c := triangle.Points[0], triangle.Points[1], triangle.Points[2] + d1 := (point.X-b.X)*(a.Y-b.Y) - (a.X-b.X)*(point.Y-b.Y) + d2 := (point.X-c.X)*(b.Y-c.Y) - (b.X-c.X)*(point.Y-c.Y) + d3 := (point.X-a.X)*(c.Y-a.Y) - (c.X-a.X)*(point.Y-a.Y) + negative := d1 < 0 || d2 < 0 || d3 < 0 + positive := d1 > 0 || d2 > 0 || d3 > 0 + if !(negative && positive) { + return true + } + } + return false +} + +// The dashed outline paints a band with holes in it: painted and unpainted +// stretches alternate along the band, which distinguishes it from a solid +// RoundedOutline (all painted) and from nothing (none painted). +func TestDashedRoundedOutlineHasGapsAndPaint(t *testing.T) { + var canvas Canvas + ink := Color{Red: 1, Alpha: .5} + rect := Rect{X: 10, Y: 10, Width: 80, Height: 40} + canvas.DashedRoundedOutline(rect, 8, 2, ink) + triangles := canvas.Triangles() + if len(triangles) == 0 { + t.Fatal("the dashed border painted no geometry") + } + for _, triangle := range triangles { + if triangle.Color != ink { + t.Errorf("a translucent dash changed color to %+v", triangle.Color) + } + } + // Sample the band a pixel above the bottom outline: paint and gaps must + // alternate along it. + bottom := rect.Y + rect.Height - 1 + painted, gaps := 0, 0 + covered := pointCovered(triangles, Point{X: rect.X + 4, Y: bottom}) + for x := rect.X + 4.5; x < rect.X+rect.Width-4; x += 0.5 { + next := pointCovered(triangles, Point{X: x, Y: bottom}) + if next { + painted++ + } + if next != covered { + gaps++ + covered = next + } + } + if painted == 0 || gaps < 2 { + t.Fatalf("%d covered samples and %d coverage changes along the bottom band, want paint and gaps to alternate", painted, gaps) + } +} + +// A rounded outline dashes through its corners: the four corner bands each +// carry paint somewhere in them, not a blank where the dash phase happened to +// end at a corner. +func TestDashedRoundedOutlineCornersCarryPaint(t *testing.T) { + var canvas Canvas + canvas.DashedRoundedOutline(Rect{Width: 60, Height: 60}, 12, 2, Color{Alpha: 1}) + triangles := canvas.Triangles() + // Each corner band is the quarter arc of the outline in that corner: a + // 12x12 box just inside it. + corners := [4][2]float32{{0, 0}, {48, 0}, {0, 48}, {48, 48}} + for _, corner := range corners { + var covered bool + for dx := float32(0); dx <= 12 && !covered; dx += 0.25 { + for dy := float32(0); dy <= 12 && !covered; dy += 0.25 { + covered = covered || pointCovered(triangles, Point{X: corner[0] + dx, Y: corner[1] + dy}) + } + } + if !covered { + t.Fatalf("corner band %v has no paint", corner) + } + } +} + +func TestDashedPixelsStayInsideThePaddedOutline(t *testing.T) { + for _, test := range []struct { + name string + bounds Rect + radius float32 + }{ + {"square", Rect{Width: 40, Height: 20}, 0}, + {"rounded", Rect{Width: 40, Height: 20}, 8}, + {"pill", Rect{Width: 60, Height: 16}, 16}, + } { + var canvas Canvas + canvas.DashedRoundedOutline(test.bounds, test.radius, 2, Color{Alpha: 1}) + if len(canvas.Triangles()) == 0 { + t.Fatalf("%s: nothing painted", test.name) + } + for _, triangle := range canvas.Triangles() { + for _, point := range triangle.Points { + if point.X < test.bounds.X-0.5 || point.Y < test.bounds.Y-0.5 || + point.X > test.bounds.X+test.bounds.Width+0.5 || point.Y > test.bounds.Y+test.bounds.Height+0.5 { + t.Fatalf("%s: stroke geometry at %+v is outside the element %+v", test.name, point, test.bounds) + } + } + } + } +} + +// PathStyle.Dashed drives the same walk: a stroked closed line breaks into +// dashes along its arc length, each painted through the stroke pipeline (so a +// translucent stroke stays seam-free and keeps its color). +func TestDrawPathDashedStrokeIsShorterThanSolid(t *testing.T) { + path := NewPath(40, 20, MoveTo(1, 1), LineTo(39, 1), LineTo(39, 19), LineTo(1, 19), ClosePath()) + var solid, dashed Canvas + solid.DrawPath(path, Rect{Width: 40, Height: 20}, PathStyle{Stroke: Color{Alpha: .5}, StrokeWidth: 2, Join: JoinMiter}) + dashed.DrawPath(path, Rect{Width: 40, Height: 20}, PathStyle{Stroke: Color{Alpha: .5}, StrokeWidth: 2, Join: JoinMiter, Dashed: true}) + solidArea, dashedArea := triangleCoverArea(solid.Triangles()), triangleCoverArea(dashed.Triangles()) + if len(dashed.Triangles()) == 0 || dashedArea <= 0 { + t.Fatal("the dashed stroke painted nothing") + } + if dashedArea >= solidArea { + t.Fatalf("dashed stroke area %v, want less than the solid stroke's %v", dashedArea, solidArea) + } + for _, triangle := range dashed.Triangles() { + if triangle.Color != (Color{Alpha: .5}) { + t.Fatalf("a translucent dash changed color to %+v", triangle.Color) + } + } + // The fitted pattern paints about the 6:4 share of the solid band; the + // tolerance covers the corner joins of the closed square. + if math.Abs(float64(dashedArea)-float64(solidArea)*0.6) > float64(solidArea)*0.25 { + t.Fatalf("dashed stroke area %v, solid %v: not the 6:4 rhythm", dashedArea, solidArea) + } +} + +// A closed outline fits whole pattern periods to its perimeter: no stub dash is +// left at the starting corner and no gap is painted over. Whatever the radius, +// sampling the whole top edge band finds some painted samples and some gaps, +// and the outline is never empty or solid. +func TestDashedOutlineSplitsIntoAlternatingPaintAndGaps(t *testing.T) { + rect := Rect{X: 5, Y: 5, Width: 100, Height: 58} + for _, radius := range []float32{0, 6, 14} { + var canvas Canvas + canvas.DashedRoundedOutline(rect, radius, 2, Color{Alpha: 1}) + triangles := canvas.Triangles() + if len(triangles) == 0 { + t.Fatalf("radius %v: nothing painted", radius) + } + covered := 0 + total := 0 + for x := rect.X + 0.5; x < rect.X+rect.Width; x += 0.5 { + total++ + if pointCovered(triangles, Point{X: x, Y: rect.Y + 1}) { + covered++ + } + } + if covered == 0 || covered == total { + t.Fatalf("radius %v: %d of %d samples covered, want an alternation", radius, covered, total) + } + } +} + +func TestDashedOutlineIsAllocationFreeOnAWarmCanvas(t *testing.T) { + var canvas Canvas + paint := func() { + canvas.DashedRoundedOutline(Rect{X: 10, Y: 10, Width: 80, Height: 40}, 8, 2, Color{Alpha: 1}) + } + paint() + if allocs := testing.AllocsPerRun(200, paint); allocs != 0 { + t.Fatalf("warm dashed outline allocates %v per paint, want 0", allocs) + } +} diff --git a/gfx/path.go b/gfx/path.go index 104111ef8..f96dfc8b7 100644 --- a/gfx/path.go +++ b/gfx/path.go @@ -98,9 +98,12 @@ type PathStyle struct { FillGradient *LinearGradient Stroke Color StrokeWidth float32 - FillRule PathFillRule - Cap StrokeCap - Join StrokeJoin + // Dashed breaks the stroke into equal dashes and gaps, continuing around + // corners and closed contours without closing a short gap. + Dashed bool + FillRule PathFillRule + Cap StrokeCap + Join StrokeJoin } // Path is immutable vector geometry in a fixed view box. NewPath copies the @@ -242,25 +245,124 @@ func (canvas *Canvas) drawPath(path Path, bounds Rect, style PathStyle) { if style.Stroke.Alpha > 0 && style.StrokeWidth > 0 { half := style.StrokeWidth * 0.5 opaque := style.Stroke.Alpha >= 0.999 - start := int32(0) - for index, end := range canvas.contourEnds { - points := canvas.pathPoints[start:end] - if len(points) >= 2 { - if opaque { - // Opaque strokes take the overlapping decomposition: - // segment quads plus round join discs. Overlap is - // invisible at full alpha and the geometry stays - // robust when contour features shrink below the - // stroke width, where offset outlines self-intersect. - canvas.strokeContourOverlapping(points, canvas.contourClosed[index], half, style.Cap, style.Join, style.Stroke) + if style.Dashed { + canvas.dashStrokeContours(opaque, half, style.Cap, style.Join, style.Stroke) + } else { + start := int32(0) + for index, end := range canvas.contourEnds { + points := canvas.pathPoints[start:end] + canvas.strokeFlattenedContour(points, canvas.contourClosed[index], opaque, half, style.Cap, style.Join, style.Stroke) + start = end + } + } + } +} + +// strokeFlattenedContour gives one flattened contour the cap and join it was asked for. +func (canvas *Canvas) strokeFlattenedContour(points []Point, closed, opaque bool, half float32, cap StrokeCap, join StrokeJoin, color Color) { + if len(points) >= 2 { + if opaque { + // Opaque strokes take the overlapping decomposition: + // segment quads plus round join discs. Overlap is + // invisible at full alpha and the geometry stays + // robust when contour features shrink below the + // stroke width, where offset outlines self-intersect. + canvas.strokeContourOverlapping(points, closed, half, cap, join, color) + } else { + canvas.strokeContour(points, closed, half, cap, join, color) + } + } else if len(points) == 1 && cap == CapRound { + canvas.appendDisc(points[0], half, color) + } +} + +// dashStrokeContours splits flattened contours into equal dashes and gaps, +// keeping the 6:4 dash-to-gap ratio of the dashed box-drawing glyphs. On a +// closed contour the repetition is fitted to the perimeter — the same number of +// periods however long the outline is, each a whole pattern cycle — so the +// pattern closes exactly at its starting corner instead of leaving a partial +// dash. Arc-length phase continues across corners and curves; the outline of +// every dash is cut at the phase boundary itself, so a translucent stroke +// stays seam-free. +func (canvas *Canvas) dashStrokeContours(opaque bool, half float32, cap StrokeCap, join StrokeJoin, color Color) { + const ( + dashShare = 6 + gapShare = 4 + ) + // dashUnitCut is the arc length one full period is aimed at, in stroke + // widths: ten times the width, as a dashed UI border reads at any size. + aimedPeriod := half * 2 * 10 + sourceStart := int32(0) + for contour, end := range canvas.contourEnds { + source := canvas.pathPoints[sourceStart:end] + sourceStart = end + if len(source) < 2 { + continue + } + closed := canvas.contourClosed[contour] + last := len(source) + if !closed { + last-- + } + var length float32 + for index := 0; index < last; index++ { + length += distance(source[index], source[(index+1)%len(source)]) + } + if length <= 0 { + continue + } + dash, gap := aimedPeriod*dashShare/10, aimedPeriod*gapShare/10 + if closed { + // A whole number of periods closes the contour: the pattern's phase + // returns to its start exactly as the point does. + periods := max(int(length/aimedPeriod+0.5), 1) + dash, gap = length/float32(periods)*dashShare/10, length/float32(periods)*gapShare/10 + } + canvas.dashPoints = canvas.dashPoints[:0] + canvas.dashPoints = append(canvas.dashPoints, source[0]) + on, remaining := true, dash + index, at := 0, float32(0) + for index < last { + from, to := source[index], source[(index+1)%len(source)] + segmentLength := distance(from, to) + if segmentLength <= 0 { + index++ + continue + } + for remaining < segmentLength-at { + cut := from + along := at + remaining + if along > 0 { + fraction := min(along/segmentLength, 1) + cut = Point{X: from.X + (to.X-from.X)*fraction, Y: from.Y + (to.Y-from.Y)*fraction} + } + if on { + canvas.dashPoints = append(canvas.dashPoints, cut) + canvas.strokeFlattenedContour(canvas.dashPoints, false, opaque, half, cap, join, color) + canvas.dashPoints = canvas.dashPoints[:0] } else { - canvas.strokeContour(points, canvas.contourClosed[index], half, style.Cap, style.Join, style.Stroke) + canvas.dashPoints = append(canvas.dashPoints, cut) + } + on, remaining = !on, gap + if on { + remaining = dash } - } else if len(points) == 1 && style.Cap == CapRound { - canvas.appendDisc(points[0], half, style.Stroke) + at = along } - start = end + remaining -= segmentLength - at + at = 0 + if on { + canvas.dashPoints = append(canvas.dashPoints, to) + } + index++ + } + if on && len(canvas.dashPoints) >= 2 { + // The contour ends inside a dash. A closed one whose whole periods + // land on source[0] never reaches here; an open one, or a rounding + // remainder, keeps the dash open rather than bridging it. + canvas.strokeFlattenedContour(canvas.dashPoints, false, opaque, half, cap, join, color) } + canvas.dashPoints = canvas.dashPoints[:0] } } From 20d160a41a0e9bcfd119fcf40a4ab5b4d03f07c9 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 02:16:47 +0800 Subject: [PATCH 13/86] feat(app): add the grabbing cursor to every backend gfx.PointerCursorGrabbing closes the hand while something is dragged: closedHandCursor on macOS, grabbing on Wayland and X11 cursor themes, the CSS grabbing keyword on the web, and a cached 16x16 cursor Win32 has no stock preset for (destroyed with the last window). Co-Authored-By: Claude Code --- app/painter.go | 17 +++- app/system.go | 2 + app/text_input.go | 5 +- app/text_input_js.go | 8 +- internal/platform/darwin/system_darwin.go | 2 +- internal/platform/darwin/system_darwin.m | 4 +- internal/platform/linux/cursor_linux.go | 2 +- internal/platform/linux/gtk_wayland_linux.go | 2 +- internal/platform/linux/system_linux.go | 4 +- internal/platform/linux/system_linux_test.go | 2 +- internal/platform/web/painter.go | 5 +- internal/platform/web/system_js.go | 1 + internal/platform/web/system_js_test.go | 2 +- internal/platform/web/text_input.go | 5 +- .../platform/windows/cursor_image_windows.go | 82 +++++++++++++++++++ .../platform/windows/cursor_windows_test.go | 26 ++++++ internal/platform/windows/system_windows.go | 5 +- internal/platform/windows/window_windows.go | 3 + 18 files changed, 157 insertions(+), 20 deletions(-) diff --git a/app/painter.go b/app/painter.go index 587adda3d..8e7c0e9a0 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1134,6 +1134,8 @@ func cursorFromHit(cursor gfx.PointerCursor) Cursor { return CursorResizeNESW case gfx.PointerCursorNotAllowed: return CursorNotAllowed + case gfx.PointerCursorGrabbing: + return CursorGrabbing case gfx.PointerCursorHidden: return CursorHidden case gfx.PointerCursorImage: @@ -1167,7 +1169,7 @@ func (painter *painter) focusedTextField() (TextInputContext, gfx.TextPlacement, ID: hit.ID, Bounds: hit.Bounds, Layer: hit.Layer, Terminal: hit.Role == gfx.RoleTerminal, TypeAhead: hit.TypeAhead && hit.Role != gfx.RoleTerminal, Multiline: hit.Multiline, ReadOnly: hit.ReadOnly, Secure: hit.Secure, NavigationKeys: hit.NavigationKeys, - TextBounds: text.Bounds, FontSize: text.Size, FontWeight: text.Weight, TextColor: text.Color, + TextBounds: text.Bounds, FontSize: text.Size, FontWeight: text.Weight, TextColor: text.Color, Alignment: text.Alignment, HideNativeOverlays: hit.HideNativeOverlays, } return context, text.Placement, index @@ -1211,6 +1213,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { } // What the application leaves unset comes from the component's declaration. bounds, fontSize, weight, tint := input.Bounds, input.FontSize, input.Weight, input.Color + alignment := input.Alignment if bounds == (gfx.Rect{}) { bounds = context.TextBounds if bounds == (gfx.Rect{}) { @@ -1229,6 +1232,9 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { if tint == (gfx.Color{}) { tint = context.TextColor } + if alignment == gfx.AlignLeft { + alignment = context.Alignment + } if !(fontSize > 0) || math.IsInf(float64(fontSize), 0) { // Every platform refuses an editor without a font size. What neither the // application nor the declaration set is the body text's. @@ -1248,9 +1254,12 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { cellWidth, _ = painter.canvas.MonoCellSize(fontSize, input.MonoFace) baseline = painter.canvas.MonoBaseline(fontSize, input.MonoFace, bounds.Height) } - alignment := gfx.AlignLeft - if !context.Terminal && !context.TypeAhead && placement == nil { - alignment = resolveTextInputAlignment(input.Alignment, input.State.Value, input.State.Selection.End) + if context.Terminal || context.TypeAhead || placement != nil { + // Terminal and self-placed inputs keep the fixed origin they had before + // alignment existed. + alignment = gfx.AlignLeft + } else { + alignment = resolveTextInputAlignment(alignment, input.State.Value, input.State.Selection.End) } native := platform.TextInput{ Target: context.ID, diff --git a/app/system.go b/app/system.go index 87144a958..f5d37334c 100644 --- a/app/system.go +++ b/app/system.go @@ -39,6 +39,8 @@ const ( CursorResizeNWSE CursorResizeNESW CursorNotAllowed + // CursorGrabbing is the closed hand shown while dragging something. + CursorGrabbing // CursorHidden removes the pointer: a surface that draws its own (a // remote desktop picture) uses it to keep the system pointer away. CursorHidden diff --git a/app/text_input.go b/app/text_input.go index e91fd610c..61ac88f63 100644 --- a/app/text_input.go +++ b/app/text_input.go @@ -138,14 +138,15 @@ type TextInputContext struct { // text being composed, at Bounds. Return an input whose OnEvent keeps the // query the application builds from the events. TypeAhead bool - // TextBounds, FontSize, FontWeight and TextColor are the text geometry the component - // declared for this field. They fill whatever the returned TextInput leaves + // TextBounds, FontSize, FontWeight, TextColor and Alignment are the text geometry + // the component declared for this field. They fill whatever the returned TextInput leaves // unset, so a bare &TextInput{Editor: editor} draws its text exactly where // the field painted it; set them only to deliberately override. TextBounds gfx.Rect FontSize float32 FontWeight float32 TextColor gfx.Color + Alignment gfx.Alignment // HideNativeOverlays requests that the platform editor keep its own caret // and selection invisible. Editing, IME and clipboard behavior are // unchanged. Components that paint those overlays themselves set it. diff --git a/app/text_input_js.go b/app/text_input_js.go index d1286ae90..3c889e00a 100644 --- a/app/text_input_js.go +++ b/app/text_input_js.go @@ -43,7 +43,7 @@ func webTextInput(provider TextInputProvider) web.TextInputProvider { Layer: context.Layer, ReadOnly: context.ReadOnly, Secure: context.Secure, NavigationKeys: context.NavigationKeys, Terminal: context.Terminal, TypeAhead: context.TypeAhead, TextBounds: context.TextBounds, FontSize: context.FontSize, FontWeight: context.FontWeight, - TextColor: context.TextColor, HideNativeOverlays: context.HideNativeOverlays, + TextColor: context.TextColor, Alignment: context.Alignment, HideNativeOverlays: context.HideNativeOverlays, }) if active == nil { return nil @@ -70,7 +70,11 @@ func webTextInput(provider TextInputProvider) web.TextInputProvider { } else { native.State = platformTextState(active.State) } - native.Alignment = resolveTextInputAlignment(active.Alignment, native.State.Value, native.State.Selection.End) + alignment := active.Alignment + if alignment == 0 { + alignment = context.Alignment + } + native.Alignment = resolveTextInputAlignment(alignment, native.State.Value, native.State.Selection.End) return &native } } diff --git a/internal/platform/darwin/system_darwin.go b/internal/platform/darwin/system_darwin.go index b769c6895..3f04e1b6d 100644 --- a/internal/platform/darwin/system_darwin.go +++ b/internal/platform/darwin/system_darwin.go @@ -201,7 +201,7 @@ func vivaSystemAppearanceChanged() { // lastCursorShape is the highest shape number the native side knows. A number // beyond it is refused here, without a trip to the main thread, which the native // side would also refuse with the same words. -const lastCursorShape = 10 +const lastCursorShape = 11 func SetCursorShape(shape uint8) error { if shape > lastCursorShape { diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m index a44104802..b6926c423 100644 --- a/internal/platform/darwin/system_darwin.m +++ b/internal/platform/darwin/system_darwin.m @@ -455,7 +455,9 @@ int viva_system_pasteboard_put_files(const char *pasteboard, const char *const * return nil; case 9: return NSCursor.operationNotAllowedCursor; - case 10: { + case 10: + return NSCursor.closedHandCursor; + case 11: { // A fully transparent cursor: a surface that draws its own pointer // (a remote desktop picture) uses it to keep the system pointer // out of the way. Its masks touch no pixel of the screen. diff --git a/internal/platform/linux/cursor_linux.go b/internal/platform/linux/cursor_linux.go index d98497864..8232710f3 100644 --- a/internal/platform/linux/cursor_linux.go +++ b/internal/platform/linux/cursor_linux.go @@ -21,7 +21,7 @@ type themedCursors struct { // cursorNames are the theme names of the cursors, in app.Cursor order. var cursorNames = [...]string{ "left_ptr", "xterm", "hand2", "crosshair", "watch", - "sb_h_double_arrow", "sb_v_double_arrow", "size_fdiag", "size_bdiag", "crossed_circle", + "sb_h_double_arrow", "sb_v_double_arrow", "size_fdiag", "size_bdiag", "crossed_circle", "grabbing", } // openThemedCursors returns nil when the library or the theme is not there. diff --git a/internal/platform/linux/gtk_wayland_linux.go b/internal/platform/linux/gtk_wayland_linux.go index b521e56cc..908506810 100644 --- a/internal/platform/linux/gtk_wayland_linux.go +++ b/internal/platform/linux/gtk_wayland_linux.go @@ -668,7 +668,7 @@ func intersectScissor(a, b render.Scissor) render.Scissor { } // wp_cursor_shape_device_v1.shape for the cursors the application asks for, in app.Cursor order. -var cursorShapes = [...]uint32{1 /* default */, 9 /* text */, 4 /* pointer */, 8 /* crosshair */, 6 /* wait */, 26 /* ew-resize */, 27 /* ns-resize */, 29 /* nwse-resize */, 28 /* nesw-resize */, 15 /* not-allowed */} +var cursorShapes = [...]uint32{1 /* default */, 9 /* text */, 4 /* pointer */, 8 /* crosshair */, 6 /* wait */, 26 /* ew-resize */, 27 /* ns-resize */, 29 /* nwse-resize */, 28 /* nesw-resize */, 15 /* not-allowed */, 5 /* grabbing */} // applyCursor shows the window's cursor on the subsurface, which GDK does not manage. func (s *waylandSurface) applyCursor() { diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index 9877a3bc8..1b12c18f8 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -1091,8 +1091,8 @@ func (win *window) checkRequest(action string, cookie xcbVoidCookie) error { } // cursorHidden is the shape a surface that draws its own pointer asks for: app.CursorHidden, -// after the ten shapes of the cursor font and the theme. -const cursorHidden uint8 = 10 +// after the eleven shapes of the cursor font and the theme. +const cursorHidden uint8 = 11 // applyHiddenCursor makes a fully transparent cursor: a 1x1 bitmap, cleared to zero, as both the // source and the mask of the cursor, so no pixel of the pointer shows. The contents of a new diff --git a/internal/platform/linux/system_linux_test.go b/internal/platform/linux/system_linux_test.go index bc3fff523..784ca10a1 100644 --- a/internal/platform/linux/system_linux_test.go +++ b/internal/platform/linux/system_linux_test.go @@ -270,7 +270,7 @@ func TestSetCursorShapeAppliesAndReleasesCursor(t *testing.T) { } } -// The hidden cursor is the eleventh shape, past the end of the cursor font's glyphs: it makes a +// The hidden cursor is the twelfth shape, past the end of the cursor font's glyphs: it makes a // cursor of a 1x1 bitmap that is cleared first, since a new pixmap has undefined contents, and // applies it in place of the one the window had. func TestSetCursorShapeHiddenClearsItsBitmapAndReplacesTheCursor(t *testing.T) { diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index 8dc66f309..7adb0feb6 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -517,7 +517,7 @@ func (p *painter) syncTextInput() { ID: field.ID, Bounds: field.Bounds, Layer: field.Layer, Multiline: field.Multiline, ReadOnly: field.ReadOnly, Secure: field.Secure, NavigationKeys: field.NavigationKeys, Terminal: field.Role == gfx.RoleTerminal, TypeAhead: field.TypeAhead && field.Role != gfx.RoleTerminal, - TextBounds: text.Bounds, FontSize: text.Size, FontWeight: text.Weight, TextColor: text.Color, + TextBounds: text.Bounds, FontSize: text.Size, FontWeight: text.Weight, TextColor: text.Color, Alignment: text.Alignment, HideNativeOverlays: field.HideNativeOverlays, } if field.ReadOnly { @@ -531,6 +531,9 @@ func (p *painter) syncTextInput() { } p.textInputID = field.ID p.textInput = *input + if p.textInput.Alignment == gfx.AlignLeft { + p.textInput.Alignment = context.Alignment + } p.textInput.Multiline = field.Multiline p.textInput.Placed = text.Placement != nil p.textInput.Terminal = context.Terminal || context.TypeAhead diff --git a/internal/platform/web/system_js.go b/internal/platform/web/system_js.go index 9c88a02c9..b2435fc05 100644 --- a/internal/platform/web/system_js.go +++ b/internal/platform/web/system_js.go @@ -270,6 +270,7 @@ func cursorCSS(shape uint8) (string, error) { "nwse-resize", "nesw-resize", "not-allowed", + "grabbing", "none", } if int(shape) >= len(values) { diff --git a/internal/platform/web/system_js_test.go b/internal/platform/web/system_js_test.go index 4a33382b4..aa41c4273 100644 --- a/internal/platform/web/system_js_test.go +++ b/internal/platform/web/system_js_test.go @@ -8,7 +8,7 @@ import ( ) func TestCursorCSS(t *testing.T) { - want := [...]string{"default", "text", "pointer", "crosshair", "wait", "ew-resize", "ns-resize", "nwse-resize", "nesw-resize", "not-allowed", "none"} + want := [...]string{"default", "text", "pointer", "crosshair", "wait", "ew-resize", "ns-resize", "nwse-resize", "nesw-resize", "not-allowed", "grabbing", "none"} for shape, expected := range want { actual, err := cursorCSS(uint8(shape)) if err != nil || actual != expected { diff --git a/internal/platform/web/text_input.go b/internal/platform/web/text_input.go index 66f208948..3f0bd2d40 100644 --- a/internal/platform/web/text_input.go +++ b/internal/platform/web/text_input.go @@ -25,12 +25,13 @@ type TextInputContext struct { Terminal bool // TypeAhead reports a hit that takes typed text without being a text field. TypeAhead bool - // TextBounds, FontSize, FontWeight and TextColor are the text geometry the component - // declared; they fill whatever the returned input leaves unset. + // TextBounds, FontSize, FontWeight, TextColor and Alignment are the text + // geometry the component declared; they fill what the input leaves unset. TextBounds gfx.Rect FontSize float32 FontWeight float32 TextColor gfx.Color + Alignment gfx.Alignment HideNativeOverlays bool } diff --git a/internal/platform/windows/cursor_image_windows.go b/internal/platform/windows/cursor_image_windows.go index 598773586..37e9d2225 100644 --- a/internal/platform/windows/cursor_image_windows.go +++ b/internal/platform/windows/cursor_image_windows.go @@ -58,6 +58,88 @@ func retireCustomCursor(handle uintptr, image *gfx.CursorImage, scale float32) { customCursors.image, customCursors.scale = image, scale } +// grabbingCursorImage draws the closed-hand cursor that Win32 does not expose as +// a stock shape. Its 16x16 alpha bitmap is built once, on the first request, and +// the HCURSOR made of it is kept for the process: stock cursors are shared by +// the system and never destroyed, so a preset recreated per request would leak +// one per change. +var grabbingCursor = struct { + once sync.Once + image *gfx.CursorImage + handle uintptr + failure error +}{} + +func grabbingCursorHandle() (uintptr, error) { + grabbingCursor.once.Do(func() { + 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 { + grabbingCursor.failure = err + return + } + 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. +func closeGrabbingCursor() { + if handle := grabbingCursor.handle; handle != 0 { + grabbingCursor.handle = 0 + destroyIcon.Call(handle) + } +} + +func grabbingCursorPixels() []byte { + pixels := make([]byte, 16*16*4) + inside := func(x, y int) bool { + if x < 0 || x >= 16 || y < 0 || y >= 16 { + return false + } + switch { + case y == 2 && x >= 5 && x <= 6: // index finger + return true + case y == 3 && x >= 4 && x <= 7: + return true + case y >= 4 && y <= 5 && x >= 4 && x <= 7: + return true + case y >= 6 && y <= 8 && x >= 3 && x <= 12: + return true + case y >= 9 && y <= 10 && x >= 4 && x <= 12: + return true + case y == 11 && x >= 5 && x <= 11: + return true + case y >= 12 && y <= 13 && x >= 6 && x <= 11: + return true + } + return false + } + set := func(x, y int, shade byte) { + at := (y*16 + x) * 4 + pixels[at], pixels[at+1], pixels[at+2], pixels[at+3] = shade, shade, shade, 255 + } + for y := 16; y > 0; { + y-- + for x := 16; x > 0; { + x-- + if inside(x, y) { + set(x, y, 255) + continue + } + if inside(x-1, y) || inside(x+1, y) || inside(x, y-1) || inside(x, y+1) { + set(x, y, 0) + } + } + } + return pixels +} + // newCursorHandle makes an HCURSOR of the picture with its hotspot. A 32-bit cursor bitmap is // read as plain ARGB, the color not multiplied by alpha, which the cursor tests read back // from Windows itself. diff --git a/internal/platform/windows/cursor_windows_test.go b/internal/platform/windows/cursor_windows_test.go index d6b5d34df..ec8eef341 100644 --- a/internal/platform/windows/cursor_windows_test.go +++ b/internal/platform/windows/cursor_windows_test.go @@ -20,3 +20,29 @@ func TestCursorShapesIncludeHidden(t *testing.T) { t.Fatal("a shape past the last one was accepted") } } + +// The closed-hand cursor this package draws itself is made once and shared, as +// the stock cursors are: asking twice must not grow a second one. +func TestGrabbingCursorIsMadeOnce(t *testing.T) { + first, err := grabbingCursorHandle() + if err != nil { + t.Fatal(err) + } + second, err := grabbingCursorHandle() + if err != nil { + t.Fatal(err) + } + if first == 0 || first != second { + t.Fatalf("grabbing cursor handles = %d then %d, want one shared handle", first, second) + } + // closeGrabbingCursor destroys the handle; a later call makes a fresh one. + closeGrabbingCursor() + third, err := grabbingCursorHandle() + 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) + } + closeGrabbingCursor() +} diff --git a/internal/platform/windows/system_windows.go b/internal/platform/windows/system_windows.go index e5af5c770..710e13dcd 100644 --- a/internal/platform/windows/system_windows.go +++ b/internal/platform/windows/system_windows.go @@ -734,6 +734,9 @@ func cursorHandle(shape uint8) (uintptr, error) { if shape == cursorHidden { return hiddenCursor() } + if shape == 10 { // app.CursorGrabbing, kept numeric so backend shape IDs stay thin. + return grabbingCursorHandle() + } identifiers := [...]uintptr{32512, 32513, 32649, 32515, 32514, 32644, 32645, 32642, 32643, 32648} if int(shape) >= len(identifiers) { return 0, fmt.Errorf("windows: invalid cursor %d", shape) @@ -989,7 +992,7 @@ func notificationIcon(host uintptr) uintptr { } // cursorHidden is the shape a surface that draws its own pointer asks for. -const cursorHidden uint8 = 10 +const cursorHidden uint8 = 11 var createCursor = user.NewProc("CreateCursor") diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index db3a9fb58..3fd088f18 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -411,6 +411,9 @@ func (application *windowsApplication) closeAll() { } return true }) + // The one cursor this package made — the closed hand Win32 does not ship — + // is destroyed once no window can still be showing it. + closeGrabbingCursor() } func windowProc(window, kind, first, second uintptr) (result uintptr) { From a7345fa83b6e795f8e827b0395ff03927660a98b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 02:16:55 +0800 Subject: [PATCH 14/86] feat(components): optional text alignment for InputSnapshot InputSnapshot.Alignment places a field's line inside its content box; the zero value keeps the direction-dependent start alignment fields had. The value drives the painted line, caret, selection (including the clip re-paint), composition and the geometry the platform editor is told, so a right-aligned number field stays right-aligned while focused. ui.Field and ui.Page pass the declaration to editors that leave their own unset. Co-Authored-By: Claude Code --- components/input.go | 25 +++++++----- components/input_text_style_test.go | 60 +++++++++++++++++++++++++++++ ui/field.go | 1 + ui/page.go | 1 + 4 files changed, 78 insertions(+), 9 deletions(-) diff --git a/components/input.go b/components/input.go index 5c0a851be..53c12dcc7 100644 --- a/components/input.go +++ b/components/input.go @@ -12,8 +12,13 @@ import ( // it a password field: the value is never exposed, DisplayValue is ignored, // and the field paints one bullet per character. type InputSnapshot struct { - ID gfx.ID - Label string + ID gfx.ID + Label string + // Alignment places the text within the content rectangle. Zero preserves + // the ordinary direction-dependent start alignment, which is left-to-right + // for Latin text. AlignRight suits a numeric field. The label, caret, + // selection, composition and platform editor all take the same alignment. + Alignment gfx.Alignment Value string DisplayValue string Placeholder string @@ -133,6 +138,9 @@ func PaintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. // is where the glyphs are painted: a content rectangle exactly one line tall is its // own line box, and a taller one (a padded field, or the whole control) is not. func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx.Rect, snapshot InputSnapshot, focused bool) { + if snapshot.Alignment == gfx.AlignLeft { + snapshot.Alignment = gfx.AlignStart + } style := snapshot.Text.style(&theme) // A mono field is painted by the component whatever the snapshot says of the platform: the // platform's text service cannot draw its face, so its text and overlays are hidden. A @@ -170,7 +178,7 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, Disabled: snapshot.Disabled, ReadOnly: snapshot.ReadOnly, Secure: snapshot.Secure, NavigationKeys: snapshot.NavigationKeys, - TextBounds: textBounds, TextSize: size, TextWeight: weight, TextColor: platformInk, + TextBounds: textBounds, TextSize: size, TextWeight: weight, TextColor: platformInk, TextAlignment: snapshot.Alignment, HideNativeOverlays: selfPainted, }) } @@ -215,10 +223,9 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholderShown := snapshot.Value == "" && snapshot.DisplayValue == "" style := textStyle style.Color = color - // The line starts where the label puts it: the right end of the field for text that - // reads right to left. The caret, selection and composition are measured from there, - // and follow the visual order of mixed text (a selection may be several stretches). - origin := canvas.LabelOrigin(value, bounds, style, gfx.AlignStart) + // The caret, selection and composition share the glyphs' origin and follow + // the visual order of mixed text (a selection may be several stretches). + origin := canvas.LabelOrigin(value, bounds, style, snapshot.Alignment) var ranges [4]gfx.Rect selectionStart, selectionEnd := inputRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) var selections []gfx.Rect @@ -255,7 +262,7 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, // bounds, and those should describe the glyph line the field draws. lineTop, lineHeight := inputLineBox(bounds, fontSize) line := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} - canvas.Label(value, line, style) + canvas.LabelAligned(value, line, style, snapshot.Alignment) for _, selection := range selections { if selection.Width <= 0 { continue @@ -267,7 +274,7 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, } selected := textStyle selected.Color = selectedColor - canvas.Label(value, line, selected) + canvas.LabelAligned(value, line, selected, snapshot.Alignment) canvas.Unclip() } canvas.Unclip() diff --git a/components/input_text_style_test.go b/components/input_text_style_test.go index 453e7a67f..d1dc94dfd 100644 --- a/components/input_text_style_test.go +++ b/components/input_text_style_test.go @@ -169,6 +169,66 @@ func TestMonoInputIsPaintedByTheComponentAndTheNativeLayerIsHidden(t *testing.T) } } +// Numeric fields opt into a right edge without leaving their selection, caret, +// composition or platform editor at the ordinary start edge. +func TestInputAlignmentDrivesTheLineAndItsEditingGeometry(t *testing.T) { + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 10, Width: 200, Height: 32} + snapshot := InputSnapshot{ID: gfx.Item(1), Value: "1234", Alignment: gfx.AlignRight, HideEditorText: true, + Focused: true, ShowCaret: true, Caret: 3, SelectionStart: 1, SelectionEnd: 3} + canvas := weightedCanvas() + PaintInputContent(canvas, theme, bounds, bounds, snapshot) + var line gfx.Text + for _, text := range canvas.Texts() { + if text.Value == "1234" { + line = text + } + } + width := canvas.TextWidthStyle(line.Value, line.Style) + if line.Bounds.X != bounds.X+bounds.Width-width { + t.Fatalf("text origin = %v, want %v for right-aligned text", line.Bounds.X, bounds.X+bounds.Width-width) + } + var carets, selections []gfx.Rectangle + for _, rectangle := range canvas.Rectangles() { + switch { + case rectangle.Bounds.Width == 1: + carets = append(carets, rectangle) + case rectangle.Bounds.Width > 1: + selections = append(selections, rectangle) + } + } + if len(carets) != 1 { + t.Fatalf("carets = %+v, want one", carets) + } + if want := line.Bounds.X + canvas.TextCaretStyle(line.Value, line.Style, 3); carets[0].Bounds.X != want { + t.Errorf("caret at %v, want %v from the right origin", carets[0].Bounds.X, want) + } + if len(selections) != 1 { + t.Fatalf("the selection painted %+v, want one band", selections) + } + var spans [4]gfx.TextSpan + selection := canvas.TextSelectionStyle(spans[:0], line.Value, line.Style, 1, 3) + if len(selection) == 0 || selections[0].Bounds.X != line.Bounds.X+selection[0].X { + t.Errorf("selection at %+v, want the measured range %v from the right origin", selections[0].Bounds, selection) + } + text := hitText(canvas, &canvas.Hits()[0]) + if text.Alignment != gfx.AlignRight { + t.Fatalf("the platform is told alignment %v, want right", text.Alignment) + } +} + +func TestDefaultInputAlignmentStaysDirectionDependent(t *testing.T) { + canvas := weightedCanvas() + bounds := gfx.Rect{Width: 200, Height: 32} + PaintInputContent(canvas, gfx.LightTheme(), bounds, bounds, InputSnapshot{ID: gfx.Item(1), Value: "abc"}) + if text := canvas.Texts()[0]; text.Bounds.X != bounds.X { + t.Fatalf("the ordinary field starts at %v, want %v", text.Bounds.X, bounds.X) + } + if text := hitText(canvas, &canvas.Hits()[0]); text.Alignment != gfx.AlignStart { + t.Errorf("the default promises the runtime alignment %v, want start", text.Alignment) + } +} + // The caret of a self-painted field is drawn only while its blink phase has it lit. func TestMonoInputCaretFollowsItsBlinkPhase(t *testing.T) { theme := gfx.LightTheme() diff --git a/ui/field.go b/ui/field.go index 8498167b7..81b8590b9 100644 --- a/ui/field.go +++ b/ui/field.go @@ -257,6 +257,7 @@ func Fields(fields ...*Field) func(app.TextInputContext) *app.TextInput { return func(context app.TextInputContext) *app.TextInput { for _, field := range fields { if field.id == context.ID && !context.ID.IsZero() { + field.input.Alignment = context.Alignment field.input.Editor = field.ensure() return &field.input } diff --git a/ui/page.go b/ui/page.go index c8bb7c471..2934402a6 100644 --- a/ui/page.go +++ b/ui/page.go @@ -1063,6 +1063,7 @@ func (p *Page) guard(b Box, id gfx.ID, label string) { func (p *Page) TextInput(context app.TextInputContext) *app.TextInput { for _, entry := range p.fields { if entry.id == context.ID && !context.ID.IsZero() { + entry.field.input.Alignment = context.Alignment entry.field.input.Editor = entry.field.ensure() return &entry.field.input } From e1a04ae1494610e0b3d7946355edd9e293fc668f Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 02:17:00 +0800 Subject: [PATCH 15/86] feat(ui): dashed element borders and injected dashed frames Box.Dashed() and Look.Dashed(bool) take an element's border in and out of the dash pattern, painted over the fill like a translucent border is; DrawContext.DashedBorder paints a dashed frame with the element's fade. The generated guide names all three, and the component templates are regenerated (a stale color-swatch template from main is caught up with it). Co-Authored-By: Claude Code --- cmd/viva/initfiles/AGENTS.md.txt | 7 +- cmd/viva/templates/color_swatch.go.txt | 18 ++++- cmd/viva/templates/dropdown_menu.go.txt | 7 +- cmd/viva/templates/input.go.txt | 25 ++++--- headless/ui_gaps_test.go | 97 +++++++++++++++++++++++++ ui/box.go | 10 +++ ui/draw.go | 9 ++- ui/frame.go | 5 +- ui/paint.go | 8 +- ui/style.go | 16 +++- ui/style_test.go | 64 ++++++++++++++++ 11 files changed, 245 insertions(+), 21 deletions(-) create mode 100644 headless/ui_gaps_test.go diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 0ce5e7fdf..ba26bf6f0 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -225,7 +225,8 @@ func (m *model) page(c ui.C) { - Effects, all typed and checked by the compiler (there is no class string): `Ring(3, c)` draws a line around the outside without taking room (a focus ring); `Opacity(0.5)` fades the element and everything in it (it is still laid out and clickable); `Gradient(ui.ToBottomRight, from, to)` and `GradientStops(angle, gfx.Stop(0, a), gfx.Stop(1, b), ...)` - fill the element, corners included, over `Background` and under `Border`. + fill the element, corners included, over `Background` and under `Border`; `Dashed()` breaks the `Border` line into + equal dashes and gaps (a drop target's frame), and `Look{}` has `Dashed(bool)` too. - States: an element with an identity (`Hit`, which also makes it focusable) changes with `Hover(ui.Look{}.Background(theme.Hover))`, `Pressed(...)` and `Focus(ui.Look{}.Ring(3, theme.Ring))` (keyboard focus, as `:focus-visible`), plus `Focused(...)` for any focus (a click in a text field focuses it without making it visible; a group box that frames its field follows the field with `StateFrom(field)`). A `Look` lists only what differs from rest and has `Background`, `Border`, @@ -546,7 +547,9 @@ copied with it). They take a Painting your own thing in a slot: `ui.Slot(c).Grow(1).Draw(func(d *ui.DrawContext) { ... })`, with `d.Canvas.Fill(rect, color)`, `Rounded(rect, radius, color)`, `Border`, `RoundedBorder`, `Elevate(rect, radius, gfx.ShadowMD)` (a drop shadow: call it before the surface), `DrawPath` and `d.Canvas.Label(text, rect, gfx.TextStyle{Size: 14, Color: c})` (`LabelCenter` is the same, centered) are all of -it; there is no arc, circle or line call (a circle is a `Rounded` square, or a `Box` with `Radius`). +it; there is no arc, circle or line call (a circle is a `Rounded` square, or a `Box` with `Radius`). `d.Fade(color)` applies the +element's opacity to a color you supply, and `d.DashedBorder(rect, radius, 1, d.Fade(color))` paints a dashed frame the +element fades with. For tabs, tables and text fields use `ui.Tabs`, `ui.Table` and `ui.TextField` above, not the components by hand. ## Background work diff --git a/cmd/viva/templates/color_swatch.go.txt b/cmd/viva/templates/color_swatch.go.txt index 62d5dec81..c6354daef 100644 --- a/cmd/viva/templates/color_swatch.go.txt +++ b/cmd/viva/templates/color_swatch.go.txt @@ -13,6 +13,7 @@ type ColorSwatch struct { label string selected, disabled bool skipTab bool + flush bool } // BeginColorSwatch centers a color disc inside bounds, leaving room for its @@ -25,6 +26,12 @@ func (s ColorSwatch) Label(label string) ColorSwatch { s.label = label; retu func (s ColorSwatch) Selected(selected bool) ColorSwatch { s.selected = selected; return s } func (s ColorSwatch) Disabled() ColorSwatch { s.disabled = true; return s } +// Flush paints the colour disc against the border instead of leaving a +// background-coloured ring between them. A swatch in a dense row then reads as +// one solid colour inside a hairline circle rather than a smaller disc with a +// visible gap. +func (s ColorSwatch) Flush() ColorSwatch { s.flush = true; return s } + // TabStop says whether Tab may enter this choice. A radio set gives its // selected choice the tab stop, marks the others false, and uses // RadioGroupKeyDown for arrow navigation. @@ -63,9 +70,14 @@ func (s ColorSwatch) Paint() ColorSwatchResult { border.Alpha *= 0.4 } s.canvas.Rounded(b, side/2, border) - inner := gfx.Rect{X: b.X + 2, Y: b.Y + 2, Width: side - 4, Height: side - 4} - s.canvas.Rounded(inner, inner.Width/2, s.theme.Background) - disc := gfx.Rect{X: b.X + 5, Y: b.Y + 5, Width: side - 10, Height: side - 10} + var disc gfx.Rect + if s.flush { + disc = gfx.Rect{X: b.X + 1, Y: b.Y + 1, Width: max(side-2, 0), Height: max(side-2, 0)} + } else { + inner := gfx.Rect{X: b.X + 2, Y: b.Y + 2, Width: side - 4, Height: side - 4} + s.canvas.Rounded(inner, inner.Width/2, s.theme.Background) + disc = gfx.Rect{X: b.X + 5, Y: b.Y + 5, Width: side - 10, Height: side - 10} + } color := s.color if color.Alpha == 0 { color = s.theme.Muted diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index 87871b418..973533a97 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -950,6 +950,11 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { // 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 + // switch), no row is the menu's current row: keeping the last focused row + // tinted would fight the control under the pointer. Menu rows themselves + // declare RoleMenuItem. + inContent := !hovered.IsZero() && canvas.HoveredRole() != 0 && canvas.HoveredRole() != gfx.RoleMenuItem if claim && hovered == item.ID { // A disabled row cannot take focus, but the frame is still repainted so // the row that kept focus is tinted again on the next paint. @@ -960,7 +965,7 @@ 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 && (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 } diff --git a/cmd/viva/templates/input.go.txt b/cmd/viva/templates/input.go.txt index 3a17cca73..6b638afef 100644 --- a/cmd/viva/templates/input.go.txt +++ b/cmd/viva/templates/input.go.txt @@ -12,8 +12,13 @@ import ( // it a password field: the value is never exposed, DisplayValue is ignored, // and the field paints one bullet per character. type InputSnapshot struct { - ID gfx.ID - Label string + ID gfx.ID + Label string + // Alignment places the text within the content rectangle. Zero preserves + // the ordinary direction-dependent start alignment, which is left-to-right + // for Latin text. AlignRight suits a numeric field. The label, caret, + // selection, composition and platform editor all take the same alignment. + Alignment gfx.Alignment Value string DisplayValue string Placeholder string @@ -133,6 +138,9 @@ func PaintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. // is where the glyphs are painted: a content rectangle exactly one line tall is its // own line box, and a taller one (a padded field, or the whole control) is not. func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx.Rect, snapshot InputSnapshot, focused bool) { + if snapshot.Alignment == gfx.AlignLeft { + snapshot.Alignment = gfx.AlignStart + } style := snapshot.Text.style(&theme) // A mono field is painted by the component whatever the snapshot says of the platform: the // platform's text service cannot draw its face, so its text and overlays are hidden. A @@ -170,7 +178,7 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, Disabled: snapshot.Disabled, ReadOnly: snapshot.ReadOnly, Secure: snapshot.Secure, NavigationKeys: snapshot.NavigationKeys, - TextBounds: textBounds, TextSize: size, TextWeight: weight, TextColor: platformInk, + TextBounds: textBounds, TextSize: size, TextWeight: weight, TextColor: platformInk, TextAlignment: snapshot.Alignment, HideNativeOverlays: selfPainted, }) } @@ -215,10 +223,9 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholderShown := snapshot.Value == "" && snapshot.DisplayValue == "" style := textStyle style.Color = color - // The line starts where the label puts it: the right end of the field for text that - // reads right to left. The caret, selection and composition are measured from there, - // and follow the visual order of mixed text (a selection may be several stretches). - origin := canvas.LabelOrigin(value, bounds, style, gfx.AlignStart) + // The caret, selection and composition share the glyphs' origin and follow + // the visual order of mixed text (a selection may be several stretches). + origin := canvas.LabelOrigin(value, bounds, style, snapshot.Alignment) var ranges [4]gfx.Rect selectionStart, selectionEnd := inputRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) var selections []gfx.Rect @@ -255,7 +262,7 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, // bounds, and those should describe the glyph line the field draws. lineTop, lineHeight := inputLineBox(bounds, fontSize) line := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} - canvas.Label(value, line, style) + canvas.LabelAligned(value, line, style, snapshot.Alignment) for _, selection := range selections { if selection.Width <= 0 { continue @@ -267,7 +274,7 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, } selected := textStyle selected.Color = selectedColor - canvas.Label(value, line, selected) + canvas.LabelAligned(value, line, selected, snapshot.Alignment) canvas.Unclip() } canvas.Unclip() diff --git a/headless/ui_gaps_test.go b/headless/ui_gaps_test.go new file mode 100644 index 000000000..a7dfa18e2 --- /dev/null +++ b/headless/ui_gaps_test.go @@ -0,0 +1,97 @@ +//go:build darwin || windows || linux + +package headless + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// A hit that asks for the grabbing cursor shows it while the pointer is over +// it, end to end: HitOptions.Cursor through the painter into the driver the +// same gesture carries to a real window's backend. +func TestHeadlessGrabbingHitIsThePointer(t *testing.T) { + session, err := Open(app.Config{Title: "cursor", Width: 80, Height: 60, Paint: func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{Width: 60, Height: 40}, "drag", gfx.HitOptions{Cursor: gfx.PointerCursorGrabbing}) + }}, nil, Options{ReferenceText: true}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + if err := session.Move(30, 20); err != nil { + t.Fatal(err) + } + if cursor := session.Snapshot().Cursor; cursor != app.CursorGrabbing { + t.Fatalf("headless cursor = %v, want grabbing", cursor) + } +} + +// An InputSnapshot that aligns its text to the right carries that through the +// whole stack: the static line is painted right-aligned, the hit declares it, +// and the native editor the focused field is given resolves to AlignRight and +// keeps the line box the component declared, so the text does not move when +// the field gains focus. +func TestInputSnapshotRightAlignmentReachesTheHeadlessEditor(t *testing.T) { + editor := text.NewEditor("1234") + bounds := gfx.Rect{X: 20, Y: 20, Width: 220, Height: 32} + hittest := func() (hits []gfx.Hit) { return } + _ = hittest + config := app.Config{ + Title: "aligned number", Width: 260, Height: 80, + Paint: func(canvas *gfx.Canvas, size gfx.Size) { + components.PaintInput(canvas, gfx.LightTheme(), bounds, components.InputSnapshot{ID: gfx.Item(1), Label: "Amount", Value: editor.String(), Alignment: gfx.AlignRight}) + }, + TextInput: func(context app.TextInputContext) *app.TextInput { + if context.ID != gfx.Item(1) { + t.Fatalf("text input is for %v, want the field", context.ID) + } + if context.Alignment != gfx.AlignRight { + t.Fatalf("the declaration reached the provider as %v, want right", context.Alignment) + } + return &app.TextInput{Editor: editor} + }, + } + session, err := Open(config, nil, Options{ReferenceText: true}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + + // Static frame: the line is right-aligned in the content box, and says so. + snapshot := session.Snapshot() + var textBounds gfx.Rect + for i, hit := range snapshot.Hits { + if hit.ID == gfx.Item(1) { + if declared, ok := snapshot.HitTextAt(i); ok { + textBounds = declared.Bounds + if declared.Alignment != gfx.AlignRight { + t.Fatalf("the declared alignment is %v, want right", declared.Alignment) + } + } + } + } + if textBounds == (gfx.Rect{}) { + t.Fatal("the field declared no text geometry") + } + + if err := session.Click(bounds.X+bounds.Width/2, bounds.Y+bounds.Height/2); err != nil { + t.Fatal(err) + } + snapshot = session.Snapshot() + if snapshot.Editor == nil { + t.Fatal("the click did not focus the field") + } + if snapshot.Editor.Alignment != gfx.AlignRight { + t.Fatalf("the native editor alignment is %v, want right", snapshot.Editor.Alignment) + } + // The editor sits where the component said the text is: the line box inside + // the content rectangle, so the glyphs platform rendering draws are exactly + // where the painted ones were. + if snapshot.Editor.Bounds != textBounds { + t.Fatalf("editor bounds %+v, want the declared text box %+v", snapshot.Editor.Bounds, textBounds) + } +} diff --git a/ui/box.go b/ui/box.go index 3d5e30b13..4314d3382 100644 --- a/ui/box.go +++ b/ui/box.go @@ -285,6 +285,16 @@ func (b Box) Border(width float32, c Color) Box { return b } +// Dashed gives the element's Border or Stroke a repeating dash pattern, +// continuing around rounded corners. It has no effect without a line width; +// calling it again switches back to a solid line. +func (b Box) Dashed() Box { + b.n() + extra := b.f.extra(b.i) + extra.borderDashed = !extra.borderDashed + return b +} + // Shadow casts the shadow of that level of the elevation scale (gfx.ShadowXS to // gfx.ShadowLG) around the element's rounded rectangle, under its fill. func (b Box) Shadow(level gfx.ShadowLevel) Box { diff --git a/ui/draw.go b/ui/draw.go index 76ff4317c..8e9674705 100644 --- a/ui/draw.go +++ b/ui/draw.go @@ -49,12 +49,19 @@ type DrawContext struct { func (d *DrawContext) Part(i int) Rect { return d.frame.selectPart(d.node, i) } // Fade returns c with the opacity of the element, as the colors of the element itself -// are. Colors taken from Theme are faded already. +// are. The color of State looks is already faded; other colors taken from Theme +// are not. func (d *DrawContext) Fade(c Color) Color { c.Alpha *= d.Opacity return c } +// DashedBorder draws a repeating border inside bounds with the element's fade. +// Set bounds to d.Rect for the element whose callback is drawing. +func (d *DrawContext) DashedBorder(bounds Rect, radius, width float32, color Color) { + d.Canvas.DashedRoundedOutline(bounds, radius, width, d.Fade(color)) +} + // drawHooks is what Draw and DrawOver declared on one element. type drawHooks struct { under, over func(*DrawContext) diff --git a/ui/frame.go b/ui/frame.go index 9b58d5b2b..5687eb37e 100644 --- a/ui/frame.go +++ b/ui/frame.go @@ -191,8 +191,9 @@ type extra struct { iconTransform gfx.IconTransform // moves the icon inside its box without moving the box border Color shadow gfx.ShadowLevel - ring Color // Ring: a line around the outside of the element - ringWidth float32 // its width; zero is none + ring Color // Ring: a line around the outside of the element + ringWidth float32 // its width; zero is none + borderDashed bool fade float32 // 1 less the opacity, so that the zero value is opaque gradient int32 // 1 + the index of the element's gradient in frame.gradients, or 0 for none states int32 // 1 + the index of the element's Hover, Pressed and Focus looks in frame.states, or 0 for none diff --git a/ui/paint.go b/ui/paint.go index d4ee50847..62eeb1ea1 100644 --- a/ui/paint.go +++ b/ui/paint.go @@ -58,7 +58,7 @@ func (f *frame) paint(i int32) { canvas.ElevateFaded(r, n.radius, style.shadow, f.opacity) } switch { - case n.borderWidth > 0 && extra.gradient == 0 && f.opacity >= 1 && background.Alpha >= 1: + case n.borderWidth > 0 && !style.dashed && extra.gradient == 0 && f.opacity >= 1 && background.Alpha >= 1: canvas.RoundedBorder(r, n.radius, n.borderWidth, border, background) default: // RoundedBorder paints the border color as a solid backing under the fill, which a @@ -77,7 +77,11 @@ func (f *frame) paint(i int32) { f.paintGradient(n, extra) } if n.borderWidth > 0 { - canvas.RoundedOutline(r, n.radius, n.borderWidth, border) + if style.dashed { + canvas.DashedRoundedOutline(n.rect, n.radius, n.borderWidth, border) + } else { + canvas.RoundedOutline(r, n.radius, n.borderWidth, border) + } } } if extra.moves { diff --git a/ui/style.go b/ui/style.go index a0c2d4818..df4f4a57e 100644 --- a/ui/style.go +++ b/ui/style.go @@ -45,6 +45,7 @@ type Look struct { color, ring Color ringWidth, opacity float32 shadow gfx.ShadowLevel + dashed bool } type lookFields uint8 @@ -52,6 +53,7 @@ type lookFields uint8 const ( lookBackground lookFields = 1 << iota lookBorder + lookDashed lookColor lookRing lookShadow @@ -73,6 +75,14 @@ func (l Look) Border(c Color) Look { return l } +// Dashed switches between the dashed and solid border when this look applies. +// Unlike colors and opacity, a pattern does not blend part way through a transition; +// it changes when the transition is half done. +func (l Look) Dashed(dashed bool) Look { + l.set, l.dashed = l.set|lookDashed, dashed + return l +} + // Color replaces the color of a Text or the tint of an Icon. func (l Look) Color(c Color) Look { l.set, l.color = l.set|lookColor, c @@ -271,12 +281,13 @@ type resolved struct { background, border, color, ring Color ringWidth, opacity float32 shadow gfx.ShadowLevel + dashed bool } func (f *frame) resolve(n *node, extra *extra) resolved { s := resolved{ background: n.background, border: extra.border, color: n.color, ring: extra.ring, - ringWidth: extra.ringWidth, opacity: 1 - extra.fade, shadow: extra.shadow, + ringWidth: extra.ringWidth, opacity: 1 - extra.fade, shadow: extra.shadow, dashed: extra.borderDashed, } if n.flags&flagThemed != 0 { f.themedDefaults(n, extra, &s) @@ -326,6 +337,9 @@ func (s *resolved) apply(look *Look, progress float32) { if look.set&lookBorder != 0 { s.border = s.border.Mix(look.border, progress) } + if look.set&lookDashed != 0 && progress >= 0.5 { + s.dashed = look.dashed + } if look.set&lookColor != 0 { s.color = s.color.Mix(look.color, progress) } diff --git a/ui/style_test.go b/ui/style_test.go index dfb79bb81..2147d9d1a 100644 --- a/ui/style_test.go +++ b/ui/style_test.go @@ -329,6 +329,70 @@ func TestGradientFillsTheElementUnderItsBorderAndFades(t *testing.T) { } } +// A dashed border is a line over the fill, never a solid shape behind it, and +// a look can switch the pattern back to solid while hovered. Both go through +// the stroke pipeline the element's own stroke does. +func TestDashedBorderAndStatefulLookUseTheStrokePipeline(t *testing.T) { + var view View + paint := func(hovered gfx.ID) *gfx.Canvas { + canvas := styleCanvas(hovered, gfx.ID{}, gfx.ID{}, false) + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 80, Height: 50}, func(f *Frame) { + f.Row().Size(80, 50).Radius(6).Background(colorRest).Border(2, colorHover).Dashed(). + Hit(styleRow, "row").Hover(Look{}.Dashed(false)) + }) + return canvas + } + rest := paint(gfx.ID{}) + if len(rest.Triangles()) == 0 { + t.Fatal("the dashed border painted no triangles at rest") + } + for _, rectangle := range rest.Rectangles() { + if rectangle.Color == colorHover { + t.Fatal("the dashed border is a solid rectangle behind its fill") + } + } + hovered := paint(styleRow) + solid := false + for _, rectangle := range hovered.Rectangles() { + if rectangle.Color == colorHover { + solid = true + } + } + if !solid { + t.Fatal("the hover look did not take the border back to a solid one behind its fill") + } + for _, triangle := range hovered.Triangles() { + if triangle.Color == colorHover { + t.Error("a dashed-border triangle survived the hover look that made the border solid") + } + } +} + +// DrawContext.DashedBorder paints a dashed outline inside the element with its +// fade, so a row that draws its own dashed frame follows the element's opacity +// like every other thing it paints. +func TestDrawContextDashedBorderIsFadedWithTheElement(t *testing.T) { + var view View + canvas := testCanvas() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 80, Height: 50}, func(f *Frame) { + f.Row().Size(80, 50).Opacity(0.5).Draw(func(d *DrawContext) { + d.DashedBorder(d.Rect, 4, 1, colorPressed) + }) + }) + painted := false + faded := colorPressed + faded.Alpha *= 0.5 + for _, triangle := range canvas.Triangles() { + if triangle.Color != faded { + t.Fatalf("a dash has color %+v, want the element-faded %+v", triangle.Color, faded) + } + painted = true + } + if !painted { + t.Fatal("DrawContext.DashedBorder painted nothing") + } +} + // styled declares a page with every look, ring, gradient and fade, to count what // it allocates. func styled(view *View, canvas *gfx.Canvas, theme gfx.Theme) { From 6bfd5e27e70b9c57d4a3950e33f081731dbb6528 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 03:27:13 +0800 Subject: [PATCH 16/86] fix(ui): keep a table's horizontal scrollbar inside its reserved gutter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The area a self-scrolling Table declared for its bars took X and Width from its outer frame but Y and Height from the body after the gutter was cut off it: the vertical bar landed in the gutter it reserved, while the horizontal bar's track landed on the deepest visible row instead of the strip below the body — covering the row's hits and taking the right-click on its text, and leaving the reserved strip empty. The bars now own the whole frame below the header, the body plus both reserved gutters, so each bar lands in its own gutter symmetrically with the other and the corner between two bars stays clear. A gutter also reserves the component's viewport beside the bars (ReserveScrollbars), matching the strip the columns and rows have already given up, so a drag maps the body it scrolls exactly; without a gutter the bars keep riding the table's edges over its rows, as before — a table with no bar IDs paints none and keeps the single whole-grid offset the wheel moves. --- ui/table.go | 17 +++++-- ui/table_scroll_horizontal_test.go | 75 ++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 4 deletions(-) diff --git a/ui/table.go b/ui/table.go index d68917d61..2296f66ed 100644 --- a/ui/table.go +++ b/ui/table.go @@ -444,13 +444,22 @@ func (f *frame) paintTableScrollbars(t *tableDecl, r, body Rect, content gfx.Siz size = f.page.config.ScrollbarSize } // The bars sit at the table's own edges, over the body's clips: the component - // places their tracks from these bounds alone, so a gutter only trims what the - // columns and rows paint under them. - areaBounds := Rect{X: r.X, Y: body.Y, Width: r.Width, Height: body.Height} + // places their tracks from these bounds alone. The area they own is the whole + // table below its header, the body plus the gutters it reserved, so a bar + // lands in its gutter symmetrically with the other one and the corner between + // two bars stays clear. A gutter also moves the bars beside the viewport: the + // component takes the bars' strips out of it, matching the strip the columns + // and rows have already given up, so a drag maps the body it scrolls exactly. + // Without a gutter the bars keep sitting over the table's edges, as they had. + areaBounds := Rect{X: r.X, Y: body.Y, Width: r.Width, Height: r.Y + r.Height - body.Y} area := components.BeginScrollArea(f.canvas, f.theme, areaBounds, content). Offset(offsetX, offsetY). ScrollbarSize(size). - HoverScrollbars(revealed). + HoverScrollbars(revealed) + if t.spec.ScrollbarGutter > 0 { + area = area.ReserveScrollbars() + } + area = area. VerticalScrollbar(t.spec.Scrollbar, label, ""). HorizontalScrollbar(t.spec.HorizontalScrollbar, horizontalLabel, "") geometry := area.Geometry() diff --git a/ui/table_scroll_horizontal_test.go b/ui/table_scroll_horizontal_test.go index ce6b2d41b..c1780ae3a 100644 --- a/ui/table_scroll_horizontal_test.go +++ b/ui/table_scroll_horizontal_test.go @@ -338,3 +338,78 @@ func BenchmarkWideTable(b *testing.B) { }) } } + +// gutterColumns are three explicitly 240-wide columns: 720 in a 480-wide table, +// so it scrolls its columns sideways while its 30-tall rows overflow the body +// below a 30-tall header — both bars, both gutters. +var gutterColumns = []components.TableColumn{{Width: 240}, {Width: 240}, {Width: 240}} + +// A table that reserves a gutter for its horizontal scrollbar keeps the bar in +// the reserved strip below its rows, so the bar's track covers no row and the +// right-click on the last visible row's text still reaches the row. A table +// without a gutter keeps the bar riding its bottom edge, as it always has. +func TestTableHorizontalBarKeepsTheGutterStripAndClearRows(t *testing.T) { + theme := gfx.LightTheme() + viewport := gfx.Size{Width: 480, Height: 172} + rows := make(TableRows, 20) + for i := range rows { + rows[i] = []string{"aa", "bb", "cc"} + } + paint := func(canvas *gfx.Canvas, view *View, state *TableState, gutter float32) { + canvas.Reset() + view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(state, TableSpec{ + Rows: tableScope, Columns: gutterColumns, Headers: []string{"A", "B", "C"}, + Source: &rows, RowHeight: 30, + Scrollbar: gfx.Item(900), HorizontalScrollbar: gfx.Item(901), + ScrollbarSize: 12, ScrollbarGutter: gutter, + }).Size(viewport.Width, viewport.Height) + }) + }) + } + canvas, view, state := testCanvas(), &View{}, &TableState{} + paint(canvas, view, state, 12) + deepest := gfx.Hit{} + for _, hit := range canvas.Hits() { + if hit.ID.Scope() == tableScope && hit.Bounds.Bottom() > deepest.Bounds.Bottom() { + deepest = hit + } + } + if deepest.ID.IsZero() { + t.Fatal("no row is painted") + } + bar := hitByID(canvas, gfx.Item(901)) + if bar.ID.IsZero() { + t.Fatal("the horizontal scrollbar is not painted") + } + if bar.Bounds.Y < deepest.Bounds.Bottom()-0.01 || bar.Bounds.Bottom() > viewport.Height+0.01 { + t.Fatalf("the horizontal bar sits at %+v over the deepest row ending at %v; it belongs in the strip between the rows and the table's bottom edge %v", + bar.Bounds, deepest.Bounds.Bottom(), viewport.Height) + } + frontMost := func(x, y float32) gfx.ID { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + hit := hits[i] + if hit.IsLabel || hit.Backdrop || hit.ID.IsZero() { + continue + } + if x >= hit.Bounds.X && x <= hit.Bounds.Right() && y >= hit.Bounds.Y && y <= hit.Bounds.Bottom() { + return hit.ID + } + } + return gfx.ID{} + } + id := frontMost(deepest.Bounds.X+20, deepest.Bounds.Bottom()-5) + if _, ok := id.In(tableScope); !ok { + t.Fatalf("the front-most hit at the last visible row's text is %v, want the row: the bar takes the row's right-click", id) + } + + // Without a gutter the bar rides the table's bottom edge, as it always did. + paint(canvas, view, state, 0) + bar = hitByID(canvas, gfx.Item(901)) + if bar.Bounds.Bottom() != viewport.Height || bar.Bounds.Height != 12 { + t.Fatalf("without a gutter the bar sits at %+v, want it on the bottom edge: 12 tall and flush with the table's bottom %v", + bar.Bounds, viewport.Height) + } +} From 9a72c1293417ade29d978d9deb3369a627b6f7fc Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 03:32:14 +0800 Subject: [PATCH 17/86] feat(app): write HTML and plain text to the clipboard in one copy SetClipboardHTML(html, alt) puts a rich flavour beside a plain one in a single write: NSPasteboard public.html beside public.utf8-plain-text, Windows' registered HTML Format (CF_HTML, header of byte offsets) beside CF_UNICODETEXT, and the CLIPBOARD selection's text/html target beside UTF8_STRING. The GTK shell serves the same pair through gtk_clipboard_set_with_data; an older GTK without it reports ErrUnsupported without disabling plain text. The browser answers through a Promise, so the synchronous call returns ErrAsyncRequired and SetClipboardHTMLAsync writes one ClipboardItem with both MIME flavours. An empty html writes alt with SetClipboardText's exact shape, so the degradation is the copy the caller already spelled out. The headless driver stores the pair beside its private clipboard text and clears it with every other copy, as a real clipboard does. --- app/capabilities.go | 1 + app/capabilities_native.go | 1 + app/capabilities_web.go | 1 + app/clipboard_html.go | 37 +++++ app/clipboard_html_darwin.go | 9 ++ app/clipboard_html_js.go | 9 ++ app/clipboard_html_linux.go | 9 ++ app/clipboard_html_test.go | 136 +++++++++++++++++ app/clipboard_html_unsupported.go | 5 + app/clipboard_html_windows.go | 9 ++ app/driver.go | 2 + app/driver_system.go | 33 +++- app/driver_system_test.go | 21 +++ app/driver_system_unsupported.go | 2 + app/system_async.go | 22 +++ app/system_async_js.go | 6 + app/system_async_other.go | 5 + app/system_js_test.go | 3 + docs/system-integrations.md | 3 +- .../platform/darwin/clipboard_html_darwin.go | 69 +++++++++ .../darwin/clipboard_html_darwin_test.go | 38 +++++ internal/platform/darwin/system_darwin.h | 8 + internal/platform/darwin/system_darwin.m | 141 ++++++++++++++++++ .../linux/clipboard_files_write_linux.go | 1 + .../linux/clipboard_html_linux_test.go | 102 +++++++++++++ .../linux/clipboard_html_write_linux.go | 43 ++++++ .../linux/gtk_clipboard_html_linux_test.go | 53 +++++++ internal/platform/linux/gtk_system_linux.go | 72 +++++++++ internal/platform/linux/selection_linux.go | 20 ++- internal/platform/linux/shell_hooks_linux.go | 1 + internal/platform/linux/system_linux.go | 1 + internal/platform/linux/window_linux.go | 2 + internal/platform/web/clipboard_async_js.go | 60 ++++++++ .../platform/web/clipboard_html_js_test.go | 77 ++++++++++ internal/platform/web/system_js.go | 6 + .../windows/clipboard_html_windows.go | 108 ++++++++++++++ .../windows/clipboard_html_windows_test.go | 94 ++++++++++++ 37 files changed, 1204 insertions(+), 6 deletions(-) create mode 100644 app/clipboard_html.go create mode 100644 app/clipboard_html_darwin.go create mode 100644 app/clipboard_html_js.go create mode 100644 app/clipboard_html_linux.go create mode 100644 app/clipboard_html_test.go create mode 100644 app/clipboard_html_unsupported.go create mode 100644 app/clipboard_html_windows.go create mode 100644 internal/platform/darwin/clipboard_html_darwin.go create mode 100644 internal/platform/darwin/clipboard_html_darwin_test.go create mode 100644 internal/platform/linux/clipboard_html_linux_test.go create mode 100644 internal/platform/linux/clipboard_html_write_linux.go create mode 100644 internal/platform/linux/gtk_clipboard_html_linux_test.go create mode 100644 internal/platform/web/clipboard_html_js_test.go create mode 100644 internal/platform/windows/clipboard_html_windows.go create mode 100644 internal/platform/windows/clipboard_html_windows_test.go diff --git a/app/capabilities.go b/app/capabilities.go index a8a642f1e..56761c77d 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -14,6 +14,7 @@ const ( CapabilityClipboardImage CapabilityClipboardImageAsync CapabilityClipboardFiles + CapabilityClipboardHTML CapabilityFileDialogs CapabilityFileDialogsAsync CapabilityDirectoryDialogs diff --git a/app/capabilities_native.go b/app/capabilities_native.go index ab82c3d45..5cb9a2890 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -13,6 +13,7 @@ func nativeCapabilities() Capabilities { CapabilityClipboardImage | CapabilityClipboardImageAsync | CapabilityClipboardFiles | + CapabilityClipboardHTML | CapabilityFileDialogs | CapabilityFileDialogsAsync | CapabilityDirectoryDialogs | diff --git a/app/capabilities_web.go b/app/capabilities_web.go index be9fd61e3..8b6468fbd 100644 --- a/app/capabilities_web.go +++ b/app/capabilities_web.go @@ -6,6 +6,7 @@ func nativeCapabilities() Capabilities { return Capabilities( CapabilityFileDrop | CapabilityClipboardTextAsync | + CapabilityClipboardHTML | CapabilityClipboardImageAsync | CapabilityFileDialogsAsync | CapabilitySecretStoreAsync | diff --git a/app/clipboard_html.go b/app/clipboard_html.go new file mode 100644 index 000000000..5042a22d0 --- /dev/null +++ b/app/clipboard_html.go @@ -0,0 +1,37 @@ +package app + +import ( + "fmt" + "strings" +) + +// SetClipboardHTML makes the system clipboard hold html as its rich flavour and +// alt as its plain one, in a single write, for a copy a reader may take either +// way: a query result that pastes with its colours into a document and as text +// into an editor. alt is what plain-text readers get — deriving it from html is +// the caller's job, not the clipboard's. +// +// The flavours are what each platform calls rich text: NSPasteboard's +// public.html beside public.utf8-plain-text, Windows' registered "HTML Format" +// (CF_HTML) with the plain text as CF_UNICODETEXT, and the CLIPBOARD +// selection's text/html target beside UTF8_STRING. Nothing is written when +// either string contains NUL; an empty html writes alt as plain text only, with +// exactly SetClipboardText's shape, so the degradation is the copy the caller +// already spelled out. The Web target cannot answer a synchronous write +// (Clipboard.write resolves a Promise) and returns ErrAsyncRequired; +// SetClipboardHTMLAsync writes both flavours there. +func SetClipboardHTML(html, alt string) error { + if strings.IndexByte(html, 0) >= 0 { + return fmt.Errorf("app: clipboard html contains NUL") + } + if strings.IndexByte(alt, 0) >= 0 { + return fmt.Errorf("app: clipboard text contains NUL") + } + if html == "" { + return SetClipboardText(alt) + } + if err, handled := driverSetClipboardHTML(html, alt); handled { + return err + } + return nativeSetClipboardHTML(html, alt) +} diff --git a/app/clipboard_html_darwin.go b/app/clipboard_html_darwin.go new file mode 100644 index 000000000..2d2a93461 --- /dev/null +++ b/app/clipboard_html_darwin.go @@ -0,0 +1,9 @@ +//go:build darwin + +package app + +import darwinplatform "github.com/vivaui/viva/internal/platform/darwin" + +func nativeSetClipboardHTML(html, alt string) error { + return darwinplatform.SetClipboardHTML(html, alt) +} diff --git a/app/clipboard_html_js.go b/app/clipboard_html_js.go new file mode 100644 index 000000000..f26268f81 --- /dev/null +++ b/app/clipboard_html_js.go @@ -0,0 +1,9 @@ +//go:build js && wasm + +package app + +import webplatform "github.com/vivaui/viva/internal/platform/web" + +func nativeSetClipboardHTML(html, alt string) error { + return webSystemError("write clipboard html", webplatform.SetClipboardHTML(html, alt)) +} diff --git a/app/clipboard_html_linux.go b/app/clipboard_html_linux.go new file mode 100644 index 000000000..b3e171b0f --- /dev/null +++ b/app/clipboard_html_linux.go @@ -0,0 +1,9 @@ +//go:build linux + +package app + +import linuxplatform "github.com/vivaui/viva/internal/platform/linux" + +func nativeSetClipboardHTML(html, alt string) error { + return linuxSystemError(linuxplatform.SetClipboardHTML(html, alt)) +} diff --git a/app/clipboard_html_test.go b/app/clipboard_html_test.go new file mode 100644 index 000000000..1b4cf6982 --- /dev/null +++ b/app/clipboard_html_test.go @@ -0,0 +1,136 @@ +//go:build darwin || windows || linux + +package app + +import ( + "testing" +) + +// TestDriverSetClipboardHoldsBothFlavours exercises the headless store of a +// rich copy: both flavours are answered by their own readers, the plain one is +// the driver's clipboard (the text path a paste already uses), and anything +// else copied replaces the pair, as on a real clipboard. +func TestDriverSetClipboardHoldsBothFlavours(t *testing.T) { + driver, err := NewDriver(Config{}, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + + const html = `bold and 中文` + const alt = "bold and 中文" + if err := SetClipboardHTML(html, alt); err != nil { + t.Fatal(err) + } + if got := driver.ClipboardHTML(); got != html { + t.Fatalf("driver html = %q, want %q", got, html) + } + if text, err := ClipboardText(); err != nil || text != alt { + t.Fatalf("plain flavour = %q, %v, want %q", text, err, alt) + } + if err := SetClipboardText("typed"); err != nil { + t.Fatal(err) + } + if got := driver.ClipboardHTML(); got != "" { + t.Fatalf("after text replaced the pair: html = %q, want empty", got) + } + + driver.SetClipboardHTML("one", "one") + if err := driver.SetClipboardImage(onePixelPNG(t)); err != nil { + t.Fatal(err) + } + if got := driver.ClipboardHTML(); got != "" { + t.Fatalf("after an image replaced the pair: html = %q, want empty", got) + } + + // The pre-seeded half of the pair: tests put a rich copy on the private + // clipboard the way another application would. + driver.SetClipboardHTML("y", "y") + if got := driver.ClipboardHTML(); got != "y" { + t.Fatalf("SetClipboardHTML of the driver = %q", got) + } + if text, err := ClipboardText(); err != nil || text != "y" { + t.Fatalf("after the seeded pair: text = %q, %v", text, err) + } +} + +// TestSetClipboardHTMLDegradesToSetClipboardText pins the empty-html path to +// SetClipboardText's own shape: the copy is plain either way, and a refused +// copy writes nothing. +func TestSetClipboardHTMLDegradesToSetClipboardText(t *testing.T) { + driver, err := NewDriver(Config{}, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + + if err := SetClipboardHTML("", "plain only"); err != nil { + t.Fatal(err) + } + if text, err := ClipboardText(); err != nil || text != "plain only" { + t.Fatalf("plain flavour = %q, %v", text, err) + } + if got := driver.ClipboardHTML(); got != "" { + t.Fatalf("an empty html left a rich flavour behind: %q", got) + } + + if err := SetClipboardHTML("", ""); err != nil { + t.Fatal(err) + } + if text, err := ClipboardText(); err != nil || text != "" { + t.Fatalf("empty copy: text = %q, %v", text, err) + } + + if err := SetClipboardHTML("a\x00b", "alt"); err == nil { + t.Fatal("html with NUL was accepted") + } + if err := SetClipboardHTML("x", "a\x00b"); err == nil { + t.Fatal("alt with NUL was accepted") + } + if text, _ := ClipboardText(); text != "" { + t.Fatalf("a refused copy wrote %q", text) + } +} + +// TestSetClipboardHTMLAsyncOfADriverRun pins the async write to the same store; +// on native targets it completes before the call returns. +func TestSetClipboardHTMLAsyncOfADriverRun(t *testing.T) { + driver, err := NewDriver(Config{}, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + + var written bool + if err := SetClipboardHTMLAsync("q", "q", func(err error) { + written = true + if err != nil { + t.Fatal(err) + } + }); err != nil { + t.Fatal(err) + } + if !written { + t.Fatal("the async write did not complete on a driver-backed run") + } + if got := driver.ClipboardHTML(); got != "q" { + t.Fatalf("driver html = %q", got) + } + if text, err := ClipboardText(); err != nil || text != "q" { + t.Fatalf("plain flavour = %q, %v", text, err) + } + + if err := SetClipboardHTMLAsync("", "plain", func(err error) { + if err != nil { + t.Fatal(err) + } + }); err != nil { + t.Fatal(err) + } + if got := driver.ClipboardHTML(); got != "" { + t.Fatalf("an empty async html left a rich flavour behind: %q", got) + } + if text, _ := ClipboardText(); text != "plain" { + t.Fatalf("after the empty-html async copy: text = %q", text) + } +} diff --git a/app/clipboard_html_unsupported.go b/app/clipboard_html_unsupported.go new file mode 100644 index 000000000..7df134a5f --- /dev/null +++ b/app/clipboard_html_unsupported.go @@ -0,0 +1,5 @@ +//go:build !darwin && !windows && !linux && !(js && wasm) + +package app + +func nativeSetClipboardHTML(html, alt string) error { return ErrUnsupported } diff --git a/app/clipboard_html_windows.go b/app/clipboard_html_windows.go new file mode 100644 index 000000000..7799e8b1e --- /dev/null +++ b/app/clipboard_html_windows.go @@ -0,0 +1,9 @@ +//go:build windows + +package app + +import windowsplatform "github.com/vivaui/viva/internal/platform/windows" + +func nativeSetClipboardHTML(html, alt string) error { + return windowsplatform.SetClipboardHTML(html, alt) +} diff --git a/app/driver.go b/app/driver.go index 9c80938b7..69cab7f10 100644 --- a/app/driver.go +++ b/app/driver.go @@ -144,6 +144,7 @@ func NewDriver(config Config, canvas *gfx.Canvas) (*Driver, error) { } driver.painter.setClipboardText = func(value string) { driver.clipboard, driver.system.clipboardImage, driver.system.clipboardFiles = value, nil, nil + driver.system.clipboardHTML = "" } driver.painter.setCursor = func(Cursor) error { return nil } driver.painter.setCursorImage = func(*gfx.CursorImage) error { return nil } @@ -942,6 +943,7 @@ func (driver *Driver) Clipboard() string { return driver.clipboard } // SetClipboard replaces the driver's private clipboard. func (driver *Driver) SetClipboard(value string) { driver.clipboard, driver.system.clipboardImage, driver.system.clipboardFiles = value, nil, nil + driver.system.clipboardHTML = "" } // LastOpenedURL returns the most recent target passed to OpenURL while this diff --git a/app/driver_system.go b/app/driver_system.go index f29a05a92..2b412c34f 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -27,6 +27,7 @@ type driverSystem struct { driver *Driver clipboardImage []byte // PNG bytes; the clipboard holds this or text, never both clipboardFiles []string // paths of copied files, held beside the text a file manager adds + 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 } @@ -80,10 +81,24 @@ func driverSetClipboardText(value string) (error, bool) { if system == nil { return nil, false } - system.driver.clipboard, system.driver.system.clipboardImage, system.driver.system.clipboardFiles = value, nil, nil + system.driver.SetClipboard(value) return nil, true } +// SetClipboardHTML makes the driver's private clipboard hold both flavours of a +// rich copy, as SetClipboardHTML does on the system clipboard: html beside alt +// as the plain text, replacing the image and the files. An empty html writes +// alt as plain text only, like SetClipboard. +func (driver *Driver) SetClipboardHTML(html, alt string) { + driver.system.clipboardHTML = html + driver.clipboard, driver.system.clipboardImage, driver.system.clipboardFiles = alt, nil, nil +} + +// ClipboardHTML is the rich flavour the driver's private clipboard holds, "" +// when the last copy was plain. The string is the driver's own; do not modify +// it. +func (driver *Driver) ClipboardHTML() string { return driver.system.clipboardHTML } + func driverSetClipboardFiles(paths []string) (error, bool) { system := activeDriverSystem.Load() if system == nil { @@ -93,6 +108,18 @@ func driverSetClipboardFiles(paths []string) (error, bool) { return nil, true } +// driverSetClipboardHTML answers the rich copy of a driver-backed run: the +// driver's private clipboard holds html beside alt as its text, the shape the +// native paste paths already read, and anything else copied clears both. +func driverSetClipboardHTML(html, alt string) (error, bool) { + system := activeDriverSystem.Load() + if system == nil { + return nil, false + } + system.driver.SetClipboardHTML(html, alt) + return nil, true +} + // driverSetPrimarySelection and driverPrimarySelection are the primary selection of a driver-backed // run, which exists where the real one does, on Linux. func driverSetPrimarySelection(value string) (error, bool) { @@ -491,7 +518,7 @@ func (driver *Driver) SetClipboardImage(png []byte) error { } driver.system.clipboardImage = append([]byte(nil), png...) driver.system.clipboardFiles = nil - driver.clipboard = "" + driver.clipboard, driver.system.clipboardHTML = "", "" return nil } @@ -532,5 +559,5 @@ func (driver *Driver) SetClipboardFiles(paths []string) { } names = append(names, filepath.Base(path)...) } - driver.clipboard = string(names) + driver.clipboard, driver.system.clipboardHTML = string(names), "" } diff --git a/app/driver_system_test.go b/app/driver_system_test.go index 3f40e132d..3c318f856 100644 --- a/app/driver_system_test.go +++ b/app/driver_system_test.go @@ -299,6 +299,27 @@ func BenchmarkDriverClipboardAndOpenURL(b *testing.B) { } } +func BenchmarkDriverClipboardHTML(b *testing.B) { + driver, err := NewDriver(Config{}, nil) + if err != nil { + b.Fatal(err) + } + defer driver.Close() + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + if err := SetClipboardHTML("remote", "remote text"); err != nil { + b.Fatal(err) + } + if value, err := ClipboardText(); err != nil || value != "remote text" { + b.Fatalf("ClipboardText = %q, %v", value, err) + } + if html := driver.ClipboardHTML(); html != "remote" { + b.Fatalf("ClipboardHTML = %q", html) + } + } +} + func TestDriverInterceptsOpenDirectory(t *testing.T) { driver, err := NewDriver(Config{}, nil) if err != nil { diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index 0785b0b6d..89db8d3ed 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -18,6 +18,8 @@ func driverClipboardFiles() (paths []string, err error, handled bool) { return n func driverSetClipboardFiles([]string) (error, bool) { return nil, false } +func driverSetClipboardHTML(string, string) (error, bool) { return nil, false } + func driverOpenURL(string) (error, bool) { return nil, false } func driverOpenPath(string) (error, bool) { return nil, false } func driverRevealPath(string) (error, bool) { return nil, false } diff --git a/app/system_async.go b/app/system_async.go index e0b303f0f..3bf11ac56 100644 --- a/app/system_async.go +++ b/app/system_async.go @@ -40,6 +40,28 @@ func SetClipboardTextAsync(value string, done func(error)) error { return nativeSetClipboardTextAsync(value, done) } +// SetClipboardHTMLAsync starts SetClipboardHTML's write and calls done with nil +// once the platform accepted it. The call returns immediately when the request +// starts; an error means it could not start and done is not called. Native +// targets complete before the call returns; the browser writes both flavours +// through one ClipboardItem, which needs a user gesture. +func SetClipboardHTMLAsync(html, alt string, done func(error)) error { + if done == nil { + return fmt.Errorf("app: nil clipboard callback") + } + if strings.IndexByte(html, 0) >= 0 || strings.IndexByte(alt, 0) >= 0 { + return fmt.Errorf("app: clipboard html write contains NUL") + } + if html == "" { + return SetClipboardTextAsync(alt, done) + } + if err, handled := driverSetClipboardHTML(html, alt); handled { + done(err) + return nil + } + return nativeSetClipboardHTMLAsync(html, alt, done) +} + // RequestNotificationPermission asks the browser for permission to show // notifications. On desktop it calls done with Granted because the operating // system asks for permission when a notification is delivered. done runs diff --git a/app/system_async_js.go b/app/system_async_js.go index cfa83a9a4..7e8f7ca0f 100644 --- a/app/system_async_js.go +++ b/app/system_async_js.go @@ -16,6 +16,12 @@ func nativeSetClipboardTextAsync(value string, done func(error)) error { })) } +func nativeSetClipboardHTMLAsync(html, alt string, done func(error)) error { + return webSystemError("write clipboard", webplatform.SetClipboardHTMLAsync(html, alt, func(err error) { + done(webSystemError("write clipboard", err)) + })) +} + func nativeRequestNotificationPermission(done func(NotificationPermission, error)) error { return webSystemError("request notification permission", webplatform.RequestNotificationPermission(func(granted bool, err error) { if err != nil { diff --git a/app/system_async_other.go b/app/system_async_other.go index 33cae1e51..5a74bea4e 100644 --- a/app/system_async_other.go +++ b/app/system_async_other.go @@ -13,6 +13,11 @@ func nativeSetClipboardTextAsync(value string, done func(error)) error { return nil } +func nativeSetClipboardHTMLAsync(html, alt string, done func(error)) error { + done(nativeSetClipboardHTML(html, alt)) + return nil +} + func nativeRequestNotificationPermission(done func(NotificationPermission, error)) error { done(NotificationPermissionGranted, nil) return nil diff --git a/app/system_js_test.go b/app/system_js_test.go index 17e0a3d0e..461550c78 100644 --- a/app/system_js_test.go +++ b/app/system_js_test.go @@ -14,6 +14,9 @@ func TestBrowserPromiseOnlySystemAPIsExposeAsyncConstraint(t *testing.T) { if err := SetClipboardText("viva"); !errors.Is(err, ErrAsyncRequired) { t.Fatalf("SetClipboardText error = %v", err) } + if err := SetClipboardHTML("viva", "viva"); !errors.Is(err, ErrAsyncRequired) { + t.Fatalf("SetClipboardHTML error = %v", err) + } if _, err := OpenFiles(OpenFileOptions{}); !errors.Is(err, ErrAsyncRequired) { t.Fatalf("OpenFiles error = %v", err) } diff --git a/docs/system-integrations.md b/docs/system-integrations.md index 8892c8cd6..5eec83a39 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -10,6 +10,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Capability | macOS | Windows | Linux/X11 | WebAssembly browser | | --- | --- | --- | --- | --- | | Read/write text clipboard | `NSPasteboard` | Unicode Win32 clipboard | X11 `CLIPBOARD`, `UTF8_STRING` with `STRING` read fallback; text above 128 KiB is served and read in pieces (INCR); handed to the clipboard manager when the owning window closes, if the desktop has one | synchronous calls return `ErrAsyncRequired`; `ClipboardTextAsync` and `SetClipboardTextAsync` use the Clipboard API and require a user gesture | +| Rich copy (`SetClipboardHTML`, html + plain alt) | `NSPasteboard`: `public.html` beside `public.utf8-plain-text` | registered `HTML Format` (CF_HTML, with its header of byte offsets) beside `CF_UNICODETEXT` | X11 `CLIPBOARD`: `text/html` target beside `UTF8_STRING`; the GTK shell serves the same pair through `gtk_clipboard_set_with_data` | synchronous calls return `ErrAsyncRequired`; `SetClipboardHTMLAsync` writes one `ClipboardItem` with both MIME flavours and needs a user gesture | | Copied files (`ClipboardFiles`, returns `[]string`) | the pasteboard's file URLs, file reference URLs resolved to paths; promised files have no path and are not listed | the `CF_HDROP` list (UTF-16 form) | X11 `CLIPBOARD`: `x-special/gnome-copied-files` (Nautilus, Nemo, Caja, Thunar) or `text/uri-list` (Dolphin, most toolkits); the GTK shell asks GTK for `text/uri-list` | `ErrUnsupported` | | Primary selection (`SetPrimarySelection`, `PrimarySelection`) | `ErrUnsupported` | `ErrUnsupported` | X11 `PRIMARY`: selected text, pasted with a middle click | `ErrUnsupported` | | Cursor shape | AppKit cursor; wait unsupported, diagonal resize requires macOS 15 | Win32 system cursors; running window required | XCB cursor font; running window required | CSS cursor on `documentElement` | @@ -136,7 +137,7 @@ Clipboard operations, file pickers, secret storage and font loading settle through Promises. They are intentionally not started from the synchronous API: returning before the Promise settles would lie about success, and waiting would deadlock the WASM event loop. The typed asynchronous counterparts are -`ClipboardTextAsync`, `SetClipboardTextAsync`, `RequestClipboardImage`, +`ClipboardTextAsync`, `SetClipboardTextAsync`, `SetClipboardHTMLAsync`, `RequestClipboardImage`, `OpenFilesAsync`, `SaveFileAsync`, `StoreSecretAsync`, `LoadSecretAsync`, `DeleteSecretAsync`, `RegisterFontAsync` and `RequestNotificationPermission`. Each calls its completion exactly once; native targets complete before the call diff --git a/internal/platform/darwin/clipboard_html_darwin.go b/internal/platform/darwin/clipboard_html_darwin.go new file mode 100644 index 000000000..77d192176 --- /dev/null +++ b/internal/platform/darwin/clipboard_html_darwin.go @@ -0,0 +1,69 @@ +//go:build darwin + +package darwin + +/* +#include +#include "system_darwin.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" +) + +// SetClipboardHTML puts html on the general pasteboard as public.html beside +// alt as public.utf8-plain-text, the pair a rich copy leaves. The flavours are +// the pasteboard's own types, so a reader takes whichever it knows. +func SetClipboardHTML(html, alt string) error { return putPasteboardHTML(nil, html, alt) } + +func putPasteboardHTML(name *C.char, html, alt string) error { + nativeHTML, err := systemCString("clipboard html", html) + if err != nil { + return err + } + defer C.free(unsafe.Pointer(nativeHTML)) + nativeAlt, err := systemCString("clipboard alt", alt) + if err != nil { + return err + } + defer C.free(unsafe.Pointer(nativeAlt)) + if C.viva_system_pasteboard_put_html(name, nativeHTML, nativeAlt) != 0 { + if name == nil { + return fmt.Errorf("darwin: put html on the clipboard failed") + } + return fmt.Errorf("darwin: put html on pasteboard %q failed", C.GoString(name)) + } + return nil +} + +func putPrivatePasteboardHTML(name, html, alt string) error { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + return putPasteboardHTML(cName, html, alt) +} + +func privatePasteboardHTML(name string) (string, error) { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + var value *C.char + var nativeError *C.char + if C.viva_system_pasteboard_html(cName, &value, &nativeError) != 0 { + return "", systemError("read pasteboard html", nativeError) + } + defer C.viva_system_free(unsafe.Pointer(value)) + return C.GoString(value), nil +} + +func privatePasteboardText(name string) (string, error) { + cName := C.CString(name) + defer C.free(unsafe.Pointer(cName)) + var value *C.char + var nativeError *C.char + if C.viva_system_pasteboard_text(cName, &value, &nativeError) != 0 { + return "", systemError("read pasteboard text", nativeError) + } + defer C.viva_system_free(unsafe.Pointer(value)) + return C.GoString(value), nil +} diff --git a/internal/platform/darwin/clipboard_html_darwin_test.go b/internal/platform/darwin/clipboard_html_darwin_test.go new file mode 100644 index 000000000..5ea73e263 --- /dev/null +++ b/internal/platform/darwin/clipboard_html_darwin_test.go @@ -0,0 +1,38 @@ +//go:build darwin + +package darwin + +import ( + "testing" +) + +// TestPasteboardHTMLOffersBothFlavours writes the pair on a private pasteboard +// and reads each flavour back the way an application that asks for it would: +// an html reader takes public.html, a plain reader the text beside it. +func TestPasteboardHTMLOffersBothFlavours(t *testing.T) { + name := privateName(t) + const html = `加粗 & text` + const alt = "加粗 & text" + if got, err := privatePasteboardHTML(name); err != nil || got != "" { + t.Fatalf("a fresh pasteboard: html = %q, %v", got, err) + } + if err := putPrivatePasteboardHTML(name, html, alt); err != nil { + t.Fatal(err) + } + got, err := privatePasteboardHTML(name) + if err != nil || got != html { + t.Fatalf("pasteboard html = %q, %v, want %q", got, err, html) + } + text, err := privatePasteboardText(name) + if err != nil || text != alt { + t.Fatalf("pasteboard text beside the html = %q, %v, want %q", text, err, alt) + } + + // A copy of another kind replaces the pair, as every write clears the board. + if err := putPrivatePasteboardFiles(name, []string{"/tmp/report.txt"}); err != nil { + t.Fatal(err) + } + if got, err := privatePasteboardHTML(name); err != nil || got != "" { + t.Fatalf("after files replaced the pair: html = %q, %v", got, err) + } +} diff --git a/internal/platform/darwin/system_darwin.h b/internal/platform/darwin/system_darwin.h index 301d86d40..b55e5755b 100644 --- a/internal/platform/darwin/system_darwin.h +++ b/internal/platform/darwin/system_darwin.h @@ -26,6 +26,14 @@ int viva_system_clipboard_files(const char *pasteboard, size_t max, viva_system_ // Puts file URLs on a named pasteboard, as Finder does after a copy. names is // the text a file manager also leaves there (the file names, one per line). int viva_system_pasteboard_put_files(const char *pasteboard, const char *const *paths, size_t count, const char *names); +// Writes html as public.html beside alt as public.utf8-plain-text on a named +// pasteboard; NULL is the general one (main thread). +int viva_system_pasteboard_put_html(const char *pasteboard, const char *html, const char *alt); +// Reads a named pasteboard's public.html as UTF-8 into *value (free with +// viva_system_free); "" when it holds none. +int viva_system_pasteboard_html(const char *pasteboard, char **value, char **error_message); +// Reads a named pasteboard's plain text the same way. +int viva_system_pasteboard_text(const char *pasteboard, char **value, char **error_message); // Shows a modal alert. It must run on the main thread; elsewhere it returns -1. int viva_system_show_fatal_error(const char *title, const char *message); int viva_system_set_cursor(uint8_t shape, char **error_message); diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m index b6926c423..04a685674 100644 --- a/internal/platform/darwin/system_darwin.m +++ b/internal/platform/darwin/system_darwin.m @@ -208,6 +208,147 @@ int viva_system_set_clipboard_text(const char *text, char **error_message) { return [NSPasteboard pasteboardWithName:viva_string(name)]; } +// viva_system_pasteboard_put_html writes html as public.html beside alt as +// public.utf8-plain-text, the pair a rich copy leaves: a reader takes whichever +// flavour it knows, and a plain reader still pastes. +int viva_system_pasteboard_put_html(const char *pasteboard, const char *html, const char *alt) { + __block char *failure = NULL; + dispatch_block_t operation = ^{ + @autoreleasepool { + NSString *rich = viva_string(html); + NSString *plain = viva_string(alt); + if (rich == nil || plain == nil) { + failure = viva_copy_utf8(@"clipboard html is not valid UTF-8"); + return; + } + NSPasteboard *board = viva_pasteboard_named(pasteboard); + NSData *data = [rich dataUsingEncoding:NSUTF8StringEncoding]; + [board clearContents]; + if (![board setData:data forType:NSPasteboardTypeHTML]) { + failure = viva_copy_utf8(@"AppKit refused clipboard html"); + return; + } + [board setString:plain forType:NSPasteboardTypeString]; + } + }; + if (pasteboard == NULL) { + viva_on_main_sync(operation); + } else { + operation(); + } + if (failure != NULL) { + free(failure); + return -1; + } + return 0; +} + +// viva_system_pasteboard_html reads a named pasteboard's public.html as UTF-8, +// "" when it holds none. Status: 0 html in *value, -1 failure with *error_message. +int viva_system_pasteboard_html(const char *pasteboard, char **value, char **error_message) { + if (value == NULL) { + viva_set_error(error_message, @"clipboard output is missing"); + return -1; + } + *value = NULL; + __block int status = 0; + __block char *result = NULL; + __block char *failure = NULL; + dispatch_block_t operation = ^{ + @autoreleasepool { + NSPasteboard *board = viva_pasteboard_named(pasteboard); + NSData *data = [board dataForType:NSPasteboardTypeHTML]; + if (data == nil) { + return; + } + if (data.length > viva_max_clipboard_bytes) { + failure = viva_copy_utf8(@"clipboard html exceeds 64 MiB"); + status = -1; + return; + } + NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + if (html == nil) { + failure = viva_copy_utf8(@"clipboard html is not valid UTF-8"); + status = -1; + return; + } + result = viva_copy_utf8(html); + if (result == NULL) { + failure = viva_copy_utf8(@"failed to allocate clipboard html"); + status = -1; + } + } + }; + if (pasteboard == NULL) { + viva_on_main_sync(operation); + } else { + operation(); + } + if (status != 0) { + if (error_message != NULL) { + *error_message = failure; + } else { + free(failure); + } + return status; + } + if (result == NULL) { + result = strdup(""); + } + *value = result; + return 0; +} + +// viva_system_pasteboard_text is viva_system_clipboard_text for a named +// pasteboard, the plain flavour of the pair put_html writes. +int viva_system_pasteboard_text(const char *pasteboard, char **value, char **error_message) { + if (value == NULL) { + viva_set_error(error_message, @"clipboard output is missing"); + return -1; + } + *value = NULL; + __block int status = 0; + __block char *result = NULL; + __block char *failure = NULL; + dispatch_block_t operation = ^{ + @autoreleasepool { + NSPasteboard *board = viva_pasteboard_named(pasteboard); + NSString *text = [board stringForType:NSPasteboardTypeString]; + if (text == nil) { + return; + } + if ([text lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > viva_max_clipboard_bytes) { + failure = viva_copy_utf8(@"clipboard text exceeds 64 MiB"); + status = -1; + return; + } + result = viva_copy_utf8(text); + if (result == NULL) { + failure = viva_copy_utf8(@"failed to allocate clipboard text"); + status = -1; + } + } + }; + if (pasteboard == NULL) { + viva_on_main_sync(operation); + } else { + operation(); + } + if (status != 0) { + if (error_message != NULL) { + *error_message = failure; + } else { + free(failure); + } + return status; + } + if (result == NULL) { + result = strdup(""); + } + *value = result; + return 0; +} + static NSArray *viva_image_types(void) { return @[NSPasteboardTypePNG, NSPasteboardTypeTIFF]; } diff --git a/internal/platform/linux/clipboard_files_write_linux.go b/internal/platform/linux/clipboard_files_write_linux.go index 9ec85fa61..bcf155ec5 100644 --- a/internal/platform/linux/clipboard_files_write_linux.go +++ b/internal/platform/linux/clipboard_files_write_linux.go @@ -44,6 +44,7 @@ func SetClipboardFiles(paths []string) error { names[index] = filepath.Base(path) } win.clipboard = strings.Join(names, "\n") + win.clipboardHTML = "" win.clipboardFiles = append([]string(nil), paths...) win.ownsClipboard = true return nil diff --git a/internal/platform/linux/clipboard_html_linux_test.go b/internal/platform/linux/clipboard_html_linux_test.go new file mode 100644 index 000000000..676d82e11 --- /dev/null +++ b/internal/platform/linux/clipboard_html_linux_test.go @@ -0,0 +1,102 @@ +package linux + +import ( + "testing" +) + +// TestAClipboardHTMLOfferedAsTextHTMLBesideUTF8 pins the selection request +// service of a rich copy: TARGETS names text/html only while the pair is on +// the board, the html target hands over the fragment, and the plain targets +// beside it are untouched. +func TestAClipboardHTMLOfferedAsTextHTMLBesideUTF8(t *testing.T) { + recorder := &selectionRecorder{} + win := newSelectionWindowWithHTML(recorder, "alt text", "rich and 中文") + request := func(target uint32) propertyWrite { + t.Helper() + before := len(recorder.writes) + if err := win.handleSelectionRequest(&xcbSelectionRequestEvent{Requestor: 3, Selection: 10, Target: target, Property: 14}); err != nil { + t.Fatal(err) + } + return recorder.writes[before] + } + targets := request(13) + var offered []uint32 + for offset := 0; offset+4 <= len(targets.data); offset += 4 { + offered = append(offered, uint32(targets.data[offset])|uint32(targets.data[offset+1])<<8|uint32(targets.data[offset+2])<<16|uint32(targets.data[offset+3])<<24) + } + if len(offered) != 5 || offered[0] != 13 || offered[4] != win.htmlAtom { + t.Fatalf("TARGETS = %v, want [13 .. html=17], the html named only while the pair holds", offered) + } + write := request(win.htmlAtom) + if write.kind != win.htmlAtom || string(write.data) != "rich and 中文" { + t.Fatalf("text/html = kind %d data %q", write.kind, write.data) + } + if write := request(11); string(write.data) != "alt text" { + t.Fatalf("UTF8_STRING beside the html = %q", write.data) + } + + // Another copy drops the flavour: TARGETS stops naming text/html, and asking + // for it anyway is refused (the notify carries no property). + win.clipboard, win.clipboardHTML = "typed", "" + recorder.writes = nil + targets = request(13) + offered = nil + for offset := 0; offset+4 <= len(targets.data); offset += 4 { + offered = append(offered, uint32(targets.data[offset])|uint32(targets.data[offset+1])<<8|uint32(targets.data[offset+2])<<16|uint32(targets.data[offset+3])<<24) + } + for _, atom := range offered { + if atom == win.htmlAtom { + t.Fatal("TARGETS still names text/html after a plain copy") + } + } + recorder.writes, recorder.sent = nil, nil + if err := win.handleSelectionRequest(&xcbSelectionRequestEvent{Requestor: 3, Selection: 10, Target: win.htmlAtom, Property: 14}); err != nil { + t.Fatal(err) + } + if len(recorder.writes) != 0 || len(recorder.sent) != 1 || recorder.sent[0].Property != xcbAtomNone { + t.Fatalf("after the pair was replaced: writes %+v sent %+v", recorder.writes, recorder.sent) + } + // And losing the clipboard loses the flavour with it. + win.ownsClipboard = true + win.handleSelectionClear(&xcbSelectionClearEvent{Selection: 10}) + if win.clipboardHTML != "" || win.ownsClipboard { + t.Fatal("clearing the clipboard kept the rich flavour") + } +} + +func newSelectionWindowWithHTML(recorder *selectionRecorder, text, html string) *window { + win := newSelectionWindow(recorder, text) + win.clipboardHTML = html + win.htmlAtom = 17 + return win +} + +// TestSetClipboardHTMLClaimsTheBoardAndRefusesBadInput covers the ownership +// path: the pair claims the CLIPBOARD selection, invalid input is refused +// before anything is claimed, and without a shell hook that can write the pair +// the X11 event loop's own serve path is what answers. +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} + activeWindow.Store(win) + t.Cleanup(func() { activeWindow.Store(nil) }) + 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") + } + activeWindow.Store(nil) + if err := SetClipboardHTML("x", "x"); err == nil || err.Error() == "" { + t.Fatal("a copy without a window was accepted") + } +} diff --git a/internal/platform/linux/clipboard_html_write_linux.go b/internal/platform/linux/clipboard_html_write_linux.go new file mode 100644 index 000000000..3815b7fa5 --- /dev/null +++ b/internal/platform/linux/clipboard_html_write_linux.go @@ -0,0 +1,43 @@ +package linux + +import ( + "fmt" + "unicode/utf8" +) + +// SetClipboardHTML makes the CLIPBOARD selection hold html as its text/html +// target beside alt as the UTF8_STRING one: a rich reader asks for text/html, a +// plain one the text, both from one copy. The X11 owner serves the pair while +// this window lives; GTK, which owns the display connection on Wayland, serves +// the same two targets through its own clipboard. +func SetClipboardHTML(html, alt string) error { + if len(html) > maxClipboardBytes { + return fmt.Errorf("linux: clipboard html exceeds 64 MiB") + } + if !utf8.ValidString(html) || !utf8.ValidString(alt) { + return fmt.Errorf("linux: clipboard html is not valid UTF-8") + } + if hooks := shellHooks.Load(); hooks != nil { + if hooks.setClipboardHTML == nil { + return ErrUnsupported + } + return hooks.setClipboardHTML(html, alt) + } + win := activeWindow.Load() + if win == nil { + return fmt.Errorf("linux: clipboard ownership requires a running window") + } + win.mu.Lock() + defer win.mu.Unlock() + if activeWindow.Load() != win || win.connection == 0 { + return fmt.Errorf("linux: clipboard ownership requires a running window") + } + if err := win.claimClipboardLocked(); err != nil { + return err + } + win.clipboard = alt + win.clipboardHTML = html + win.clipboardFiles = nil + win.ownsClipboard = true + return nil +} diff --git a/internal/platform/linux/gtk_clipboard_html_linux_test.go b/internal/platform/linux/gtk_clipboard_html_linux_test.go new file mode 100644 index 000000000..73b8d715e --- /dev/null +++ b/internal/platform/linux/gtk_clipboard_html_linux_test.go @@ -0,0 +1,53 @@ +//go:build linux && vivagtk + +package linux + +import ( + "errors" + "runtime" + "syscall" + "testing" +) + +// The rich pair is an optional GTK capability, like the file list: without +// gtk_clipboard_set_with_data its absence must reach callers as the Linux +// unsupported sentinel, and with it the pair goes through one call, without +// disabling plain text. +func TestGTKClipboardHTMLWriteReportsUnsupportedWithoutSetWithData(t *testing.T) { + runtime.LockOSThread() + t.Cleanup(runtime.UnlockOSThread) + previousClipboards, previousHooks := clipboards, shellHooks.Load() + t.Cleanup(func() { + clipboards = previousClipboards + shellHooks.Store(previousHooks) + }) + textWrites := 0 + clipboards = gtkClipboards{ + ok: true, clipboard: 17, + setText: func(board uintptr, value *byte, length int32) { textWrites++ }, + } + application := >kApplication{mainThread: syscall.Gettid()} + application.installHooks() + if err := SetClipboardHTML("bold", "bold"); !errors.Is(err, ErrUnsupported) { + t.Fatalf("GTK without rich writes returned %v, want ErrUnsupported", err) + } + if err := SetClipboardText("hello"); err != nil || textWrites != 1 { + t.Fatalf("optional rich support broke text writes: error=%v writes=%d", err, textWrites) + } + htmlWrites := 0 + clipboards.setWithData = func(clipboard, targets uintptr, count int32, get, clear, data uintptr) int32 { + if clipboard != 17 || targets == 0 || count != 2 || get == 0 || clear == 0 { + t.Fatalf("unexpected set_with_data call: clipboard=%d targets=%d count=%d", clipboard, targets, count) + } + htmlWrites++ + return 1 + } + clipboards.selectionGet = func(uintptr) uintptr { return 1 } + clipboards.selectionSet = func(data, kind uintptr, format int32, bytes *byte, length int32) int32 { return 1 } + if err := SetClipboardHTML("bold", "bold"); err != nil || htmlWrites != 1 { + t.Fatalf("GTK with rich writes returned error=%v writes=%d", err, htmlWrites) + } + if err := SetClipboardText("hello again"); err != nil || textWrites != 2 { + t.Fatalf("rich writes broke text writes: error=%v writes=%d", err, textWrites) + } +} diff --git a/internal/platform/linux/gtk_system_linux.go b/internal/platform/linux/gtk_system_linux.go index 5d82bbbbf..7c8b88542 100644 --- a/internal/platform/linux/gtk_system_linux.go +++ b/internal/platform/linux/gtk_system_linux.go @@ -34,6 +34,12 @@ type gtkClipboards struct { waitURIs func(clipboard uintptr) uintptr setURIs func(clipboard, uris uintptr) strfreev func(list uintptr) + // The rich pair: set_with_data owns the clipboard until another copy and + // answers the requested target from the get callback. + setWithData func(clipboard, targets uintptr, count int32, get, clear, data uintptr) int32 + selectionData func(data uintptr) uintptr + selectionSet func(data, kind uintptr, format int32, bytes *byte, length int32) int32 + selectionGet func(data uintptr) uintptr clipboard, primary uintptr ok bool @@ -79,6 +85,14 @@ func (a *gtkApplication) clipboardAPI() (*gtkClipboards, error) { c.saveBuffer = nil } } + // The rich pair is optional as the file list is: an older GTK without + // gtk_clipboard_set_with_data still has plain text. + if !g.lookup(&c.setWithData, "gtk_clipboard_set_with_data") || + !g.lookup(&c.selectionData, "gtk_selection_data_get_data") || + !g.lookup(&c.selectionSet, "gtk_selection_data_set") || + !g.lookup(&c.selectionGet, "gtk_selection_data_get_target") { + c.setWithData, c.selectionData, c.selectionSet, c.selectionGet = nil, nil, nil, nil + } c.ok = true return c, nil } @@ -115,6 +129,12 @@ func (a *gtkApplication) installHooks() { } return }, + setClipboardHTML: func(html, alt string) (err error) { + if e := a.onMain(func() { err = a.writeHTML(html, alt) }); e != nil { + return e + } + return + }, primaryText: func() (value string, err error) { err = a.onMain(func() { value, err = a.readText(true) }) return @@ -200,6 +220,58 @@ func (a *gtkApplication) writeText(primary bool, value string) error { return nil } +// gtkTargetEntry is C's GtkTargetEntry: the target's name, its flags and the +// info the get callback matches on, laid out for the call that takes an array. +type gtkTargetEntry struct { + target uintptr + flags uint32 + info uint32 +} + +// writeHTML makes the clipboard hold html as text/html beside alt as plain +// text. GTK owns the pair through gtk_clipboard_set_with_data, whose get +// callback answers whichever target the requestor asked for; the flavour lives +// as long as the clipboard does, as it does on X11. +func (a *gtkApplication) writeHTML(html, alt string) error { + c, err := a.clipboardAPI() + if err != nil { + return err + } + if c.setWithData == nil { + return ErrUnsupported + } + htmlName := cString("text/html") + textName := cString("UTF8_STRING") + targets := [2]gtkTargetEntry{ + {target: uintptr(unsafe.Pointer(&htmlName[0]))}, + {target: uintptr(unsafe.Pointer(&textName[0]))}, + } + htmlAtom := c.atomIntern(&htmlName[0], 0) + htmlBytes, textBytes := cString(html), cString(alt) + // The get callback runs on GTK's thread with the pair this closure captured, + // answering the target the requestor asked for by the atom of its name. + get := purego.NewCallback(func(clipboard, selection, data uintptr) uintptr { + kind := c.selectionGet(data) + value := textBytes + if kind == htmlAtom { + value = htmlBytes + } + c.selectionSet(data, kind, 8, &value[0], int32(len(value))) + return 0 + }) + clearCallback := purego.NewCallback(func(clipboard, userData uintptr) uintptr { return 0 }) + if c.setWithData(c.clipboard, uintptr(unsafe.Pointer(&targets[0])), 2, get, clearCallback, 0) == 0 { + return fmt.Errorf("linux: gtk_clipboard_set_with_data failed") + } + // gtk_clipboard_set_with_data reads the entries in the call; the get callback + // keeps the two flavours for as long as GTK may ask for them. + runtime.KeepAlive(htmlName) + runtime.KeepAlive(textName) + runtime.KeepAlive(htmlBytes) + runtime.KeepAlive(textBytes) + return nil +} + // readFiles returns the paths of the file URIs the clipboard holds. GTK asks the owner for // text/uri-list and hands over a NULL-terminated array of strings. func (a *gtkApplication) readFiles() ([]string, error) { diff --git a/internal/platform/linux/selection_linux.go b/internal/platform/linux/selection_linux.go index ea07b7b1f..8fd86259b 100644 --- a/internal/platform/linux/selection_linux.go +++ b/internal/platform/linux/selection_linux.go @@ -58,6 +58,9 @@ func (win *window) ensureClipboardAtoms() error { if win.gnomeFilesAtom, err = win.api.atom(win.connection, "x-special/gnome-copied-files"); err != nil { return err } + if win.htmlAtom, err = win.api.atom(win.connection, "text/html"); err != nil { + return err + } return nil } @@ -159,13 +162,23 @@ func (win *window) handleSelectionRequest(request *xcbSelectionRequestEvent) err } switch request.Target { case win.targetsAtom: - targets := make([]uint32, 0, 6) + targets := make([]uint32, 0, 7) targets = append(targets, win.targetsAtom, win.utf8Atom, win.textAtom, xcbAtomString) + if request.Selection == win.clipboardAtom && win.clipboardHTML != "" { + targets = append(targets, win.htmlAtom) + } if request.Selection == win.clipboardAtom && len(win.clipboardFiles) > 0 { targets = append(targets, win.uriListAtom, win.gnomeFilesAtom) } win.api.changeProperty(win.connection, xcbPropertyReplace, request.Requestor, property, xcbAtomAtom, 32, uint32(len(targets)), unsafe.Pointer(&targets[0])) notify.Property = property + case win.htmlAtom: + // The rich flavour of a rich copy, beside the text its plain readers + // take; only the CLIPBOARD holds one, and only until another copy. + if request.Selection == win.clipboardAtom && win.clipboardHTML != "" && + win.writeSelection(request.Requestor, property, request.Target, []byte(win.clipboardHTML)) { + notify.Property = property + } case win.uriListAtom: if request.Selection == win.clipboardAtom && len(win.clipboardFiles) > 0 && win.writeSelection(request.Requestor, property, request.Target, platform.FileURIList(win.clipboardFiles)) { notify.Property = property @@ -270,7 +283,7 @@ func (win *window) handleSelectionClear(event *xcbSelectionClearEvent) { defer win.mu.Unlock() switch { case event.Selection == win.clipboardAtom && win.clipboardAtom != 0: - win.clipboard, win.clipboardFiles = "", nil + win.clipboard, win.clipboardHTML, win.clipboardFiles = "", "", nil win.ownsClipboard = false case event.Selection == xcbAtomPrimary: win.selections.primary = "" @@ -310,6 +323,9 @@ func (win *window) saveClipboardToManager() { win.mu.Lock() err = win.ensureClipboardAtoms() targets := []uint32{win.utf8Atom, win.textAtom, xcbAtomString} + if win.clipboardHTML != "" { + targets = append(targets, win.htmlAtom) + } if len(win.clipboardFiles) > 0 { targets = append(targets, win.uriListAtom, win.gnomeFilesAtom) } diff --git a/internal/platform/linux/shell_hooks_linux.go b/internal/platform/linux/shell_hooks_linux.go index d2a2d0876..2e1389950 100644 --- a/internal/platform/linux/shell_hooks_linux.go +++ b/internal/platform/linux/shell_hooks_linux.go @@ -15,6 +15,7 @@ var shellHooks atomic.Pointer[desktopHooks] type desktopHooks struct { clipboardText func() (string, error) setClipboardText func(string) error + setClipboardHTML func(html, alt string) error hasClipboardImage func() bool clipboardImagePNG func() ([]byte, error) clipboardFiles func() ([]string, error) diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index 1b12c18f8..5f6ab41cf 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -475,6 +475,7 @@ func SetClipboardText(value string) error { return err } win.clipboard = value + win.clipboardHTML = "" win.clipboardFiles = nil win.ownsClipboard = true return nil diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 7b85b844a..f4dbc8b42 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -44,8 +44,10 @@ type window struct { renderTried bool renderErr error clipboard string + clipboardHTML string clipboardFiles []string clipboardAtom uint32 + htmlAtom uint32 utf8Atom uint32 textAtom uint32 targetsAtom uint32 diff --git a/internal/platform/web/clipboard_async_js.go b/internal/platform/web/clipboard_async_js.go index fee92881c..d1721dcb5 100644 --- a/internal/platform/web/clipboard_async_js.go +++ b/internal/platform/web/clipboard_async_js.go @@ -85,6 +85,66 @@ func SetClipboardTextAsync(value string, done func(error)) error { return nil } +// SetClipboardHTMLAsync writes the rich copy through one ClipboardItem, the +// browser's own form of a clipboard entry that carries several flavours at +// once: text/html beside text/plain, so a rich reader takes the html and a +// plain one the alt. The browser resolves a Promise; done runs on the event +// loop, exactly once. The call retains the user gesture, so invoke it from an +// input handler when the browser asks for permission. +func SetClipboardHTMLAsync(html, alt string, done func(error)) error { + if done == nil { + return fmt.Errorf("%w: nil clipboard callback", ErrUnavailable) + } + navigator := js.Global().Get("navigator") + if navigator.Type() != js.TypeObject || navigator.IsNull() { + return fmt.Errorf("%w: navigator is missing", ErrUnavailable) + } + clipboard := navigator.Get("clipboard") + if clipboard.Type() != js.TypeObject || clipboard.IsNull() { + return fmt.Errorf("%w: navigator.clipboard is missing", ErrUnavailable) + } + if clipboard.Get("write").Type() != js.TypeFunction { + return fmt.Errorf("%w: navigator.clipboard.write is missing", ErrUnavailable) + } + item := js.Global().Get("ClipboardItem") + if item.Type() != js.TypeFunction { + return fmt.Errorf("%w: ClipboardItem is missing", ErrUnavailable) + } + blob := js.Global().Get("Blob") + flavours := map[string]any{ + "text/html": blob.New([]any{html}, map[string]any{"type": "text/html"}), + "text/plain": blob.New([]any{alt}, map[string]any{"type": "text/plain"}), + } + var promise js.Value + if err := catchJS("write clipboard html", func() { promise = clipboard.Call("write", js.Global().Get("Array").New(item.New(flavours))) }); err != nil { + return err + } + var release []js.Func + finish := func(err error) { + for _, function := range release { + function.Release() + } + done(err) + } + callback := func(handler func([]js.Value) any) js.Func { + function := js.FuncOf(func(_ js.Value, args []js.Value) any { return handler(args) }) + release = append(release, function) + return function + } + fail := callback(func(args []js.Value) any { + finish(clipboardError(args)) + return nil + }) + then := callback(func([]js.Value) any { + finish(nil) + return nil + }) + if err := catchJS("write clipboard html", func() { promise.Call("then", then, fail) }); err != nil { + finish(err) + } + return nil +} + func clipboardCall(name string, arguments ...any) (js.Value, error) { navigator := js.Global().Get("navigator") if navigator.Type() != js.TypeObject || navigator.IsNull() { diff --git a/internal/platform/web/clipboard_html_js_test.go b/internal/platform/web/clipboard_html_js_test.go new file mode 100644 index 000000000..f33a0ab1b --- /dev/null +++ b/internal/platform/web/clipboard_html_js_test.go @@ -0,0 +1,77 @@ +//go:build js && wasm + +package web + +import ( + "errors" + "syscall/js" + "testing" + "time" +) + +// writeClipboardHTML runs the rich copy against the installed stub and waits +// for the callback. +func writeClipboardHTML(t *testing.T, html, alt string) error { + t.Helper() + done := make(chan error, 1) + if err := SetClipboardHTMLAsync(html, alt, func(err error) { done <- err }); err != nil { + return err + } + select { + case err := <-done: + return err + case <-time.After(5 * time.Second): + t.Fatal("the clipboard write never completed") + return nil + } +} + +// installClipboardItem gives the runtime under test a ClipboardItem, which the +// js/wasm test environment itself does not provide, built the way the browser +// builds one: an object that answers getType with the flavour's Blob. +func installClipboardItem(t *testing.T) { + t.Helper() + class := js.Global().Get("Function").New(` + return class ClipboardItem { + constructor(flavours) { this.flavours = flavours; } + get types() { return Object.keys(this.flavours); } + getType(type) { return this.flavours[type]; } + }`).Invoke() + js.Global().Set("ClipboardItem", class) +} + +func TestSetClipboardHTMLAsyncWritesBothFlavours(t *testing.T) { + installClipboardItem(t) + installClipboard(t, `return { + write: items => { + const flavours = {}; + for (const type of items[0].types) { + flavours[type] = items[0].getType(type); + } + globalThis.vivaWritten = flavours; + return Promise.resolve(); + }, + }`) + if err := writeClipboardHTML(t, "加粗", "加粗"); err != nil { + t.Fatalf("write = %v", err) + } + value := js.Global().Get("vivaWritten") + if value.Type() != js.TypeObject { + t.Fatal("the ClipboardItem was not written") + } + // Both flavours must be on the one item, as the ClipboardItem spec takes them. + if value.Get("text/html").Type() != js.TypeObject || value.Get("text/plain").Type() != js.TypeObject { + t.Fatalf("the ClipboardItem carries neither MIME flavour: %v", value) + } +} + +func TestSetClipboardHTMLAsyncReportsBrowserRefusal(t *testing.T) { + installClipboard(t, `return { write: items => Promise.reject(Object.assign(new Error("no"), { name: "NotAllowedError" })) }`) + if err := writeClipboardHTML(t, "x", "x"); !errors.Is(err, ErrPermissionDenied) { + t.Fatalf("refused write error = %v", err) + } + installClipboard(t, `return {}`) + if err := writeClipboardHTML(t, "x", "x"); err == nil { + t.Fatal("a missing clipboard API reported success") + } +} diff --git a/internal/platform/web/system_js.go b/internal/platform/web/system_js.go index b2435fc05..f3315db76 100644 --- a/internal/platform/web/system_js.go +++ b/internal/platform/web/system_js.go @@ -28,6 +28,12 @@ func SetClipboardText(string) error { return fmt.Errorf("%w: Clipboard.writeText returns a Promise", ErrAsyncRequired) } +// SetClipboardHTML is the synchronous form of the rich copy: the browser answers +// it through a Promise, so use SetClipboardHTMLAsync. +func SetClipboardHTML(html, alt string) error { + return fmt.Errorf("%w: Clipboard.write returns a Promise", ErrAsyncRequired) +} + // ClipboardImagePNG cannot answer synchronously: Clipboard.read returns a Promise. func ClipboardImagePNG() error { return fmt.Errorf("%w: Clipboard.read returns a Promise", ErrAsyncRequired) diff --git a/internal/platform/windows/clipboard_html_windows.go b/internal/platform/windows/clipboard_html_windows.go new file mode 100644 index 000000000..c35fdf5a5 --- /dev/null +++ b/internal/platform/windows/clipboard_html_windows.go @@ -0,0 +1,108 @@ +package windows + +import ( + "encoding/binary" + "fmt" + "strconv" + "sync" + "syscall" + "unsafe" +) + +// SetClipboardHTML writes html as the clipboard's registered "HTML Format" +// (CF_HTML) beside alt as CF_UNICODETEXT: a rich reader takes the CF_HTML, a +// plain one the text, both from one copy. The CF_HTML header carries byte +// offsets into its own block, which the format pins to ten digits, so its +// length is the same whatever they say and one pass fixes every offset. +func SetClipboardHTML(html, alt string) error { + if len(html) > maxClipboardBytes { + return fmt.Errorf("windows: clipboard html exceeds 64 MiB") + } + encoded, err := syscall.UTF16FromString(alt) + if err != nil { + return fmt.Errorf("windows: encode clipboard text: %w", err) + } + // The block API takes bytes; the UTF-16 the clipboard wants is the same + // units little-endian, the encoding the file list's names already use. + text := make([]byte, len(encoded)*2) + for index, unit := range encoded { + binary.LittleEndian.PutUint16(text[index*2:], unit) + } + block := cfHTML(html) + clipboardMu.Lock() + defer clipboardMu.Unlock() + owner := uintptr(0) + if state := active.Load(); state != nil { + owner = state.window + } + if opened, _, callErr := openClipboard.Call(owner); opened == 0 { + return windowsCallError("open clipboard", callErr) + } + defer closeClipboard.Call() + if emptied, _, callErr := emptyClipboard.Call(); emptied == 0 { + return windowsCallError("empty clipboard", callErr) + } + if err := setClipboardBlock(clipboardUnicodeText, text); err != nil { + return err + } + return registeredSetClipboardHTML(block) +} + +// registeredSetClipboardHTML puts the CF_HTML block of a rich copy on the open +// clipboard, the registered "HTML Format" every CF_HTML reader looks for. +func registeredSetClipboardHTML(block []byte) error { + format := registeredHTMLFormat() + if format == 0 { + return fmt.Errorf("windows: register clipboard format failed") + } + return setClipboardBlock(format, block) +} + +var htmlFormatOnce sync.Once +var htmlFormat uintptr + +// registeredHTMLFormat is the clipboard format named "HTML Format"; 0 when it +// cannot be registered. +func registeredHTMLFormat() uintptr { + htmlFormatOnce.Do(func() { + name, _ := syscall.UTF16PtrFromString("HTML Format") + htmlFormat, _, _ = registerClipboardFormat.Call(uintptr(unsafe.Pointer(name))) + }) + return htmlFormat +} + +// cfHTML builds the CF_HTML block around html: a header of byte offsets and +// the document they point into, exactly the shape the format's published +// description builds (the fragment wrapped in body comments, offsets counted +// from the start of the block, in UTF-8). +func cfHTML(html string) []byte { + const ( + front = "\r\n" + back = "\r\n\r\n" + // 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 := len(lands) + 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 = append(block, front...) + block = append(block, html...) + block = append(block, back...) + return block +} diff --git a/internal/platform/windows/clipboard_html_windows_test.go b/internal/platform/windows/clipboard_html_windows_test.go new file mode 100644 index 000000000..ee4c88d4b --- /dev/null +++ b/internal/platform/windows/clipboard_html_windows_test.go @@ -0,0 +1,94 @@ +package windows + +import ( + "os" + "strconv" + "strings" + "testing" +) + +// TestCFHTMLHeaderPointsAtTheDocument pins the CF_HTML block to the shape +// readers slice the fragment out of: the header's byte offsets are counted from +// the start of the block, and the fragment they name is the html the caller +// passed, wrapped the way the format's description wraps it. +func TestCFHTMLHeaderPointsAtTheDocument(t *testing.T) { + const html = `加粗 and text` + block := cfHTML(html) + whole := string(block) + if !strings.HasPrefix(whole, "Version:0.9\r\nStartHTML:") { + t.Fatalf("the block does not begin with the header: %q", whole[:40]) + } + field := func(name string) int { + t.Helper() + mark := strings.Index(whole, name+":") + if mark < 0 { + t.Fatalf("the header has no %s", name) + } + end := mark + len(name) + 1 + value, err := strconv.Atoi(whole[end : end+10]) + if err != nil { + t.Fatalf("%s is not ten digits: %q", name, whole[end:end+10]) + } + return value + } + startHTML := field("StartHTML") + endHTML := field("EndHTML") + startFragment := field("StartFragment") + endFragment := field("EndFragment") + // The header's own length: each line is its field name, ten digits and a + // CRLF, so the document starts right behind them. + const headerLength = len("Version:0.9\r\n") + + len("StartHTML:") + 10 + 2 + + len("EndHTML:") + 10 + 2 + + len("StartFragment:") + 10 + 2 + + len("EndFragment:") + 10 + 2 + if startHTML != headerLength { + t.Fatalf("StartHTML = %d, want the header's own length %d: %q", startHTML, headerLength, whole[:startHTML]) + } + if !strings.HasPrefix(whole[startHTML:], "") { + t.Fatalf("the document does not start at StartHTML: %q", whole[startHTML:]) + } + if string(block[startFragment:endFragment]) != html { + t.Fatalf("the fragment = %q, want %q", block[startFragment:endFragment], html) + } + if !strings.HasSuffix(string(block[startHTML:endHTML]), "\r\n") { + t.Fatalf("the document does not end at EndHTML: %q", whole[startHTML:endHTML]) + } +} + +// TestSetClipboardHTMLRoundTrip writes both flavours and has the clipboard read +// them the way an application pastes: CF_UNICODETEXT as the plain text, +// "HTML Format" as the CF_HTML. It replaces the clipboard, so it runs only on +// request, on a machine whose clipboard may be overwritten. +func TestSetClipboardHTMLRoundTrip(t *testing.T) { + if os.Getenv("VIVA_WINDOWS_CLIPBOARD") == "" { + t.Skip("set VIVA_WINDOWS_CLIPBOARD=1 to overwrite the real clipboard") + } + const html = `加粗 and text` + const alt = "加粗 and text" + if err := SetClipboardHTML(html, alt); err != nil { + t.Fatal(err) + } + text, err := ClipboardText() + if err != nil || text != alt { + t.Fatalf("plain flavour = %q, %v, want %q", text, err, alt) + } + if available, _, _ := clipboardFormatAvailable.Call(registeredHTMLFormat()); available == 0 { + t.Fatal("the clipboard holds no HTML Format flavour") + } + block, err := clipboardBytes(registeredHTMLFormat(), maxClipboardBytes) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(block), html) { + t.Fatalf("the CF_HTML block does not carry the html: %q", block) + } + + // Another copy replaces the pair, as every write clears the clipboard. + if err := SetClipboardText("plain again"); err != nil { + t.Fatal(err) + } + if available, _, _ := clipboardFormatAvailable.Call(registeredHTMLFormat()); available != 0 { + t.Fatal("a plain copy left a rich flavour behind") + } +} From 9d0abefba0da6b3af8a3e16e3071969bc08583a5 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 05:33:01 +0800 Subject: [PATCH 18/86] feat(ui): frozen table columns pinned to a scrolling body's left edge --- components/scroll_area.go | 48 +++- components/scroll_area_frozen_test.go | 92 ++++++++ ui/table.go | 176 +++++++++++--- ui/table_frozen_test.go | 319 ++++++++++++++++++++++++++ 4 files changed, 597 insertions(+), 38 deletions(-) create mode 100644 components/scroll_area_frozen_test.go create mode 100644 ui/table_frozen_test.go diff --git a/components/scroll_area.go b/components/scroll_area.go index bc445feab..a4a6a898f 100644 --- a/components/scroll_area.go +++ b/components/scroll_area.go @@ -50,6 +50,7 @@ type ScrollArea struct { hoverBars bool barsRevealed bool barWidth float32 + frozen float32 contentClipIsActive bool } @@ -125,6 +126,19 @@ func (area ScrollArea) ScrollbarSize(size float32) ScrollArea { return area } +// Frozen declares that the leading px of the content stays pinned at the +// viewport's leading edge while the rest scrolls, as the frozen columns of a +// table stay put. The pinned width leaves MaxOffsetX the value an unfrozen +// area reports — the offset never scrolls the pinned columns — while the +// horizontal track, thumb and drag mapping shrink to the window past them and +// span exactly what scrolls. A zero or negative px, one with nothing to scroll +// around, or one at or past the viewport, freezes nothing. The vertical +// geometry is the unfrozen one. +func (area ScrollArea) Frozen(px float32) ScrollArea { + area.frozen = px + return area +} + // Disabled preserves geometry and typed semantics while making both scrollbars inert. func (area ScrollArea) Disabled() ScrollArea { area.disabled = true @@ -144,7 +158,10 @@ func (area ScrollArea) barSize() float32 { } // Geometry returns clamped viewport, translated content, track, thumb, and -// corner geometry without painting or changing Canvas state. +// corner geometry without painting or changing Canvas state. A frozen area +// keeps the unfrozen content, offset and vertical geometry; only the +// horizontal track, thumb and corner move to the scrolling window past the +// pinned band, spanning exactly what scrolls. func (area ScrollArea) Geometry() ScrollAreaGeometry { bounds := scrollAreaNormalizeRect(area.bounds) barSize := area.barSize() @@ -161,6 +178,16 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { contentHeight = viewport.Height } + // A pinned band needs a window left to scroll in: something to either + // side of it, and a width inside the viewport. + // A pinned band changes nothing about the translation: Content keeps the + // unfrozen origin, because the caller clips the pinned columns out of it + // and paints them itself at the viewport's edge. Only the bar belongs to + // the scrolling window past the band. + frozen := area.frozen + if frozen <= 0 || frozen >= viewport.Width || contentWidth <= viewport.Width { + frozen = 0 + } maximumX := scrollAreaMax(contentWidth-viewport.Width, 0) maximumY := scrollAreaMax(contentHeight-viewport.Height, 0) offsetX := scrollAreaClamp(area.offsetX, 0, maximumX) @@ -168,10 +195,11 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { hasHorizontal := maximumX > 0 && viewport.Height > 0 hasVertical := maximumY > 0 && viewport.Width > 0 + contentX := viewport.X - offsetX geometry := ScrollAreaGeometry{ Bounds: bounds, Viewport: viewport, Content: gfx.Rect{ - X: viewport.X - offsetX, Y: viewport.Y - offsetY, + X: contentX, Y: viewport.Y - offsetY, Width: contentWidth, Height: contentHeight, }, OffsetX: offsetX, OffsetY: offsetY, @@ -180,7 +208,9 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { // The bars lie along the outer bounds. Where the viewport already excludes them // (ReserveScrollbars) their extents are the viewport's; otherwise the corner is - // taken out of whichever track shares it. + // taken out of whichever track shares it. With a pinned band the horizontal bar + // starts at the band's far edge: its thumb spans the scrolling window, and the + // track covers the content its offset can reach. verticalExtent := bounds.Height horizontalExtent := bounds.Width if hasHorizontal && hasVertical { @@ -200,11 +230,17 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { geometry.VerticalThumb = scrollAreaThumb(geometry.VerticalTrack, true, viewport.Height, contentHeight, offsetY, maximumY) } if hasHorizontal { + trackX := bounds.X + horizontalViewport := viewport.Width + if frozen > 0 { + trackX = bounds.X + frozen + horizontalViewport = viewport.Width - frozen + } geometry.HorizontalTrack = gfx.Rect{ - X: bounds.X, Y: bounds.Y + bounds.Height - barSize, - Width: horizontalExtent, Height: barSize, + X: trackX, Y: bounds.Y + bounds.Height - barSize, + Width: scrollAreaMax(horizontalExtent-(trackX-bounds.X), 0), Height: barSize, } - geometry.HorizontalThumb = scrollAreaThumb(geometry.HorizontalTrack, false, viewport.Width, contentWidth, offsetX, maximumX) + geometry.HorizontalThumb = scrollAreaThumb(geometry.HorizontalTrack, false, horizontalViewport, contentWidth-frozen, offsetX, maximumX) } return geometry } diff --git a/components/scroll_area_frozen_test.go b/components/scroll_area_frozen_test.go new file mode 100644 index 000000000..2d35042ab --- /dev/null +++ b/components/scroll_area_frozen_test.go @@ -0,0 +1,92 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A frozen area scrolls its content around the pinned band: the offset's +// maximum keeps the unfrozen value — the offset never moves what is pinned — +// while the translated content moves by the pinned width and the offset +// together, so the caller paints the scrolling columns of a frozen table into +// the window the seam leaves. +func TestFrozenScrollAreaScrollsAroundThePinnedBand(t *testing.T) { + area := BeginScrollArea(nil, gfx.LightTheme(), gfx.Rect{X: 10, Y: 20, Width: 200, Height: 100}, gfx.Size{Width: 500, Height: 400}). + Frozen(60).Offset(120, 0) + geometry := area.Geometry() + // 300 is the unfrozen 500-200: the offset reaches exactly what an + // unfrozen area's would, and the translated content keeps the unfrozen + // origin, because the caller paints the pinned columns itself over it. + if geometry.MaxOffsetX != 300 { + t.Fatalf("MaxOffsetX = %v, want the unfrozen 300", geometry.MaxOffsetX) + } + if geometry.Content.X != 10-120 { + t.Fatalf("the content starts at %v, want the unfrozen origin 10 - the offset 120", geometry.Content.X) + } + // The horizontal bar belongs to the scrolling window: its track starts at + // the pinned band's far edge — less the corner a vertical bar takes — and + // its thumb spans exactly what scrolls. + if geometry.HorizontalTrack.X != 10+60 || geometry.HorizontalTrack.Width != 190-60 { + t.Fatalf("the horizontal track is %+v, want it past the pinned 60 px of the 190 the corner leaves", geometry.HorizontalTrack) + } + scrolled := geometry.HorizontalTrack.Width + if thumb := geometry.HorizontalThumb; thumb.X < geometry.HorizontalTrack.X+1 || thumb.X+thumb.Width > geometry.HorizontalTrack.X+scrolled { + t.Fatalf("the horizontal thumb is %+v, want it inside the scrolling window of %v px alone", thumb, scrolled) + } + // The offset reaches every scrolled pixel of content while never moving + // the pinned ones: a drag to the thumb's far end is the whole content's. + area = area.Offset(geometry.MaxOffsetX, 0) + end := area.Geometry() + if end.Content.X+end.Content.Width != 10+200 { + t.Fatalf("at the end the content reaches %v, want the viewport's far edge", end.Content.X+end.Content.Width) + } +} + +// The drag mapping stays the inverse of the thumb: a press at some offset maps +// back to the same offset, and moving the thumb to the end of the scrolling +// window scrolls to the end of the content. +func TestFrozenScrollAreaDragMapsWhatTheThumbSpans(t *testing.T) { + area := BeginScrollArea(nil, gfx.LightTheme(), gfx.Rect{X: 10, Y: 20, Width: 200, Height: 100}, gfx.Size{Width: 500, Height: 400}). + Frozen(60).HorizontalScrollbar(gfx.Item(1), "Columns", "") + geometry := area.Geometry() + if got := geometry.HorizontalOffsetForThumb(geometry.HorizontalThumb.X); got != 0 { + t.Fatalf("the resting thumb maps back to %v, want 0", got) + } + thumbAt := func(offset float32) float32 { + return area.Offset(offset, 0).Geometry().HorizontalThumb.X + } + for _, offset := range []float32{60, 150, 300} { + if geometry := area.Offset(offset, 0).Geometry(); geometry.OffsetX != offset { + t.Fatalf("offset %v clamped to %v", offset, geometry.OffsetX) + } + if back := geometry.HorizontalOffsetForThumb(thumbAt(offset)); back-offset > 0.01 || offset-back > 0.01 { + t.Fatalf("thumb for %v maps back to %v", offset, back) + } + } +} + +// A frozen area without a horizontal overflow, with nothing pinned, or with +// the whole viewport pinned, is the unfrozen area it always was: same +// geometry, byte for byte. +func TestFrozenScrollAreaWithoutOverflowOrBandKeepsUnfrozenGeometry(t *testing.T) { + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 10, Y: 20, Width: 200, Height: 100} + cases := []struct { + name string + frozen float32 + content gfx.Size + }{ + {"nothing pinned", 0, gfx.Size{Width: 500, Height: 400}}, + {"no overflow", 60, gfx.Size{Width: 200, Height: 400}}, + {"overflow shorter than the band", 300, gfx.Size{Width: 240, Height: 400}}, + {"whole viewport pinned", 200, gfx.Size{Width: 500, Height: 400}}, + } + for _, c := range cases { + plain := BeginScrollArea(nil, theme, bounds, c.content).Offset(120, 40) + frozen := BeginScrollArea(nil, theme, bounds, c.content).Frozen(c.frozen).Offset(120, 40) + if got, want := frozen.Geometry(), plain.Geometry(); got != want { + t.Fatalf("%s: frozen geometry is %+v, want the unfrozen %+v", c.name, got, want) + } + } +} diff --git a/ui/table.go b/ui/table.go index 2296f66ed..aceddc73b 100644 --- a/ui/table.go +++ b/ui/table.go @@ -54,6 +54,14 @@ type TableSpec struct { CellPadding float32 // Striped shades every second row. Striped bool + // FrozenColumns pins the first columns that have explicit widths to the + // table's left edge while the rest scroll under OffsetX: the vertical + // identity rows keep, a header's sort hits keep their place in paint + // order, and the horizontal scrollbar and drag mapping account for the + // frozen width. Zero, the default, keeps every column moving with the + // scroll, as tables always have; a table that does not scroll sideways + // ignores it. + FrozenColumns int // Scrollbar is the identity of the vertical bar a table that scrolls itself // draws under its columns; zero paints the bar without an action. Scrollbar gfx.ID @@ -188,10 +196,15 @@ type tableDecl struct { // right under its fixed header, the header riding along with its rows: the // horizontal wheel, Shift with the wheel, or a horizontal scrollbar // (HorizontalScrollbar) moves the columns, and state.Scroll reports how far -// across it is. A table whose last column has no width keeps the layout it -// always had: the last column takes what is left, however narrow that is. A -// table inside a ScrollArea is never scrolled across by itself; the area owns -// its width, sideways or not. +// across it is. FrozenColumns pins the first columns to the table's left edge +// while the rest scroll: the pinned band covers what passes under it, a rule +// at its right edge keeps the two apart, hits over the band still name the +// row and column under the pointer whatever the offset, and the horizontal +// scrollbar maps exactly the columns that move — MaxX reaches every scrolled +// pixel while the offset never moves the pinned ones. A table whose last +// column has no width keeps the layout it always had: the last column takes +// what is left, however narrow that is. A table inside a ScrollArea is never +// scrolled across by itself; the area owns its width, sideways or not. // // tbl := f.Table(&state, ui.TableSpec{Rows: rows, Header: heads, Columns: cols, Headers: titles, Sortable: sortable, Source: &data}) // if row, ok := tbl.RowClicked(); ok { state.Select(row) } @@ -264,6 +277,37 @@ func tableColumnsWidth(columns []components.TableColumn) float32 { return width } +// frozenColumnCount is how many leading columns a table with FrozenColumns +// count pins: the count itself, cut at the first column without a width of +// its own, which takes what is left and pins nothing after it. +func frozenColumnCount(columns []components.TableColumn, count int) int { + if count <= 0 { + return 0 + } + frozen := min(count, len(columns)) + for index := 0; index < frozen; index++ { + if columns[index].Width <= 0 { + return index + } + } + return frozen +} + +// frozenColumnsWidth is the combined width of the columns a table freezes. +// Every one of them must declare an explicit width, so a flexible column ends +// the frozen band: it takes what is left and pins nothing. The count was cut +// at it already. Zero when the table pins nothing. +func frozenColumnsWidth(columns []components.TableColumn, count int) float32 { + width := float32(0) + for index := 0; index < count && index < len(columns); index++ { + width += columns[index].Width + } + return width +} + +// tableFrozenSeparator is how wide the rule at a frozen band's right edge is. +const tableFrozenSeparator = float32(2) + // scrollAncestor is the state and viewport of the ScrollArea nearest around element n. func (f *frame) scrollAncestor(n *node) (*ScrollState, Rect) { for p := n.parent; p >= 0; p = f.nodes[p].parent { @@ -343,6 +387,17 @@ func (f *frame) paintTable(n *node) { offsetX = snapScroll(s.OffsetX) } left := body.X - offsetX + // Frozen columns pin a band of the body's leading width while the rest + // 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) + if sideways { + frozenWidth = frozenColumnsWidth(t.spec.Columns, frozenColumnCount(t.spec.Columns, t.spec.FrozenColumns)) + if frozenWidth <= 0 || frozenWidth >= body.Width { + frozenWidth = 0 + } + } + seam := body.X + frozenWidth // The rows on screen: the table's body, cut by every clip it sits in. top := body.Y - offset @@ -374,7 +429,7 @@ func (f *frame) paintTable(n *node) { if !scrolls && !sticky { // Height: r.Height lets paintTableHeader keep its rule of the header's // bottom rule needing room below it. - f.paintTableHeader(t, Rect{X: left, Y: r.Y, Width: contentWidth, Height: r.Height}, body, headerHeight, rowHeight, sideways) + f.paintTableHeader(t, Rect{X: left, Y: r.Y, Width: contentWidth, Height: r.Height}, body, headerHeight, rowHeight, sideways && frozenWidth == 0, frozenWidth) } if last > first { extra := float32(0) @@ -387,49 +442,77 @@ func (f *frame) paintTable(n *node) { below := headerY + headerHeight canvas.Clip(Rect{X: r.X, Y: below, Width: body.Width, Height: max(r.Y+r.Height-below, 0)}) } - table := components.BeginTable(canvas, f.theme, Rect{X: left, Y: top + float32(first)*rowHeight, Width: contentWidth, Height: float32(last-first)*rowHeight + extra}, t.spec.Columns). - RowHeight(rowHeight).FontSize(t.spec.FontSize).CellPadding(t.spec.CellPadding) - w := &f.widgets - if cap(w.cells) < len(t.spec.Columns) { - w.cells = make([]string, len(t.spec.Columns)) + // The scrolling pass paints every column of the on-screen rows, and the + // clip does the work of the segmentation: the frozen columns fall + // outside the window the clip leaves and stay out of it. + if sideways && frozenWidth > 0 { + canvas.Clip(Rect{X: seam, Y: body.Y, Width: max(body.X+body.Width-seam, 0), Height: body.Height}) } - cells := w.cells[:len(t.spec.Columns)] - for row := first; row < last; row++ { - for column := range cells { - cells[column] = t.spec.Source.Cell(row, column) - } - if t.spec.Striped && row%2 == 1 { - stripe := f.theme.Muted - stripe.Alpha *= 0.6 - canvas.Fill(Rect{X: left, Y: top + float32(row)*rowHeight, Width: contentWidth, Height: rowHeight}, stripe) - } - // A press on the bar owns the pointer: the row under it neither - // highlights nor takes a click while the bar is held. - id := t.spec.Rows.At(row) - if t.state.Scroll.dragging { - id = gfx.ID{} - } - table.RowState(id, cells, components.TableRowState{Selected: row == t.state.Selected()}) + f.paintTableRows(t, Rect{X: left, Y: top + float32(first)*rowHeight, Width: contentWidth, Height: float32(last-first)*rowHeight + extra}, first, last, top, contentWidth, rowHeight) + if sideways && frozenWidth > 0 { + // The frozen band rides above, opaque, on the unscrolled origin: + // the same rows again, clipped to the band, with the columns + // painted from the body's left edge rather than the offset one. + canvas.Unclip() + canvas.Clip(Rect{X: body.X, Y: body.Y, Width: frozenWidth, Height: body.Height}) + canvas.Fill(Rect{X: body.X, Y: top + float32(first)*rowHeight, Width: frozenWidth, Height: float32(last-first)*rowHeight + extra}, f.theme.Background) + f.paintTableRows(t, Rect{X: body.X, Y: top + float32(first)*rowHeight, Width: contentWidth, Height: float32(last-first)*rowHeight + extra}, first, last, top, contentWidth, rowHeight) + canvas.Unclip() } if scrolls || sideways || sticky { canvas.Unclip() } + if sideways && frozenWidth > 0 { + canvas.Fill(Rect{X: seam - tableFrozenSeparator, Y: top + float32(first)*rowHeight, Width: tableFrozenSeparator, Height: float32(last-first)*rowHeight + extra}, f.theme.Border) + } } if scrolls || sticky { if headerHeight > 0 { canvas.Fill(Rect{X: r.X, Y: headerY, Width: body.Width, Height: headerHeight}, f.theme.Background) } - f.paintTableHeader(t, Rect{X: left, Y: headerY, Width: contentWidth, Height: r.Height}, body, headerHeight, rowHeight, sideways) + f.paintTableHeader(t, Rect{X: left, Y: headerY, Width: contentWidth, Height: r.Height}, body, headerHeight, rowHeight, sideways && frozenWidth == 0, frozenWidth) } if scrolls || sideways { - f.paintTableScrollbars(t, r, body, gfx.Size{Width: contentWidth, Height: content}, offsetX, offset) + f.paintTableScrollbars(t, r, body, gfx.Size{Width: contentWidth, Height: content}, offsetX, offset, frozenWidth) + } +} + +// paintTableRows paints the on-screen rows of a table once, with the same +// components.Table calls an application would make by hand. The caller has +// already clipped to the band the rows belong to, and rows keeps the whole +// grid's geometry: every column paints, and the clip does the segmentation. +func (f *frame) paintTableRows(t *tableDecl, rows Rect, first, last int, top, contentWidth, rowHeight float32) { + canvas := f.canvas + table := components.BeginTable(canvas, f.theme, rows, t.spec.Columns). + RowHeight(rowHeight).FontSize(t.spec.FontSize).CellPadding(t.spec.CellPadding) + w := &f.widgets + if cap(w.cells) < len(t.spec.Columns) { + w.cells = make([]string, len(t.spec.Columns)) + } + cells := w.cells[:len(t.spec.Columns)] + for row := first; row < last; row++ { + for column := range cells { + cells[column] = t.spec.Source.Cell(row, column) + } + if t.spec.Striped && row%2 == 1 { + stripe := f.theme.Muted + stripe.Alpha *= 0.6 + canvas.Fill(Rect{X: rows.X, Y: top + float32(row)*rowHeight, Width: contentWidth, Height: rowHeight}, stripe) + } + // A press on the bar owns the pointer: the row under it neither + // highlights nor takes a click while the bar is held. + id := t.spec.Rows.At(row) + if t.state.Scroll.dragging { + id = gfx.ID{} + } + table.RowState(id, cells, components.TableRowState{Selected: row == t.state.Selected()}) } } // paintTableScrollbars paints and drags the bars of a Table that scrolls itself. // They share the body's content extents and offsets; a bar sits in the gutter the // spec asked for and over the body's edge when it did not. -func (f *frame) paintTableScrollbars(t *tableDecl, r, body Rect, content gfx.Size, offsetX, offsetY float32) { +func (f *frame) paintTableScrollbars(t *tableDecl, r, body Rect, content gfx.Size, offsetX, offsetY, frozenWidth float32) { revealed := f.page == nil || f.page.pointerOver(r) || t.state.Scroll.dragging label := t.spec.ScrollbarLabel if label == "" { @@ -454,6 +537,7 @@ func (f *frame) paintTableScrollbars(t *tableDecl, r, body Rect, content gfx.Siz areaBounds := Rect{X: r.X, Y: body.Y, Width: r.Width, Height: r.Y + r.Height - body.Y} area := components.BeginScrollArea(f.canvas, f.theme, areaBounds, content). Offset(offsetX, offsetY). + Frozen(frozenWidth). ScrollbarSize(size). HoverScrollbars(revealed) if t.spec.ScrollbarGutter > 0 { @@ -508,8 +592,10 @@ func (f *frame) revealSelected(n *node, t *tableDecl, body Rect, rowHeight, head } // paintTableHeader paints the header row and, over it, the hit regions and arrow -// of the sortable columns. -func (f *frame) paintTableHeader(t *tableDecl, r, viewport Rect, headerHeight, rowHeight float32, sideways bool) { +// of the sortable columns. A sideways table clips it to the body's columns, and +// one with frozen columns paints it in two passes clipped to each band, so the +// header of the frozen columns rides above what scrolls under it. +func (f *frame) paintTableHeader(t *tableDecl, r, viewport Rect, headerHeight, rowHeight float32, sideways bool, frozenWidth float32) { if headerHeight <= 0 { return } @@ -520,6 +606,32 @@ func (f *frame) paintTableHeader(t *tableDecl, r, viewport Rect, headerHeight, r canvas.Clip(Rect{X: viewport.X, Y: r.Y, Width: viewport.Width, Height: headerHeight}) defer canvas.Unclip() } + if frozenWidth > 0 { + // Frozen columns are only of a sideways table, whose clip is already + // on. The scrolling pass narrows it to the window past the frozen + // band; the band then paints its header above, opaque, from the + // body's unscrolled origin, and rules itself off from the columns + // that pass under it. + seam := viewport.X + frozenWidth + canvas.Clip(Rect{X: seam, Y: r.Y, Width: max(viewport.X+viewport.Width-seam, 0), Height: headerHeight}) + f.paintTableHeaderRow(t, r, headerHeight, rowHeight) + canvas.Unclip() + canvas.Clip(Rect{X: viewport.X, Y: r.Y, Width: frozenWidth, Height: headerHeight}) + canvas.Fill(Rect{X: viewport.X, Y: r.Y, Width: frozenWidth, Height: headerHeight}, f.theme.Background) + pinned := r + pinned.X = viewport.X + f.paintTableHeaderRow(t, pinned, headerHeight, rowHeight) + canvas.Fill(Rect{X: seam - tableFrozenSeparator, Y: r.Y, Width: tableFrozenSeparator, Height: headerHeight}, f.theme.Border) + canvas.Unclip() + return + } + f.paintTableHeaderRow(t, r, headerHeight, rowHeight) +} + +// paintTableHeaderRow paints the header cells of r once, with the hover fills, +// the sort arrows and the hit regions of the sortable columns. +func (f *frame) paintTableHeaderRow(t *tableDecl, r Rect, headerHeight, rowHeight float32) { + canvas := f.canvas bounds := Rect{X: r.X, Y: r.Y, Width: r.Width, Height: headerHeight} cells := components.TableCellBounds(t.spec.Columns, bounds, f.widgets.rects[:0]) f.widgets.rects = cells[:0] diff --git a/ui/table_frozen_test.go b/ui/table_frozen_test.go new file mode 100644 index 000000000..fdc819f54 --- /dev/null +++ b/ui/table_frozen_test.go @@ -0,0 +1,319 @@ +package ui + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// frozenSpec is the spec of a 400x300 table of six 120-wide columns with the +// first two frozen: 240 pinned at the left edge, 480 scrolling past them. +func frozenSpec(state *TableState, rows TableSource) TableSpec { + return TableSpec{ + Rows: tableScope, Header: headerScope, Columns: wideSixColumns, Headers: sixTitles, + Sortable: allSortableSix, Source: rows, FrozenColumns: 2, + } +} + +// textX reports where the last text equal to value is painted: the pass a +// table bands its columns into paints several times, and the last is the one +// that showed. A return of false means no such text. The scrolled pass of a +// banded table is the first, so its caller pairs this with firstX below. +func textX(canvas *gfx.Canvas, value string) (float32, bool) { + x, seen := float32(0), false + for _, text := range canvas.Texts() { + if text.Value == value { + x, seen = text.Bounds.X, true + } + } + return x, seen +} + +// firstX reports where the first text equal to value is painted. +func firstX(canvas *gfx.Canvas, value string) (float32, bool) { + for _, text := range canvas.Texts() { + if text.Value == value { + return text.Bounds.X, true + } + } + return 0, false +} + +// The frozen columns stay pinned at the table's left edge while the rest +// scroll under OffsetX, the separator stays where it was, and MaxX keeps +// the unfrozen value: the offset covers exactly the columns that move. +func TestFrozenColumnsStayPutWhileTheRestScroll(t *testing.T) { + rows := make(TableRows, 100) + for i := range rows { + rows[i] = []string{"aa", "bb", "cc", "dd", "ee", "ff"} + } + var state TableState + canvas := testCanvas() + var view View + paint := func() { + canvas.Reset() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, frozenSpec(&state, &rows)).Fill() + }) + }) + } + paint() + if max := state.Scroll.MaxX(); max != 320 { // 720 declared in 400 shown, as unfrozen + t.Fatalf("MaxX = %v, want the unfrozen 320", max) + } + frozenHeader, _ := textX(canvas, "A") + frozenCell, _ := textX(canvas, "aa") + if frozenHeader != 8 || frozenCell != 8 { // the theme's cell padding + t.Fatalf("the frozen header sits at %v and its first cell at %v, want both at the table's left edge plus its padding", frozenHeader, frozenCell) + } + scrolledHeader, _ := firstX(canvas, "C") + scrolledCell, _ := firstX(canvas, "cc") + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 200, Precise: true}) + paint() + if state.Scroll.OffsetX != 200 { + t.Fatalf("OffsetX = %v, want 200", state.Scroll.OffsetX) + } + if x, _ := textX(canvas, "A"); x != frozenHeader { + t.Errorf("the frozen header moved to %v, want it at %v", x, frozenHeader) + } + if x, _ := textX(canvas, "aa"); x != frozenCell { + t.Errorf("the frozen cell moved to %v, want it at %v", x, frozenCell) + } + if x, _ := firstX(canvas, "C"); x != scrolledHeader-200 { + t.Errorf("the scrolled header sits at %v, want %v", x, scrolledHeader-200) + } + if x, _ := firstX(canvas, "cc"); x != scrolledCell-200 { + t.Errorf("the scrolled cell sits at %v, want %v", x, scrolledCell-200) + } +} + +// The horizontal scrollbar of a frozen table keeps the drag the component +// maps: the bar belongs to the scrolling window past the frozen columns, and +// a thumb dragged across it scrolls exactly what the offset can reach. +func TestFrozenTableScrollbarDragsWhatScrolls(t *testing.T) { + rows := make(TableRows, 20) + var state TableState + canvas := testCanvas() + var view View + paint := func() { + canvas.Reset() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, func() TableSpec { + spec := frozenSpec(&state, &rows) + spec.HorizontalScrollbar = gfx.Item(901) + return spec + }()).Fill() + }) + }) + } + paint() + bar := hitByID(canvas, gfx.Item(901)) + if bar.ID.IsZero() { + t.Fatal("the horizontal scrollbar is not painted") + } + // The track starts past the 240 px of frozen columns and spans the 160 + // px of scrolling window, less the corner of the vertical bar. + if bar.Bounds.X < 240 { + t.Fatalf("the horizontal bar starts at %v, past the frozen columns at 240", bar.Bounds.X) + } + deliver := func(kind gfx.PointerEventKind, x, y float32) bool { + return canvas.DeliverPointer(gfx.PointerEvent{Kind: kind, Button: gfx.PointerButtonPrimary, Target: gfx.Item(901), Captured: kind != gfx.PointerDown, X: x, Y: y}, gfx.Size{Width: 400, Height: 300}, func(*gfx.Canvas, gfx.Size) { paint() }) + } + x, y := bar.Bounds.X+2, bar.Bounds.Y+bar.Bounds.Height/2 + if ok := deliver(gfx.PointerDown, x, y); !ok { + t.Fatal("a press on the horizontal bar was not taken") + } + if !deliver(gfx.PointerMove, x+50, y) { + t.Fatal("the drag of the bar was not taken") + } + deliver(gfx.PointerUp, x+50, y) + paint() + if got := state.Scroll.OffsetX; got <= 0 || got > 320 { + t.Errorf("dragging the bar left the columns at %v, want some of the 320 px of range", got) + } +} + +// The rows of a frozen table keep the identities the same table has +// unfrozen: every row hit has its source row, and RowID answers for them. +func TestFrozenTableKeepsRowIdentities(t *testing.T) { + rows := make(TableRows, 100) + paint := func(frozen int) (*TableState, []gfx.Hit) { + var state TableState + canvas := testCanvas() + var view View + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + spec := frozenSpec(&state, &rows) + spec.FrozenColumns = frozen + f.Table(&state, spec).Fill() + }) + }) + return &state, canvas.Hits() + } + plainState, _ := paint(0) + frozenState, frozenHits := paint(2) + if plainState.Rows() != frozenState.Rows() { + t.Fatalf("the frozen table named its rows %v, want the unfrozen %v", frozenState.Rows(), plainState.Rows()) + } + if plainState.rowFirst != frozenState.rowFirst || plainState.rowEnd != frozenState.rowEnd { + t.Fatalf("the frozen table painted rows %d..%d, want the unfrozen %d..%d", + frozenState.rowFirst, frozenState.rowEnd, plainState.rowFirst, plainState.rowEnd) + } + rowNamed := func(hits []gfx.Hit, row int) bool { + for _, hit := range hits { + if index, ok := hit.ID.In(tableScope); ok && index == row { + return true + } + } + return false + } + for row := int(plainState.rowFirst); row < int(plainState.rowEnd); row++ { + _, ok := frozenState.RowID(row) + if !rowNamed(frozenHits, row) { + t.Errorf("row %d of the frozen table declares no hit", row) + } + if !ok { + t.Errorf("RowID does not answer for row %d of the frozen layout", row) + } + } +} + +// A press on a frozen column's row still names that row after the table has +// scrolled across: the overlay's hits stay above the scrolled ones, and the +// row under the frozen band's clip is the one the pointer rests on. +func TestFrozenColumnHitsKeepTheirRowsAfterScrolling(t *testing.T) { + rows := make(TableRows, 100) + for i := range rows { + rows[i] = []string{"aa", "bb", "cc", "dd", "ee", "ff"} + } + var state TableState + canvas := testCanvas() + var view View + paint := func() { + canvas.Reset() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, frozenSpec(&state, &rows)).Fill() + }) + }) + } + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 150, Precise: true}) + paint() + // Every row hit of the frozen band keeps its row's own bounds: none of + // them follows the scrolled columns out from under the band. + seen := map[int]bool{} + for _, hit := range canvas.Hits() { + index, ok := hit.ID.In(tableScope) + if !ok { + continue + } + if seen[index] { + continue // one hit a row arrives twice, clipped to each band + } + if hit.Bounds.Width > 240.01 { + t.Errorf("row %d reaches %v px across, past the frozen band and into the scrolled columns", index, hit.Bounds.Width) + } + seen[index] = true + } + // The front-most hit at a point inside the frozen band is the row itself — + // the overlay's, not a scrolled one underneath. + for _, hit := range canvas.Hits() { + if _, ok := hit.ID.In(tableScope); !ok { + continue + } + if hit.Bounds.X != 0 || hit.Bounds.Width != 240 { + continue + } + row, _ := hit.ID.In(tableScope) + x, y := hit.Bounds.X+10, hit.Bounds.Y+hit.Bounds.Height/2 + front := gfx.ID{} + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + region := hits[i] + if region.IsLabel || region.Backdrop || region.ID.IsZero() { + continue + } + if x >= region.Bounds.X && x <= region.Bounds.Right() && y >= region.Bounds.Y && y <= region.Bounds.Bottom() { + front = region.ID + break + } + } + if index, ok := front.In(tableScope); !ok || index != row { + t.Fatalf("the front-most hit over frozen row %d is %v, want the row itself", row, front) + } + break + } +} + +// A warm frozen table paints without allocating: the two bands cost no more +// a frame than the wide table's one. +func TestFrozenTableAllocatesNothingOnceWarm(t *testing.T) { + rows := &countingRows{n: 100} + var state TableState + canvas := testCanvas() + var view View + paint := func() { + canvas.Reset() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + spec := frozenSpec(&state, rows) + spec.Scrollbar, spec.HorizontalScrollbar = gfx.Item(900), gfx.Item(901) + f.Table(&state, spec).Fill() + }) + }) + } + paint() + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 40, Precise: true}) + state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 90, Precise: true}) + for range 3 { + paint() + } + if allocs := testing.AllocsPerRun(100, paint); allocs != 0 { + t.Fatalf("a warm frozen table allocates %v times a frame, want 0", allocs) + } +} + +func BenchmarkFrozenTable(b *testing.B) { + rows := &countingRows{n: 1000} + var state TableState + state.Scroll.Wheel(gfx.ScrollEvent{DeltaX: 60, Precise: true}) + state.Scroll.Wheel(gfx.ScrollEvent{DeltaY: 3000, Precise: true}) + canvas := testCanvas() + view := View{} + b.ReportAllocs() + for b.Loop() { + canvas.Reset() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + spec := frozenSpec(&state, rows) + spec.Scrollbar, spec.HorizontalScrollbar = gfx.Item(900), gfx.Item(901) + f.Table(&state, spec).Fill() + }) + }) + } +} + +// A table whose FrozenColumns pins nothing — zero, negative, or every column, +// leaving nothing to scroll — paints exactly the canvas it did before the +// field existed: rectangles, texts and hits, end to end. +func TestTableWithNothingFrozenPaintsAsItAlwaysDid(t *testing.T) { + rows := make(TableRows, 50) + paint := func(columns int) *gfx.Canvas { + canvas := testCanvas() + var view View + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Fill().Children(func() { + spec := frozenSpec(&TableState{}, &rows) + spec.FrozenColumns = columns + f.Table(&TableState{}, spec).Fill() + }) + }) + return canvas + } + plain := paint(0) + for _, count := range []int{-3, 0, 6} { // 6 would pin every column: as wide as the content, so nothing scrolls and nothing freezes + sameCanvas(t, "count that pins nothing", plain, paint(count)) + } +} From 449079bfd7e2c5f792b461efe31e1d872a7ebefc Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 05:47:29 +0800 Subject: [PATCH 19/86] fix(components): refresh the scroll-area recipe for the frozen band --- cmd/viva/templates/scroll_area.go.txt | 48 +++++++++++++++++++++++---- components/scroll_area.go | 12 +++---- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/cmd/viva/templates/scroll_area.go.txt b/cmd/viva/templates/scroll_area.go.txt index d2561cc65..09c0002c3 100644 --- a/cmd/viva/templates/scroll_area.go.txt +++ b/cmd/viva/templates/scroll_area.go.txt @@ -50,6 +50,7 @@ type ScrollArea struct { hoverBars bool barsRevealed bool barWidth float32 + frozen float32 contentClipIsActive bool } @@ -125,6 +126,19 @@ func (area ScrollArea) ScrollbarSize(size float32) ScrollArea { return area } +// Frozen declares that the leading px of the content stays pinned at the +// viewport's leading edge while the rest scrolls, as the frozen columns of a +// table stay put. The pinned width leaves MaxOffsetX the value an unfrozen +// area reports — the offset never scrolls the pinned columns — while the +// horizontal track, thumb and drag mapping shrink to the window past them and +// span exactly what scrolls. A zero or negative px, one with nothing to scroll +// around, or one at or past the viewport, freezes nothing. The vertical +// geometry is the unfrozen one. +func (area ScrollArea) Frozen(px float32) ScrollArea { + area.frozen = px + return area +} + // Disabled preserves geometry and typed semantics while making both scrollbars inert. func (area ScrollArea) Disabled() ScrollArea { area.disabled = true @@ -144,7 +158,10 @@ func (area ScrollArea) barSize() float32 { } // Geometry returns clamped viewport, translated content, track, thumb, and -// corner geometry without painting or changing Canvas state. +// corner geometry without painting or changing Canvas state. A frozen area +// keeps the unfrozen content, offset and vertical geometry; only the +// horizontal track, thumb and corner move to the scrolling window past the +// pinned band, spanning exactly what scrolls. func (area ScrollArea) Geometry() ScrollAreaGeometry { bounds := scrollAreaNormalizeRect(area.bounds) barSize := area.barSize() @@ -161,6 +178,16 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { contentHeight = viewport.Height } + // A pinned band needs a window left to scroll in — something to either + // side of it, and a width inside the viewport — and changes nothing about + // the translation: Content keeps the unfrozen origin, because the caller + // clips the pinned columns out of it and paints them itself at the + // viewport's edge. Only the horizontal bar belongs to the scrolling window + // past the band. + frozen := area.frozen + if frozen <= 0 || frozen >= viewport.Width || contentWidth <= viewport.Width { + frozen = 0 + } maximumX := scrollAreaMax(contentWidth-viewport.Width, 0) maximumY := scrollAreaMax(contentHeight-viewport.Height, 0) offsetX := scrollAreaClamp(area.offsetX, 0, maximumX) @@ -168,10 +195,11 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { hasHorizontal := maximumX > 0 && viewport.Height > 0 hasVertical := maximumY > 0 && viewport.Width > 0 + contentX := viewport.X - offsetX geometry := ScrollAreaGeometry{ Bounds: bounds, Viewport: viewport, Content: gfx.Rect{ - X: viewport.X - offsetX, Y: viewport.Y - offsetY, + X: contentX, Y: viewport.Y - offsetY, Width: contentWidth, Height: contentHeight, }, OffsetX: offsetX, OffsetY: offsetY, @@ -180,7 +208,9 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { // The bars lie along the outer bounds. Where the viewport already excludes them // (ReserveScrollbars) their extents are the viewport's; otherwise the corner is - // taken out of whichever track shares it. + // taken out of whichever track shares it. With a pinned band the horizontal bar + // starts at the band's far edge: its thumb spans the scrolling window, and the + // track covers the content its offset can reach. verticalExtent := bounds.Height horizontalExtent := bounds.Width if hasHorizontal && hasVertical { @@ -200,11 +230,17 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { geometry.VerticalThumb = scrollAreaThumb(geometry.VerticalTrack, true, viewport.Height, contentHeight, offsetY, maximumY) } if hasHorizontal { + trackX := bounds.X + horizontalViewport := viewport.Width + if frozen > 0 { + trackX = bounds.X + frozen + horizontalViewport = viewport.Width - frozen + } geometry.HorizontalTrack = gfx.Rect{ - X: bounds.X, Y: bounds.Y + bounds.Height - barSize, - Width: horizontalExtent, Height: barSize, + X: trackX, Y: bounds.Y + bounds.Height - barSize, + Width: scrollAreaMax(horizontalExtent-(trackX-bounds.X), 0), Height: barSize, } - geometry.HorizontalThumb = scrollAreaThumb(geometry.HorizontalTrack, false, viewport.Width, contentWidth, offsetX, maximumX) + geometry.HorizontalThumb = scrollAreaThumb(geometry.HorizontalTrack, false, horizontalViewport, contentWidth-frozen, offsetX, maximumX) } return geometry } diff --git a/components/scroll_area.go b/components/scroll_area.go index a4a6a898f..4e47479d5 100644 --- a/components/scroll_area.go +++ b/components/scroll_area.go @@ -178,12 +178,12 @@ func (area ScrollArea) Geometry() ScrollAreaGeometry { contentHeight = viewport.Height } - // A pinned band needs a window left to scroll in: something to either - // side of it, and a width inside the viewport. - // A pinned band changes nothing about the translation: Content keeps the - // unfrozen origin, because the caller clips the pinned columns out of it - // and paints them itself at the viewport's edge. Only the bar belongs to - // the scrolling window past the band. + // A pinned band needs a window left to scroll in — something to either + // side of it, and a width inside the viewport — and changes nothing about + // the translation: Content keeps the unfrozen origin, because the caller + // clips the pinned columns out of it and paints them itself at the + // viewport's edge. Only the horizontal bar belongs to the scrolling window + // past the band. frozen := area.frozen if frozen <= 0 || frozen >= viewport.Width || contentWidth <= viewport.Width { frozen = 0 From d62171244aa212340ba878059e0c721612727e42 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 08:26:56 +0800 Subject: [PATCH 20/86] fix(components): keep long tooltip text whole when wrapping Wrap tooltip labels to the available viewport instead of applying the shared eight-line, ellipsizing overlay budget. Unbroken filenames retain all their text so Motty can identify truncated files without a local popup implementation. Refs: #828 --- components/tooltip.go | 7 +++++-- components/tooltip_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/components/tooltip.go b/components/tooltip.go index 4e2134df9..709e950da 100644 --- a/components/tooltip.go +++ b/components/tooltip.go @@ -131,8 +131,11 @@ func (tooltip Tooltip) Paint(label string) gfx.Rect { } maxWidth = min(maxWidth, tooltip.viewport.Width-8) const padX, padY = float32(12), float32(6) - var scratch overlayLines - lines := overlayWrap(tooltip.canvas, &scratch, label, metrics.FontSizeS, gfx.WeightRegular, maxWidth-2*padX) + // A filename or another unbroken token has no natural short form: keep all + // of it even when a bounded descriptive tooltip would use an ellipsis. Long + // tokens already break at whole grapheme clusters in the text engine. The + // viewport is a bound on excessive content, not an interactive text limit. + lines := tooltip.canvas.WrapLines(nil, label, metrics.FontSizeS, gfx.WeightRegular, maxWidth-2*padX, int(tooltip.viewport.Height)) // One line takes the width of its text; a wrapped label fills the whole // maximum, as a `w-fit max-w-xs` box does. textWidth := maxWidth - 2*padX diff --git a/components/tooltip_test.go b/components/tooltip_test.go index 408f1ecc4..1f003f700 100644 --- a/components/tooltip_test.go +++ b/components/tooltip_test.go @@ -1,6 +1,7 @@ package components import ( + "strings" "testing" "time" @@ -107,6 +108,38 @@ func TestTooltipWrapsALabelWiderThanItsMaximum(t *testing.T) { } } +func TestTooltipKeepsAnUnbrokenLabelWholeWhenItWraps(t *testing.T) { + var canvas gfx.Canvas + label := strings.Repeat("long-file-name-part-", 12) + ".txt" + BeginTooltip(&canvas, gfx.DarkTheme(), gfx.Rect{Width: 600, Height: 400}, gfx.Rect{X: 260, Y: 180, Width: 80, Height: 32}, TooltipOptions{}).Paint(label) + var painted string + for _, text := range canvas.Texts() { + if strings.ContainsRune(text.Value, '…') { + t.Fatalf("the tooltip dropped part of the name: %q", text.Value) + } + if text.Style.Size != gfx.DarkTheme().Metrics.FontSizeS || text.Style.Weight != gfx.WeightRegular { + t.Fatalf("line is not measured with the tooltip's text style: %+v", text) + } + painted += text.Value + } + if painted != label || len(canvas.Texts()) < 2 { + t.Fatalf("painted = %q, want all of %q in multiple lines", painted, label) + } +} + +func BenchmarkTooltipLongUnbrokenLabel(b *testing.B) { + var canvas gfx.Canvas + label := strings.Repeat("long-file-name-part-", 12) + ".txt" + theme := gfx.DarkTheme() + viewport := gfx.Rect{Width: 600, Height: 400} + anchor := gfx.Rect{X: 260, Y: 180, Width: 80, Height: 32} + b.ReportAllocs() + for b.Loop() { + canvas.Reset() + BeginTooltip(&canvas, theme, viewport, anchor, TooltipOptions{}).Paint(label) + } +} + func TestTooltipOpensOnTheOtherSideWhenThereIsNoRoomAndItsArrowFollows(t *testing.T) { var canvas gfx.Canvas viewport, anchor := gfx.Rect{Width: 600, Height: 400}, gfx.Rect{X: 260, Y: 8, Width: 80, Height: 32} From be5d296c0cb114f546540ecd619e011f18034d60 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 11:11:57 +0800 Subject: [PATCH 21/86] fix(ui): hide duplicate anonymous table hover bars Let a table omit its un-owned vertical hover overlay when the application paints its own vertical bar beside it. Keep scrolling, gutter geometry, the horizontal hover bar, and explicitly identified scrollbar interactions unchanged. --- cmd/viva/initfiles/AGENTS.md.txt | 4 +- cmd/viva/templates/scroll_area.go.txt | 7 +- components/scroll_area.go | 7 +- ui/table.go | 14 +++- ui/table_scrollbars_test.go | 106 ++++++++++++++++++++++++++ 5 files changed, 134 insertions(+), 4 deletions(-) diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index ba26bf6f0..ecc45173e 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -333,7 +333,9 @@ func (m *model) page(c ui.C) { `ui.Scroll` the table is as tall as its rows and only visible rows are read; with `Height`, `Fill` or `Grow` it scrolls its rows under a fixed header and draws its own hover bars: `Scrollbar` names the bar's hit, `ScrollbarLabel` names it for assistive technology, `ScrollbarSize` sets its thickness (else the page's `PageConfig.ScrollbarSize`) and - `ScrollbarGutter` keeps a strip beside the columns for it. The page gives the wheel to a self-scrolling table under the pointer; give the `app.Config` passed to + `ScrollbarGutter` keeps a strip beside the columns for it. An application painting its own vertical bar sets + `HideHoverScrollbars: true` to omit the anonymous vertical hover thumb only; the horizontal overlay, gutter, wheel, + and an explicitly identified draggable `Scrollbar` are unchanged. The page gives the wheel to a self-scrolling table under the pointer; give the `app.Config` passed to `page.Config` `OnKey: m.table.Key` for Up/Down/Page/Home/End selection (a host that routes its own scroll gives `m.table.Wheel` the wheel). - Tabs: `if ui.Tabs(c, &m.tab, tabs, nil).Line().Changed() { ... }`, then declare the active tab's content under it with an diff --git a/cmd/viva/templates/scroll_area.go.txt b/cmd/viva/templates/scroll_area.go.txt index 09c0002c3..053226500 100644 --- a/cmd/viva/templates/scroll_area.go.txt +++ b/cmd/viva/templates/scroll_area.go.txt @@ -68,7 +68,9 @@ func (area ScrollArea) Offset(x, y float32) ScrollArea { } // VerticalScrollbar assigns the stable action ID and accessibility strings for -// the vertical thumb. ID zero keeps the visual geometry non-interactive. +// the vertical thumb. ID zero keeps the visual geometry non-interactive. An ID +// zero with an empty label omits the overlay while preserving its geometry, for +// a caller that paints the vertical bar itself. func (area ScrollArea) VerticalScrollbar(id gfx.ID, label, value string) ScrollArea { area.verticalID = id area.verticalLabel = label @@ -331,6 +333,9 @@ func (area *ScrollArea) EndContent() ScrollAreaGeometry { } func (area ScrollArea) paintScrollbar(track, thumb gfx.Rect, id gfx.ID, label, value string) { + if id.IsZero() && label == "" { + return + } if area.hoverBars && !area.barsRevealed { return } diff --git a/components/scroll_area.go b/components/scroll_area.go index 4e47479d5..4adee7762 100644 --- a/components/scroll_area.go +++ b/components/scroll_area.go @@ -68,7 +68,9 @@ func (area ScrollArea) Offset(x, y float32) ScrollArea { } // VerticalScrollbar assigns the stable action ID and accessibility strings for -// the vertical thumb. ID zero keeps the visual geometry non-interactive. +// the vertical thumb. ID zero keeps the visual geometry non-interactive. An ID +// zero with an empty label omits the overlay while preserving its geometry, for +// a caller that paints the vertical bar itself. func (area ScrollArea) VerticalScrollbar(id gfx.ID, label, value string) ScrollArea { area.verticalID = id area.verticalLabel = label @@ -331,6 +333,9 @@ func (area *ScrollArea) EndContent() ScrollAreaGeometry { } func (area ScrollArea) paintScrollbar(track, thumb gfx.Rect, id gfx.ID, label, value string) { + if id.IsZero() && label == "" { + return + } if area.hoverBars && !area.barsRevealed { return } diff --git a/ui/table.go b/ui/table.go index aceddc73b..d3ef258ba 100644 --- a/ui/table.go +++ b/ui/table.go @@ -79,6 +79,11 @@ type TableSpec struct { // overflowing bar; zero lets the bars sit over their edges. The columns lose // the width of a vertical gutter, and the rows the height of a horizontal one. ScrollbarGutter float32 + // HideHoverScrollbars hides the un-named vertical hover overlay for an + // application that paints its own vertical bar beside the table. It does not + // change scrollbar geometry, the horizontal overlay, scrolling, or any bar + // with an explicit Scrollbar ID. The default paints the overlay as usual. + HideHoverScrollbars bool } // tableRoute is a Table of the last paint that scrolls itself, and where: the @@ -534,6 +539,13 @@ func (f *frame) paintTableScrollbars(t *tableDecl, r, body Rect, content gfx.Siz // component takes the bars' strips out of it, matching the strip the columns // and rows have already given up, so a drag maps the body it scrolls exactly. // Without a gutter the bars keep sitting over the table's edges, as they had. + // An un-owned vertical hover thumb may duplicate an application's adjacent + // bar. Omit its component declaration: an explicit ID still paints and keeps + // its hit and drag, while the area's geometry and horizontal bar are unchanged. + verticalID, verticalLabel := t.spec.Scrollbar, label + if t.spec.HideHoverScrollbars && verticalID.IsZero() { + verticalLabel = "" + } areaBounds := Rect{X: r.X, Y: body.Y, Width: r.Width, Height: r.Y + r.Height - body.Y} area := components.BeginScrollArea(f.canvas, f.theme, areaBounds, content). Offset(offsetX, offsetY). @@ -544,7 +556,7 @@ func (f *frame) paintTableScrollbars(t *tableDecl, r, body Rect, content gfx.Siz area = area.ReserveScrollbars() } area = area. - VerticalScrollbar(t.spec.Scrollbar, label, ""). + VerticalScrollbar(verticalID, verticalLabel, ""). HorizontalScrollbar(t.spec.HorizontalScrollbar, horizontalLabel, "") geometry := area.Geometry() area.EndContent() diff --git a/ui/table_scrollbars_test.go b/ui/table_scrollbars_test.go index 735506ea7..7038eefb3 100644 --- a/ui/table_scrollbars_test.go +++ b/ui/table_scrollbars_test.go @@ -57,6 +57,112 @@ func TestScrollAreaBarsFollowThePointerAtTheirSize(t *testing.T) { } } +// An application-owned vertical bar can replace a table's anonymous hover +// overlay without losing the table's geometry, wheel, or horizontal overlay. +func TestTableHideHoverScrollbarsOmitsOnlyTheAnonymousVerticalThumb(t *testing.T) { + for _, test := range []struct { + name string + hide bool + gutter float32 + }{ + {name: "default overlay", gutter: 0}, + {name: "default over a gutter", gutter: 10}, + {name: "hidden overlay", hide: true, gutter: 0}, + {name: "hidden overlay over a gutter", hide: true, gutter: 10}, + } { + t.Run(test.name, func(t *testing.T) { + rows := make(ui.TableRows, 100) + for i := range rows { + rows[i] = []string{"row", "a", "b", "c"} + } + var state ui.TableState + var table ui.Box + view := func(c ui.C) { + ui.Column(c).Children(func() { + table = ui.Table(c, &state, ui.TableSpec{ + Columns: []components.TableColumn{{Width: 120}, {Width: 120}, {Width: 120}, {Width: 120}}, + Headers: []string{"A", "B", "C", "D"}, Rows: gfx.Item(1).Scope(), Source: &rows, + ScrollbarSize: 10, ScrollbarGutter: test.gutter, + HideHoverScrollbars: test.hide, + }).Size(320, 200) + }) + } + d := openPage(t, view) + d.driver.Move(150, 100) // rest over the overflowing table + bounds := table.Rect() + bounds.Y += components.TableHeaderHeight(pageTheme) + bounds.Height -= components.TableHeaderHeight(pageTheme) + layout := components.BeginScrollArea(nil, pageTheme, bounds, gfx.Size{Width: 480, Height: float32(len(rows)) * components.TableRowHeight(pageTheme)}). + ScrollbarSize(10).HoverScrollbars(true) + if test.gutter > 0 { + layout = layout.ReserveScrollbars() + } + geometry := layout.Geometry() + if geometry.MaxOffsetX <= 0 || geometry.MaxOffsetY <= 0 { + t.Fatalf("the table does not overflow both ways: %+v", geometry) + } + haveVertical, haveHorizontal := false, false + for _, primitive := range d.driver.Snapshot().Primitives { + if primitive.Kind != app.RectanglePrimitive || primitive.Radius <= 0 { + continue + } + switch primitive.Bounds { + case geometry.VerticalThumb: + haveVertical = true + case geometry.HorizontalThumb: + haveHorizontal = true + } + } + if haveVertical == test.hide { + t.Errorf("vertical thumb painted = %v with HideHoverScrollbars %v", haveVertical, test.hide) + } + if !haveHorizontal { + t.Error("the horizontal thumb disappeared") + } + if err := d.driver.Scroll(gfx.ScrollEvent{X: 150, Y: 100, DeltaY: 100, Precise: true}); err != nil { + t.Fatal(err) + } + if state.Scroll.Offset == 0 { + t.Error("hiding the overlay stopped the table's wheel") + } + }) + } +} + +// An explicitly owned scrollbar is not an anonymous hover ornament: the opt-out +// leaves it painted, hit, draggable, and able to move the table. +func TestTableHideHoverScrollbarsKeepsAnExplicitVerticalBarInteractive(t *testing.T) { + rows := make(ui.TableRows, 100) + for i := range rows { + rows[i] = []string{"row", "state"} + } + var state ui.TableState + view := func(c ui.C) { + ui.Table(c, &state, ui.TableSpec{ + Columns: []components.TableColumn{{Width: 200}, {Width: 0}}, + Rows: gfx.Item(1).Scope(), Source: &rows, + Scrollbar: gfx.Item(900), ScrollbarLabel: "Table rows", + ScrollbarSize: 10, HideHoverScrollbars: true, + }).Size(320, 200) + } + d := openPage(t, view) + d.driver.Move(150, 100) + bar := d.hit("Table rows") + at := gfx.Point{X: bar.Bounds.X + bar.Bounds.Width/2, Y: bar.Bounds.Y + 20} + if err := d.driver.Press(at.X, at.Y, gfx.PointerButtonPrimary); err != nil { + t.Fatal(err) + } + if err := d.driver.Move(at.X, at.Y+50); err != nil { + t.Fatal(err) + } + if err := d.driver.Release(at.X, at.Y+50, gfx.PointerButtonPrimary); err != nil { + t.Fatal(err) + } + if state.Scroll.Offset == 0 { + t.Fatal("the explicit vertical scrollbar did not drag the table") + } +} + // A table given a smaller height than its rows scrolls them itself, with the // bar in the gutter it is asked for, and keeps the pointer from the rows while // the bar is held. Config.OnKey hands it the keys, as the application does. From 39c770ae74579fac040f610b1e5c964aac43252d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 10:57:03 +0800 Subject: [PATCH 22/86] fix(components): tint the caret's row in an empty CodeEditor CodeMirror's highlightActiveLine paints the row the caret is on even when the document is empty, so an empty editor's first line has a row background exactly like any populated caret line. The placeholder guard around currentLine suppressed that tint whenever Value was empty, leaving an empty document's first line the only row in the widget without a background. Keep Placeholder text styling as-is and stop treating an empty document as if it had no caret line. Co-Authored-By: Kimi --- components/code_editor.go | 7 ++++++- components/code_editor_test.go | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/components/code_editor.go b/components/code_editor.go index f6d6a5f0f..7819088cb 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -494,7 +494,12 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. canvas.Label(snapshot.Placeholder, gfx.Rect{X: content.X, Y: content.Y + (lineHeight-cellHeight)/2, Width: content.Width, Height: cellHeight}, style) } currentLine := -1 - if snapshot.CurrentLine && selectionStart == selectionEnd && len(selectionRanges) == 0 && !placeholder { + // The caret's line is tinted even while the document is empty: editing + // surfaces (CodeMirror's highlightActiveLine, VS Code) paint a row highlight + // wherever the caret sits, including the single empty row of a fresh + // document. Suppressing it on the placeholder row would make an empty + // editor's first line the only line in the widget without a background. + if snapshot.CurrentLine && selectionStart == selectionEnd && len(selectionRanges) == 0 { currentLine = int(editor.rows[caretRow].line) } markerIndex := 0 diff --git a/components/code_editor_test.go b/components/code_editor_test.go index d84409130..54883009a 100644 --- a/components/code_editor_test.go +++ b/components/code_editor_test.go @@ -836,6 +836,28 @@ func TestCodeEditorCurrentLineTint(t *testing.T) { } } +// An empty document is still one line, and the caret is on it. Code surfaces +// (CodeMirror's highlightActiveLine, VS Code) tint that row exactly like any +// other caret line, so an empty editor's first line carries the same +// background as a populated one — the placeholder is text styling, not a +// signal that there is no caret line. +func TestCodeEditorCurrentLineTintOnEmptyDocument(t *testing.T) { + f := newCodeFixture("") + f.snapshot.CurrentLine = true + f.snapshot.Placeholder = "Type SQL" + f.paint() + tint := f.theme.Foreground + tint.Alpha *= 0.05 + got := f.fills(tint) + if len(got) != 1 { + t.Fatalf("an empty document must tint its single caret row, got %+v", got) + } + _, _, lineHeight := f.cell() + if got[0].Y != f.editor.content.Y || got[0].Height != lineHeight { + t.Fatalf("tint = %+v, want Y=%v height=%v", got[0], f.editor.content.Y, lineHeight) + } +} + func TestCodeEditorCompositionIsUnderlined(t *testing.T) { f := newCodeFixture("ab你好c") f.snapshot.CompositionStart, f.snapshot.CompositionEnd, f.snapshot.Caret = 2, 8, 8 From 0a4e75612e7b00c584654b3bf9a5cbea591a359a Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 12:15:21 +0800 Subject: [PATCH 23/86] feat(ui): TextEnd places an Input's text at the end of its direction ui.Box.TextEnd() aligned a Text but did nothing to an Input, a TextField or an InputBase: paintInput never read n.textEnd, so a field declared with .TextEnd() kept the ordinary start alignment. paintTextarea's rows follow the textarea's own row layout (TextareaSnapshot has no Alignment), so it was left alone. paintInput now carries the element's TextEnd() into the snapshot as AlignEnd when the snapshot left its alignment at the zero value. The overwrite happens where the snapshot is styled from the element, in the same direction as FontSize, Weight, Color and Mono: an explicit snapshot alignment (AlignCenter, AlignRight, AlignEnd or a AlignStart that came in as AlignLeft, which components treats as the default) is kept, so a caller that declared its own alignment is never written over. Through InputSnapshot's own a7345fa paths, the one value drives the painted line, the caret, the selection, the composition and the text geometry the hit declares, which focusedTextField, painter.syncTextInput and the Fields / Page editor fallback chains hand to the platform editor: a focused number field stays right-aligned. --- ui/field_alignment_test.go | 80 ++++++++++++++++++++++++++++++++++++++ ui/input_base_test.go | 55 ++++++++++++++++++++++++++ ui/paint.go | 8 ++++ 3 files changed, 143 insertions(+) create mode 100644 ui/field_alignment_test.go diff --git a/ui/field_alignment_test.go b/ui/field_alignment_test.go new file mode 100644 index 000000000..9492eca5e --- /dev/null +++ b/ui/field_alignment_test.go @@ -0,0 +1,80 @@ +//go:build darwin || windows || linux + +package ui + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +// TextEnd reaches the platform through the whole chain: the hit the field declares +// tells the focused editor its alignment, so a number field stays right-aligned +// while it is being edited in, and a field that did not ask stays start-aligned. +func TestFieldTextEndToldToThePlatformEditor(t *testing.T) { + var amount, note Field + var view View + amountID, noteID := tree.ID(page, "amount"), tree.ID(page, "note") + amount.SetText("42") + config := app.Config{ + Tree: &tree, Title: "aligned", Width: 300, Height: 200, + Paint: func(canvas *gfx.Canvas, size gfx.Size) { + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: size.Width, Height: size.Height}, func(f *Frame) { + f.Column().Fill().Pad(12).Gap(8).Children(func() { + f.Field(&amount, amountID, "Amount", "").TextEnd() + f.Field(¬e, noteID, "Note", "") + }) + }) + }, + TextInput: Fields(&amount, ¬e), + } + var canvas gfx.Canvas + driver, err := app.NewDriver(config, &canvas) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + click := func(id gfx.ID) { + for _, hit := range driver.Snapshot().Hits { + if hit.ID == id { + if err := driver.Click(hit.Bounds.X+hit.Bounds.Width/2, hit.Bounds.Y+hit.Bounds.Height/2); err != nil { + t.Fatal(err) + } + return + } + } + t.Fatalf("no field %v on screen", id) + } + editorAlignment := func() gfx.Alignment { + snapshot := driver.Snapshot() + if snapshot.Editor == nil { + t.Fatal("no focused editor on screen") + } + return snapshot.Editor.Alignment + } + click(amountID) + if got := editorAlignment(); got != gfx.AlignRight { + t.Errorf("the right-aligned field's editor = %v, want AlignRight (resolved from AlignEnd)", got) + } + // The line the editor draws sits at the same right edge the paint put it at, and + // the field's own painted line is right-aligned too. + snapshot := driver.Snapshot() + var line gfx.Text + for _, text := range snapshot.Texts { + if text.Value == "42" && text.Bounds.Width == snapshot.Editor.Bounds.Width { + line = text + break + } + } + if line.Value == "" { + t.Fatalf("the value was not painted: %+v", snapshot.Texts) + } + if line.Bounds.X < snapshot.Editor.Bounds.X+snapshot.Editor.Bounds.Width/2 { + t.Errorf("the painted value starts at %v, left of center: it was not right-aligned", line.Bounds.X) + } + click(noteID) + if got := editorAlignment(); got != gfx.AlignLeft { + t.Errorf("an ordinary field's editor = %v, want AlignLeft (start for LTR)", got) + } +} diff --git a/ui/input_base_test.go b/ui/input_base_test.go index a49e85a23..5d9f22e10 100644 --- a/ui/input_base_test.go +++ b/ui/input_base_test.go @@ -214,6 +214,7 @@ func TestInputIsTheBaseDressedByTheRecipeAndPaintsAsTheComponentDoes(t *testing. "secure": {ID: baseField, Label: "Name", Value: "hunter2", Secure: true}, "composition": {ID: baseField, Label: "Name", Value: "Gopher", Focused: true, CompositionStart: 2, CompositionEnd: 4}, "platform": {ID: baseField, Label: "Name", Value: "Gopher", Focused: true, PlatformEditing: true}, + "aligned": {ID: baseField, Label: "Name", Value: "Gopher", Alignment: gfx.AlignEnd}, } for themeName, theme := range themes { for name, snapshot := range snapshots { @@ -513,3 +514,57 @@ func TestInputBaseLineHeightIsTheElementsAndThePadComesOnTop(t *testing.T) { t.Errorf("height of a 20 point field = %v, want the size plus seven, 27", got) } } + +// TextEnd right-aligns the value of an Input: the element's declaration reaches where the +// glyph line is painted, and the hit tells the platform the same end. What the snapshot +// declared itself is not written over. +func TestInputTextEndRightAlignsTheValueAndTheEditorGeometry(t *testing.T) { + theme := gfx.LightTheme() + snapshot := components.InputSnapshot{ID: baseField, Label: "Amount", Value: "42", Text: components.InputTextStyle{Size: 14}} + paint := func(style func(Box) Box) *gfx.Canvas { + var view View + canvas := testCanvas() + view.Draw(canvas, theme, gfx.Rect{Width: 240, Height: 80}, func(f *Frame) { + f.Row().Items(Start).Children(func() { + style(f.InputBase(snapshot).Width(200)) + }) + }) + return canvas + } + lineOf := func(canvas *gfx.Canvas) gfx.Text { + for _, text := range canvas.Texts() { + if text.Value == "42" { + return text + } + } + t.Fatalf("no value painted: %+v", canvas.Texts()) + return gfx.Text{} + } + plain, ended := paint(func(b Box) Box { return b }), paint(func(b Box) Box { return b.TextEnd() }) + // The element's TextEnd() reaches the painted line. + if lineOf(plain).Bounds.X == lineOf(ended).Bounds.X { + t.Fatalf("the value did not move: %+v and %+v", lineOf(plain).Bounds, lineOf(ended).Bounds) + } + if lineOf(ended).Bounds.X <= lineOf(plain).Bounds.X { + t.Errorf("the value starts at %v, want it right of the start-aligned %v", lineOf(ended).Bounds.X, lineOf(plain).Bounds.X) + } + // What the hit tells the platform is the same edge. + if text := hitText(plain, &plain.Hits()[0]); text.Alignment != gfx.AlignStart { + t.Errorf("a field without TextEnd promises alignment %v, want AlignStart", text.Alignment) + } + if text := hitText(ended, &ended.Hits()[0]); text.Alignment != gfx.AlignEnd { + t.Errorf("the platform is told alignment %v, want AlignEnd", text.Alignment) + } + // The element does not write over a snapshot that declared its own. + own := components.InputSnapshot{ID: baseField, Label: "Amount", Value: "42", Alignment: gfx.AlignCenter} + var view View + centered := testCanvas() + view.Draw(centered, theme, gfx.Rect{Width: 240, Height: 80}, func(f *Frame) { + f.Row().Items(Start).Children(func() { + f.InputBase(own).Width(200).TextEnd() + }) + }) + if text := hitText(centered, ¢ered.Hits()[0]); text.Alignment != gfx.AlignCenter { + t.Errorf("the snapshot's own alignment was written over: %v, want the declared AlignCenter", text.Alignment) + } +} diff --git a/ui/paint.go b/ui/paint.go index 62eeb1ea1..9ec550b01 100644 --- a/ui/paint.go +++ b/ui/paint.go @@ -305,7 +305,15 @@ func (f *frame) paintButton(n *node) { func (f *frame) paintInput(n *node) { // What the element says of its text (FontSize, Weight, Color) is the field's text style, // over the snapshot's own: the one value the glyphs, the caret and the platform follow. + // What it says of its alignment is the same, but a field is start-aligned unless it says + // otherwise, so the snapshot's own declaration is left alone only by an alignment it + // declares. What the snapshot leaves at AlignLeft the element's TextEnd() takes. snapshot := f.inputs[n.aux] + if n.textEnd { + if snapshot.Alignment == gfx.AlignLeft || snapshot.Alignment == gfx.AlignStart { + snapshot.Alignment = gfx.AlignEnd + } + } if n.fontSize > 0 { snapshot.Text.Size = n.fontSize } From 5cce5aa9e9b8fb21935e67e6c8bca60206088bfc Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 12:32:55 +0800 Subject: [PATCH 24/86] fix(instance): claim with a named pipe on Windows AF_UNIX exists only from Windows 10 1803 and Windows Server 2019. On every Windows below that (Windows 10 1607 and 1709, Windows Server 2016) net.Listen("unix") failed, the dial that followed failed with the same address-family error, and Claim reported only "no process is listening": the platform's reason was dropped, so a system without the address looked like an application that was not running. Claim at a per-user named pipe on Windows instead. The pipe namespace is machine-wide, so the name carries a digest of the user's SID; the pipe rejects remote clients and its ACL admits only its creator. A pipe also needs no directory, no permission check and no stale-file clean-up. macOS and Linux keep the Unix socket unchanged. Claim now names the listener error next to "nobody listens", so a future failure reports what the platform refused. Motty's accompanying commit stops the fatal message from naming a log that a run failing before logging never opened. A copy from a build before this change claims at the socket, so it meets this build only after every running copy has exited; the in-app updater restarts that way. Tests ran on macOS and on the physical Windows 11 machine, including the two-process hand-off; Claim+Close on Windows costs 23 us and 18 allocations. --- app/singleinstance/singleinstance.go | 11 +- go.mod | 2 + go.sum | 4 + internal/instance/claim_unix.go | 115 ++++++++++++++ internal/instance/claim_windows.go | 60 ++++++++ internal/instance/instance.go | 167 ++++++--------------- internal/instance/instance_test.go | 125 ++++----------- internal/instance/instance_unix_test.go | 101 +++++++++++++ internal/instance/instance_windows_test.go | 28 ++++ internal/instance/owner_windows.go | 6 - internal/instance/shortpath_other.go | 6 - internal/instance/shortpath_windows.go | 27 ---- 12 files changed, 385 insertions(+), 267 deletions(-) create mode 100644 internal/instance/claim_unix.go create mode 100644 internal/instance/claim_windows.go create mode 100644 internal/instance/instance_unix_test.go create mode 100644 internal/instance/instance_windows_test.go delete mode 100644 internal/instance/owner_windows.go delete mode 100644 internal/instance/shortpath_other.go delete mode 100644 internal/instance/shortpath_windows.go diff --git a/app/singleinstance/singleinstance.go b/app/singleinstance/singleinstance.go index a94f5e002..1cd17d14f 100644 --- a/app/singleinstance/singleinstance.go +++ b/app/singleinstance/singleinstance.go @@ -1,9 +1,9 @@ //go:build darwin || windows || linux // Package singleinstance keeps an application to one running copy per user. -// It is separate from package app because it uses a local socket and the net -// package: an application that does not import this package does not link -// them. +// It is separate from package app because it uses a local socket or named pipe +// and the net package: an application that does not import this package does not +// link them. package singleinstance import ( @@ -36,8 +36,9 @@ func (claim *Instance) Close() { // // id names the application and must be the same for every copy, as its bundle // or reverse-DNS identifier. Copies run by different users do not meet. The -// claim lives in a per-user directory the platform keeps across launches, so -// copies started from a desktop and from a terminal meet whatever temporary +// claim lives at a per-user address the platform keeps across launches (a Unix +// socket in a per-user directory on macOS and Linux, a named pipe on Windows), +// so copies started from a desktop and from a terminal meet whatever temporary // directories their shells set. An error means the claim could not be made // either way; the caller may carry on as an unclaimed copy. func SingleInstance(id string, args []string, onLaunch func(args []string)) (claim *Instance, primary bool, err error) { diff --git a/go.mod b/go.mod index 7d4b079fd..34af71a85 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,9 @@ module github.com/vivaui/viva go 1.26.0 require ( + github.com/Microsoft/go-winio v0.6.4 github.com/ebitengine/purego v0.11.1 github.com/pelletier/go-toml/v2 v2.4.3 + golang.org/x/sys v0.50.0 golang.org/x/text v0.44.0 ) diff --git a/go.sum b/go.sum index d7aef6e26..429c75911 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,10 @@ +github.com/Microsoft/go-winio v0.6.4 h1:kJF2pamtYCWXf0xAT8sAkwKC0pMl2HYBrRPHAqyUc+g= +github.com/Microsoft/go-winio v0.6.4/go.mod h1:1xl5JXG4ze/m74GH6Dc4Mwxfc3VL5siRVQjIAlHH07U= github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0= github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= diff --git a/internal/instance/claim_unix.go b/internal/instance/claim_unix.go new file mode 100644 index 000000000..5b1b0bab1 --- /dev/null +++ b/internal/instance/claim_unix.go @@ -0,0 +1,115 @@ +//go:build darwin || linux + +package instance + +import ( + "fmt" + "net" + "os" + "path/filepath" + "runtime" +) + +// maxSocketPath is below the 104 bytes a Unix socket path may have on macOS. +const maxSocketPath = 100 + +// claimDirectory is the directory a claim lives in. It is a variable so tests +// can use a directory of their own; the program never changes it. +var claimDirectory = defaultClaimDirectory + +// claimAddress is where the id's socket lives: in a directory only this user can +// enter, short enough for the 104-byte limit of a Unix socket path. +func claimAddress(id string) (string, error) { + dir, err := claimDirectory() + if err != nil { + return "", err + } + return socketPathIn(dir, id) +} + +// defaultClaimDirectory is the per-user directory claims live in. It is derived +// from the user, not from the environment: a copy started from a desktop and one +// started from a terminal must find each other, and their TMPDIR and +// XDG_RUNTIME_DIR can differ (an SSH session, a service or a shell profile can +// leave the first unset or set it to another place). If the claim followed the +// environment, both copies would bind a socket and both would believe they are +// the one running copy, writing the same saved data from two processes. +func defaultClaimDirectory() (string, error) { + if runtime.GOOS == "linux" { + // The session runtime directory, derived from the user rather than read + // from XDG_RUNTIME_DIR, so a launch without the variable agrees with the + // desktop's own. + session := fmt.Sprintf("/run/user/%d", os.Getuid()) + if info, err := os.Stat(session); err == nil && info.IsDir() && ownedByUser(info) { + return filepath.Join(session, "viva"), nil + } + return filepath.Join("/tmp", fmt.Sprintf("viva-%d", os.Getuid())), nil + } + // ~/Library/Application Support on macOS. The cache directory can be purged + // under disk pressure, which would remove the socket of a running copy and + // let a second one claim the application. + base, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(base, "viva"), nil +} + +// socketPathIn is claimAddress for a claim directory. The split lets a test +// reach the length fallback without a machine whose home directory is that deep. +func socketPathIn(dir, id string) (string, error) { + name := claimName(id) + ".sock" + if len(dir)+len(name)+1 > maxSocketPath { + // A very long home directory: /tmp is always short, and every copy + // derives the same fallback from the user, not from the environment. + dir = filepath.Join("/tmp", fmt.Sprintf("viva-%d", os.Getuid())) + } + socket := filepath.Join(dir, name) + if len(socket) > maxSocketPath { + return "", fmt.Errorf("instance: the claim path %s is %d bytes, over the %d-byte limit; the user's home directory is too deep", socket, len(socket), maxSocketPath) + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", err + } + info, err := os.Lstat(dir) + if err != nil { + return "", err + } + if !info.IsDir() { + return "", fmt.Errorf("instance: %s is not a directory", dir) + } + if info.Mode().Perm()&0o077 != 0 { + if err := os.Chmod(dir, 0o700); err != nil { + return "", fmt.Errorf("instance: %s is open to other users: %w", dir, err) + } + } + if !ownedByUser(info) { + return "", fmt.Errorf("instance: %s belongs to another user", dir) + } + return socket, nil +} + +// listen takes the address. It fails while another copy's socket is there, which +// is what makes the first process the one that runs. +func listen(address string) (net.Listener, error) { + listener, err := net.Listen("unix", address) + if err != nil { + return nil, err + } + os.Chmod(address, 0o600) + return listener, nil +} + +// send hands args to the copy listening on the socket. A socket that nobody +// listens on is the stale file of a process that died, and the caller replaces +// it after errNobody. +func send(address string, args []string) error { + conn, err := net.DialTimeout("unix", address, ioDeadline) + if err != nil { + return fmt.Errorf("%w: %v", errNobody, err) + } + return sendArgs(conn, args) +} + +// discard removes a socket nobody listens on. +func discard(address string) { os.Remove(address) } diff --git a/internal/instance/claim_windows.go b/internal/instance/claim_windows.go new file mode 100644 index 000000000..fd7b70a23 --- /dev/null +++ b/internal/instance/claim_windows.go @@ -0,0 +1,60 @@ +//go:build windows + +package instance + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net" + "os" + + "github.com/Microsoft/go-winio" + "golang.org/x/sys/windows" +) + +// pipePrefix is where the named pipes of the machine live. +const pipePrefix = `\\.\pipe\` + +// claimAddress is the pipe the claim lives at. The pipe namespace is +// machine-wide, not per user like the Unix claim directory, so the name carries +// a digest of the user's SID: two users running the same application must not +// find each other's pipe in the way. The pipe itself rejects remote clients and +// admits only the user who made it, so the name is the other half of keeping +// copies apart. Unlike a socket file, the pipe needs no directory, no permission +// check and no clean-up: it exists exactly as long as its process does. +func claimAddress(id string) (string, error) { + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + return "", fmt.Errorf("instance: the user of this process: %w", err) + } + sum := sha256.Sum256([]byte(user.User.Sid.String())) + return pipePrefix + "viva-" + hex.EncodeToString(sum[:6]) + "-" + claimName(id), nil +} + +// listen takes the pipe name. It fails while another copy's pipe has it, which +// is what makes the first process the one that runs. +func listen(address string) (net.Listener, error) { + return winio.ListenPipe(address, nil) +} + +// send hands args to the copy listening on the pipe. A pipe that is not there +// fails with ERROR_FILE_NOT_FOUND, which means no copy is running; any other +// failure means a copy exists and could not be reached, so its claim is not +// taken over. +func send(address string, args []string) error { + timeout := ioDeadline + conn, err := winio.DialPipe(address, &timeout) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("%w: %v", errNobody, err) + } + return fmt.Errorf("instance: the running copy cannot be reached: %w", err) + } + return sendArgs(conn, args) +} + +// discard has nothing to remove: a named pipe goes away with the process that +// made it, so a claim left by a crash is not there for the next launch to find. +func discard(string) {} diff --git a/internal/instance/instance.go b/internal/instance/instance.go index 242650f94..d051f215f 100644 --- a/internal/instance/instance.go +++ b/internal/instance/instance.go @@ -1,12 +1,19 @@ // Package instance makes an application run once per user. The first process -// listens on a local socket; a later one connects, hands over its command line -// and exits. No file lock, polling or timer is involved: the first process +// listens at the claim address; a later one connects, hands over its command +// line and exits. No file lock, polling or timer is involved: the first process // holds one blocked accept, and nothing else runs until a second process starts. // -// The socket lives in a per-user directory the platform keeps across launches, -// never in the process's temporary directory: TMPDIR and XDG_RUNTIME_DIR are -// set by whichever shell or session started the process, and two copies that -// disagree on them would not meet. +// The address belongs to the user, not to the environment: a copy started from +// a desktop and one started from a terminal must find each other, and their +// TMPDIR and XDG_RUNTIME_DIR can differ (an SSH session, a service or a shell +// profile can leave the first unset or set it to another place). If the claim +// followed the environment, both copies would listen and both would believe they +// are the one running copy, writing the same saved data from two processes. +// +// The platform files say where the address is. macOS and Linux claim at a Unix +// socket in a per-user directory. Windows claims at a per-user named pipe: +// AF_UNIX exists only from Windows 10 1803 and Windows Server 2019, while the +// named pipe is there on every Windows a Go program runs on. package instance import ( @@ -18,9 +25,6 @@ import ( "fmt" "io" "net" - "os" - "path/filepath" - "runtime" "strings" "sync" "time" @@ -30,14 +34,12 @@ const ( maxMessage = 1 << 20 maxArgs = 4096 ioDeadline = 3 * time.Second - // maxSocketPath is below the 104 bytes a Unix socket path may have on macOS. - maxSocketPath = 100 ) // Instance is the first process's claim on the application. type Instance struct { listener net.Listener - path string + address string once sync.Once done chan struct{} } @@ -50,141 +52,61 @@ func Claim(id string, args []string, handler func(args []string)) (instance *Ins if id == "" { return nil, false, errors.New("instance: an application id is required") } - path, err := socketPath(id) + address, err := claimAddress(id) if err != nil { return nil, false, err } + var listenErr error for attempt := 0; attempt < 3; attempt++ { - listener, listenErr := net.Listen("unix", path) - if listenErr == nil { - os.Chmod(path, 0o600) - instance = &Instance{listener: listener, path: path, done: make(chan struct{})} + listener, attemptErr := listen(address) + if attemptErr == nil { + instance = &Instance{listener: listener, address: address, done: make(chan struct{})} go instance.serve(handler) return instance, true, nil } - sendErr := send(path, args) + listenErr = attemptErr + sendErr := send(address, args) if sendErr == nil { return nil, false, nil } if !errors.Is(sendErr, errNobody) { return nil, false, sendErr } - // Nobody answers: the socket is left from a process that died. - os.Remove(path) + // Nobody answers: the address is left from a process that died. + discard(address) } - return nil, false, fmt.Errorf("instance: cannot claim %s: %w", path, errNobody) + return nil, false, claimFailure(address, listenErr) +} + +// claimFailure is the error of a claim that could be neither handed to a running +// copy nor made by this process. Both halves are named: the platform's own +// reason for refusing the address is what a report needs, and leaving it out +// made a platform without that address look like an application that was not +// running. +func claimFailure(address string, listenErr error) error { + return fmt.Errorf("instance: cannot claim %s: %w, and this process cannot listen there: %v", address, errNobody, listenErr) } -// Close stops listening and removes the socket. It is idempotent. +// Close stops listening and removes the claim. It is idempotent. func (instance *Instance) Close() { if instance == nil { return } instance.once.Do(func() { instance.listener.Close() - os.Remove(instance.path) + discard(instance.address) <-instance.done }) } var errNobody = errors.New("instance: no process is listening") -// claimDirectory is the directory a claim lives in. It is a variable so tests -// can use a directory of their own; the program never changes it. -var claimDirectory = defaultClaimDirectory - -// defaultClaimDirectory is the per-user directory claims live in. It is derived -// from the user, not from the environment: a copy started from a desktop and one -// started from a terminal must find each other, and their TMPDIR and -// XDG_RUNTIME_DIR can differ (an SSH session, a service or a shell profile can -// leave the first unset or set it to another place). If the claim followed the -// environment, both copies would bind a socket and both would believe they are -// the one running copy, writing the same saved data from two processes. -func defaultClaimDirectory() (string, error) { - switch runtime.GOOS { - case "linux": - // The session runtime directory, derived from the user rather than read - // from XDG_RUNTIME_DIR, so a launch without the variable agrees with the - // desktop's own. - session := fmt.Sprintf("/run/user/%d", os.Getuid()) - if info, err := os.Stat(session); err == nil && info.IsDir() && ownedByUser(info) { - return filepath.Join(session, "viva"), nil - } - return filepath.Join("/tmp", fmt.Sprintf("viva-%d", os.Getuid())), nil - case "windows": - // %LocalAppData%, which is the user's own and is not roamed between - // computers; a socket must stay on this machine. - base, err := os.UserCacheDir() - if err != nil { - return "", err - } - return filepath.Join(base, "viva"), nil - default: - // ~/Library/Application Support on macOS. The cache directory can be - // purged under disk pressure, which would remove the socket of a - // running copy and let a second one claim the application. - base, err := os.UserConfigDir() - if err != nil { - return "", err - } - return filepath.Join(base, "viva"), nil - } -} - -// socketPath is where the id's socket lives: in a directory only this user can -// enter, short enough for the 104-byte limit of a Unix socket path. -func socketPath(id string) (string, error) { - dir, err := claimDirectory() - if err != nil { - return "", err - } - return socketPathIn(dir, id) -} - -// socketPathIn is socketPath for a claim directory. The split lets a test reach -// the length fallback without a machine whose home directory is that deep. -func socketPathIn(dir, id string) (string, error) { +// claimName is the part of the address that names the application. A digest +// keeps the address inside the length limit of both a socket path and a pipe +// name whatever the id is. +func claimName(id string) string { sum := sha256.Sum256([]byte(id)) - name := "i-" + hex.EncodeToString(sum[:6]) + ".sock" - if len(dir)+len(name)+1 > maxSocketPath { - if runtime.GOOS == "windows" { - // Windows AF_UNIX paths share the sockaddr limit, and there is no - // short system directory to fall back to; the 8.3 short form of the - // existing parent usually fits. The claim directory itself need not - // exist yet, so only its parent is shortened. - if short, ok := shortPath(filepath.Dir(dir)); ok { - dir = filepath.Join(short, filepath.Base(dir)) - } - } else { - // A very long home directory: /tmp is always short, and every copy - // derives the same fallback from the user, not from the environment. - dir = filepath.Join("/tmp", fmt.Sprintf("viva-%d", os.Getuid())) - } - } - if socket := filepath.Join(dir, name); len(socket) > maxSocketPath { - return "", fmt.Errorf("instance: the claim path %s is %d bytes, over the %d-byte limit; the user's home directory is too deep", socket, len(socket), maxSocketPath) - } - if err := os.MkdirAll(dir, 0o700); err != nil { - return "", err - } - info, err := os.Lstat(dir) - if err != nil { - return "", err - } - if !info.IsDir() { - return "", fmt.Errorf("instance: %s is not a directory", dir) - } - if runtime.GOOS != "windows" { - if info.Mode().Perm()&0o077 != 0 { - if err := os.Chmod(dir, 0o700); err != nil { - return "", fmt.Errorf("instance: %s is open to other users: %w", dir, err) - } - } - if !ownedByUser(info) { - return "", fmt.Errorf("instance: %s belongs to another user", dir) - } - } - return filepath.Join(dir, name), nil + return "i-" + hex.EncodeToString(sum[:6]) } func (instance *Instance) serve(handler func([]string)) { @@ -203,12 +125,9 @@ func (instance *Instance) serve(handler func([]string)) { } } -// send hands args to the process listening on path. -func send(path string, args []string) error { - conn, err := net.DialTimeout("unix", path, ioDeadline) - if err != nil { - return fmt.Errorf("%w: %v", errNobody, err) - } +// sendArgs hands args to a connected running process and waits for its +// acknowledgement. The connection is closed either way. +func sendArgs(conn net.Conn, args []string) error { defer conn.Close() conn.SetDeadline(time.Now().Add(ioDeadline)) if err := writeArgs(conn, args); err != nil { diff --git a/internal/instance/instance_test.go b/internal/instance/instance_test.go index 6464e559b..020f75f83 100644 --- a/internal/instance/instance_test.go +++ b/internal/instance/instance_test.go @@ -1,11 +1,8 @@ package instance import ( - "fmt" - "os" - "path/filepath" + "errors" "reflect" - "runtime" "strings" "testing" "time" @@ -55,13 +52,15 @@ func TestDifferentIDsDoNotMeetAndEmptyArgumentsWork(t *testing.T) { } } -func TestAStaleSocketIsReplaced(t *testing.T) { +func TestAClosedClaimIsReclaimed(t *testing.T) { isolate(t) first, primary, _ := Claim("dev.test.stale", nil, func([]string) {}) if !primary { t.Fatal("not primary") } - // A process that died leaves its socket file: close the listener only. + // A process that died leaves its listener behind: close that only. On Windows + // the pipe goes with it and nothing is left; on Unix the socket file stays + // until the next claim replaces it. first.listener.Close() <-first.done second, primary, err := Claim("dev.test.stale", nil, func([]string) {}) @@ -83,102 +82,30 @@ func TestOversizeAndMalformedMessagesAreRefused(t *testing.T) { } } -// isolate gives a test its own claim directory. -func isolate(t *testing.T) { - t.Helper() - dir, err := os.MkdirTemp("", "gi") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.RemoveAll(dir) }) - previous := claimDirectory - claimDirectory = func() (string, error) { return dir, nil } - t.Cleanup(func() { claimDirectory = previous }) -} - -// A copy started from a desktop and one started from a terminal can carry -// different temporary directories. The claim must not move with the environment: -// if it did, each copy would bind its own socket, both would become primary, and -// both would hold the same saved data. -func TestTheClaimDirectoryDoesNotFollowTheEnvironment(t *testing.T) { - before, err := defaultClaimDirectory() - if err != nil { - t.Fatal(err) - } - if !filepath.IsAbs(before) { - t.Fatalf("the claim directory %q is not absolute", before) - } - other := filepath.Join(t.TempDir(), strings.Repeat("deep-directory-", 6)) - t.Setenv("XDG_RUNTIME_DIR", other) - t.Setenv("TMPDIR", other) - t.Setenv("TEMP", other) - t.Setenv("TMP", other) - after, err := defaultClaimDirectory() - if err != nil { - t.Fatal(err) - } - if before != after { - t.Fatalf("the claim directory moved from %q to %q with the environment", before, after) - } -} - -// A claim directory too deep for a socket path must still claim: the path falls -// back to a short one instead of failing to bind, and both launches agree on it. -func TestALongClaimDirectoryKeepsTheSocketPathShort(t *testing.T) { - base := t.TempDir() - deep := filepath.Join(base, strings.Repeat("deep-directory-", 6), strings.Repeat("x", 40)) - if err := os.MkdirAll(deep, 0o700); err != nil { - t.Fatal(err) - } - if len(deep) <= maxSocketPath { - t.Fatalf("the test needs a directory over %d bytes, got %d", maxSocketPath, len(deep)) - } - - path, err := socketPathIn(deep, "dev.test.deep") - if err != nil { - if runtime.GOOS == "windows" { - // The fallback asks the volume for its 8.3 names, and a volume may - // have them switched off; there is no portable shorter path to try. - t.Skipf("the volume offers no short path: %v", err) - } - t.Fatalf("a deep claim directory leaves no socket path: %v", err) - } - if len(path) > maxSocketPath { - t.Fatalf("socket path %q is %d bytes, over the %d-byte limit", path, len(path), maxSocketPath) - } - if runtime.GOOS != "windows" { - short := filepath.Join("/tmp", fmt.Sprintf("viva-%d", os.Getuid())) - if !strings.HasPrefix(path, short+string(os.PathSeparator)) { - t.Fatalf("a deep directory did not fall back to %s: %q", short, path) +// The claim failed twice over, and the platform's reason for the half this +// process tried must be in the error: without it an address the system does not +// have looked exactly like an application that was not running. +func TestClaimFailureNamesTheListenerError(t *testing.T) { + cause := errors.New("socket: address family not supported") + err := claimFailure(`\\.\pipe\viva-test`, cause) + if !errors.Is(err, errNobody) { + t.Fatalf("the failure does not report that nobody listens: %v", err) + } + for _, want := range []string{"cannot claim", `\\.\pipe\viva-test`, cause.Error()} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("the failure %q does not name %q", err, want) } } - if again, err := socketPathIn(deep, "dev.test.deep"); err != nil || again != path { - t.Fatalf("the socket path is not stable: %q then %q (%v)", path, again, err) - } - - // Claim goes through the same fallback: the directory the platform would - // give is replaced by the deep one, so both launches below must still agree. - previous := claimDirectory - claimDirectory = func() (string, error) { return deep, nil } - t.Cleanup(func() { claimDirectory = previous }) +} - got := make(chan []string, 1) - first, primary, err := Claim("dev.test.deep", nil, func(args []string) { got <- args }) - if err != nil || !primary { - t.Fatalf("claim with a deep directory: primary %v, err %v", primary, err) - } - defer first.Close() - if second, primary, err := Claim("dev.test.deep", []string{"handoff"}, func([]string) { - t.Error("the second process must not serve") - }); err != nil || primary || second != nil { - t.Fatalf("second claim: primary %v, err %v", primary, err) - } - select { - case args := <-got: - if !reflect.DeepEqual(args, []string{"handoff"}) { - t.Fatalf("handler got %q", args) +func BenchmarkClaimAndClose(b *testing.B) { + isolate(b) + b.ReportAllocs() + for b.Loop() { + claim, primary, err := Claim("dev.test.bench", nil, func([]string) {}) + if err != nil || !primary { + b.Fatalf("claim: primary %v, err %v", primary, err) } - case <-time.After(3 * time.Second): - t.Fatal("the arguments never arrived") + claim.Close() } } diff --git a/internal/instance/instance_unix_test.go b/internal/instance/instance_unix_test.go new file mode 100644 index 000000000..21df3fc21 --- /dev/null +++ b/internal/instance/instance_unix_test.go @@ -0,0 +1,101 @@ +//go:build darwin || linux + +package instance + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// isolate gives a test its own claim directory. +func isolate(t testing.TB) { + t.Helper() + dir := t.TempDir() + previous := claimDirectory + claimDirectory = func() (string, error) { return dir, nil } + t.Cleanup(func() { claimDirectory = previous }) +} + +// A copy started from a desktop and one started from a terminal can carry +// different temporary directories. The claim must not move with the environment: +// if it did, each copy would bind its own socket, both would become primary, and +// both would hold the same saved data. +func TestTheClaimDirectoryDoesNotFollowTheEnvironment(t *testing.T) { + before, err := defaultClaimDirectory() + if err != nil { + t.Fatal(err) + } + if !filepath.IsAbs(before) { + t.Fatalf("the claim directory %q is not absolute", before) + } + other := filepath.Join(t.TempDir(), strings.Repeat("deep-directory-", 6)) + t.Setenv("XDG_RUNTIME_DIR", other) + t.Setenv("TMPDIR", other) + t.Setenv("TEMP", other) + t.Setenv("TMP", other) + after, err := defaultClaimDirectory() + if err != nil { + t.Fatal(err) + } + if before != after { + t.Fatalf("the claim directory moved from %q to %q with the environment", before, after) + } +} + +// A claim directory too deep for a socket path must still claim: the path falls +// back to a short one instead of failing to bind, and both launches agree on it. +func TestALongClaimDirectoryKeepsTheSocketPathShort(t *testing.T) { + base := t.TempDir() + deep := filepath.Join(base, strings.Repeat("deep-directory-", 6), strings.Repeat("x", 40)) + if err := os.MkdirAll(deep, 0o700); err != nil { + t.Fatal(err) + } + if len(deep) <= maxSocketPath { + t.Fatalf("the test needs a directory over %d bytes, got %d", maxSocketPath, len(deep)) + } + + path, err := socketPathIn(deep, "dev.test.deep") + if err != nil { + t.Fatalf("a deep claim directory leaves no socket path: %v", err) + } + if len(path) > maxSocketPath { + t.Fatalf("socket path %q is %d bytes, over the %d-byte limit", path, len(path), maxSocketPath) + } + short := filepath.Join("/tmp", fmt.Sprintf("viva-%d", os.Getuid())) + if !strings.HasPrefix(path, short+string(os.PathSeparator)) { + t.Fatalf("a deep directory did not fall back to %s: %q", short, path) + } + if again, err := socketPathIn(deep, "dev.test.deep"); err != nil || again != path { + t.Fatalf("the socket path is not stable: %q then %q (%v)", path, again, err) + } + + // Claim goes through the same fallback: the directory the platform would + // give is replaced by the deep one, so both launches below must still agree. + previous := claimDirectory + claimDirectory = func() (string, error) { return deep, nil } + t.Cleanup(func() { claimDirectory = previous }) + + got := make(chan []string, 1) + first, primary, err := Claim("dev.test.deep", nil, func(args []string) { got <- args }) + if err != nil || !primary { + t.Fatalf("claim with a deep directory: primary %v, err %v", primary, err) + } + defer first.Close() + if second, primary, err := Claim("dev.test.deep", []string{"handoff"}, func([]string) { + t.Error("the second process must not serve") + }); err != nil || primary || second != nil { + t.Fatalf("second claim: primary %v, err %v", primary, err) + } + select { + case args := <-got: + if len(args) != 1 || args[0] != "handoff" { + t.Fatalf("handler got %q", args) + } + case <-time.After(3 * time.Second): + t.Fatal("the arguments never arrived") + } +} diff --git a/internal/instance/instance_windows_test.go b/internal/instance/instance_windows_test.go new file mode 100644 index 000000000..0d92d675f --- /dev/null +++ b/internal/instance/instance_windows_test.go @@ -0,0 +1,28 @@ +//go:build windows + +package instance + +import "testing" + +// isolate has nothing to hand out on Windows: a claim is a named pipe, not a +// file in a directory, so the tests share the machine's pipe namespace. Each +// test names an application of its own, which is what keeps them apart. +func isolate(t testing.TB) { t.Helper() } + +// The address must be a pipe and must not move between calls: every copy of the +// application computes it on its own and has to arrive at the same one. +func TestTheClaimAddressIsAStablePipe(t *testing.T) { + address, err := claimAddress("dev.test.pipe") + if err != nil { + t.Fatal(err) + } + if len(address) <= len(pipePrefix) || address[:len(pipePrefix)] != pipePrefix { + t.Fatalf("the claim address %q is not a named pipe", address) + } + if again, err := claimAddress("dev.test.pipe"); err != nil || again != address { + t.Fatalf("the claim address is not stable: %q then %q (%v)", address, again, err) + } + if other, _ := claimAddress("dev.test.other"); other == address { + t.Fatalf("two applications share the claim address %q", address) + } +} diff --git a/internal/instance/owner_windows.go b/internal/instance/owner_windows.go deleted file mode 100644 index d4712d893..000000000 --- a/internal/instance/owner_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -package instance - -import "os" - -// A Windows temporary directory belongs to the user already. -func ownedByUser(os.FileInfo) bool { return true } diff --git a/internal/instance/shortpath_other.go b/internal/instance/shortpath_other.go deleted file mode 100644 index 6fcad3d42..000000000 --- a/internal/instance/shortpath_other.go +++ /dev/null @@ -1,6 +0,0 @@ -//go:build !windows - -package instance - -// shortPath is a Windows-only fallback; other systems report no short form. -func shortPath(string) (string, bool) { return "", false } diff --git a/internal/instance/shortpath_windows.go b/internal/instance/shortpath_windows.go deleted file mode 100644 index 747629d49..000000000 --- a/internal/instance/shortpath_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build windows - -package instance - -import "syscall" - -// shortPath returns the 8.3 short form of an existing absolute path. Volumes -// with short names disabled, and paths already short, return ok false. -func shortPath(path string) (string, bool) { - ptr, err := syscall.UTF16PtrFromString(path) - if err != nil { - return "", false - } - size, err := syscall.GetShortPathName(ptr, nil, 0) - if err != nil || size == 0 { - return "", false - } - buf := make([]uint16, size) - if n, err := syscall.GetShortPathName(ptr, &buf[0], size); err != nil || n == 0 { - return "", false - } - short := syscall.UTF16ToString(buf) - if short == "" || short == path { - return "", false - } - return short, true -} From b8ae4373a70ce6d0bcc5414087a0c80b83a78fec Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 12:46:24 +0800 Subject: [PATCH 25/86] fix(instance): keep the claim off the browser target Splitting the package into per-platform claim files left instance.go and its shared test untagged while claimAddress lives only in the darwin/linux and windows files, so GOOS=js GOARCH=wasm go vet failed with "undefined: claimAddress". Tag the package for the platforms that have a claim, as app/singleinstance already is, and narrow owner_unix.go to darwin and linux so no file is left for the browser target. --- internal/instance/instance.go | 2 ++ internal/instance/instance_test.go | 2 ++ internal/instance/owner_unix.go | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/internal/instance/instance.go b/internal/instance/instance.go index d051f215f..d8b29187b 100644 --- a/internal/instance/instance.go +++ b/internal/instance/instance.go @@ -1,3 +1,5 @@ +//go:build darwin || windows || linux + // Package instance makes an application run once per user. The first process // listens at the claim address; a later one connects, hands over its command // line and exits. No file lock, polling or timer is involved: the first process diff --git a/internal/instance/instance_test.go b/internal/instance/instance_test.go index 020f75f83..24be62c38 100644 --- a/internal/instance/instance_test.go +++ b/internal/instance/instance_test.go @@ -1,3 +1,5 @@ +//go:build darwin || windows || linux + package instance import ( diff --git a/internal/instance/owner_unix.go b/internal/instance/owner_unix.go index 44970fe0a..4a1c268cc 100644 --- a/internal/instance/owner_unix.go +++ b/internal/instance/owner_unix.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build darwin || linux package instance From 11a62ef78fc1291886ae92222cfdb19ba9c61e82 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 12:46:24 +0800 Subject: [PATCH 26/86] fix(components): wrap tooltip labels through a stack scratch Wrapping the label moved from the overlay's own scratch to canvas.WrapLines(nil, ...), so every warm tooltip paint allocated the line slice again: the gallery and component demo allocation checks counted four allocations per paint. Pass a stack scratch, as the wrapping API asks callers to. The regenerated tooltip recipe carries the same change. --- cmd/viva/templates/tooltip.go.txt | 10 ++++++++-- components/tooltip.go | 5 ++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/cmd/viva/templates/tooltip.go.txt b/cmd/viva/templates/tooltip.go.txt index 37fc971db..500acc8d6 100644 --- a/cmd/viva/templates/tooltip.go.txt +++ b/cmd/viva/templates/tooltip.go.txt @@ -131,8 +131,14 @@ func (tooltip Tooltip) Paint(label string) gfx.Rect { } maxWidth = min(maxWidth, tooltip.viewport.Width-8) const padX, padY = float32(12), float32(6) - var scratch overlayLines - lines := overlayWrap(tooltip.canvas, &scratch, label, metrics.FontSizeS, gfx.WeightRegular, maxWidth-2*padX) + // A filename or another unbroken token has no natural short form: keep all + // of it even when a bounded descriptive tooltip would use an ellipsis. Long + // tokens already break at whole grapheme clusters in the text engine. The + // viewport is a bound on excessive content, not an interactive text limit. + // The lines live in a stack scratch: a tooltip that is painted every frame + // must not allocate for wrapping that has not changed. + var scratch [8]string + lines := tooltip.canvas.WrapLines(scratch[:0], label, metrics.FontSizeS, gfx.WeightRegular, maxWidth-2*padX, int(tooltip.viewport.Height)) // One line takes the width of its text; a wrapped label fills the whole // maximum, as a `w-fit max-w-xs` box does. textWidth := maxWidth - 2*padX diff --git a/components/tooltip.go b/components/tooltip.go index 709e950da..a37b3a4c4 100644 --- a/components/tooltip.go +++ b/components/tooltip.go @@ -135,7 +135,10 @@ func (tooltip Tooltip) Paint(label string) gfx.Rect { // of it even when a bounded descriptive tooltip would use an ellipsis. Long // tokens already break at whole grapheme clusters in the text engine. The // viewport is a bound on excessive content, not an interactive text limit. - lines := tooltip.canvas.WrapLines(nil, label, metrics.FontSizeS, gfx.WeightRegular, maxWidth-2*padX, int(tooltip.viewport.Height)) + // The lines live in a stack scratch: a tooltip that is painted every frame + // must not allocate for wrapping that has not changed. + var scratch [8]string + lines := tooltip.canvas.WrapLines(scratch[:0], label, metrics.FontSizeS, gfx.WeightRegular, maxWidth-2*padX, int(tooltip.viewport.Height)) // One line takes the width of its text; a wrapped label fills the whole // maximum, as a `w-fit max-w-xs` box does. textWidth := maxWidth - 2*padX From 2382a5aec7d088fe108d462bd313bf8495e2cd4e Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 12:46:24 +0800 Subject: [PATCH 27/86] fix(components): regenerate the stale code-editor recipe The empty-document caret tint changed the CodeEditor component without regenerating its installation recipe, so the generator checks failed. --- cmd/viva/templates/code_editor.go.txt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index 5c50a4234..b574f35ea 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -494,7 +494,12 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. canvas.Label(snapshot.Placeholder, gfx.Rect{X: content.X, Y: content.Y + (lineHeight-cellHeight)/2, Width: content.Width, Height: cellHeight}, style) } currentLine := -1 - if snapshot.CurrentLine && selectionStart == selectionEnd && len(selectionRanges) == 0 && !placeholder { + // The caret's line is tinted even while the document is empty: editing + // surfaces (CodeMirror's highlightActiveLine, VS Code) paint a row highlight + // wherever the caret sits, including the single empty row of a fresh + // document. Suppressing it on the placeholder row would make an empty + // editor's first line the only line in the widget without a background. + if snapshot.CurrentLine && selectionStart == selectionEnd && len(selectionRanges) == 0 { currentLine = int(editor.rows[caretRow].line) } markerIndex := 0 From b5cd71e015c6b98a22c7beded96b53cfaad771f6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 12:51:06 +0800 Subject: [PATCH 28/86] docs(release): v0.6.3 notes --- docs/releases/0.6.3.md | 97 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 docs/releases/0.6.3.md diff --git a/docs/releases/0.6.3.md b/docs/releases/0.6.3.md new file mode 100644 index 000000000..7c7280d4c --- /dev/null +++ b/docs/releases/0.6.3.md @@ -0,0 +1,97 @@ +v0.6.3 是 v0.6.2 之后的 patch 版本:修复 Windows 旧系统上的单实例启动、macOS 输入法组合、表格滚动条与提示框绘制等问题,并新增固定列、表格横向滚动、虚线边框、可调列宽与网页视图回调等一批可选 API 与能力,已有 API 不变,升级不需要改调用点。macOS 是参考平台。 + +v0.6.3 is a patch release after v0.6.2: it fixes single-instance startup on older Windows systems, input-method composition on macOS, table scrollbars and tooltip painting, and adds a set of opt-in APIs and capabilities, including frozen columns, horizontal table scrolling, dashed borders, resizable columns and web view callbacks. Existing 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.3`,需要 Go 1.26 或更新;系统依赖与 v0.6.2 相同。每个 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.3` needs Go 1.26 or newer; the system requirements are those of v0.6.2. 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 + +- Windows 的单实例认领改用每用户命名管道,Windows 10 1803 之前与 Windows Server 2016 可以正常启动,认领失败时的错误会带上平台给出的原因 +- `Box.TextEnd()` 现在也把 `Input`、`TextField` 的文字放到行尾,聚焦时的光标、选区与平台编辑器保持同一边 +- 空的 `CodeEditor` 也绘制光标行的底色,与有内容的编辑器一致 +- `TableSpec.HideHoverScrollbars` 让应用自己绘制垂直滚动条时不再叠加表格的匿名悬停条 +- 提示框的长文本按可见区域换行,不再套用八行省略预算,未断开的文件名可以完整显示 +- `TableSpec.FrozenColumns` 把左侧若干列固定在原地,横向滚动时它们与表头一起保持可见 +- `SetClipboardHTML(html, alt)` 在一次写入中放入 HTML 与纯文本两种格式,浏览器里通过 `SetClipboardHTMLAsync` 返回 Promise +- 自绘表格的横向滚动条落在为它保留的 gutter 里,不再盖住最下面一行 +- 虚线边框通过 `Box.Dashed()`、`Look.Dashed(bool)` 与 `DrawContext.DashedBorder` 使用 +- `InputSnapshot.Alignment` 让字段的文字、光标、选区与平台编辑器在聚焦时保持同一对齐 +- `gfx.PointerCursorGrabbing` 在 macOS、Wayland/X11、Web 与 Windows 上都有对应的抓取光标 +- `PathStyle.Dashed` 与 `Canvas.DashedRoundedOutline` 通过路径管线绘制虚线轮廓,闭合轮廓按整周期收口,热画布不分配 +- 宽表格可以横向滚动:固定的表头随列移动,`TableSpec.HorizontalScrollbar` 指定表体下方的滚动条,`TableState.Scroll` 报告两轴的偏移与视口,Shift+滚轮横向移动列 +- `TableState.RowID` 与 `TableState.Rows` 暴露上次绘制中每一行的身份与范围,应用可以按行的身份而不是行号处理指针 +- 框线与块元素字形按字体自身的下划线厚度绘制,opencode 的提示边框不再随显示缩放退化成细线 +- `Window.SetSize` 与 `ContentWindow.SetSize` 请求原生窗口内容尺寸,headless driver 同样支持,不支持的主机返回 `ErrUnsupported` (contributed by @Ezreal-byte) (PR [#172](https://github.com/vivaui/viva/pull/172)) +- 自定义标题栏的 macOS 交通灯可以通过 `TrafficLightScale` 缩放 (contributed by @imjakey) (PR [#254](https://github.com/vivaui/viva/pull/254)) +- `WebViewConfig.Proxy` 设为 `WebProxyDirect` 时该页面绕过系统代理 (contributed by @imjakey) (PR [#253](https://github.com/vivaui/viva/pull/253)) +- `Box.TooltipOn(side)` 让提示框在指定的一边打开,`TooltipSide` 与四个方向常量随包导出 (contributed by @xiaoyumuxi) (PR [#252](https://github.com/vivaui/viva/pull/252)) +- 菜单行只在指针不在菜单内其它控件上时绘制当前项底色,应用不必再为嵌入控件做绘制期的焦点绕行 +- `ColorSwatch.Flush()` 让色块填满边框内的圆 +- macOS 在输入法组合期间更新文本输入布局时不再丢弃已输入的拼音 +- 提示框箭头改成一个按设备像素羽化的三角形,100% 与 125% 缩放下不再出现粗糙台阶 +- Windows 的 `FileIcon` 返回系统图标,文本文件与未知类型不再共用同一个图标 (contributed by @Zer0ON1) (PR [#249](https://github.com/vivaui/viva/pull/249)) +- `components.BeginColumnResize` 提供可拖动的表格列宽,支持最小宽度与按内容贴合 (contributed by @Zer0ON1) (PR [#247](https://github.com/vivaui/viva/pull/247)) +- `WebViewConfig.Ephemeral` 让网页视图的数据留在临时存储里,不写入持久化目录 (contributed by @1lck) (PR [#244](https://github.com/vivaui/viva/pull/244)) +- `WebViewConfig.Navigate`、`NewWindow` 与 `Download` 让应用在导航、弹窗和下载发生前先做决定,`WebNavigation` 说明是哪个 frame 发起的 (contributed by @1lck) (PR [#243](https://github.com/vivaui/viva/pull/243)) +- 网页视图的顶部圆角由 `TopCornerRadius` 设置,光标由原生视图自己维护 (contributed by @imjakey) (PR [#248](https://github.com/vivaui/viva/pull/248)) +- `OpenDirectoryPath` 返回用户选择的一个现有目录,取消时返回 `ErrCanceled` +- `CodeEditorSnapshot.GutterMarkers` 在行号旁的行内绘制并暴露可点击的标记区,`CodeEditorGutterMarker` 的 `ID` 由调用方处理点击 +- Linux 与 Windows 的构建固定 `CGO_ENABLED=0`,在 Ubuntu 上构建的 Linux 程序不再携带构建机的 glibc,可以在更旧的发行版上启动 +- 重新生成 scroll-area、tooltip 与 code-editor 的组件安装模板,组件生成器的检查重新通过 + +- Windows claims single-instance ownership at a per-user named pipe, so Windows 10 before 1803 and Windows Server 2016 start normally, and a failed claim reports the platform's reason +- `Box.TextEnd()` now places an `Input` or `TextField`'s text at the end of its line, including the caret, selection and platform editor while focused +- An empty `CodeEditor` now tints the caret's row like a populated one +- `TableSpec.HideHoverScrollbars` lets an application that paints its own vertical bar omit the table's anonymous hover overlay +- Tooltips wrap a long label to the visible area instead of the eight-line ellipsizing budget, so an unbroken filename stays whole +- `TableSpec.FrozenColumns` pins the leftmost columns while the table scrolls sideways, keeping them and the header visible +- `SetClipboardHTML` writes an HTML flavour beside a plain-text one in a single copy, and `SetClipboardHTMLAsync` answers through the browser's Promise +- A self-scrolling table's horizontal bar lands in its reserved gutter instead of covering the last visible row +- Dashed borders are available as `Box.Dashed()`, `Look.Dashed(bool)` and `DrawContext.DashedBorder` +- `InputSnapshot.Alignment` keeps a field's line, caret, selection and platform editor on the same alignment while focused +- `gfx.PointerCursorGrabbing` gives macOS, Wayland/X11, the web and Windows a grabbing cursor +- `PathStyle.Dashed` and `Canvas.DashedRoundedOutline` stroke dashed outlines through the path pipeline, closing whole dash periods and allocating nothing on a warm canvas +- A wide table scrolls sideways under its fixed header, with `TableSpec.HorizontalScrollbar` naming the bar below the body, `TableState.Scroll` reporting both axes, and Shift+wheel moving the columns +- `TableState.RowID` and `TableState.Rows` expose the identity and scope of the rows the last paint drew, so pointers can be handled by row identity instead of index +- Box-drawing and block glyphs now use the font's own underline thickness, so opencode's prompt border no longer thins out with display scale +- `Window.SetSize` and `ContentWindow.SetSize` request a native content size, including under the headless driver, and report `ErrUnsupported` on hosts without it (contributed by @Ezreal-byte) (PR [#172](https://github.com/vivaui/viva/pull/172)) +- macOS traffic lights in a custom titlebar scale through `TrafficLightScale` (contributed by @imjakey) (PR [#254](https://github.com/vivaui/viva/pull/254)) +- `WebViewConfig.Proxy` set to `WebProxyDirect` bypasses the system proxies for that page (contributed by @imjakey) (PR [#253](https://github.com/vivaui/viva/pull/253)) +- `Box.TooltipOn` opens a tooltip on a chosen side, with `TooltipSide` and its four constants exported beside it (contributed by @xiaoyumuxi) (PR [#252](https://github.com/vivaui/viva/pull/252)) +- A menu row draws its current-item tint only when the pointer is not over another control inside the menu, so applications no longer need a paint-time focus workaround +- `ColorSwatch.Flush()` lets a swatch fill the circle inside its border +- macOS keeps the input method's composition across text-input layout updates instead of discarding the pinyin being typed +- The tooltip arrow is one triangle feathered over a device pixel, so it stays clean at 100% and 125% scaling +- `FileIcon` returns Windows' own system icons, so a text file and an unknown file no longer look the same (contributed by @Zer0ON1) (PR [#249](https://github.com/vivaui/viva/pull/249)) +- `components.BeginColumnResize` adds draggable table column widths with minimums and content-fit (contributed by @Zer0ON1) (PR [#247](https://github.com/vivaui/viva/pull/247)) +- `WebViewConfig.Ephemeral` keeps a web view's data in an ephemeral store instead of the persistent one (contributed by @1lck) (PR [#244](https://github.com/vivaui/viva/pull/244)) +- `WebViewConfig.Navigate`, `NewWindow` and `Download` let the application decide before a navigation, popup or download happens, with `WebNavigation` naming the frame (contributed by @1lck) (PR [#243](https://github.com/vivaui/viva/pull/243)) +- A web view's top corners round through `TopCornerRadius`, and the native view owns its cursor (contributed by @imjakey) (PR [#248](https://github.com/vivaui/viva/pull/248)) +- `OpenDirectoryPath` returns one existing directory the user picked, or `ErrCanceled` when they cancel +- `CodeEditorSnapshot.GutterMarkers` paints per-line markers in a lane beside the line numbers and exposes each marker's `ID` as a button the caller handles +- Linux and Windows builds pin `CGO_ENABLED=0`, so a Linux program built on Ubuntu no longer carries the builder's glibc and starts on older distributions +- The scroll-area, tooltip and code-editor component installation templates are regenerated, so the component generator checks pass again + +## 证据在哪 · Where the evidence is + +- 发布门禁在 macOS 上运行 `gofmt`、`go vet ./...`、`go test ./... -count=1`、`-tags vivahead` 的 darwin 与 headless vet,以及 linux/arm64、windows/amd64、windows/arm64 的交叉 vet 与 js/wasm 的 vet +- 单实例修复在 macOS 与一台物理 Windows 11 机器上用两个进程验证了参数交接;Windows 上 `Claim` 加 `Close` 为 23 µs、18 次分配 +- 表格横向滚动、冻结列、虚线轮廓与列宽调整的回归测试带零分配检查(`BenchmarkWideTable`、`BenchmarkColumnResizePaint`、`TestDashedOutlineIsAllocationFreeOnAWarmCanvas`) + +- The release gate runs `gofmt`, `go vet ./...`, `go test ./... -count=1`, the `-tags vivahead` darwin and headless vet, and cross-vet for linux/arm64, windows/amd64 and windows/arm64 plus the js/wasm vet on macOS +- The single-instance fix was checked with two processes on macOS and on a physical Windows 11 machine; `Claim` plus `Close` costs 23 µs and 18 allocations on Windows +- The horizontal table scrolling, frozen columns, dashed outlines and column resize carry zero-allocation regression checks (`BenchmarkWideTable`, `BenchmarkColumnResizePaint`, `TestDashedOutlineIsAllocationFreeOnAWarmCanvas`) + +## 注意 · Caveats + +- 本版使用 patch 版本号,但包含新增 API;没有删除或改变已有导出 API,升级不需要迁移 +- Windows 上,改动前构建的副本用 Unix socket 认领、改动后构建的副本用命名管道,两者互不相认;升级时让旧进程全部退出后再启动新版本即可 +- Linux 与 Windows 的 `viva build` 固定 `CGO_ENABLED=0`,应用自带的 cgo 代码在这两个平台上需要改为纯 Go 或系统调用 + +- This release uses a patch version number but adds APIs; no existing exported API is removed or changed, so no migration is needed +- On Windows a copy built before this change claims at a Unix socket while one built after claims at a named pipe, so they do not meet; exit every old process before starting the new build +- `viva build` pins `CGO_ENABLED=0` for Linux and Windows, so application code that uses cgo on those targets needs pure Go or system calls instead From 4510c7017d5b20c1bec976810a19fd4bde447f7a Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 12:57:05 +0800 Subject: [PATCH 29/86] docs: point at v0.6.3 --- README.md | 2 +- README.zh-CN.md | 2 +- website/content/guides/en/getting-started.md | 2 +- website/content/guides/zh/getting-started.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index aefb4a847..3c79b1eb6 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.1`; name it explicitly (`@v0.6.1`) to pin it. Guides, +The current release is `v0.6.3`; name it explicitly (`@v0.6.3`) 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 diff --git a/README.zh-CN.md b/README.zh-CN.md index 77a137ce4..c3237e9c0 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.1`;要固定版本就写明(`@v0.6.1`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 +当前版本是 `v0.6.3`;要固定版本就写明(`@v0.6.3`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 下面的一切描述的都是这个仓库:它的测量、它自己的程序,以及如何开发框架本身,而不是如何用框架。 diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md index 8255e2e2c..be08cb710 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.1`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.1`. 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.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. 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 a52e04e29..5ab36bfc8 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.1`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.1`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 +`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.3`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.3`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 如果你是在 Viva 仓库里改框架本身、而不是使用它,改用 `replace` 指向检出目录: From ef9f0bdaa13788e0516de50844506d3d83da0710 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 13:12:44 +0800 Subject: [PATCH 30/86] feat(app): report a content window's frame and minimize state Motty hit-tests a detached SFTP window while a file is dragged outside the source window. Window.Frame already documents finding another window by comparing frames, but ContentWindow hid the window it wraps. This exposes the same content rectangle and minimize state, and a test covers the frame, the minimize flag and a closed window. Companion to the Motty change that copies files between servers. --- app/content_window.go | 17 +++++++++++++++++ app/content_window_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/app/content_window.go b/app/content_window.go index e574ba442..217762422 100644 --- a/app/content_window.go +++ b/app/content_window.go @@ -124,6 +124,23 @@ func (content *ContentWindow) Closed() bool { return content == nil || content.window == nil || content.window.Closed() } +// Frame reports where the content area is on screen, as Window.Frame does: a +// drag that ends over another of the application's windows finds it by comparing +// its pointer with their frames. The second result is false once the window is +// closed. +func (content *ContentWindow) Frame() (gfx.Rect, bool) { + if content == nil || content.window == nil { + return gfx.Rect{}, false + } + return content.window.Frame() +} + +// Minimized reports whether the window manager has the window minimized, as +// Window.Minimized does. A minimized window covers no screen point. +func (content *ContentWindow) Minimized() bool { + return content != nil && content.window.Minimized() +} + // Close force-closes the window, as application teardown does. RequestClose is // the ordinary UI action and honors unsaved-content confirmation. func (content *ContentWindow) Close() { diff --git a/app/content_window_test.go b/app/content_window_test.go index 9fba5f3df..b3c516666 100644 --- a/app/content_window_test.go +++ b/app/content_window_test.go @@ -5,6 +5,8 @@ package app import ( "sync" "testing" + + "github.com/vivaui/viva/gfx" ) func TestContentWindowDeliversUpdatesAndHonorsClosePolicy(t *testing.T) { @@ -67,6 +69,41 @@ func TestContentWindowDeliversUpdatesAndHonorsClosePolicy(t *testing.T) { } } +func TestContentWindowReportsFrameAndMinimizeState(t *testing.T) { + host := &fakeHost{} + useHost(t, host) + if err := RunApplication(func(application *Application) error { + origin := gfx.Point{X: 120, Y: 240} + content, err := application.OpenContentWindow(Config{Width: 500, Height: 300, Origin: &origin}, nil) + if err != nil { + return err + } + frame, ok := content.Frame() + if !ok || frame != (gfx.Rect{X: 120, Y: 240, Width: 500, Height: 300}) { + t.Fatalf("frame = %+v, ok = %t", frame, ok) + } + if content.Minimized() { + t.Fatal("a new content window reports minimized") + } + host.windows[0].config.OnMinimize(true) + if !content.Minimized() { + t.Fatal("minimize state did not follow the window") + } + host.windows[0].config.OnMinimize(false) + if content.Minimized() { + t.Fatal("minimize state stayed after restore") + } + content.Close() + host.windows[0].config.OnClosed() + if _, ok := content.Frame(); ok { + t.Fatal("closed content window still reports a frame") + } + return nil + }); err != nil { + t.Fatal(err) + } +} + func TestContentWindowRejectedOpenAndPendingUpdateTeardown(t *testing.T) { host := &fakeHost{reject: "rejected"} useHost(t, host) From ba876bc6c1fc288b71bd490976234d764b8f6d12 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 13:20:44 +0800 Subject: [PATCH 31/86] fix(gfx): draw cell glyphs with the font's own box stroke A cell glyph's stroke came from the face's underline thickness, doubled for a heavy line, the source Ghostty takes its box thickness from. An underline is not the weight of a box drawing line: Cascadia Mono draws its heavy stem at 4.24 times its underline, so opencode's prompt border (U+2503) at 16 px and a 175 percent display was 4 device pixels where the font's own glyph is 6. Consolas sits at 2.08, which is why the earlier fix held there. The text engines now report the ink width of the face's own light and heavy box drawing glyphs (MonoCellMetrics.Rule and HeavyRule): CoreText's glyph bounds, DirectWrite's design glyph metrics, and Pango's ink extents with font fallback off, so only the chosen face's glyph is measured. A cell glyph takes both weights, rounded to the nearest device pixel and never thinner than one; a face without the glyph leaves the reference 0.05 em. Refs: t8y2/motty#833 --- gfx/box_drawing.go | 8 +- gfx/canvas.go | 55 +++++---- gfx/cell_glyphs.go | 35 +++--- gfx/cell_glyphs_test.go | 81 ++++++++++--- gfx/text_engine.go | 16 ++- internal/platform/darwin/native.h | 4 +- internal/platform/darwin/native.m | 22 +++- internal/platform/darwin/text.go | 9 +- internal/platform/darwin/text_engine.go | 2 +- internal/platform/darwin/text_test.go | 24 ++-- internal/platform/linux/text_engine_linux.go | 5 +- internal/platform/linux/text_linux.go | 112 ++++++++++++++---- internal/platform/linux/text_linux_test.go | 30 +++-- .../platform/windows/text_box_windows_test.go | 44 +++++++ .../windows/text_underline_windows_test.go | 37 ------ internal/platform/windows/text_windows.go | 72 ++++++++--- .../platform/windows/textengine_windows.go | 4 +- internal/textmetrics/textmetrics.go | 12 +- text/measure.go | 9 +- tools/cellatlas/draw.go | 5 +- 20 files changed, 397 insertions(+), 189 deletions(-) create mode 100644 internal/platform/windows/text_box_windows_test.go delete mode 100644 internal/platform/windows/text_underline_windows_test.go diff --git a/gfx/box_drawing.go b/gfx/box_drawing.go index b083e5d1f..7589475b2 100644 --- a/gfx/box_drawing.go +++ b/gfx/box_drawing.go @@ -148,7 +148,7 @@ func (g *cellGlyph) boxDrawing(r rune) { // instead of overdrawn. func (g *cellGlyph) drawLines(lines [4]boxStyle) { cellWidth, cellHeight := g.width, g.height - light, heavy := g.rule, g.rule*2 + light, heavy := g.rule, g.heavy hLightTop := (cellHeight - light) / 2 hLightBottom := hLightTop + light hHeavyTop := (cellHeight - heavy) / 2 @@ -273,14 +273,14 @@ func (g *cellGlyph) drawDash(dash boxDash) { length, span := g.width, g.height thick := g.rule if dash.style == boxHeavy { - thick *= 2 + thick = g.heavy } if dash.vertical { length, span = g.height, g.width } gap := g.rule if dash.gapStyle == boxHeavy { - gap *= 2 + gap = g.heavy } if gap < dash.minGap { gap = dash.minGap @@ -368,5 +368,3 @@ func (g *cellGlyph) strokeDiagonal(rising bool) { } func round32(v float64) int32 { return int32(math.Floor(v + 0.5)) } - -func ceil32(v float64) int32 { return int32(math.Ceil(v)) } diff --git a/gfx/canvas.go b/gfx/canvas.go index c85f9afd5..4c5fa290b 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -816,7 +816,7 @@ func (canvas *Canvas) CellSize(size float32) (width, height float32) { // glyph that fills its cell, such as a powerline arrow, ends where the next cell's begins // and no pixel column holds the glyphs of two cells drawn in two colors. func (canvas *Canvas) MonoCellSize(size float32, face MonoFace) (width, height float32) { - width, height, _, _ = canvas.monoCell(size, face) + width, height, _, _, _ = canvas.monoCell(size, face) return width, height } @@ -828,26 +828,27 @@ func (canvas *Canvas) MonoCellSize(size float32, face MonoFace) (width, height f // the face, and for a label of no height: the renderers then place the line by their own // rule. func (canvas *Canvas) MonoBaseline(size float32, face MonoFace, height float32) float32 { - _, cell, baseline, _ := canvas.monoCell(size, face) + _, cell, baseline, _, _ := canvas.monoCell(size, face) if cell <= 0 || baseline <= 0 || height <= 0 { return 0 } return (height-cell)/2 + baseline } -// monoCell is MonoCellSize, the baseline of the cell and the face's underline thickness, -// measured once per face, size, scale and font generation. The baseline is 0 and the -// underline the reference thickness when no engine measured the face. -func (canvas *Canvas) monoCell(size float32, face MonoFace) (width, height, baseline, underline float32) { +// monoCell is MonoCellSize, the baseline of the cell and the thicknesses of the face's own +// light and heavy box drawing strokes, measured once per face, size, scale and font +// generation. The baseline is 0 and the strokes the reference thickness when no engine +// measured the face. +func (canvas *Canvas) monoCell(size float32, face MonoFace) (width, height, baseline, rule, heavy float32) { if size <= 0 { - return 0, 0, 0, 0 + return 0, 0, 0, 0, 0 } if !validMonoFace(face) { face = MonoSystem } generation := canvas.FontGeneration() - if width, height, baseline, underline, ok := canvas.cellSizes.find(size, face, canvas.pixelScale, generation); ok { - return width, height, baseline, underline + if width, height, baseline, rule, heavy, ok := canvas.cellSizes.find(size, face, canvas.pixelScale, generation); ok { + return width, height, baseline, rule, heavy } width, height = size*textmetrics.MonoAdvance, size*textmetrics.MonoLine switch { @@ -858,31 +859,37 @@ func (canvas *Canvas) monoCell(size float32, face MonoFace) (width, height, base case canvas.monoCells != nil: if cell := canvas.monoCells.MonoCell(size, face); cell.Line() > 0 && cell.Advance > 0 { width, height, baseline = cell.Advance, cell.CellHeight(), cell.CellBaseline() - underline = cell.Underline + rule, heavy = cell.Rule, cell.HeavyRule } } - if underline <= 0 { - // No engine measured the face, or its font has no underline: the reference - // thickness stands in, in the font's own units so it follows the size. - underline = size * textmetrics.MonoUnderline + if rule <= 0 { + // No engine measured the face, or its font has no box drawing glyph: the + // reference thickness stands in, in the font's own units so it follows the size. + rule = size * textmetrics.MonoRule } + if heavy <= 0 { + // A face that draws a heavy line reports both; one that lacks the heavy glyph, + // or no engine at all, gets the weight a heavy stroke has against a light one. + heavy = rule * 2 + } + heavy = max(heavy, rule) // A font's own cell is whole already (MonoCellMetrics.CellHeight); the reference cell // and a measurer's answer are rounded up, as they always were. height = float32(int32(height + 0.999)) if canvas.pixelScale > 0 { width = float32(math.Max(math.Floor(float64(width)*float64(canvas.pixelScale)+0.5), 1)) / canvas.pixelScale } - canvas.cellSizes.put(cellSizeMemo{size: size, width: width, height: height, baseline: baseline, underline: underline, face: face, scale: canvas.pixelScale, generation: generation}) - return width, height, baseline, underline + canvas.cellSizes.put(cellSizeMemo{size: size, width: width, height: height, baseline: baseline, rule: rule, heavy: heavy, face: face, scale: canvas.pixelScale, generation: generation}) + return width, height, baseline, rule, heavy } // cellSizeMemo is one remembered MonoCellSize answer. type cellSizeMemo struct { - size, width, height, baseline, underline float32 - face MonoFace - scale float32 // the canvas's pixel scale the width was made whole for - generation uint32 // the font generation it was measured in - filled bool + size, width, height, baseline, rule, heavy float32 + face MonoFace + scale float32 // the canvas's pixel scale the width was made whole for + generation uint32 // the font generation it was measured in + filled bool } // cellSizeMemos remembers the last few MonoCellSize answers: a terminal asks every @@ -894,14 +901,14 @@ type cellSizeMemos struct { next int } -func (memos *cellSizeMemos) find(size float32, face MonoFace, scale float32, generation uint32) (width, height, baseline, underline float32, ok bool) { +func (memos *cellSizeMemos) find(size float32, face MonoFace, scale float32, generation uint32) (width, height, baseline, rule, heavy float32, ok bool) { for i := range memos.entries { memo := &memos.entries[i] if memo.filled && memo.size == size && memo.face == face && memo.scale == scale && memo.generation == generation { - return memo.width, memo.height, memo.baseline, memo.underline, true + return memo.width, memo.height, memo.baseline, memo.rule, memo.heavy, true } } - return 0, 0, 0, 0, false + return 0, 0, 0, 0, 0, false } func (memos *cellSizeMemos) put(memo cellSizeMemo) { diff --git a/gfx/cell_glyphs.go b/gfx/cell_glyphs.go index 0135df606..50b8d5a6b 100644 --- a/gfx/cell_glyphs.go +++ b/gfx/cell_glyphs.go @@ -40,11 +40,12 @@ type CellGlyphShapes struct { Triangles []Triangle } -// cellMetrics is the shape of one cell in whole device pixels: its size, the thickness a rule has -// on it, and how far a shape may reach past it. +// cellMetrics is the shape of one cell in whole device pixels: its size, the thicknesses a +// light and a heavy stroke have on it, and how far a shape may reach past it. type cellMetrics struct { width, height int32 rule int32 + heavy int32 padX, padY int32 } @@ -59,8 +60,8 @@ type cellGlyph struct { } // cellLine is a text seen as cells: the scale back to logical pixels, and what every cell of the -// line has in common — its top edge on the device pixel grid, its height, the rule its font size -// gives it, and the layer and clip its shapes are drawn in. The width is not here: it is the +// line has in common — its top edge on the device pixel grid, its height, the strokes its face +// draws, and the layer and clip its shapes are drawn in. The width is not here: it is the // distance to the next cell's snapped edge, so it belongs to the column. type cellLine struct { text Text @@ -68,16 +69,16 @@ type cellLine struct { top float32 // the line's top edge, logical pixels, on the device pixel grid height int32 // device pixels padY int32 - // rule is one rule's thickness, in device pixels. + // rule and heavy are the thicknesses, in device pixels, of a light and a heavy stroke. // - // It is the face's underline thickness (MonoCellMetrics.Underline) at the line's scale, - // rounded up to the whole device pixel a stroke covers: the weight the font itself draws - // an underline with, so a box drawing or block character drawn as geometry weighs what - // the font's own glyphs around it weigh, as in Ghostty (src/font/Metrics.zig). Rounding - // down would make a stroke thinner, relative to the glyphs, at every scale that leaves - // it a fraction of a pixel; the reference thickness stands in when no engine measured - // the face. - rule int32 + // They are the strokes the face draws its own box drawing lines with + // (MonoCellMetrics.Rule and HeavyRule) at the line's scale, rounded to the nearest whole + // device pixel and never thinner than one: a box drawing or block character drawn as + // geometry then weighs what the font's own glyph weighs, where an underline thickness or + // a share of the font size is only a guess at that weight. The reference thicknesses + // stand in when no engine measured the face. + rule int32 + heavy int32 } // rect fills the rectangle between two points of the cell, both in device pixels from its corner, @@ -234,7 +235,7 @@ func (l cellLine) cellAt(column, cells int32) (Point, cellMetrics) { to := round32((left + float64(column+cells)*float64(l.text.CellWidth)) * l.scale) width := max(to-from, 1) return Point{X: float32(float64(from) / l.scale), Y: l.top}, - cellMetrics{width: width, height: l.height, rule: l.rule, padX: width / 4, padY: l.padY} + cellMetrics{width: width, height: l.height, rule: l.rule, heavy: l.heavy, padX: width / 4, padY: l.padY} } // place appends shapes to dst at the cell's corner, scaled back to logical pixels, in the run's @@ -284,11 +285,13 @@ func (canvas *Canvas) cellLine(text Text) cellLine { scale := canvas.deviceScale() top := round32(float64(text.Bounds.Y) * scale) height := max(round32(float64(text.Bounds.Y+text.Bounds.Height)*scale)-top, 1) - _, _, _, underline := canvas.monoCell(text.Style.Size, text.Style.MonoFace) + _, _, _, rule, heavy := canvas.monoCell(text.Style.Size, text.Style.MonoFace) + light := max(round32(float64(rule)*scale), 1) return cellLine{ text: text, scale: scale, top: float32(float64(top) / scale), height: height, padY: height / 4, - rule: max(ceil32(float64(underline)*scale), 1), + rule: light, + heavy: max(round32(float64(heavy)*scale), light), } } diff --git a/gfx/cell_glyphs_test.go b/gfx/cell_glyphs_test.go index 7ea83952c..ce6fe6c8e 100644 --- a/gfx/cell_glyphs_test.go +++ b/gfx/cell_glyphs_test.go @@ -269,37 +269,40 @@ func FuzzReplaceCellGlyphs(f *testing.F) { }) } -// A cell glyph's rule is the face's underline thickness (MonoCellMetrics.Underline) at the -// line's scale, rounded up to whole device pixels, and a heavy stroke is two rules wide: a -// box drawing character drawn as geometry then weighs what the font's own glyphs weigh, and -// a fractional device pixel makes the stroke no thinner than the whole one it rounds up to. -func TestCellGlyphRuleFollowsTheFacesUnderline(t *testing.T) { +// A cell glyph's strokes are the face's own (MonoCellMetrics.Rule and HeavyRule) at the +// line's scale, each rounded to the nearest device pixel and never thinner than one: a box +// drawing character drawn as geometry then weighs what the font's own glyph weighs, light +// or heavy, and a face whose heavy line is not twice its light one keeps both weights. +func TestCellGlyphRulesFollowTheFacesOwnStrokes(t *testing.T) { for _, test := range []struct { name string - underline float32 + rule float32 // logical pixels, as the engine reports them + heavy float32 scale float32 - light float32 // device pixels + wantRule float32 // device pixels + wantHeavy float32 }{ - {"thinner than a device pixel at 1x", 0.57, 1, 1}, - {"thinner than a device pixel at 2x", 0.57, 2, 2}, - {"thicker than a device pixel", 1.2, 2, 3}, - {"a fraction at 3x", 0.4, 3, 2}, + {"thinner than a device pixel at 1x", 0.4, 0.8, 1, 1, 1}, + {"a fraction rounded down", 0.65, 1.1, 2, 1, 2}, + {"a fraction rounded up", 1.2, 2.4, 2, 2, 5}, + // The face from the issue: a 16 px Cascadia Mono cell at 175 percent, whose heavy + // stem is 4.24 times its light one and not twice its underline. + {"a font whose heavy line is over twice its light one", 1.656, 3.312, 1.75, 3, 6}, } { for _, glyph := range []struct { value string - rules float32 - }{{"│", 1}, {"┃", 2}} { + want float32 + }{{"│", test.wantRule}, {"┃", test.wantHeavy}} { var canvas Canvas canvas.SetPixelScale(test.scale) canvas.SetTextEngine(&monoCellEngine{MonoCellMetrics: MonoCellMetrics{ - Advance: 0.6, Ascent: 0.8, Descent: 0.2, Underline: test.underline, + Advance: 0.6, Ascent: 0.8, Descent: 0.2, Rule: test.rule, HeavyRule: test.heavy, }}) cellWidth, cellHeight := float32(10), float32(20) canvas.LabelRuns(glyph.value, Rect{Width: cellWidth, Height: cellHeight}, TextStyle{Size: 10}, cellWidth, []TextRun{{Column: 0, Bytes: int32(len(glyph.value)), Cells: 1, Color: Color{Red: 1, Alpha: 1}}}) texts := canvas.Texts() shapes := canvas.CellGlyphGeometry(CellGlyphShapes{}, texts[len(texts)-1]) - want := test.light * glyph.rules var strokes int for _, shape := range shapes.Rectangles { bounds := shape.Bounds @@ -307,9 +310,51 @@ func TestCellGlyphRuleFollowsTheFacesUnderline(t *testing.T) { continue // not a vertical stroke of the glyph } strokes++ - if got := bounds.Width * test.scale; math.Abs(float64(got-want)) > 1e-3 { - t.Errorf("%s at %g x %g: a vertical stroke is %g device pixels, want %g", - test.name, test.scale, test.underline, got, want) + if got := bounds.Width * test.scale; math.Abs(float64(got-glyph.want)) > 1e-3 { + t.Errorf("%s, %s at %gx: a vertical stroke is %g device pixels, want %g", + test.name, glyph.value, test.scale, got, glyph.want) + } + } + if strokes == 0 { + t.Errorf("%s: %s draws no vertical stroke", test.name, glyph.value) + } + } + } +} + +// A face that does not report a stroke falls back to the reference weight, and one that +// reports a light line but no heavy one draws the heavy line twice as wide. +func TestCellGlyphRulesFallBackToTheReferenceWeight(t *testing.T) { + for _, test := range []struct { + name string + metrics MonoCellMetrics + wantRule float32 + wantHeavy float32 + }{ + {"no measured strokes", MonoCellMetrics{Advance: 0.6, Ascent: 0.8, Descent: 0.2}, 1, 2}, + {"a light line only", MonoCellMetrics{Advance: 0.6, Ascent: 0.8, Descent: 0.2, Rule: 1}, 2, 4}, + } { + for _, glyph := range []struct { + value string + want float32 + }{{"│", test.wantRule}, {"┃", test.wantHeavy}} { + var canvas Canvas + canvas.SetPixelScale(2) + canvas.SetTextEngine(&monoCellEngine{MonoCellMetrics: test.metrics}) + cellWidth, cellHeight := float32(10), float32(20) + canvas.LabelRuns(glyph.value, Rect{Width: cellWidth, Height: cellHeight}, TextStyle{Size: 10}, cellWidth, + []TextRun{{Column: 0, Bytes: int32(len(glyph.value)), Cells: 1, Color: Color{Red: 1, Alpha: 1}}}) + texts := canvas.Texts() + shapes := canvas.CellGlyphGeometry(CellGlyphShapes{}, texts[len(texts)-1]) + var strokes int + for _, shape := range shapes.Rectangles { + bounds := shape.Bounds + if bounds.Height < cellHeight/2 || bounds.Width >= cellWidth/2 { + continue + } + strokes++ + if got := bounds.Width * 2; math.Abs(float64(got-glyph.want)) > 1e-3 { + t.Errorf("%s, %s: a vertical stroke is %g device pixels, want %g", test.name, glyph.value, got, glyph.want) } } if strokes == 0 { diff --git a/gfx/text_engine.go b/gfx/text_engine.go index 307bda64b..194eac830 100644 --- a/gfx/text_engine.go +++ b/gfx/text_engine.go @@ -84,12 +84,16 @@ type MonoCellMetrics struct { Ascent float32 // baseline to the top of the line box Descent float32 // baseline to the bottom of the line box LineGap float32 // the space the font asks between two line boxes; zero where the engine derives Descent from the font's line height (Windows and Linux), which folds the gap into it - // Underline is the thickness of the stroke the face draws an underline with, in - // logical pixels: the weight a cell glyph's rule takes, so that a box drawing or - // block character drawn as geometry weighs what the font's own glyphs weigh - // (Ghostty's Metrics.box_thickness). Zero when the engine does not report it; the - // canvas then uses the reference thickness (internal/textmetrics.MonoUnderline). - Underline float32 + // Rule and HeavyRule are the thicknesses, in logical pixels, of the strokes the + // face draws with a light (U+2502) and a heavy (U+2503) box drawing line: the + // weights a cell glyph drawn as geometry takes, so that it weighs what the font's + // own glyph would weigh. They are the glyphs' ink widths, not a share of the font + // size and not the underline thickness, which a face may draw at a different weight + // than its box lines. Zero when the engine does not report it, or its face lacks + // the glyph; the canvas then uses the reference thickness + // (internal/textmetrics.MonoRule). + Rule float32 + HeavyRule float32 } // Line is the height of the font's line box: its ascent, its descent and the gap it asks diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 27189838a..6beed09b9 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -557,8 +557,8 @@ int viva_text_line_rasterize( // viva_measure_mono reports the system fixed-pitch font's cell at a size: the advance of // one character, the ascent, descent and leading of its line box, and the thickness of -// the stroke the font underlines with. -int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading, double *underline); +// the strokes it draws its light and heavy box drawing lines with. +int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading, double *rule, double *heavy); // viva_register_mono_family teaches what a mono_face number (2 and up) stands for: the // installed family it draws in first (empty for a stack over a built-in face), whether // that built-in face is the classic one, and the families that draw the characters the diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index faa667ffd..592de6340 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -7802,8 +7802,8 @@ int viva_measure_text( } } -int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading, double *underline) { - if (advance == NULL || ascent == NULL || descent == NULL || leading == NULL || underline == NULL || font_size <= 0) { +int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading, double *rule, double *heavy) { + if (advance == NULL || ascent == NULL || descent == NULL || leading == NULL || rule == NULL || heavy == NULL || font_size <= 0) { return 1; } @autoreleasepool { @@ -7825,7 +7825,23 @@ int viva_measure_mono(double font_size, int mono_face, double *advance, double * *ascent = CTFontGetAscent(font); *descent = CTFontGetDescent(font); *leading = CTFontGetLeading(font); - *underline = CTFontGetUnderlineThickness(font); + // The weight of the face's own box drawing lines: the ink width of a light and a + // heavy stem, which the face may draw at a different weight than its underline. + // The lookup answers false when either is missing, and still fills the other, so + // each glyph is checked on its own. + *rule = 0; + *heavy = 0; + UniChar boxCharacters[2] = {0x2502, 0x2503}; /* │ ┃ */ + CGGlyph boxGlyphs[2] = {0, 0}; + CTFontGetGlyphsForCharacters(font, boxCharacters, boxGlyphs, 2); + CGRect bounds[2] = {CGRectZero, CGRectZero}; + CTFontGetBoundingRectsForGlyphs(font, kCTFontOrientationHorizontal, boxGlyphs, bounds, 2); + if (boxGlyphs[0] != 0) { + *rule = bounds[0].size.width; + } + if (boxGlyphs[1] != 0) { + *heavy = bounds[1].size.width; + } CFRelease(font); return *advance > 0 ? 0 : 4; } diff --git a/internal/platform/darwin/text.go b/internal/platform/darwin/text.go index 601b94fdd..da642d066 100644 --- a/internal/platform/darwin/text.go +++ b/internal/platform/darwin/text.go @@ -41,14 +41,14 @@ func MeasureText(value string, fontSize, weight float32) (text.Metrics, error) { // measureMonoMetrics reports the system fixed-pitch font's character cell at a size: the // advance of one character, the line box around its baseline, and the thickness of the -// stroke the font underlines with. +// strokes the face draws its light and heavy box drawing lines with. func measureMonoMetrics(fontSize float32, face gfx.MonoFace) (text.Metrics, error) { if fontSize <= 0 { return text.Metrics{}, fmt.Errorf("darwin: font size must be positive") } syncMonoFamilies() - var advance, ascent, descent, leading, underline C.double - if status := C.viva_measure_mono(C.double(fontSize), C.int(face), &advance, &ascent, &descent, &leading, &underline); status != 0 { + var advance, ascent, descent, leading, rule, heavy C.double + if status := C.viva_measure_mono(C.double(fontSize), C.int(face), &advance, &ascent, &descent, &leading, &rule, &heavy); status != 0 { return text.Metrics{}, fmt.Errorf("darwin: CoreText fixed-pitch measurement failed with status %d", status) } return text.Metrics{ @@ -57,7 +57,8 @@ func measureMonoMetrics(fontSize float32, face gfx.MonoFace) (text.Metrics, erro Ascent: float32(ascent), Descent: float32(descent), Leading: float32(leading), - Underline: float32(underline), + Rule: float32(rule), + HeavyRule: float32(heavy), }, nil } diff --git a/internal/platform/darwin/text_engine.go b/internal/platform/darwin/text_engine.go index 17cc20628..c18a7294a 100644 --- a/internal/platform/darwin/text_engine.go +++ b/internal/platform/darwin/text_engine.go @@ -112,7 +112,7 @@ func (engine *TextEngine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCell if err != nil { return gfx.MonoCellMetrics{} } - return gfx.MonoCellMetrics{Advance: metrics.Width, Ascent: metrics.Ascent, Descent: metrics.Descent, LineGap: metrics.Leading, Underline: metrics.Underline} + return gfx.MonoCellMetrics{Advance: metrics.Width, Ascent: metrics.Ascent, Descent: metrics.Descent, LineGap: metrics.Leading, Rule: metrics.Rule, HeavyRule: metrics.HeavyRule} } // FontGeneration implements gfx.FontFamilyAware. diff --git a/internal/platform/darwin/text_test.go b/internal/platform/darwin/text_test.go index 17541065b..d21c662f1 100644 --- a/internal/platform/darwin/text_test.go +++ b/internal/platform/darwin/text_test.go @@ -600,21 +600,29 @@ func TestACanvasOnTheEngineSizesTheTerminalCellByTheFont(t *testing.T) { } } -// The engine reports the thickness the font underlines with, in logical pixels at the size -// asked: that is the rule a cell glyph is drawn with, so box drawing geometry is as thick as -// the font's own glyphs. -func TestTheEngineReportsTheFontsUnderline(t *testing.T) { +// The engine reports the thicknesses the face draws its own box drawing lines with, in +// logical pixels at the size asked: those are the strokes a cell glyph is drawn with, so box +// drawing geometry weighs what the font's own glyphs weigh. CoreText measures the ink of the +// light and heavy stems; a face that lacks one answers 0 for it. +func TestTheEngineReportsTheFontsBoxDrawingStrokes(t *testing.T) { engine := SharedTextEngine() for _, face := range []gfx.MonoFace{gfx.MonoSystem, gfx.MonoFamily("Courier New")} { cell := engine.MonoCell(13, face) if cell.Advance <= 0 { t.Fatalf("face %v: no cell", face) } - if cell.Underline <= 0 || cell.Underline >= cell.Advance { - t.Errorf("face %v: underline %v of a cell %v wide, want a positive stroke narrower than the cell", face, cell.Underline, cell.Advance) + if cell.Rule <= 0 || cell.Rule >= cell.Advance { + t.Errorf("face %v: light line %v of a cell %v wide, want a positive stroke narrower than the cell", face, cell.Rule, cell.Advance) } - if at26 := engine.MonoCell(26, face); at26.Underline <= cell.Underline { - t.Errorf("face %v: underline %v at 26, %v at 13, want it to follow the size", face, at26.Underline, cell.Underline) + if cell.HeavyRule > 0 && cell.HeavyRule < cell.Rule { + t.Errorf("face %v: heavy line %v is thinner than the light one %v", face, cell.HeavyRule, cell.Rule) + } + at26 := engine.MonoCell(26, face) + if at26.Rule <= cell.Rule { + t.Errorf("face %v: light line %v at 26, %v at 13, want it to follow the size", face, at26.Rule, cell.Rule) + } + if cell.HeavyRule > 0 && at26.HeavyRule <= cell.HeavyRule { + t.Errorf("face %v: heavy line %v at 26, %v at 13, want it to follow the size", face, at26.HeavyRule, cell.HeavyRule) } } } diff --git a/internal/platform/linux/text_engine_linux.go b/internal/platform/linux/text_engine_linux.go index d0a765258..aa33822a6 100644 --- a/internal/platform/linux/text_engine_linux.go +++ b/internal/platform/linux/text_engine_linux.go @@ -138,7 +138,7 @@ func (engine *textEngine) SetFontFamily(family string) { func (engine *textEngine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCellMetrics { engine.mu.Lock() defer engine.mu.Unlock() - metrics, err := engine.services.configureLayout("M", monoFamily(face), size, 0, false) + metrics, err := engine.services.configureMonoLayout(monoFamily(face), size) if err != nil { return gfx.MonoCellMetrics{} } @@ -147,7 +147,8 @@ func (engine *textEngine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCell Ascent: metrics.Ascent, Descent: metrics.Descent, LineGap: max(metrics.Height-metrics.Ascent-metrics.Descent, 0), - Underline: metrics.Underline, + Rule: metrics.Rule, + HeavyRule: metrics.HeavyRule, } } diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go index 7eee8b1ca..6be23c2bd 100644 --- a/internal/platform/linux/text_linux.go +++ b/internal/platform/linux/text_linux.go @@ -40,9 +40,20 @@ type textServices struct { layoutSetSingleParagraph func(uintptr, int32) layoutGetExtents func(uintptr, *pangoRectangle, *pangoRectangle) layoutGetBaseline func(uintptr) int32 - layoutGetCursorPos func(uintptr, int32, *pangoRectangle, *pangoRectangle) - layoutIndexToPos func(uintptr, int32, *pangoRectangle) - fontFromString func(*byte) uintptr + layoutSetAttributes func(uintptr, uintptr) + // layoutGetUnknownGlyphs is pango_layout_get_unknown_glyphs_count; nil on a Pango old + // enough not to have it. + layoutGetUnknownGlyphs func(uintptr) int32 + layoutGetCursorPos func(uintptr, int32, *pangoRectangle, *pangoRectangle) + layoutIndexToPos func(uintptr, int32, *pangoRectangle) + fontFromString func(*byte) uintptr + // noFallback is the attribute list that turns Pango's font fallback off, for measuring + // a box drawing stroke in the face's own font; 0 when this Pango cannot make it. + noFallback uintptr + attrListNew func() uintptr + attrListUnref func(uintptr) + attrListInsert func(uintptr, uintptr) + attrFallbackNew func(int32) uintptr // contextSetRoundGlyphs is pango_context_set_round_glyph_positions (Pango 1.44); nil // before it. contextSetRoundGlyphs func(uintptr, int32) @@ -53,9 +64,6 @@ type textServices struct { fontSetWeight func(uintptr, int32) fontSetStyle func(uintptr, int32) objectUnref func(uintptr) - contextGetMetrics func(uintptr, uintptr, uintptr) uintptr - fontMetricsUnderline func(uintptr) int32 - fontMetricsUnref func(uintptr) imageSurfaceCreateForData func(*byte, int32, int32, int32, int32) uintptr surfaceStatus func(uintptr) int32 @@ -127,6 +135,15 @@ func loadTextAPI() (*textServices, error) { purego.RegisterLibFunc(&services.layoutSetSingleParagraph, services.pango, "pango_layout_set_single_paragraph_mode") purego.RegisterLibFunc(&services.layoutGetExtents, services.pango, "pango_layout_get_extents") purego.RegisterLibFunc(&services.layoutGetBaseline, services.pango, "pango_layout_get_baseline") + purego.RegisterLibFunc(&services.layoutSetAttributes, services.pango, "pango_layout_set_attributes") + if symbol, err := purego.Dlsym(services.pango, "pango_layout_get_unknown_glyphs_count"); err == nil && symbol != 0 { + purego.RegisterLibFunc(&services.layoutGetUnknownGlyphs, services.pango, "pango_layout_get_unknown_glyphs_count") + } + purego.RegisterLibFunc(&services.attrListNew, services.pango, "pango_attr_list_new") + purego.RegisterLibFunc(&services.attrListUnref, services.pango, "pango_attr_list_unref") + purego.RegisterLibFunc(&services.attrListInsert, services.pango, "pango_attr_list_insert") + purego.RegisterLibFunc(&services.attrFallbackNew, services.pango, "pango_attr_fallback_new") + services.noFallback = services.fallbackOff() if symbol, err := purego.Dlsym(services.pango, "pango_context_set_round_glyph_positions"); err == nil && symbol != 0 { purego.RegisterLibFunc(&services.contextSetRoundGlyphs, services.pango, "pango_context_set_round_glyph_positions") } @@ -140,9 +157,6 @@ func loadTextAPI() (*textServices, error) { purego.RegisterLibFunc(&services.fontSetWeight, services.pango, "pango_font_description_set_weight") purego.RegisterLibFunc(&services.fontSetStyle, services.pango, "pango_font_description_set_style") purego.RegisterLibFunc(&services.objectUnref, services.gobject, "g_object_unref") - purego.RegisterLibFunc(&services.contextGetMetrics, services.pango, "pango_context_get_metrics") - purego.RegisterLibFunc(&services.fontMetricsUnderline, services.pango, "pango_font_metrics_get_underline_thickness") - purego.RegisterLibFunc(&services.fontMetricsUnref, services.pango, "pango_font_metrics_unref") purego.RegisterLibFunc(&services.imageSurfaceCreateForData, services.cairo, "cairo_image_surface_create_for_data") purego.RegisterLibFunc(&services.surfaceStatus, services.cairo, "cairo_surface_status") @@ -238,6 +252,10 @@ func (services *textServices) close() { } func (services *textServices) closeLibraries() { + if services.noFallback != 0 && services.attrListUnref != nil { + services.attrListUnref(services.noFallback) + services.noFallback = 0 + } for _, library := range []*uintptr{&services.gobject, &services.cairo, &services.pangoCairo, &services.pango} { if *library != 0 { purego.Dlclose(*library) @@ -246,6 +264,22 @@ func (services *textServices) closeLibraries() { } } +// fallbackOff is the attribute list that turns Pango's font fallback off, so a glyph laid +// out under it comes from the description's own family; 0 when Pango cannot build it. +func (services *textServices) fallbackOff() uintptr { + list := services.attrListNew() + if list == 0 { + return 0 + } + attribute := services.attrFallbackNew(0) // false: no fallback + if attribute == 0 { + services.attrListUnref(list) + return 0 + } + services.attrListInsert(list, attribute) // the list takes the attribute + return list +} + func cString(value string) []byte { result := make([]byte, len(value)+1) copy(result, value) @@ -316,38 +350,70 @@ func (services *textServices) configureLayout(value, family string, size, weight return text.Metrics{}, err } defer services.fontFree(description) + logical, _, baseline := services.layoutValue(description, value) + metrics := text.Metrics{ + Width: float32(logical.Width) / pangoScale, + Height: float32(logical.Height) / pangoScale, + Ascent: float32(baseline) / pangoScale, + Descent: float32(logical.Height-baseline) / pangoScale, + } + return metrics, nil +} + +// layoutValue lays value out in the layout under description and reports its logical +// extents, the ink extents of its glyphs, and its baseline. +func (services *textServices) layoutValue(description uintptr, value string) (logical, ink pangoRectangle, baseline int32) { valueBytes := cString(value) services.layoutSetWidth(services.layout, -1) services.layoutSetFont(services.layout, description) services.layoutSetText(services.layout, &valueBytes[0], int32(len(value))) - var logical pangoRectangle - services.layoutGetExtents(services.layout, nil, &logical) - baseline := services.layoutGetBaseline(services.layout) + services.layoutGetExtents(services.layout, &ink, &logical) + baseline = services.layoutGetBaseline(services.layout) runtime.KeepAlive(valueBytes) + return logical, ink, baseline +} + +// configureMonoLayout is configureLayout for a fixed-pitch face: the cell of "M" and the +// thicknesses of the strokes the face draws a light and a heavy box drawing line with, in +// logical pixels. The stroke is the ink width of the stem glyph in the face's own family. +func (services *textServices) configureMonoLayout(family string, size float32) (text.Metrics, error) { + if !validFontSize(size) { + return text.Metrics{}, fmt.Errorf("linux: invalid font size") + } + description, err := services.description(family, size, 0, false) + if err != nil { + return text.Metrics{}, err + } + defer services.fontFree(description) + logical, _, baseline := services.layoutValue(description, "M") metrics := text.Metrics{ Width: float32(logical.Width) / pangoScale, Height: float32(logical.Height) / pangoScale, Ascent: float32(baseline) / pangoScale, Descent: float32(logical.Height-baseline) / pangoScale, - // The stroke the face underlines with, at the description's absolute size: - // the weight a fixed-pitch cell glyph's rule takes. - Underline: services.underline(description), } + metrics.Rule = services.boxRule(description, "│") + metrics.HeavyRule = services.boxRule(description, "┃") return metrics, nil } -// underline is the thickness of the stroke description's face underlines with, in logical -// pixels, or 0 when Pango cannot report it. -func (services *textServices) underline(description uintptr) float32 { - if services.contextGetMetrics == nil || services.fontMetricsUnderline == nil || services.fontMetricsUnref == nil { +// boxRule is the thickness, in logical pixels, of the stroke the face draws value with: the +// ink width of the glyph in the description's own family, or 0 when that family lacks the +// glyph. The layout is measured with fallback off, so a family the face does not have is +// never taken as its weight, and a glyph the face lacks is a missing-glyph box rather than +// another family's stem. +func (services *textServices) boxRule(description uintptr, value string) float32 { + if services.noFallback == 0 || services.layoutGetUnknownGlyphs == nil { return 0 } - metrics := services.contextGetMetrics(services.context, description, 0) - if metrics == 0 { + services.layoutSetAttributes(services.layout, services.noFallback) + _, ink, _ := services.layoutValue(description, value) + unknown := services.layoutGetUnknownGlyphs(services.layout) + services.layoutSetAttributes(services.layout, 0) + if unknown > 0 { return 0 } - defer services.fontMetricsUnref(metrics) - return float32(services.fontMetricsUnderline(metrics)) / pangoScale + return float32(ink.Width) / pangoScale } func (services *textServices) measure(value string, size, weight float32) (text.Metrics, error) { diff --git a/internal/platform/linux/text_linux_test.go b/internal/platform/linux/text_linux_test.go index d2c361c47..b3ceb5293 100644 --- a/internal/platform/linux/text_linux_test.go +++ b/internal/platform/linux/text_linux_test.go @@ -312,23 +312,31 @@ func TestMeasureTextIsWiderAtAHeavierWeight(t *testing.T) { } } -// The engine reports the thickness the font underlines with, in logical pixels at the size -// asked: that is the rule a cell glyph is drawn with, so box drawing geometry weighs what -// the font's own glyphs weigh. Pango reads it from the face; a face that files no underline -// thickness answers 0, and the canvas then uses the reference thickness. -func TestTheEngineReportsTheFontsUnderline(t *testing.T) { +// The engine reports the thicknesses the face draws its own box drawing lines with, in +// logical pixels at the size asked: those are the strokes a cell glyph is drawn with, so box +// drawing geometry weighs what the font's own glyphs weigh. Pango measures the ink of the +// light and heavy stems; a face that has no box drawing glyph answers 0 for it, and the +// canvas then uses the reference thickness. +func TestTheEngineReportsTheFontsBoxDrawingStrokes(t *testing.T) { engine := sharedTextEngine() cell := engine.MonoCell(13, gfx.MonoSystem) if cell.Advance <= 0 { t.Fatal("no fixed-pitch cell on this runner") } - if cell.Underline == 0 { - t.Skip("the runner's fixed-pitch face reports no underline thickness") + if cell.Rule == 0 { + t.Skip("the runner's fixed-pitch face has no light box drawing glyph") } - if cell.Underline < 0 || cell.Underline >= cell.Advance { - t.Fatalf("underline %v of a cell %v wide, want a positive stroke narrower than the cell", cell.Underline, cell.Advance) + if cell.Rule < 0 || cell.Rule >= cell.Advance { + t.Fatalf("light line %v of a cell %v wide, want a positive stroke narrower than the cell", cell.Rule, cell.Advance) } - if at26 := engine.MonoCell(26, gfx.MonoSystem); at26.Underline <= cell.Underline { - t.Errorf("underline %v at size 26, %v at size 13, want it to follow the size", at26.Underline, cell.Underline) + if cell.HeavyRule > 0 && cell.HeavyRule < cell.Rule { + t.Fatalf("heavy line %v is thinner than the light one %v", cell.HeavyRule, cell.Rule) + } + at26 := engine.MonoCell(26, gfx.MonoSystem) + if at26.Rule <= cell.Rule { + t.Errorf("light line %v at size 26, %v at size 13, want it to follow the size", at26.Rule, cell.Rule) + } + if cell.HeavyRule > 0 && at26.HeavyRule <= cell.HeavyRule { + t.Errorf("heavy line %v at size 26, %v at size 13, want it to follow the size", at26.HeavyRule, cell.HeavyRule) } } diff --git a/internal/platform/windows/text_box_windows_test.go b/internal/platform/windows/text_box_windows_test.go new file mode 100644 index 000000000..eb5a9ab79 --- /dev/null +++ b/internal/platform/windows/text_box_windows_test.go @@ -0,0 +1,44 @@ +package windows + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A cell carries the thicknesses the face draws its own box drawing lines with +// (gfx.MonoCellMetrics.Rule and HeavyRule), so a border drawn as geometry weighs what the +// font's own glyphs weigh. DirectWrite reports each glyph's bearings in design units; the +// engine scales the ink between them to the logical size asked. +func TestTheEngineReportsTheFontsBoxDrawingStrokes(t *testing.T) { + engine, err := theTextEngine() + if err != nil { + t.Skipf("no DirectWrite text engine: %v", err) + } + reported := 0 + for _, name := range []string{"Consolas", "Cascadia Mono", "Courier New"} { + face := gfx.MonoFamily(name) + cell := engine.MonoCell(13, face) + if cell.Advance <= 0 { + continue // the runner does not have this family + } + if cell.Rule <= 0 || cell.Rule >= cell.Advance { + t.Errorf("%s: light line %v of a cell %v wide, want a positive stroke narrower than the cell", name, cell.Rule, cell.Advance) + continue + } + if cell.HeavyRule > 0 && cell.HeavyRule < cell.Rule { + t.Errorf("%s: heavy line %v is thinner than the light one %v", name, cell.HeavyRule, cell.Rule) + } + reported++ + at26 := engine.MonoCell(26, face) + if at26.Rule <= cell.Rule { + t.Errorf("%s: light line %v at size 26, %v at size 13, want it to follow the size", name, at26.Rule, cell.Rule) + } + if cell.HeavyRule > 0 && at26.HeavyRule <= cell.HeavyRule { + t.Errorf("%s: heavy line %v at size 26, %v at size 13, want it to follow the size", name, at26.HeavyRule, cell.HeavyRule) + } + } + if reported == 0 { + t.Fatal("no installed fixed-pitch face reported its box drawing strokes") + } +} diff --git a/internal/platform/windows/text_underline_windows_test.go b/internal/platform/windows/text_underline_windows_test.go deleted file mode 100644 index 12fbecd66..000000000 --- a/internal/platform/windows/text_underline_windows_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package windows - -import ( - "testing" - - "github.com/vivaui/viva/gfx" -) - -// The cell of a fixed-pitch face carries the thickness the font underlines with: the rule -// a cell glyph draws with (gfx.MonoCellMetrics.Underline), so a box drawing border drawn -// as geometry weighs what the font's own glyphs weigh. DirectWrite reports the thickness -// in design units; the engine scales it to the logical size asked. -func TestTheEngineReportsTheFontsUnderline(t *testing.T) { - engine, err := theTextEngine() - if err != nil { - t.Skipf("no DirectWrite text engine: %v", err) - } - reported := 0 - for _, name := range []string{"Consolas", "Cascadia Mono", "Courier New"} { - face := gfx.MonoFamily(name) - cell := engine.MonoCell(13, face) - if cell.Advance <= 0 { - continue // the runner does not have this family - } - if cell.Underline <= 0 || cell.Underline >= cell.Advance { - t.Errorf("%s: underline %v of a cell %v wide, want a positive stroke narrower than the cell", name, cell.Underline, cell.Advance) - continue - } - reported++ - if at26 := engine.MonoCell(26, face); at26.Underline <= cell.Underline { - t.Errorf("%s: underline %v at size 26, %v at size 13, want it to follow the size", name, at26.Underline, cell.Underline) - } - } - if reported == 0 { - t.Fatal("no installed fixed-pitch face reported its underline thickness") - } -} diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index a25219a7e..cf931fe63 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -473,14 +473,17 @@ func (services *textServices) measureIn(typeface, value string, size, weight flo return text.Metrics{Width: metrics.WidthTrailing, Height: metrics.Height, Ascent: line.Baseline, Descent: line.Height - line.Baseline}, nil } -// Method slots of IDWriteFactory, IDWriteFontCollection, IDWriteFontFamily and -// IDWriteFont (checked against dwrite.h). +// Method slots of IDWriteFactory, IDWriteFontCollection, IDWriteFontFamily, IDWriteFont +// and IDWriteFontFace (checked against dwrite.h). const ( writeFactoryGetSystemFontCollection = 3 writeCollectionGetFontFamily = 4 writeCollectionFindFamilyName = 5 writeFontFamilyGetFirstMatchingFont = 7 writeFontGetMetrics = 11 + writeFontCreateFontFace = 13 + writeFontFaceGetDesignGlyphMetrics = 10 + writeFontFaceGetGlyphIndices = 11 ) // writeFontMetrics is DWRITE_FONT_METRICS: the face's design units per em and the @@ -495,16 +498,28 @@ type writeFontMetrics struct { StrikethroughThickness uint16 } -// underline is the thickness of the stroke typeface's face at weight underlines with, in -// logical pixels, or 0 when DirectWrite cannot report it: the weight a fixed-pitch cell -// glyph's rule takes. -func (services *textServices) underline(typeface string, size, weight float32) float32 { +// writeGlyphMetrics is DWRITE_GLYPH_METRICS: a glyph's advance and the bearings around +// its ink, in design units. +type writeGlyphMetrics struct { + LeftSideBearing int32 + AdvanceWidth uint32 + RightSideBearing int32 + TopSideBearing int32 + AdvanceHeight uint32 + BottomSideBearing int32 + VerticalOriginY int32 +} + +// boxStrokes reports the thicknesses, in logical pixels, of the strokes typeface's face at +// weight draws a light (U+2502) and a heavy (U+2503) box drawing line with: the ink width of +// each glyph, or 0 when DirectWrite cannot report it or the face lacks the glyph. +func (services *textServices) boxStrokes(typeface string, size, weight float32) (light, heavy float32) { if size <= 0 || typeface == "" { - return 0 + return 0, 0 } familyName, err := syscall.UTF16PtrFromString(typeface) if err != nil { - return 0 + return 0, 0 } // The collection every text format is made from: the application's fonts and the // system's, or the system's alone. A registered collection is held by the process @@ -515,7 +530,7 @@ func (services *textServices) underline(typeface string, size, weight float32) f customFonts.RUnlock() status := comCall(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&collection)), 0) if err = hresult(status); err != nil || collection == 0 { - return 0 + return 0, 0 } owned = true } else { @@ -526,11 +541,11 @@ func (services *textServices) underline(typeface string, size, weight float32) f } var index, exists uint32 if err := hresult(comCall(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(familyName)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil || exists == 0 { - return 0 + return 0, 0 } var family, font uintptr if err := hresult(comCall(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&family)))); err != nil { - return 0 + return 0, 0 } defer release(&family) const ( @@ -538,12 +553,37 @@ func (services *textServices) underline(typeface string, size, weight float32) f styleNormal = 0 ) if err := hresult(comCall(family, writeFontFamilyGetFirstMatchingFont, uintptr(nativeFontWeight(weight)), stretchNormal, styleNormal, uintptr(unsafe.Pointer(&font)))); err != nil { - return 0 + return 0, 0 } defer release(&font) - var metrics writeFontMetrics - if err := hresult(comCall(font, writeFontGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil || metrics.DesignUnitsPerEm == 0 { - return 0 + var fontMetrics writeFontMetrics + if err := hresult(comCall(font, writeFontGetMetrics, uintptr(unsafe.Pointer(&fontMetrics)))); err != nil || fontMetrics.DesignUnitsPerEm == 0 { + return 0, 0 + } + var face uintptr + if err := hresult(comCall(font, writeFontCreateFontFace, uintptr(unsafe.Pointer(&face)))); err != nil || face == 0 { + return 0, 0 + } + defer release(&face) + codepoints := [2]uint32{0x2502, 0x2503} // │ ┃ + var glyphs [2]uint16 + if err := hresult(comCall(face, writeFontFaceGetGlyphIndices, uintptr(unsafe.Pointer(&codepoints[0])), uintptr(len(codepoints)), uintptr(unsafe.Pointer(&glyphs[0])))); err != nil { + return 0, 0 + } + var glyphMetrics [2]writeGlyphMetrics + if err := hresult(comCall(face, writeFontFaceGetDesignGlyphMetrics, uintptr(unsafe.Pointer(&glyphs[0])), uintptr(len(glyphs)), uintptr(unsafe.Pointer(&glyphMetrics[0])), 0)); err != nil { + return 0, 0 + } + em := float32(fontMetrics.DesignUnitsPerEm) + stroke := func(glyph uint16, metrics writeGlyphMetrics) float32 { + if glyph == 0 { + return 0 + } + ink := int32(metrics.AdvanceWidth) - metrics.LeftSideBearing - metrics.RightSideBearing + if ink <= 0 { + return 0 + } + return float32(ink) / em * size } - return float32(metrics.UnderlineThickness) / float32(metrics.DesignUnitsPerEm) * size + return stroke(glyphs[0], glyphMetrics[0]), stroke(glyphs[1], glyphMetrics[1]) } diff --git a/internal/platform/windows/textengine_windows.go b/internal/platform/windows/textengine_windows.go index 9f0ce0d6f..d8079cd1b 100644 --- a/internal/platform/windows/textengine_windows.go +++ b/internal/platform/windows/textengine_windows.go @@ -186,12 +186,14 @@ func (engine *textEngine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCell if err != nil { return gfx.MonoCellMetrics{} } + rule, heavy := engine.services.boxStrokes(family, size, 0) return gfx.MonoCellMetrics{ Advance: metrics.Width, Ascent: metrics.Ascent, Descent: metrics.Descent, LineGap: max(metrics.Height-metrics.Ascent-metrics.Descent, 0), - Underline: engine.services.underline(family, size, 0), + Rule: rule, + HeavyRule: heavy, } } diff --git a/internal/textmetrics/textmetrics.go b/internal/textmetrics/textmetrics.go index 80bec0677..682a4a0d8 100644 --- a/internal/textmetrics/textmetrics.go +++ b/internal/textmetrics/textmetrics.go @@ -53,12 +53,12 @@ const ( const ( MonoAdvance = 0.6 MonoLine = 1.18 - // MonoUnderline is the reference thickness of the stroke an underline draws, - // in units of the font size: the rule a cell glyph is drawn with when the text - // engine does not report the face's own underline thickness. A fixed-pitch face - // draws its underline at 5 to 10 percent of the size, and its heavy box drawing - // strokes at twice that, which is what the reference cell stands for. - MonoUnderline = 0.05 + // MonoRule is the reference thickness of the stroke a fixed-pitch face draws a light + // box drawing line with, in units of the font size: the rule a cell glyph is drawn + // with when the text engine does not report the face's own stroke. A fixed-pitch face + // draws its box lines at 5 to 15 percent of the size; the reference takes the low end, + // and a heavy stroke is twice that. + MonoRule = 0.05 ) // weightIndex selects the table for a Viva weight (gfx.TextStyle.Weight: 0 regular, diff --git a/text/measure.go b/text/measure.go index 689dcb657..d23152a1f 100644 --- a/text/measure.go +++ b/text/measure.go @@ -7,10 +7,11 @@ type Metrics struct { Ascent float32 Descent float32 Leading float32 - // Underline is the thickness of the stroke the font underlines with, in logical - // pixels: the weight a fixed-pitch cell glyph's rule takes. Zero where the - // platform's measurement does not include it. - Underline float32 + // Rule and HeavyRule are the thicknesses, in logical pixels, of the strokes the font + // draws with a light and a heavy box drawing line: the weights a fixed-pitch cell + // glyph's strokes take. Zero where the platform's measurement does not include them. + Rule float32 + HeavyRule float32 } // MeasureFunc shapes and measures one line at a logical font size and weight diff --git a/tools/cellatlas/draw.go b/tools/cellatlas/draw.go index 8db1eba90..f57da6bbb 100644 --- a/tools/cellatlas/draw.go +++ b/tools/cellatlas/draw.go @@ -57,8 +57,9 @@ func (s *sprite) drawAt(index int) { } // shapes is what gfx draws for r in a cell of the atlas's size: device pixels from the cell's -// corner. The rule a cell glyph is drawn with is 5% of the text's size until a text engine reports -// the underline thickness (see gfx cellLine), so the atlas's rule asks for the size that gives it. +// corner. A cell glyph's rule is the stroke its face draws a light box drawing line with, and +// the reference 5% of the text's size until a text engine measures the face (see gfx cellLine), +// so the atlas's rule asks for the size that gives it. func (s *sprite) shapes(r rune) gfx.CellGlyphShapes { value := string(r) bounds := gfx.Rect{Width: float32(s.atlas.width), Height: float32(s.atlas.height)} From 4e0105290106d4b12ea519495789c9aebb37ada9 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 14:21:41 +0800 Subject: [PATCH 32/86] feat(package): write a PKGBUILD for Arch Linux viva package --format pkgbuild writes PKGBUILD and .SRCINFO for a binary package that installs the released tar.gz under /opt and links it into /usr/bin, with its menu entry, icon and MIME types. [linux] arch_depends names the Arch packages the application needs beyond Vulkan, XCB and Cairo. --- cmd/viva/package.go | 11 +- cmd/viva/package_tarball.go | 119 +++++++-- cmd/viva/package_tarball_test.go | 90 +++++++ docs/conformance.md | 2 +- tools/manifest/manifest.go | 22 +- tools/manifest/manifest_deb.go | 8 + tools/pkgbuild/pkgbuild.go | 248 ++++++++++++++++++ tools/pkgbuild/pkgbuild_test.go | 192 ++++++++++++++ .../content/guides/en/build-and-package.md | 7 +- .../content/guides/zh/build-and-package.md | 7 +- 10 files changed, 675 insertions(+), 31 deletions(-) create mode 100644 tools/pkgbuild/pkgbuild.go create mode 100644 tools/pkgbuild/pkgbuild_test.go diff --git a/cmd/viva/package.go b/cmd/viva/package.go index 5cb917166..a75ce5f70 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"}, + "linux": {"tar.gz", "deb", "pkgbuild"}, } // packageRequest is what one target's packager is given. @@ -39,6 +39,9 @@ type packageRequest struct { // fileArgs are --file SRC=DEST values, resolved against the manifest when // the Windows packages are made. fileArgs []string + // pkgbuildURL is --pkgbuild-url: where makepkg downloads the tar.gz from. + // Empty means the archive is beside the PKGBUILD. + pkgbuildURL string } // build makes the program, unless --program supplied one. @@ -60,10 +63,12 @@ func runPackage(arguments []string, output, errorOutput io.Writer) error { var makeZip bool var sign signingOptions var extraFiles []string + 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") + flags.StringVar(&formatList, "format", "", "comma-separated formats: darwin app, zip, dmg; windows nsis, zip; linux tar.gz, deb, pkgbuild") 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") flags.Func("file", "windows: ship SRC beside the program as DEST (repeatable, SRC=DEST; DEST is relative)", func(value string) error { source, destination, ok := strings.Cut(value, "=") @@ -111,7 +116,7 @@ func runPackage(arguments []string, output, errorOutput io.Writer) error { } defer os.RemoveAll(scratch) request := packageRequest{ - plan: plan, formats: formats, out: requested, sign: sign, fileArgs: extraFiles, + plan: plan, formats: formats, out: requested, sign: sign, fileArgs: extraFiles, pkgbuildURL: pkgbuildURL, program: filepath.Join(scratch, plan.executable), output: output, errorOutput: errorOutput, } if program != "" { diff --git a/cmd/viva/package_tarball.go b/cmd/viva/package_tarball.go index 298b23099..02ec2ad5e 100644 --- a/cmd/viva/package_tarball.go +++ b/cmd/viva/package_tarball.go @@ -1,6 +1,8 @@ package main import ( + "crypto/sha256" + "encoding/hex" "fmt" "io" "os" @@ -10,6 +12,7 @@ import ( "github.com/vivaui/viva/tools/debpkg" "github.com/vivaui/viva/tools/linuxicon" "github.com/vivaui/viva/tools/manifest" + "github.com/vivaui/viva/tools/pkgbuild" "github.com/vivaui/viva/tools/tarball" ) @@ -18,10 +21,13 @@ import ( // them, so a .deb has to say so itself. var linuxRuntimeDepends = []string{"libvulkan1", "libxcb1", "libcairo2"} -// packageLinux builds the program and writes the Linux packages asked for, a -// .tar.gz with an install script and a .deb, into the output directory. Both -// are written beside their final names and renamed once every one of them is -// complete, so a failure leaves earlier output alone. +// linuxArchRuntimeDepends are the same libraries under Arch's names. +var linuxArchRuntimeDepends = []string{"vulkan-icd-loader", "libxcb", "cairo"} + +// 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 +// once every one of them is complete, so a failure leaves earlier output alone. func packageLinux(request packageRequest) error { plan, loaded, output := request.plan, request.plan.manifest, request.output dest := request.out @@ -79,35 +85,47 @@ func packageLinux(request packageRequest) error { if err := os.MkdirAll(dest, 0o755); err != nil { return err } - write := func(label, name string, build func(io.Writer) error) error { + // write writes one artifact and returns its SHA-256, which the PKGBUILD + // needs for the archive it installs. + write := func(label, name string, build func(io.Writer) error) (string, error) { final := filepath.Join(dest, name) file, err := os.CreateTemp(dest, "."+name+".viva-tmp-*") if err != nil { - return err + return "", err } item := artifact{label: label, temporary: file.Name(), final: final} artifacts = append(artifacts, item) - if err := build(file); err != nil { + digest := sha256.New() + if err := build(io.MultiWriter(file, digest)); err != nil { file.Close() - return err + return "", err } if err := file.Chmod(0o644); err != nil { file.Close() - return err + return "", err + } + if err := file.Close(); err != nil { + return "", err } - return file.Close() + return hex.EncodeToString(digest.Sum(nil)), nil } - if request.wants("tar.gz") { + var largest linuxicon.Rendition + if len(icons) > 0 { + largest = linuxicon.Largest(icons) + } + tarballName, tarballHash := "", "" + if request.wants("tar.gz") || request.wants("pkgbuild") { spec := tarball.Linux{ Executable: plan.executable, Name: loaded.App.Name, Version: loaded.App.Version, Arch: plan.arch, Comment: loaded.Linux.Comment, Category: category, Keywords: loaded.Linux.Keywords, URLSchemes: loaded.App.URLSchemes, FileTypes: linuxFileTypes(loaded.App.FileTypes), Program: program, } - if len(icons) > 0 { - largest := linuxicon.Largest(icons) + if largest.Pixels > 0 { spec.Icon, spec.IconPixels = largest.PNG, largest.Pixels } - if err := write("tar.gz", spec.Directory()+".tar.gz", spec.Write); err != nil { + tarballName = spec.Directory() + ".tar.gz" + tarballHash, err = write("tar.gz", tarballName, spec.Write) + if err != nil { return err } } @@ -124,7 +142,39 @@ func packageLinux(request packageRequest) error { if debName, err = spec.FileName(); err != nil { return err } - if err := write("deb", debName, spec.Write); err != nil { + if _, err := write("deb", debName, spec.Write); err != nil { + return err + } + } + if request.wants("pkgbuild") { + maintainer := loaded.Linux.Maintainer + if maintainer == "" { + maintainer = loaded.App.Name + } + spec := pkgbuild.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, + Depends: archDepends(loaded.Linux.ArchDepends), Archive: tarballName, SHA256: tarballHash, + SourceURL: request.pkgbuildURL, IconPixels: largest.Pixels, + } + text, err := spec.PKGBUILD() + if err != nil { + return err + } + if _, err := write("pkgbuild", "PKGBUILD", func(w io.Writer) error { + _, err := w.Write(text) + return err + }); err != nil { + return err + } + srcinfo, err := spec.SRCINFO() + if err != nil { + return err + } + if _, err := write("srcinfo", ".SRCINFO", func(w io.Writer) error { + _, err := w.Write(srcinfo) + return err + }); err != nil { return err } } @@ -179,6 +229,45 @@ func debDepends(own []string) []string { return append(depends, own...) } +// archDepends is debDepends for Arch, whose package names differ and whose +// relations may be written without spaces (libxcb>=1.16). +func archDepends(own []string) []string { + depends := make([]string, 0, len(linuxArchRuntimeDepends)+len(own)) + for _, library := range linuxArchRuntimeDepends { + named := false + for _, dependency := range own { + if archDependencyName(dependency) == library { + named = true + } + } + if !named { + depends = append(depends, library) + } + } + seen := make(map[string]bool, len(depends)+len(own)) + for _, dependency := range depends { + seen[archDependencyName(dependency)] = true + } + for _, dependency := range own { + if name := archDependencyName(dependency); !seen[name] { + seen[name] = true + depends = append(depends, dependency) + } + } + return depends +} + +// archDependencyName is the package name of an Arch dependency without its +// version relation. +func archDependencyName(dependency string) string { + for _, relation := range []string{">=", "<=", ">", "<", "="} { + if before, _, ok := strings.Cut(dependency, relation); ok { + return strings.TrimSpace(before) + } + } + return strings.TrimSpace(dependency) +} + // loadLinuxIcon reads the [app] icon, which must be a PNG, and renders its // hicolor sizes. func loadLinuxIcon(path string) ([]linuxicon.Rendition, int, error) { diff --git a/cmd/viva/package_tarball_test.go b/cmd/viva/package_tarball_test.go index 59737ca0d..c542b474b 100644 --- a/cmd/viva/package_tarball_test.go +++ b/cmd/viva/package_tarball_test.go @@ -4,9 +4,12 @@ import ( "archive/tar" "bytes" "compress/gzip" + "crypto/sha256" + "encoding/hex" "fmt" "io" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -359,3 +362,90 @@ extensions = ["note"] t.Errorf("mime package:\n%s", types) } } + +const linuxArchTOML = linuxTOML + `arch_depends = ["libxcb>=1.16", "cairo", "extra-lib"] +` + +func TestPackageLinuxMakesAPKGBUILD(t *testing.T) { + dir := packageLinuxFixture(t, linuxArchTOML, 256) + output, err := runLinuxPackage(t, dir, "--format", "pkgbuild") + if err != nil { + t.Fatalf("%v\n%s", err, output) + } + for _, want := range []string{" tar.gz ", " pkgbuild ", " srcinfo "} { + if !strings.Contains(output, want) { + t.Errorf("the report lacks %q:\n%s", want, output) + } + } + archive := filepath.Join(dir, "build", "fixture-notes-2.0.1-linux-amd64.tar.gz") + data, err := os.ReadFile(archive) + if err != nil { + t.Fatalf("the tarball is not beside the PKGBUILD: %v", err) + } + digest := sha256.Sum256(data) + pkgbuildBytes, err := os.ReadFile(filepath.Join(dir, "build", "PKGBUILD")) + if err != nil { + t.Fatal(err) + } + pkgbuild := string(pkgbuildBytes) + for _, want := range []string{ + "pkgname='fixture-notes-bin'", + "pkgver='2.0.1'", + "arch=('x86_64')", + "depends=('vulkan-icd-loader' 'libxcb>=1.16' 'cairo' 'extra-lib')", + "source=('fixture-notes-2.0.1-linux-amd64.tar.gz')", + "sha256sums=('" + hex.EncodeToString(digest[:]) + "')", + "_icon_size=256", + } { + if !strings.Contains(pkgbuild, want) { + t.Errorf("the PKGBUILD lacks %q:\n%s", want, pkgbuild) + } + } + if strings.Contains(pkgbuild, "libfoo1") { + t.Errorf("a Debian dependency reached the Arch package:\n%s", pkgbuild) + } + srcinfo, err := os.ReadFile(filepath.Join(dir, "build", ".SRCINFO")) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"pkgbase = fixture-notes-bin", "\tarch = x86_64", "\tdepends = extra-lib", "pkgname = fixture-notes-bin"} { + if !strings.Contains(string(srcinfo), want) { + t.Errorf("the .SRCINFO lacks %q:\n%s", want, srcinfo) + } + } + if bash, err := exec.LookPath("bash"); err == nil { + command := exec.Command(bash, "-n") + command.Stdin = bytes.NewReader(pkgbuildBytes) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("bash -n: %v\n%s", err, output) + } + } +} + +func TestPackageLinuxPKGBUILDSourceURL(t *testing.T) { + dir := packageLinuxFixture(t, linuxTOML, 256) + url := "https://example.com/downloads/fixture-notes-2.0.1-linux-amd64.tar.gz" + output, err := runLinuxPackage(t, dir, "--format", "pkgbuild", "--pkgbuild-url", url) + if err != nil { + t.Fatalf("%v\n%s", err, output) + } + data, err := os.ReadFile(filepath.Join(dir, "build", "PKGBUILD")) + if err != nil { + t.Fatal(err) + } + want := "source=('fixture-notes-2.0.1-linux-amd64.tar.gz::" + url + "')" + if !strings.Contains(string(data), want) { + t.Fatalf("the PKGBUILD lacks %q:\n%s", want, data) + } +} + +func TestPackageLinuxRefusesABadPKGBUILDURL(t *testing.T) { + dir := packageLinuxFixture(t, linuxTOML, 256) + output, err := runLinuxPackage(t, dir, "--format", "pkgbuild", "--pkgbuild-url", "file:///tmp/app.tar.gz") + if err == nil { + t.Fatalf("a file URL was accepted:\n%s", output) + } + if _, statErr := os.Stat(filepath.Join(dir, "build", "PKGBUILD")); !os.IsNotExist(statErr) { + t.Errorf("a PKGBUILD was written after the failure: %v", statErr) + } +} diff --git a/docs/conformance.md b/docs/conformance.md index 0ec95767e..f93a29065 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -94,7 +94,7 @@ mistakes an absence for an oversight. Items marked *measured* were tried or size | A native application menu | all | The contract has a status-item menu only; macOS installs a Quit item. | | 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 and .deb. | +| 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. | | 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/tools/manifest/manifest.go b/tools/manifest/manifest.go index a3f01ea6e..9c016d7ae 100644 --- a/tools/manifest/manifest.go +++ b/tools/manifest/manifest.go @@ -166,6 +166,10 @@ type Linux struct { Homepage string // Depends are the .deb's dependencies, as in Debian's Depends field. Depends []string + // ArchDepends are the Arch packages the PKGBUILD depends on. They are + // written separately because Debian and Arch name the same library + // differently, and a Debian name in an Arch package cannot be resolved. + ArchDepends []string // Keywords help the desktop search find the menu entry. Keywords []string } @@ -258,12 +262,13 @@ type document struct { URL string `toml:"url"` } `toml:"windows"` Linux struct { - Category string `toml:"category"` - Comment string `toml:"comment"` - Maintainer string `toml:"maintainer"` - Homepage string `toml:"homepage"` - Depends []string `toml:"depends"` - Keywords []string `toml:"keywords"` + Category string `toml:"category"` + Comment string `toml:"comment"` + Maintainer string `toml:"maintainer"` + Homepage string `toml:"homepage"` + Depends []string `toml:"depends"` + ArchDepends []string `toml:"arch_depends"` + Keywords []string `toml:"keywords"` } `toml:"linux"` } @@ -276,7 +281,7 @@ var knownKeys = map[string][]string{ "mac": {"category", "copyright", "dmg", "entitlements", "info", "min_system"}, "mac.dmg": {"app_position", "applications_position", "background", "icon_size"}, "windows": {"publisher", "scope", "url"}, - "linux": {"category", "comment", "depends", "homepage", "keywords", "maintainer"}, + "linux": {"arch_depends", "category", "comment", "depends", "homepage", "keywords", "maintainer"}, } // Parse decodes the text of a viva.toml. name labels errors and dir becomes @@ -325,7 +330,8 @@ func Parse(name, dir, source string) (*Manifest, error) { manifest.Windows = Windows{Publisher: doc.Windows.Publisher, Scope: doc.Windows.Scope, URL: doc.Windows.URL} manifest.Linux = Linux{ Category: doc.Linux.Category, Comment: doc.Linux.Comment, Maintainer: doc.Linux.Maintainer, - Homepage: doc.Linux.Homepage, Depends: doc.Linux.Depends, Keywords: doc.Linux.Keywords, + Homepage: doc.Linux.Homepage, Depends: doc.Linux.Depends, ArchDepends: doc.Linux.ArchDepends, + Keywords: doc.Linux.Keywords, } sort.Slice(manifest.Mac.Info, func(i, j int) bool { return manifest.Mac.Info[i].Key < manifest.Mac.Info[j].Key }) diff --git a/tools/manifest/manifest_deb.go b/tools/manifest/manifest_deb.go index ffba51080..04cca41fa 100644 --- a/tools/manifest/manifest_deb.go +++ b/tools/manifest/manifest_deb.go @@ -24,6 +24,9 @@ var ( // relations in parentheses, architecture and alternatives (|). dpkg has the // final say when the package is installed. dependsPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9+.:()<>=~| -]*$`) + // archDependsPattern accepts an Arch dependency: a package name and an + // optional version relation, such as vulkan-icd-loader or libxcb>=1.16. + archDependsPattern = regexp.MustCompile(`^[a-z0-9@._+][a-z0-9@._+-]*( ?(>=|<=|=|>|<) ?[A-Za-z0-9._+:-]+)?$`) ) // LinuxCategory is the category the menu entry is filed under. @@ -64,6 +67,11 @@ func (manifest *Manifest) validateLinux() error { return fail("depends", "%q is not a Debian dependency such as libfoo1 (>= 1.2)", dependency) } } + for _, dependency := range linux.ArchDepends { + if !archDependsPattern.MatchString(dependency) || strings.TrimSpace(dependency) != dependency { + return fail("arch_depends", "%q is not an Arch dependency such as libxcb or libxcb>=1.16", dependency) + } + } for _, keyword := range linux.Keywords { if keyword == "" || strings.Contains(keyword, ";") || hasControl(keyword) { return fail("keywords", "%q must be non-empty and cannot contain ; or control characters", keyword) diff --git a/tools/pkgbuild/pkgbuild.go b/tools/pkgbuild/pkgbuild.go new file mode 100644 index 000000000..058f91b9d --- /dev/null +++ b/tools/pkgbuild/pkgbuild.go @@ -0,0 +1,248 @@ +// Package pkgbuild writes Arch Linux packages for a desktop application: a +// PKGBUILD and its .SRCINFO that install a released binary archive. +// +// The archive is the tar.gz `viva package --format tar.gz` makes: the program, +// a menu entry, an icon and document types. The package is a binary one (its +// name ends in -bin), so makepkg does not build anything; it extracts the +// archive into /opt and links the program into /usr/bin, as an AUR -bin package +// does. Nothing here runs makepkg, and nothing needs Arch to write the files. +package pkgbuild + +import ( + "fmt" + "regexp" + "strings" +) + +// Package describes one binary package. +type Package struct { + // Executable is the program's file name in the archive. The package is + // named after it (see PackageName). + Executable string + // ID is the reverse-DNS application identifier; the menu entry is + // /usr/share/applications/.desktop. + ID string + // Name is the display name, used when no Comment is set. + Name string + Version string + // Arch is amd64 or arm64. + Arch string + Maintainer string + Homepage string + // Comment is the one-line description of the package. + Comment string + // Depends are Arch package names, such as vulkan-icd-loader. + Depends []string + // Archive is the tar.gz's file name, as it is in the PKGBUILD's + // directory or at the end of SourceURL. + Archive string + // SHA256 is the archive's lowercase hexadecimal SHA-256 digest. + SHA256 string + // SourceURL, when set, is where makepkg downloads the archive from. Empty + // means the archive is beside the PKGBUILD. + SourceURL string + // IconPixels is the icon's square size in pixels, or 0 without an icon. + IconPixels int +} + +var ( + packageNamePattern = regexp.MustCompile(`^[a-z0-9@_+][a-z0-9@._+-]+$`) + versionPattern = regexp.MustCompile(`^[A-Za-z0-9_+][A-Za-z0-9._+]*$`) + idPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + digestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) +) + +// PackageName derives the Arch package name from the executable's file name: +// lowercase, with the -bin suffix a binary package has. +func PackageName(executable string) (string, error) { + name := strings.ToLower(executable) + "-bin" + if !packageNamePattern.MatchString(name) { + return "", fmt.Errorf("pkgbuild: %q cannot name an Arch package: it needs lowercase letters, digits and @ . _ + -, and must start with a letter, digit, @, _ or +", executable) + } + return name, nil +} + +// ArchName maps a Go architecture to Arch's: amd64 is x86_64 and arm64 is +// aarch64. +func ArchName(arch string) (string, error) { + switch arch { + case "amd64": + return "x86_64", nil + case "arm64": + return "aarch64", nil + } + return "", fmt.Errorf("pkgbuild: architecture %q must be amd64 or arm64", arch) +} + +func (pkg Package) check() error { + if _, err := pkg.packageNameValidated(); err != nil { + return err + } + if _, err := ArchName(pkg.Arch); err != nil { + return err + } + switch { + case !versionPattern.MatchString(pkg.Version): + return fmt.Errorf("pkgbuild: %q is not an Arch version (it cannot contain '-')", pkg.Version) + case !idPattern.MatchString(pkg.ID): + return fmt.Errorf("pkgbuild: %q cannot name a desktop file", pkg.ID) + case pkg.Name == "": + return fmt.Errorf("pkgbuild: the application needs a display name") + case pkg.Archive == "" || strings.ContainsAny(pkg.Archive, "/\\") || strings.ContainsAny(pkg.Archive, "\r\n") || pkg.Archive == "." || pkg.Archive == "..": + return fmt.Errorf("pkgbuild: %q is not an archive file name", pkg.Archive) + case !digestPattern.MatchString(pkg.SHA256): + return fmt.Errorf("pkgbuild: %q is not a lowercase SHA-256 digest", pkg.SHA256) + case strings.ContainsAny(pkg.Maintainer, "\r\n"): + return fmt.Errorf("pkgbuild: the maintainer must be one line") + case strings.ContainsAny(pkg.Comment, "\r\n"): + return fmt.Errorf("pkgbuild: the comment must be one line") + case pkg.IconPixels < 0: + return fmt.Errorf("pkgbuild: the icon size cannot be negative") + } + for _, dependency := range pkg.Depends { + if dependency == "" || strings.ContainsAny(dependency, "\r\n") { + return fmt.Errorf("pkgbuild: %q is not one dependency", dependency) + } + } + if pkg.SourceURL != "" && (!strings.HasPrefix(pkg.SourceURL, "https://") && !strings.HasPrefix(pkg.SourceURL, "http://")) { + return fmt.Errorf("pkgbuild: the source URL %q must be http or https", pkg.SourceURL) + } + return nil +} + +// packageNameValidated is PackageName plus the length rule Arch enforces. +func (pkg Package) packageNameValidated() (string, error) { + name, err := PackageName(pkg.Executable) + if err != nil { + return "", err + } + if len(name) > 255 { + return "", fmt.Errorf("pkgbuild: the package name %q is longer than 255 characters", name) + } + return name, nil +} + +// PKGBUILD is the package description makepkg reads. +func (pkg Package) PKGBUILD() ([]byte, error) { + if err := pkg.check(); err != nil { + return nil, err + } + name, _ := pkg.packageNameValidated() + arch, _ := ArchName(pkg.Arch) + maintainer := pkg.Maintainer + if maintainer == "" { + maintainer = pkg.Name + } + description := pkg.Comment + if description == "" { + description = pkg.Name + } + source := pkg.Archive + if pkg.SourceURL != "" { + source = pkg.Archive + "::" + pkg.SourceURL + } + + var b strings.Builder + fmt.Fprintf(&b, "# Maintainer: %s\n", oneLine(maintainer)) + fmt.Fprintf(&b, "pkgname=%s\n", quote(name)) + fmt.Fprintf(&b, "pkgver=%s\n", quote(pkg.Version)) + fmt.Fprintf(&b, "pkgrel=1\n") + fmt.Fprintf(&b, "pkgdesc=%s\n", quote(description)) + fmt.Fprintf(&b, "arch=(%s)\n", quote(arch)) + if pkg.Homepage != "" { + fmt.Fprintf(&b, "url=%s\n", quote(pkg.Homepage)) + } + fmt.Fprintf(&b, "license=(%s)\n", quote("custom")) + if len(pkg.Depends) > 0 { + fmt.Fprintf(&b, "depends=(%s)\n", quotedList(pkg.Depends)) + } + fmt.Fprintf(&b, "provides=(%s)\n", quote(pkg.Executable)) + fmt.Fprintf(&b, "conflicts=(%s)\n", quote(pkg.Executable)) + fmt.Fprintf(&b, "options=(%s %s)\n", quote("!strip"), quote("!debug")) + b.WriteString("\n") + fmt.Fprintf(&b, "_archive=%s\n", quote(pkg.Archive)) + fmt.Fprintf(&b, "_exe=%s\n", quote(pkg.Executable)) + fmt.Fprintf(&b, "_desktop=%s\n", quote(pkg.ID)) + fmt.Fprintf(&b, "_icon_size=%d\n", pkg.IconPixels) + b.WriteString("\n") + fmt.Fprintf(&b, "source=(%s)\n", quote(source)) + fmt.Fprintf(&b, "sha256sums=(%s)\n", quote(pkg.SHA256)) + b.WriteString(` +package() { + install -dm755 "$pkgdir/opt/$pkgname" + bsdtar -xf "$srcdir/$_archive" -C "$pkgdir/opt/$pkgname" --strip-components=1 + rm -f "$pkgdir/opt/$pkgname/install.sh" + + install -dm755 "$pkgdir/usr/bin" + ln -s "/opt/$pkgname/$_exe" "$pkgdir/usr/bin/$_exe" + + install -Dm644 "$pkgdir/opt/$pkgname/$_exe.desktop" "$pkgdir/usr/share/applications/$_desktop.desktop" + if [ "$_icon_size" -gt 0 ]; then + install -Dm644 "$pkgdir/opt/$pkgname/$_exe.png" \ + "$pkgdir/usr/share/icons/hicolor/${_icon_size}x${_icon_size}/apps/$_exe.png" + fi + if [ -f "$pkgdir/opt/$pkgname/$_exe.mime.xml" ]; then + install -Dm644 "$pkgdir/opt/$pkgname/$_exe.mime.xml" "$pkgdir/usr/share/mime/packages/$_desktop.xml" + fi + install -Dm644 "$pkgdir/opt/$pkgname/README.txt" "$pkgdir/usr/share/doc/$pkgname/README.txt" +} +`) + return []byte(b.String()), nil +} + +// SRCINFO is the package description AUR reads. It repeats the PKGBUILD's +// fields in makepkg's plain key and value format. +func (pkg Package) SRCINFO() ([]byte, error) { + if err := pkg.check(); err != nil { + return nil, err + } + name, _ := pkg.packageNameValidated() + arch, _ := ArchName(pkg.Arch) + description := pkg.Comment + if description == "" { + description = pkg.Name + } + source := pkg.Archive + if pkg.SourceURL != "" { + source = pkg.Archive + "::" + pkg.SourceURL + } + var b strings.Builder + field := func(key, value string) { b.WriteString("\t" + key + " = " + value + "\n") } + b.WriteString("pkgbase = " + name + "\n") + field("pkgdesc", oneLine(description)) + field("pkgver", pkg.Version) + field("pkgrel", "1") + if pkg.Homepage != "" { + field("url", pkg.Homepage) + } + field("arch", arch) + field("license", "custom") + for _, dependency := range pkg.Depends { + field("depends", dependency) + } + field("provides", pkg.Executable) + field("conflicts", pkg.Executable) + field("options", "!strip") + field("options", "!debug") + field("source", source) + field("sha256sums", pkg.SHA256) + b.WriteString("\npkgname = " + name + "\n") + return []byte(b.String()), nil +} + +// quote is a single-quoted shell word, safe for any value the checks accept. +func quote(value string) string { + return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'" +} + +func quotedList(values []string) string { + quoted := make([]string, len(values)) + for i, value := range values { + quoted[i] = quote(value) + } + return strings.Join(quoted, " ") +} + +func oneLine(value string) string { + return strings.Join(strings.Fields(value), " ") +} diff --git a/tools/pkgbuild/pkgbuild_test.go b/tools/pkgbuild/pkgbuild_test.go new file mode 100644 index 000000000..2ce71b5b0 --- /dev/null +++ b/tools/pkgbuild/pkgbuild_test.go @@ -0,0 +1,192 @@ +package pkgbuild + +import ( + "os/exec" + "strings" + "testing" +) + +func sample() Package { + return Package{ + Executable: "Fixture-Notes", ID: "dev.example.notes", Name: "Fixture Notes", Version: "2.0.1", Arch: "amd64", + Maintainer: "Ann Lee ", Homepage: "https://example.com/notes", + Comment: "Takes notes, doesn't lose them", + Depends: []string{"vulkan-icd-loader", "libxcb", "cairo"}, + Archive: "Fixture-Notes-2.0.1-linux-amd64.tar.gz", + SHA256: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + IconPixels: 256, + } +} + +func TestPackageName(t *testing.T) { + name, err := PackageName("Fixture-Notes") + if err != nil { + t.Fatal(err) + } + if name != "fixture-notes-bin" { + t.Fatalf("name = %q", name) + } + for _, bad := range []string{"", "-notes", ".notes", "notes app", "notes/app"} { + if _, err := PackageName(bad); err == nil { + t.Errorf("PackageName(%q) accepted", bad) + } + } +} + +func TestArchName(t *testing.T) { + cases := map[string]string{"amd64": "x86_64", "arm64": "aarch64"} + for input, want := range cases { + if got, err := ArchName(input); err != nil || got != want { + t.Errorf("ArchName(%q) = %q, %v; want %q", input, got, err, want) + } + } + if _, err := ArchName("386"); err == nil { + t.Error("ArchName(386) accepted") + } +} + +func TestPKGBUILD(t *testing.T) { + data, err := sample().PKGBUILD() + if err != nil { + t.Fatal(err) + } + pkgbuild := string(data) + for _, want := range []string{ + "pkgname='fixture-notes-bin'", + "pkgver='2.0.1'", + "pkgrel=1", + `pkgdesc='Takes notes, doesn'\''t lose them'`, + "arch=('x86_64')", + "url='https://example.com/notes'", + "license=('custom')", + "depends=('vulkan-icd-loader' 'libxcb' 'cairo')", + "provides=('Fixture-Notes')", + "conflicts=('Fixture-Notes')", + "options=('!strip' '!debug')", + "_archive='Fixture-Notes-2.0.1-linux-amd64.tar.gz'", + "_icon_size=256", + "source=('Fixture-Notes-2.0.1-linux-amd64.tar.gz')", + "sha256sums=('0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef')", + `install -dm755 "$pkgdir/opt/$pkgname"`, + `bsdtar -xf "$srcdir/$_archive" -C "$pkgdir/opt/$pkgname" --strip-components=1`, + `ln -s "/opt/$pkgname/$_exe" "$pkgdir/usr/bin/$_exe"`, + `$pkgdir/usr/share/applications/$_desktop.desktop`, + `$pkgdir/usr/share/icons/hicolor/${_icon_size}x${_icon_size}/apps/$_exe.png`, + `$pkgdir/usr/share/mime/packages/$_desktop.xml`, + `$pkgdir/usr/share/doc/$pkgname/README.txt`, + } { + if !strings.Contains(pkgbuild, want) { + t.Errorf("PKGBUILD does not contain %q:\n%s", want, pkgbuild) + } + } +} + +func TestPKGBUILDQuotesShellValues(t *testing.T) { + pkg := sample() + pkg.Comment = `Ann's "notes" $HOME ` + "`x`" + data, err := pkg.PKGBUILD() + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), `pkgdesc='Ann'\''s "notes" $HOME `+"`x`'") { + t.Fatalf("description is not single-quoted safely:\n%s", data) + } +} + +func TestPKGBUILDSourceURL(t *testing.T) { + pkg := sample() + pkg.SourceURL = "https://example.com/downloads/Fixture-Notes-2.0.1-linux-amd64.tar.gz" + data, err := pkg.PKGBUILD() + if err != nil { + t.Fatal(err) + } + want := "source=('Fixture-Notes-2.0.1-linux-amd64.tar.gz::https://example.com/downloads/Fixture-Notes-2.0.1-linux-amd64.tar.gz')" + if !strings.Contains(string(data), want) { + t.Fatalf("PKGBUILD does not contain %q:\n%s", want, data) + } +} + +func TestPKGBUILDWithoutIcon(t *testing.T) { + pkg := sample() + pkg.IconPixels = 0 + data, err := pkg.PKGBUILD() + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), `if [ "$_icon_size" -gt 0 ]; then`) { + t.Fatalf("no icon guard:\n%s", data) + } +} + +func TestPKGBUILDSyntax(t *testing.T) { + bash, err := exec.LookPath("bash") + if err != nil { + t.Skip("bash is not installed") + } + data, err := sample().PKGBUILD() + if err != nil { + t.Fatal(err) + } + command := exec.Command(bash, "-n") + command.Stdin = strings.NewReader(string(data)) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("bash -n: %v\n%s\n%s", err, output, data) + } +} + +func TestSRCINFO(t *testing.T) { + data, err := sample().SRCINFO() + if err != nil { + t.Fatal(err) + } + srcinfo := string(data) + for _, want := range []string{ + "pkgbase = fixture-notes-bin", + "\tpkgdesc = Takes notes, doesn't lose them", + "\tpkgver = 2.0.1", + "\tpkgrel = 1", + "\turl = https://example.com/notes", + "\tarch = x86_64", + "\tlicense = custom", + "\tdepends = vulkan-icd-loader", + "\tprovides = Fixture-Notes", + "\tconflicts = Fixture-Notes", + "\toptions = !strip", + "\toptions = !debug", + "\tsource = Fixture-Notes-2.0.1-linux-amd64.tar.gz", + "\tsha256sums = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "pkgname = fixture-notes-bin", + } { + if !strings.Contains(srcinfo, want) { + t.Errorf("SRCINFO does not contain %q:\n%s", want, srcinfo) + } + } +} + +func TestRejectsBadPackages(t *testing.T) { + tests := map[string]func(*Package){ + "empty name": func(p *Package) { p.Name = "" }, + "version hyphen": func(p *Package) { p.Version = "2.0.1-beta" }, + "empty archive": func(p *Package) { p.Archive = "" }, + "archive path": func(p *Package) { p.Archive = "dir/app.tar.gz" }, + "short digest": func(p *Package) { p.SHA256 = "abc" }, + "uppercase digest": func(p *Package) { p.SHA256 = strings.ToUpper(p.SHA256) }, + "arch": func(p *Package) { p.Arch = "386" }, + "bad id": func(p *Package) { p.ID = "a/b" }, + "multiline": func(p *Package) { p.Comment = "one\ntwo" }, + "bad maintainer": func(p *Package) { p.Maintainer = "two\nlines" }, + "bad source": func(p *Package) { p.SourceURL = "ftp://example.com/app.tar.gz" }, + "bad dependency": func(p *Package) { p.Depends = []string{"ok", ""} }, + "negative icon": func(p *Package) { p.IconPixels = -1 }, + } + for name, change := range tests { + pkg := sample() + change(&pkg) + if _, err := pkg.PKGBUILD(); err == nil { + t.Errorf("%s: PKGBUILD accepted", name) + } + if _, err := pkg.SRCINFO(); err == nil { + t.Errorf("%s: SRCINFO accepted", name) + } + } +} diff --git a/website/content/guides/en/build-and-package.md b/website/content/guides/en/build-and-package.md index d1306a836..8cfad3715 100644 --- a/website/content/guides/en/build-and-package.md +++ b/website/content/guides/en/build-and-package.md @@ -72,7 +72,7 @@ category = "public.app-category.productivity" entitlements = "app.entitlements" # optional: signed into the bundle with the hardened runtime ``` -The file is decoded strictly. An unknown table or key, a duplicate or a value of the wrong type is an error that names the line, so a typo never changes what gets built. `[mac.dmg]` shapes the window the `.dmg` opens in: `background` (a PNG, tagged 144 dpi for a 2x picture; its size in points is the window's size), `icon_size`, and `app_position` / `applications_position` as `[x, y]` points from the window's top left to an icon's middle. Without it the image opens in a 540×380 window with a plain light ground and an arrow from the application to the Applications shortcut. There are also `[mac.info]` for extra `Info.plist` strings, `[windows]` (publisher, install scope, URL) and `[linux]` (menu category, comment, maintainer, dependencies, keywords) for the installers. +The file is decoded strictly. An unknown table or key, a duplicate or a value of the wrong type is an error that names the line, so a typo never changes what gets built. `[mac.dmg]` shapes the window the `.dmg` opens in: `background` (a PNG, tagged 144 dpi for a 2x picture; its size in points is the window's size), `icon_size`, and `app_position` / `applications_position` as `[x, y]` points from the window's top left to an icon's middle. Without it the image opens in a 540×380 window with a plain light ground and an arrow from the application to the Applications shortcut. There are also `[mac.info]` for extra `Info.plist` strings, `[windows]` (publisher, install scope, URL) and `[linux]` (menu category, comment, maintainer, Debian dependencies, Arch dependencies, keywords) for the installers. ## Release builds @@ -92,6 +92,7 @@ viva package # build/Notes.app viva package --format app,zip,dmg viva package --target windows --format nsis,zip viva package --target linux --format tar.gz,deb +viva package --target linux --format tar.gz,pkgbuild --pkgbuild-url https://example.com/downloads/notes-1.0.0-linux-x86_64.tar.gz viva package --program ./notes-signed # package an executable you built or signed yourself ``` @@ -99,7 +100,9 @@ viva package --program ./notes-signed # package an executable you buil | --- | --- | | macOS | `.app`, reproducible `.zip`, `.dmg` | | Windows | NSIS installer (needs `makensis`), or `.zip` | -| Linux | `tar.gz` with an install script, or `.deb` | +| Linux | `tar.gz` with an install script, `.deb`, or a `PKGBUILD` with its `.SRCINFO` for an Arch binary package | + +A `PKGBUILD` installs the program under `/opt/-bin`, links it into `/usr/bin`, and installs the menu entry, icon and document types; it never builds anything, so it needs no Arch machine to write. The `tar.gz` is its source: by default makepkg looks for it beside the `PKGBUILD`, and `--pkgbuild-url` gives the address of the released archive instead (the `tar.gz::` form, so the file keeps its name). Write each architecture into its own directory, as `PKGBUILD` is one file per directory. Set `[linux] arch_depends` for libraries the application needs beyond the Vulkan, XCB and Cairo packages every Viva application uses. **Signing is optional.** With nothing configured nothing is signed: macOS blocks a downloaded bundle and Windows SmartScreen warns about the installer. `--program` exists so you can build, sign, and then package that exact executable yourself. diff --git a/website/content/guides/zh/build-and-package.md b/website/content/guides/zh/build-and-package.md index c2c1ac86f..eb3b3253e 100644 --- a/website/content/guides/zh/build-and-package.md +++ b/website/content/guides/zh/build-and-package.md @@ -72,7 +72,7 @@ category = "public.app-category.productivity" entitlements = "app.entitlements" # 可选:连同 hardened runtime 一起签进应用包 ``` -文件按严格模式解析。未知的表或键、重复项、类型错误的值,都会报出带行号的错误,所以拼写错误不会悄悄改变构建结果。`[mac.dmg]` 决定 `.dmg` 打开时的窗口样子:`background`(PNG,2x 图片标 144 dpi;其点数尺寸就是窗口尺寸)、`icon_size`,以及 `app_position` / `applications_position`(`[x, y]`,从窗口左上角到图标中心的点数)。不设置时镜像以 540×380 的窗口打开,底色为浅色,并画有从应用指向 Applications 的箭头。另外还有用于额外 `Info.plist` 字符串的 `[mac.info]`,以及供安装包使用的 `[windows]`(发布者、安装范围、网址)和 `[linux]`(菜单分类、说明、维护者、依赖、关键字)。 +文件按严格模式解析。未知的表或键、重复项、类型错误的值,都会报出带行号的错误,所以拼写错误不会悄悄改变构建结果。`[mac.dmg]` 决定 `.dmg` 打开时的窗口样子:`background`(PNG,2x 图片标 144 dpi;其点数尺寸就是窗口尺寸)、`icon_size`,以及 `app_position` / `applications_position`(`[x, y]`,从窗口左上角到图标中心的点数)。不设置时镜像以 540×380 的窗口打开,底色为浅色,并画有从应用指向 Applications 的箭头。另外还有用于额外 `Info.plist` 字符串的 `[mac.info]`,以及供安装包使用的 `[windows]`(发布者、安装范围、网址)和 `[linux]`(菜单分类、说明、维护者、Debian 依赖、Arch 依赖、关键字)。 ## 发布构建 @@ -92,6 +92,7 @@ viva package # build/Notes.app viva package --format app,zip,dmg viva package --target windows --format nsis,zip viva package --target linux --format tar.gz,deb +viva package --target linux --format tar.gz,pkgbuild --pkgbuild-url https://example.com/downloads/notes-1.0.0-linux-x86_64.tar.gz viva package --program ./notes-signed # 打包你自己构建或签名的可执行文件 ``` @@ -99,7 +100,9 @@ viva package --program ./notes-signed # 打包你自己构建或签名 | --- | --- | | macOS | `.app`、可复现的 `.zip`、`.dmg` | | Windows | NSIS 安装程序(需要 `makensis`),或 `.zip` | -| Linux | 带安装脚本的 `tar.gz`,或 `.deb` | +| Linux | 带安装脚本的 `tar.gz`、`.deb`,或 Arch 二进制包用的 `PKGBUILD` 与 `.SRCINFO` | + +`PKGBUILD` 把程序装到 `/opt/-bin`,链接到 `/usr/bin`,并安装菜单项、图标和文档类型;它不构建任何东西,所以写它不需要 Arch 机器。它的源是那个 `tar.gz`:默认 makepkg 在 `PKGBUILD` 旁边找它,`--pkgbuild-url` 则给出已发布归档的地址(写成 `tar.gz::`,保留文件名)。每个架构写到各自的目录,因为一个目录只有一个 `PKGBUILD`。除每个 Viva 应用都需要的 Vulkan、XCB 和 Cairo 包之外,应用还需要别的库时,用 `[linux] arch_depends` 列出。 **签名是可选的。** 什么都不配置就什么都不签:macOS 会阻止下载的应用包,Windows SmartScreen 会对安装程序给出警告。`--program` 的存在就是为了让你自己先构建、签名,再打包这个确定的可执行文件。 From 27429b51c0441eaff32592a1fe2aa9edcfd6be70 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 14:21:55 +0800 Subject: [PATCH 33/86] feat(update): apply signed delta updates to the installed payload The feed may list a patch per asset between an earlier version and this one. viva feed --patch-from makes it: a gzip tar with patch.json and one bsdiff per changed file, against the installed .app on macOS or the executable on Linux. DownloadPatch verifies the bytes the signed feed declares; ReadPatch/PatchReader.Apply verify every file it writes; ApplyPatch stages the result; Install replaces the application from the staged payload. A patch that does not fit falls back to the full archive. Windows has no patch: the NSIS installer owns the installation. --- THIRD_PARTY_NOTICES.md | 51 ++++ cmd/viva/feed.go | 145 ++++++++++ cmd/viva/feed_test.go | 111 ++++++++ cmd/viva/help.go | 4 +- docs/updating.md | 89 ++++++- go.mod | 3 + go.sum | 4 + internal/bsdiff/patch.go | 124 +++++++++ internal/bsdiff/patch_test.go | 87 ++++++ tools/patchgen/patchgen.go | 410 ++++++++++++++++++++++++++++ tools/patchgen/patchgen_test.go | 178 +++++++++++++ update/copy.go | 60 +++++ update/doc.go | 13 +- update/download.go | 65 +++-- update/download_test.go | 64 +++++ update/install.go | 61 +++-- update/install_darwin.go | 17 +- update/install_linux.go | 35 ++- update/install_windows.go | 3 + update/manifest.go | 58 ++++ update/manifest_test.go | 45 ++++ update/patch.go | 455 ++++++++++++++++++++++++++++++++ update/patch_test.go | 296 +++++++++++++++++++++ update/payload_darwin.go | 21 ++ update/payload_linux.go | 23 ++ update/payload_other.go | 9 + update/payload_windows.go | 11 + 27 files changed, 2373 insertions(+), 69 deletions(-) create mode 100644 internal/bsdiff/patch.go create mode 100644 internal/bsdiff/patch_test.go create mode 100644 tools/patchgen/patchgen.go create mode 100644 tools/patchgen/patchgen_test.go create mode 100644 update/copy.go create mode 100644 update/patch.go create mode 100644 update/patch_test.go create mode 100644 update/payload_darwin.go create mode 100644 update/payload_linux.go create mode 100644 update/payload_other.go create mode 100644 update/payload_windows.go diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index a159bf81c..62324ea10 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -260,3 +260,54 @@ The documentation site's JavaScript and CSS dependencies are pinned in `website/package-lock.json`. Their license texts are part of the packages installed from that lockfile; a deployed build should carry those notices in its own license page. + +### github.com/gabstv/go-bsdiff + +The MIT License (MIT) + +Copyright (c) 2019 Gabriel Ochsenhofer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +### github.com/dsnet/compress + +Copyright © 2015, Joe Tsai and The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. +* Neither the copyright holder nor the names of its contributors may be used +to endorse or promote products derived from this software without specific +prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/cmd/viva/feed.go b/cmd/viva/feed.go index cb489b91f..33ee0cd41 100644 --- a/cmd/viva/feed.go +++ b/cmd/viva/feed.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "crypto/ed25519" "crypto/rand" "crypto/sha256" @@ -20,6 +21,7 @@ import ( "time" "github.com/vivaui/viva/tools/manifest" + "github.com/vivaui/viva/tools/patchgen" "github.com/vivaui/viva/update" ) @@ -40,6 +42,15 @@ func runFeed(arguments []string, output, _ io.Writer) error { flags.StringVar(&baseURL, "base-url", "", "HTTPS address the archives are served from (required)") 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 { + parsed, err := parsePatchFrom(value) + if err != nil { + return err + } + patchFroms = append(patchFroms, parsed) + return nil + }) flags.DurationVar(&validFor, "valid-for", 0, "how long clients trust the feed, such as 2160h; 0 (the default) never expires") flags.StringVar(&keyFile, "key", "", "Ed25519 private key file (default $VIVA_UPDATE_KEY)") positional, helped, err := parseFlags(c, flags, arguments, output) @@ -94,6 +105,11 @@ func runFeed(arguments []string, output, _ io.Writer) error { if err != nil { return err } + if len(patchFroms) > 0 { + if err := addPatches(assets, patchFroms, artifactsDir, baseURL, version, app, loaded.ExecutableName()); err != nil { + return err + } + } key, err := readSigningKey(keyFile) if err != nil { return err @@ -144,6 +160,13 @@ func runFeed(arguments []string, output, _ io.Writer) error { fmt.Fprintf(output, " expires %s\n", feed.Expires.Format(time.RFC3339)) } fmt.Fprintf(output, " assets %d\n", len(assets)) + patches := 0 + for _, asset := range assets { + patches += len(asset.Patches) + } + if patches > 0 { + fmt.Fprintf(output, " patches %d\n", patches) + } fmt.Fprintf(output, " signed %s\n", displayPath(signaturePath)) return nil } @@ -395,3 +418,125 @@ func writeKeyFile(path, text string, mode os.FileMode, force bool) error { } return file.Close() } + +// patchFrom is one --patch-from value: a previous release to diff against. +type patchFrom struct { + os, arch, version, archive string +} + +func parsePatchFrom(value string) (patchFrom, error) { + parts := strings.SplitN(value, "=", 3) + if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" { + return patchFrom{}, errors.New("--patch-from wants os/arch=version=archive, such as darwin/arm64=1.0.0=dist/notes-1.0.0-darwin-arm64.zip") + } + 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 goarch != "amd64" && goarch != "arm64" { + return patchFrom{}, fmt.Errorf("--patch-from %q: architecture must be amd64 or arm64", target) + } + return patchFrom{os: goos, arch: goarch, version: version, archive: archive}, nil +} + +// 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 { + base := strings.TrimRight(baseURL, "/") + byTarget := make(map[string][]patchFrom, len(froms)) + for _, from := range froms { + key := from.os + "/" + from.arch + for _, existing := range byTarget[key] { + if existing.version == from.version { + return fmt.Errorf("feed: --patch-from %s=%s is given twice", key, from.version) + } + } + if cmp, err := update.Compare(from.version, version); err != nil { + return fmt.Errorf("feed: --patch-from %s=%s: %v", key, from.version, err) + } else if cmp >= 0 { + return fmt.Errorf("feed: --patch-from %s=%s must be older than the release %s", key, from.version, version) + } + if _, err := os.Stat(from.archive); err != nil { + return fmt.Errorf("feed: --patch-from %s=%s: %w", key, from.version, err) + } + byTarget[key] = append(byTarget[key], from) + } + matched := make(map[string]int, len(byTarget)) + for i := range assets { + asset := &assets[i] + key := asset.OS + "/" + asset.Arch + froms := byTarget[key] + if len(froms) == 0 { + continue + } + name, err := url.PathUnescape(strings.TrimPrefix(asset.URL, base+"/")) + if err != nil { + return fmt.Errorf("feed: %s: %w", asset.URL, err) + } + newArchive := filepath.Join(dir, name) + for _, from := range froms { + var encoded bytes.Buffer + if _, err := patchgen.Write(patchgen.Request{ + App: app, FromVersion: from.version, ToVersion: version, + OS: asset.OS, Arch: asset.Arch, + OldArchive: from.archive, NewArchive: newArchive, + Executable: executable, + Output: &encoded, + }); err != nil { + return fmt.Errorf("feed: patch %s from %s: %w", key, from.version, err) + } + patchName := name + "." + from.version + ".patch" + if err := writePatchFileBeside(filepath.Join(dir, patchName), encoded.Bytes()); err != nil { + return err + } + sum := sha256.Sum256(encoded.Bytes()) + asset.Patches = append(asset.Patches, update.Patch{ + FromVersion: from.version, + URL: base + "/" + url.PathEscape(patchName), + Size: int64(encoded.Len()), + SHA256: hex.EncodeToString(sum[:]), + }) + matched[key]++ + } + sort.Slice(asset.Patches, func(a, b int) bool { + order, err := update.Compare(asset.Patches[a].FromVersion, asset.Patches[b].FromVersion) + return err == nil && order < 0 + }) + } + for key, froms := range byTarget { + if matched[key] != len(froms) { + return fmt.Errorf("feed: --patch-from %s names no %s/%s archive in %s", key, strings.Split(key, "/")[0], strings.Split(key, "/")[1], displayPath(dir)) + } + } + return nil +} + +// writeFeedFile writes a patch beside the archives, named only when complete. +func writePatchFileBeside(name string, data []byte) error { + file, err := os.CreateTemp(filepath.Dir(name), "."+filepath.Base(name)+".viva-feed-*") + if err != nil { + return err + } + temporary := file.Name() + if _, err := file.Write(data); err != nil { + file.Close() + os.Remove(temporary) + return err + } + if err := file.Chmod(0o644); err != nil { + file.Close() + os.Remove(temporary) + return err + } + if err := file.Close(); err != nil { + os.Remove(temporary) + return err + } + if err := os.Rename(temporary, name); err != nil { + os.Remove(temporary) + return err + } + return nil +} diff --git a/cmd/viva/feed_test.go b/cmd/viva/feed_test.go index 93bb8c50f..a29b0f2b1 100644 --- a/cmd/viva/feed_test.go +++ b/cmd/viva/feed_test.go @@ -513,3 +513,114 @@ func TestFeedAndKeygenHelpListsFlags(t *testing.T) { } } } + +func copyFeedFile(t *testing.T, source, destination string) { + 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, 0o644); err != nil { + t.Fatal(err) + } +} + +func TestFeedAddsADeltaFromAnEarlierRelease(t *testing.T) { + t.Setenv("VIVA_UPDATE_KEY", "") + const oldTOML = `[app] +name = "Fixture Notes" +id = "dev.example.notes" +version = "2.0.0" +` + dir := t.TempDir() + oldDir, newDir := fixture(t, oldTOML), fixture(t, feedTestBasicTOML) + // A different program, so the patch has something to diff. + if err := os.WriteFile(filepath.Join(oldDir, "main.go"), []byte("package main\n\nfunc main() { extra() }\n\nfunc extra() {}\n"), 0o644); err != nil { + t.Fatal(err) + } + if output, err := runLinuxPackage(t, oldDir); err != nil { + t.Fatalf("packaging the old release: %v\n%s", err, output) + } + if output, err := runLinuxPackage(t, newDir); err != nil { + t.Fatalf("packaging the new release: %v\n%s", err, output) + } + dist := filepath.Join(dir, "dist") + oldArchive := filepath.Join(oldDir, "build", "fixture-notes-2.0.0-linux-amd64.tar.gz") + newArchive := filepath.Join(newDir, "build", "fixture-notes-2.0.1-linux-amd64.tar.gz") + copyFeedFile(t, newArchive, filepath.Join(dist, filepath.Base(newArchive))) + + key, _ := feedTestKey(t, dir) + feedPath := filepath.Join(dist, "latest.json") + var output bytes.Buffer + err := runCLI([]string{ + "feed", "-C", newDir, "-dir", dist, "-base-url", "https://example.com/app", + "-key", key, "-out", feedPath, + "--patch-from", "linux/amd64=2.0.0=" + oldArchive, + }, &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) != 1 || len(feed.Latest.Assets[0].Patches) != 1 { + t.Fatalf("the feed does not carry one patch:\n%s", data) + } + patch := feed.Latest.Assets[0].Patches[0] + if patch.FromVersion != "2.0.0" || patch.Size <= 0 || len(patch.SHA256) != 64 { + t.Fatalf("patch entry = %+v", patch) + } + patchPath := filepath.Join(dist, "fixture-notes-2.0.1-linux-amd64.tar.gz.2.0.0.patch") + reader, err := update.ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + defer reader.Close() + manifest := reader.Manifest() + if manifest.App != "dev.example.notes" || manifest.FromVersion != "2.0.0" || manifest.ToVersion != "2.0.1" || + manifest.OS != "linux" || manifest.Arch != "amd64" || manifest.Payload != "file" || len(manifest.Files) == 0 { + t.Fatalf("manifest = %+v", manifest) + } + // The patch must be much smaller than the archive it replaces. + if patch.Size >= feed.Latest.Assets[0].Size/2 { + t.Errorf("patch is %d bytes for a %d-byte archive", patch.Size, feed.Latest.Assets[0].Size) + } +} + +func TestFeedRejectsBadPatchFrom(t *testing.T) { + t.Setenv("VIVA_UPDATE_KEY", "") + dir := t.TempDir() + feedDir := fixture(t, feedTestBasicTOML) + if output, err := runLinuxPackage(t, feedDir); err != nil { + t.Fatalf("%v\n%s", err, output) + } + dist := filepath.Join(dir, "dist") + archive := filepath.Join(feedDir, "build", "fixture-notes-2.0.1-linux-amd64.tar.gz") + copyFeedFile(t, archive, filepath.Join(dist, filepath.Base(archive))) + key, _ := feedTestKey(t, dir) + run := func(extra ...string) error { + arguments := append([]string{"feed", "-C", feedDir, "-dir", dist, "-base-url", "https://example.com/app", "-key", key}, extra...) + var output bytes.Buffer + return runCLI(arguments, &output, io.Discard) + } + for name, argument := range map[string]string{ + "windows": "windows/amd64=2.0.0=" + archive, + "bad platform": "linux/sparc=2.0.0=" + archive, + "not older": "linux/amd64=2.0.1=" + archive, + "unknown asset": "darwin/arm64=2.0.0=" + archive, + "bad syntax": "linux/amd64=2.0.0", + "missing file": "linux/amd64=2.0.0=/does/not/exist.tar.gz", + } { + if err := run("--patch-from", argument); err == nil { + t.Errorf("%s: --patch-from %q was accepted", name, argument) + } + } +} diff --git a/cmd/viva/help.go b/cmd/viva/help.go index 597269acf..db2f215ee 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -76,7 +76,9 @@ func commands() []command { "signature. The feed lists only files named the way viva package names them; anything else in\n" + "the directory is ignored. -base-url is where the archives are served from and must be HTTPS,\n" + "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.", + "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.", run: func(arguments []string, output, errorOutput io.Writer) error { return runFeed(arguments, output, errorOutput) }}, diff --git a/docs/updating.md b/docs/updating.md index 10d10dd21..5daf4e513 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -2,10 +2,15 @@ Viva ships an application as a native program with no updater inside it. The `github.com/vivaui/viva/update` package adds one when an application imports it, -and nothing is linked into a program that does not. It performs **full updates**: -the feed names a complete archive, the client downloads it, verifies it, and the -platform installer replaces the running application. Delta updates are not -implemented, and the feed format reserves a place for them without using it yet. +and nothing is linked into a program that does not. + +An update is either **full** or **a delta**. A full update downloads the complete +archive the feed lists. A delta downloads a signed patch made between the +installed payload and the new one: the `.app` bundle on macOS, the executable on +Linux. The client applies the patch into a staging directory, verifies every file +it produced, and hands the result to the same installer a full update uses. A +patch that does not fit the running version, or fails at any point, leaves the +installation untouched; the application downloads the full archive instead. The package splits the work in two: @@ -49,7 +54,15 @@ not act on is refused with `update.ErrManifest`. "format": "zip", "url": "https://example.com/app/stable/Notes-1.4.2-darwin-arm64.zip", "size": 18432000, - "sha256": "9f2c…" + "sha256": "9f2c…", + "patches": [ + { + "from_version": "1.4.1", + "url": "https://example.com/app/stable/Notes-1.4.2-darwin-arm64.zip.1.4.1.patch", + "size": 240000, + "sha256": "5b71…" + } + ] }, { "os": "windows", @@ -152,6 +165,48 @@ app/beta/latest.json A feed can be checked from any HTTP client; the signature is the only thing that makes it authoritative. +## Delta updates + +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 +``` + +Each `--patch-from` is `os/arch=version=archive`, repeatable, for `darwin` and +`linux` only. 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 +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`. + +The application decides whether to use a patch. The order that keeps the +fallback simple: + +```go +if patch, ok := asset.PatchFrom(running); ok { + if path, err := client.DownloadPatch(ctx, asset, patch, dir, progress); err == nil { + if staged, err := update.ApplyPatch(path, config.App, running, release.Version); err == nil { + return update.Install(update.InstallOptions{ + Payload: staged, Asset: asset, Version: release.Version, App: config.App, + }, quit) + } + } +} +// download and install the full archive +``` + +`ApplyPatch` refuses a patch whose application, versions, OS, architecture or +payload kind do not match, copies the installed payload into a staging +directory, and applies the patch there. `Install` then runs the same checks as a +full update (the bundle identifier, version and `codesign` on macOS) and replaces +the application. A failure in either step changes nothing: the application keeps +running the old version and can download the whole archive. + ## Updating in the application Check somewhere that does not block the UI thread, and hand the result back @@ -277,8 +332,9 @@ 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.** A download is the whole archive. The feed schema leaves - room for patches; no client reads them yet. +- **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`. - **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 @@ -296,16 +352,21 @@ warning. ## Testing an update path -`go test ./update` covers the feed parser, signatures, version ordering, -download checks and archive unpacking on every host. The parts that replace a -real application need a machine and a person: +`go test ./update ./internal/bsdiff ./tools/patchgen` covers the feed parser, +signatures, version ordering, download checks, archive unpacking, patch +application and patch generation on every host. The parts that replace a real +application need a machine and a person: 1. Build version 1, package it, install it, run it. -2. Build version 2, package it, run `viva feed`, host the files over HTTPS. +2. Build version 2, package it, run `viva feed --patch-from /==`, host the files over HTTPS. 3. Start version 1, check, download, install, and confirm version 2 starts. -4. Repeat with the network dropped mid-download, with a tampered archive, and +4. Install version 1 again and repeat through the delta, then repeat the delta + with a changed installed payload, with a truncated patch, and with a patch + from another version: each must fall back to the full archive. +5. Repeat with the network dropped mid-download, with a tampered archive, and with a feed signed by another key. -5. On macOS, confirm `codesign --verify --deep --strict` passes on the new +6. On macOS, confirm `codesign --verify --deep --strict` passes on the new bundle and that the app opens with the network off (the ticket is stapled). -6. On Windows, confirm the installer is silent, per-user, and that the new + This also covers a bundle applied from a patch. +7. On Windows, confirm the installer is silent, per-user, and that the new program starts after the old one exits. diff --git a/go.mod b/go.mod index 34af71a85..1ed861c03 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,10 @@ go 1.26.0 require ( github.com/Microsoft/go-winio v0.6.4 github.com/ebitengine/purego v0.11.1 + github.com/gabstv/go-bsdiff v1.0.5 github.com/pelletier/go-toml/v2 v2.4.3 golang.org/x/sys v0.50.0 golang.org/x/text v0.44.0 ) + +require github.com/dsnet/compress v0.0.0-20171208185109-cc9eb1d7ad76 // indirect diff --git a/go.sum b/go.sum index 429c75911..43d130af8 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,11 @@ github.com/Microsoft/go-winio v0.6.4 h1:kJF2pamtYCWXf0xAT8sAkwKC0pMl2HYBrRPHAqyUc+g= github.com/Microsoft/go-winio v0.6.4/go.mod h1:1xl5JXG4ze/m74GH6Dc4Mwxfc3VL5siRVQjIAlHH07U= +github.com/dsnet/compress v0.0.0-20171208185109-cc9eb1d7ad76 h1:eX+pdPPlD279OWgdx7f6KqIRSONuK7egk+jDx7OM3Ac= +github.com/dsnet/compress v0.0.0-20171208185109-cc9eb1d7ad76/go.mod h1:KjxHHirfLaw19iGT70HvVjHQsL1vq1SRQB4yOsAfy2s= github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0= github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/gabstv/go-bsdiff v1.0.5 h1:g29MC/38Eaig+iAobW10/CiFvPtin8U3Jj4yNLcNG9k= +github.com/gabstv/go-bsdiff v1.0.5/go.mod h1:/Zz6GK+/f/TMylRtVaW3uwZlb0FZITILfA0q12XKGwg= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= diff --git a/internal/bsdiff/patch.go b/internal/bsdiff/patch.go new file mode 100644 index 000000000..63086111c --- /dev/null +++ b/internal/bsdiff/patch.go @@ -0,0 +1,124 @@ +// Package bsdiff applies bsdiff 4 patches. It reads the format +// github.com/gabstv/go-bsdiff (and Colin Percival's original bsdiff) writes: +// a "BSDIFF40" header and three bzip2 streams (control, diff and extra), with +// the standard library's bzip2 reader. +// +// The update package applies patches on the user's machine, so this file is +// deliberately the applier only: generation needs a suffix array and belongs +// in the release command (cmd/viva), which uses go-bsdiff for it. +package bsdiff + +import ( + "bytes" + "compress/bzip2" + "errors" + "fmt" + "io" +) + +// ErrPatch reports a patch that is malformed or does not fit the old data. +var ErrPatch = errors.New("bsdiff: invalid patch") + +// MaxOutput caps the size a patch may produce, so a corrupt or hostile header +// cannot make the caller allocate an arbitrary amount. Callers that know the +// size check it themselves too; this is the backstop. +const MaxOutput = 512 << 20 + +// Patch applies patch to old and returns the new data. +func Patch(old, patch []byte) ([]byte, error) { + if len(patch) < 32 || string(patch[:8]) != "BSDIFF40" { + return nil, fmt.Errorf("%w: not a BSDIFF40 patch", ErrPatch) + } + ctrlLen, err := offTin(patch[8:16]) + if err != nil { + return nil, err + } + diffLen, err := offTin(patch[16:24]) + if err != nil { + return nil, err + } + newSize, err := offTin(patch[24:32]) + if err != nil { + return nil, err + } + if ctrlLen < 0 || diffLen < 0 || newSize < 0 { + return nil, fmt.Errorf("%w: negative length", ErrPatch) + } + if newSize > MaxOutput { + return nil, fmt.Errorf("%w: output %d exceeds %d bytes", ErrPatch, newSize, MaxOutput) + } + endCtrl := 32 + int(ctrlLen) + endDiff := endCtrl + int(diffLen) + if int64(endDiff) > int64(len(patch)) || endCtrl < 32 || endDiff < endCtrl { + return nil, fmt.Errorf("%w: truncated streams", ErrPatch) + } + ctrl := bzip2.NewReader(bytes.NewReader(patch[32:endCtrl])) + diff := bzip2.NewReader(bytes.NewReader(patch[endCtrl:endDiff])) + extra := bzip2.NewReader(bytes.NewReader(patch[endDiff:])) + + out := make([]byte, newSize) + var oldPos, newPos int64 + var header [24]byte + for newPos < newSize { + if _, err := io.ReadFull(ctrl, header[:]); err != nil { + return nil, fmt.Errorf("%w: control stream: %v", ErrPatch, err) + } + x, err := offTin(header[0:8]) + if err != nil { + return nil, err + } + y, err := offTin(header[8:16]) + if err != nil { + return nil, err + } + z, err := offTin(header[16:24]) + if err != nil { + return nil, err + } + if x < 0 || y < 0 || x > newSize-newPos || y > newSize-newPos-x { + return nil, fmt.Errorf("%w: control triple out of range", ErrPatch) + } + if x == 0 && y == 0 && z == 0 { + return nil, fmt.Errorf("%w: control triple makes no progress", ErrPatch) + } + // The diff stream is added to the old data, byte by byte. Old + // positions outside the old file read as zero. + scratch := make([]byte, x) + if _, err := io.ReadFull(diff, scratch); err != nil { + return nil, fmt.Errorf("%w: diff stream: %v", ErrPatch, err) + } + for i := int64(0); i < x; i++ { + var base byte + if at := oldPos + i; at >= 0 && at < int64(len(old)) { + base = old[at] + } + out[newPos+i] = base + scratch[i] + } + newPos += x + oldPos += x + if y > 0 { + if _, err := io.ReadFull(extra, out[newPos:newPos+y]); err != nil { + return nil, fmt.Errorf("%w: extra stream: %v", ErrPatch, err) + } + newPos += y + } + oldPos += z + } + return out, nil +} + +// offTin reads a signed 64-bit value the way bsdiff writes it: seven +// little-endian bytes, the sign in the high bit of the eighth. +func offTin(b []byte) (int64, error) { + if len(b) < 8 { + return 0, fmt.Errorf("%w: short integer", ErrPatch) + } + value := int64(b[7] & 0x7f) + for i := 6; i >= 0; i-- { + value = value<<8 | int64(b[i]) + } + if b[7]&0x80 != 0 { + value = -value + } + return value, nil +} diff --git a/internal/bsdiff/patch_test.go b/internal/bsdiff/patch_test.go new file mode 100644 index 000000000..ee89b41da --- /dev/null +++ b/internal/bsdiff/patch_test.go @@ -0,0 +1,87 @@ +package bsdiff + +import ( + "bytes" + "errors" + "math/rand" + "testing" + + "github.com/gabstv/go-bsdiff/pkg/bsdiff" +) + +func TestPatchRoundTrip(t *testing.T) { + cases := map[string][2][]byte{ + "identical": {bytes.Repeat([]byte("same"), 1000), bytes.Repeat([]byte("same"), 1000)}, + "empty old": {nil, []byte("brand new content")}, + "both empty": {nil, nil}, + "insertion": {bytes.Repeat([]byte("abcdefgh"), 5000), append(bytes.Repeat([]byte("abcdefgh"), 2500), append([]byte("middle"), bytes.Repeat([]byte("abcdefgh"), 2500)...)...)}, + "deletion": {append(bytes.Repeat([]byte("abcdefgh"), 2500), append([]byte("gone"), bytes.Repeat([]byte("abcdefgh"), 2500)...)...), bytes.Repeat([]byte("abcdefgh"), 5000)}, + } + for name, data := range cases { + patch, err := bsdiff.Bytes(data[0], data[1]) + if err != nil { + t.Fatalf("%s: diff: %v", name, err) + } + got, err := Patch(data[0], patch) + if err != nil { + t.Fatalf("%s: patch: %v", name, err) + } + if !bytes.Equal(got, data[1]) { + t.Errorf("%s: patched data differs from the new data", name) + } + } +} + +func TestPatchRandomData(t *testing.T) { + rng := rand.New(rand.NewSource(1)) + old := make([]byte, 64<<10) + rng.Read(old) + fresh := make([]byte, len(old)) + copy(fresh, old) + copy(fresh[1000:], []byte("a changed stretch of bytes")) + patch, err := bsdiff.Bytes(old, fresh) + if err != nil { + t.Fatal(err) + } + got, err := Patch(old, patch) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, fresh) { + t.Fatal("patched data differs from the new data") + } +} + +func TestPatchRefusesBadInput(t *testing.T) { + old := []byte("hello") + patch, err := bsdiff.Bytes(old, []byte("hello world")) + if err != nil { + t.Fatal(err) + } + tests := map[string]struct { + old, patch []byte + }{ + "not a patch": {old, []byte("not a bsdiff patch at all")}, + "truncated": {old, patch[:len(patch)/2]}, + "truncated head": {old, patch[:20]}, + } + for name, test := range tests { + if _, err := Patch(test.old, test.patch); err == nil { + t.Errorf("%s: patch accepted", name) + } + } +} + +func TestPatchRefusesAHostileSize(t *testing.T) { + patch := make([]byte, 32) + copy(patch, "BSDIFF40") + // newSize is the third off_t: seven little-endian bytes and a sign. + patch[24+0] = 0xff + patch[24+1] = 0xff + patch[24+2] = 0xff + patch[24+3] = 0xff + patch[24+4] = 0x7f + if _, err := Patch(nil, patch); !errors.Is(err, ErrPatch) { + t.Fatalf("err = %v, want ErrPatch", err) + } +} diff --git a/tools/patchgen/patchgen.go b/tools/patchgen/patchgen.go new file mode 100644 index 000000000..f42168570 --- /dev/null +++ b/tools/patchgen/patchgen.go @@ -0,0 +1,410 @@ +// Package patchgen writes a delta update between two released payloads: the +// installed .app bundle on macOS, or the executable a Linux tar.gz installs. +// +// 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 +// user's application, only applies patches. +package patchgen + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/gabstv/go-bsdiff/pkg/bsdiff" + "github.com/vivaui/viva/update" +) + +// Request is one patch to write. +type Request struct { + App string + FromVersion string + ToVersion string + OS string + Arch string + // OldArchive and NewArchive are the released archives: the previous + // version and the one the feed lists. + OldArchive string + NewArchive string + // Executable is the program's file name in a Linux archive. Empty finds + // the only executable in it. + Executable string + // Output receives the gzip tar patch. + Output io.Writer +} + +// Write makes the patch and returns its manifest. +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.Arch != "amd64" && request.Arch != "arm64" { + return update.PatchManifest{}, fmt.Errorf("patchgen: architecture %q must be amd64 or arm64", request.Arch) + } + oldPayload, oldKind, cleanupOld, err := extractPayload(request.OldArchive, request.OS, request.Arch, request.Executable) + if err != nil { + return update.PatchManifest{}, fmt.Errorf("patchgen: old release: %w", err) + } + defer cleanupOld() + newPayload, newKind, cleanupNew, err := extractPayload(request.NewArchive, request.OS, request.Arch, request.Executable) + if err != nil { + return update.PatchManifest{}, fmt.Errorf("patchgen: new release: %w", err) + } + defer cleanupNew() + if oldKind != newKind { + return update.PatchManifest{}, fmt.Errorf("patchgen: the two archives hold different payloads (%s and %s)", oldKind, newKind) + } + manifest := update.PatchManifest{ + Schema: update.PatchSchema, App: request.App, + FromVersion: request.FromVersion, ToVersion: request.ToVersion, + OS: request.OS, Arch: request.Arch, Payload: newKind, + } + + oldFiles, err := readFiles(oldPayload) + if err != nil { + return update.PatchManifest{}, err + } + newFiles, err := readFiles(newPayload) + if err != nil { + return update.PatchManifest{}, err + } + names := make([]string, 0, len(newFiles)) + for name := range newFiles { + names = append(names, name) + } + sort.Strings(names) + + var blobs []blob + for _, name := range names { + file := newFiles[name] + old, existed := oldFiles[name] + entry := update.PatchFile{ + Path: name, Mode: uint32(file.mode.Perm()), Size: int64(len(file.data)), + SHA256: digest(file.data), + } + switch { + case existed && bytes.Equal(old.data, file.data): + entry.Op = "same" + case existed: + patch, err := bsdiff.Bytes(old.data, file.data) + if err != nil { + return update.PatchManifest{}, fmt.Errorf("patchgen: diffing %s: %w", name, err) + } + entry.Op, entry.Blob = "diff", blobName(len(blobs)+1) + blobs = append(blobs, blob{name: entry.Blob, data: patch}) + default: + entry.Op, entry.Blob = "new", blobName(len(blobs)+1) + blobs = append(blobs, blob{name: entry.Blob, data: file.data}) + } + manifest.Files = append(manifest.Files, entry) + } + if len(manifest.Files) == 0 { + return update.PatchManifest{}, fmt.Errorf("patchgen: the new payload holds no files") + } + if err := writePatch(request.Output, manifest, blobs); err != nil { + return update.PatchManifest{}, err + } + return manifest, nil +} + +type fileData struct { + data []byte + mode os.FileMode +} + +type blob struct { + name string + data []byte +} + +func blobName(index int) string { return fmt.Sprintf("files/%04d", index) } + +func digest(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +func readFiles(root string) (map[string]fileData, error) { + files := make(map[string]fileData) + err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() { + return nil + } + info, err := entry.Info() + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return fmt.Errorf("patchgen: %s is not a regular file", path) + } + relative, err := filepath.Rel(root, path) + if err != nil { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + files[filepath.ToSlash(relative)] = fileData{data: data, mode: info.Mode()} + return nil + }) + return files, err +} + +func writePatch(output io.Writer, manifest update.PatchManifest, blobs []blob) error { + encoded, err := json.Marshal(manifest) + if err != nil { + return err + } + gz := gzip.NewWriter(output) + writer := tar.NewWriter(gz) + now := time.Unix(0, 0).UTC() + writeEntry := func(name string, data []byte) error { + header := &tar.Header{Name: name, Mode: 0o644, Size: int64(len(data)), Typeflag: tar.TypeReg, ModTime: now} + if err := writer.WriteHeader(header); err != nil { + return err + } + _, err := writer.Write(data) + return err + } + if err := writeEntry("patch.json", encoded); err != nil { + return err + } + for _, item := range blobs { + if err := writeEntry(item.name, item.data); err != nil { + return err + } + } + if err := writer.Close(); err != nil { + return err + } + return gz.Close() +} + +// extractPayload unpacks archive and returns the payload root: the .app +// directory for darwin, or a directory holding just the executable for linux. +// The cleanup function removes the temporary tree. +func extractPayload(archive, goos, arch, executable string) (root, kind string, cleanup func(), err error) { + directory, err := os.MkdirTemp("", "viva-patchgen-") + if err != nil { + return "", "", nil, err + } + removeTree := func() { _ = os.RemoveAll(directory) } + switch goos { + case "darwin": + if !strings.HasSuffix(strings.ToLower(archive), ".zip") { + removeTree() + return "", "", nil, fmt.Errorf("patchgen: macOS payloads come from a .zip, not %s", filepath.Base(archive)) + } + if err := extractZip(archive, directory); err != nil { + removeTree() + return "", "", nil, err + } + bundles, err := filepath.Glob(filepath.Join(directory, "*.app")) + if err != nil || len(bundles) != 1 { + removeTree() + return "", "", nil, fmt.Errorf("patchgen: %s does not hold exactly one .app", filepath.Base(archive)) + } + if _, err := os.Stat(filepath.Join(bundles[0], "Contents", "MacOS")); err != nil { + removeTree() + return "", "", nil, fmt.Errorf("patchgen: %s is not a macOS bundle", filepath.Base(archive)) + } + return bundles[0], "app", removeTree, nil + default: + if !strings.HasSuffix(strings.ToLower(archive), ".tar.gz") { + removeTree() + return "", "", nil, fmt.Errorf("patchgen: Linux payloads come from a .tar.gz, not %s", filepath.Base(archive)) + } + if err := extractTarGz(archive, directory); err != nil { + removeTree() + return "", "", nil, err + } + program, err := findExecutable(directory, executable) + if err != nil { + removeTree() + return "", "", nil, err + } + programRoot, err := os.MkdirTemp("", "viva-patchgen-payload-") + if err != nil { + removeTree() + return "", "", nil, err + } + target := filepath.Join(programRoot, filepath.Base(program)) + if err := copyFile(program, target); err != nil { + os.RemoveAll(programRoot) + removeTree() + return "", "", nil, err + } + return programRoot, "file", func() { os.RemoveAll(programRoot); removeTree() }, nil + } +} + +// findExecutable finds the program in an unpacked Linux archive. A named +// executable wins; otherwise the archive must hold one executable besides +// install.sh. +func findExecutable(root, name string) (string, error) { + var named, candidates []string + err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + info, err := entry.Info() + if err != nil { + return err + } + if !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 || entry.Name() == "install.sh" { + return nil + } + if name != "" && entry.Name() == name { + named = append(named, path) + } + candidates = append(candidates, path) + return nil + }) + if err != nil { + return "", err + } + if len(named) == 1 { + return named[0], nil + } + if name == "" && len(candidates) == 1 { + return candidates[0], nil + } + if len(candidates) == 0 { + return "", fmt.Errorf("patchgen: the archive holds no executable") + } + return "", fmt.Errorf("patchgen: the archive holds %d executables; name one with the manifest's executable", len(candidates)) +} + +func copyFile(source, destination string) error { + data, err := os.ReadFile(source) + if err != nil { + return err + } + return os.WriteFile(destination, data, 0o755) +} + +// extractZip unpacks a zip, refusing absolute paths and entries that climb +// out of destination. +func extractZip(archive, destination string) error { + reader, err := zip.OpenReader(archive) + if err != nil { + return err + } + defer reader.Close() + for _, file := range reader.File { + target, err := safeJoin(destination, file.Name) + if err != nil { + return err + } + if file.FileInfo().IsDir() { + if err := os.MkdirAll(target, 0o755); err != nil { + return err + } + continue + } + if !file.Mode().IsRegular() { + return fmt.Errorf("patchgen: %s is not a regular file", file.Name) + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + source, err := file.Open() + if err != nil { + return err + } + output, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode().Perm()) + if err != nil { + source.Close() + return err + } + _, copyErr := io.Copy(output, source) + source.Close() + closeErr := output.Close() + if copyErr != nil { + return copyErr + } + if closeErr != nil { + return closeErr + } + } + return nil +} + +// extractTarGz unpacks a tar.gz, refusing absolute paths and entries that +// climb out of destination. +func extractTarGz(archive, destination string) error { + file, err := os.Open(archive) + if err != nil { + return err + } + defer file.Close() + gz, err := gzip.NewReader(file) + if err != nil { + return err + } + defer gz.Close() + reader := tar.NewReader(gz) + for { + header, err := reader.Next() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + target, err := safeJoin(destination, header.Name) + if err != nil { + return err + } + switch header.Typeflag { + case tar.TypeDir: + if err := os.MkdirAll(target, 0o755); err != nil { + return err + } + case tar.TypeReg: + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + output, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode)&0o777) + if err != nil { + return err + } + _, copyErr := io.Copy(output, reader) + closeErr := output.Close() + if copyErr != nil { + return copyErr + } + if closeErr != nil { + return closeErr + } + default: + return fmt.Errorf("patchgen: %s is not a regular file or directory", header.Name) + } + } +} + +func safeJoin(root, name string) (string, error) { + clean := filepath.Clean(filepath.FromSlash(name)) + if filepath.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) { + return "", fmt.Errorf("patchgen: %q escapes the archive", name) + } + return filepath.Join(root, clean), nil +} diff --git a/tools/patchgen/patchgen_test.go b/tools/patchgen/patchgen_test.go new file mode 100644 index 000000000..452793a86 --- /dev/null +++ b/tools/patchgen/patchgen_test.go @@ -0,0 +1,178 @@ +package patchgen + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "os" + "path/filepath" + "testing" + + "github.com/vivaui/viva/update" +) + +func writeTarGz(t *testing.T, path, root string, files map[string][]byte) { + t.Helper() + var encoded bytes.Buffer + gz := gzip.NewWriter(&encoded) + writer := tar.NewWriter(gz) + for name, data := range files { + header := &tar.Header{Name: root + "/" + name, Mode: 0o755, Size: int64(len(data)), Typeflag: tar.TypeReg} + if err := writer.WriteHeader(header); err != nil { + t.Fatal(err) + } + if _, err := writer.Write(data); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, encoded.Bytes(), 0o644); err != nil { + t.Fatal(err) + } +} + +func writeZip(t *testing.T, path string, files map[string][]byte) { + t.Helper() + var encoded bytes.Buffer + writer := zip.NewWriter(&encoded) + for name, data := range files { + file, err := writer.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := file.Write(data); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, encoded.Bytes(), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestWriteLinuxPatch(t *testing.T) { + dir := t.TempDir() + oldArchive := filepath.Join(dir, "app-1.0.0-linux-amd64.tar.gz") + newArchive := filepath.Join(dir, "app-1.1.0-linux-amd64.tar.gz") + writeTarGz(t, oldArchive, "app-1.0.0-linux-amd64", map[string][]byte{ + "app": []byte("the old program, with a fair amount of content"), + "install.sh": []byte("#!/bin/sh\n"), + }) + writeTarGz(t, newArchive, "app-1.1.0-linux-amd64", map[string][]byte{ + "app": []byte("the new program, with a fair amount of content and more"), + "install.sh": []byte("#!/bin/sh\n"), + }) + 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: "linux", Arch: "amd64", OldArchive: oldArchive, NewArchive: newArchive, + Executable: "app", Output: file, + }) + file.Close() + if err != nil { + t.Fatal(err) + } + if manifest.Payload != "file" || len(manifest.Files) != 1 || manifest.Files[0].Path != "app" { + t.Fatalf("manifest = %+v", manifest) + } + patch, err := update.ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + defer patch.Close() + oldRoot := t.TempDir() + if err := os.WriteFile(filepath.Join(oldRoot, "app"), []byte("the old program, with a fair amount of content"), 0o755); 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")) + if err != nil { + t.Fatal(err) + } + if string(got) != "the new program, with a fair amount of content and more" { + t.Fatalf("patched program = %q", got) + } +} + +func TestWriteDarwinPatch(t *testing.T) { + dir := t.TempDir() + oldArchive := filepath.Join(dir, "app-1.0.0-darwin-arm64.zip") + newArchive := filepath.Join(dir, "app-1.1.0-darwin-arm64.zip") + writeZip(t, oldArchive, map[string][]byte{ + "App.app/Contents/MacOS/app": []byte("old executable"), + "App.app/Contents/Info.plist": []byte("1.0.0"), + }) + writeZip(t, newArchive, map[string][]byte{ + "App.app/Contents/MacOS/app": []byte("new executable with more"), + "App.app/Contents/Info.plist": []byte("1.1.0"), + "App.app/Contents/Resources/added.txt": []byte("added"), + }) + 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: "darwin", Arch: "arm64", OldArchive: oldArchive, NewArchive: newArchive, Output: file, + }) + file.Close() + if err != nil { + t.Fatal(err) + } + if manifest.Payload != "app" || len(manifest.Files) != 3 { + t.Fatalf("manifest = %+v", manifest) + } + patch, err := update.ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + defer patch.Close() + oldRoot := t.TempDir() + for name, data := range map[string][]byte{ + "Contents/MacOS/app": []byte("old executable"), + "Contents/Info.plist": []byte("1.0.0"), + } { + path := filepath.Join(oldRoot, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0o644); err != nil { + t.Fatal(err) + } + } + staging := filepath.Join(dir, "staged") + if err := patch.Apply(oldRoot, staging); err != nil { + t.Fatal(err) + } + if data, err := os.ReadFile(filepath.Join(staging, "Contents", "Resources", "added.txt")); err != nil || string(data) != "added" { + t.Fatalf("added file = %q, %v", data, err) + } +} + +func TestWriteRefusesUnsupportedTargets(t *testing.T) { + for _, request := range []Request{ + {App: "app", FromVersion: "1.0.0", ToVersion: "1.1.0", OS: "windows", Arch: "amd64"}, + {App: "app", FromVersion: "1.0.0", ToVersion: "1.1.0", OS: "linux", Arch: "386"}, + {App: "", FromVersion: "1.0.0", ToVersion: "1.1.0", OS: "linux", Arch: "amd64"}, + } { + if _, err := Write(request); err == nil { + t.Errorf("Write(%+v) accepted", request) + } + } +} diff --git a/update/copy.go b/update/copy.go new file mode 100644 index 000000000..f0bb1980d --- /dev/null +++ b/update/copy.go @@ -0,0 +1,60 @@ +package update + +import ( + "fmt" + "io" + "os" + "path/filepath" +) + +// copyTree copies the regular files and directories under source into +// destination, which is created. Links, devices and other entries are refused: +// a payload is made of files a patch wrote. +func copyTree(source, destination string) error { + return filepath.WalkDir(source, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + relative, err := filepath.Rel(source, path) + if err != nil { + return err + } + target := filepath.Join(destination, relative) + info, err := entry.Info() + if err != nil { + return err + } + switch { + case entry.IsDir(): + return os.MkdirAll(target, info.Mode().Perm()|0o700) + case info.Mode().IsRegular(): + return copyRegularFile(path, target, info.Mode().Perm()) + default: + return fmt.Errorf("%w: %s is not a regular file or directory", ErrUnsafeArchive, path) + } + }) +} + +// copyRegularFile copies source to destination, which is created with mode. +func copyRegularFile(source, destination string, mode os.FileMode) error { + in, err := os.Open(source) + if err != nil { + return err + } + defer in.Close() + if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil { + return err + } + out, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + return err + } + if err := out.Close(); err != nil { + return err + } + return os.Chmod(destination, mode) +} diff --git a/update/doc.go b/update/doc.go index fb040d301..5025c1b61 100644 --- a/update/doc.go +++ b/update/doc.go @@ -31,8 +31,17 @@ // // It does not show a dialog, decide whether updating is allowed, check on a // timer, or stage a release. The application decides when to call Check, what -// to ask, and when to call Download and Install. It also does not do delta -// updates: a download is the complete archive the feed lists. +// to ask, and when to call Download and Install. +// +// # Delta updates +// +// A feed may list patches for an asset, each between an earlier version's +// 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. // // # Installing // diff --git a/update/download.go b/update/download.go index 24e6c9aa0..0d0fe95ec 100644 --- a/update/download.go +++ b/update/download.go @@ -34,13 +34,38 @@ func (client *Client) Download(ctx context.Context, asset Asset, dir string, pro if asset.Size > client.maxAsset { return "", fmt.Errorf("%w: archive is %d bytes, limit is %d", ErrTooLarge, asset.Size, client.maxAsset) } - if asset.Size >= math.MaxInt64 { - return "", fmt.Errorf("%w: archive is %d bytes", ErrTooLarge, asset.Size) + return client.download(ctx, asset.URL, asset.Size, asset.SHA256, assetFileName(asset), dir, progress) +} + +// DownloadPatch streams a delta update into dir and returns the patch file's +// path. It checks the bytes exactly as Download does, against the size and +// SHA-256 the signed feed declared for the patch. The patch is not applied +// here: ReadPatch and PatchReader.Apply do that, after the caller has checked the +// patch names the running application and version. +func (client *Client) DownloadPatch(ctx context.Context, asset Asset, patch Patch, dir string, progress func(done, total int64)) (string, error) { + if err := asset.validate(); err != nil { + return "", fmt.Errorf("%w: %w", ErrManifest, err) + } + if err := patch.validate(); err != nil { + return "", fmt.Errorf("%w: %w", ErrManifest, err) + } + if patch.Size > client.maxAsset { + return "", fmt.Errorf("%w: patch is %d bytes, limit is %d", ErrTooLarge, patch.Size, client.maxAsset) + } + name := assetFileName(asset) + "." + patch.FromVersion + ".patch" + return client.download(ctx, patch.URL, patch.Size, patch.SHA256, name, dir, progress) +} + +// download fetches one file and keeps it only when its length and digest are +// the declared ones. +func (client *Client) download(ctx context.Context, rawURL string, size int64, digest string, name, dir string, progress func(done, total int64)) (string, error) { + if size >= math.MaxInt64 { + return "", fmt.Errorf("%w: file is %d bytes", ErrTooLarge, size) } if err := os.MkdirAll(dir, 0o755); err != nil { return "", fmt.Errorf("update: %w", err) } - request, err := http.NewRequestWithContext(ctx, http.MethodGet, asset.URL, nil) + request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) if err != nil { return "", fmt.Errorf("update: %w", err) } @@ -51,55 +76,55 @@ func (client *Client) Download(ctx context.Context, asset Asset, dir string, pro } defer response.Body.Close() if response.Request != nil && response.Request.URL != nil && response.Request.URL.Scheme != "https" { - return "", fmt.Errorf("%w: %s redirected to %s", ErrInsecureURL, asset.URL, response.Request.URL) + return "", fmt.Errorf("%w: %s redirected to %s", ErrInsecureURL, rawURL, response.Request.URL) } if response.StatusCode != http.StatusOK { - return "", fmt.Errorf("update: %s: %s", asset.URL, response.Status) + return "", fmt.Errorf("update: %s: %s", rawURL, response.Status) } file, err := os.CreateTemp(dir, ".viva-update-*") if err != nil { return "", fmt.Errorf("update: %w", err) } - name := file.Name() + temporary := file.Name() keep := false defer func() { _ = file.Close() if !keep { - _ = os.Remove(name) + _ = os.Remove(temporary) } }() hasher := sha256.New() writer := io.MultiWriter(file, hasher) if progress != nil { - progress(0, asset.Size) + progress(0, size) } - counter := &progressWriter{writer: writer, total: asset.Size, progress: progress} - written, err := io.Copy(counter, io.LimitReader(response.Body, asset.Size+1)) + counter := &progressWriter{writer: writer, total: size, progress: progress} + written, err := io.Copy(counter, io.LimitReader(response.Body, size+1)) if err != nil { - return "", fmt.Errorf("update: reading %s: %w", asset.URL, err) + return "", fmt.Errorf("update: reading %s: %w", rawURL, err) } - if written != asset.Size { - return "", fmt.Errorf("%w: got %d bytes, feed declares %d", ErrSize, written, asset.Size) + if written != size { + return "", fmt.Errorf("%w: got %d bytes, feed declares %d", ErrSize, written, size) } if err := file.Close(); err != nil { return "", fmt.Errorf("update: %w", err) } - digest := hex.EncodeToString(hasher.Sum(nil)) - if !strings.EqualFold(digest, asset.SHA256) { - return "", fmt.Errorf("%w: %s", ErrChecksum, digest) + sum := hex.EncodeToString(hasher.Sum(nil)) + if !strings.EqualFold(sum, digest) { + return "", fmt.Errorf("%w: %s", ErrChecksum, sum) } - if err := os.Chmod(name, 0o644); err != nil { + if err := os.Chmod(temporary, 0o644); err != nil { return "", fmt.Errorf("update: %w", err) } - destination := filepath.Join(dir, assetFileName(asset)) - if err := os.Rename(name, destination); err != nil { + destination := filepath.Join(dir, name) + if err := os.Rename(temporary, destination); err != nil { return "", fmt.Errorf("update: %w", err) } keep = true if progress != nil { - progress(asset.Size, asset.Size) + progress(size, size) } return destination, nil } diff --git a/update/download_test.go b/update/download_test.go index 513cf7a9d..969176ea1 100644 --- a/update/download_test.go +++ b/update/download_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "strings" "testing" ) @@ -206,3 +207,66 @@ func TestAssetFileNameRefusesAPathFromTheURL(t *testing.T) { } } } + +func TestDownloadPatchWritesTheVerifiedFile(t *testing.T) { + content := []byte("a delta between two versions") + server, client := downloadFixture(t, content) + asset := testAsset(server, []byte("the full archive")) + patch := Patch{ + FromVersion: "0.9.0", URL: server.URL + "/downloads/app.patch", + Size: int64(len(content)), SHA256: testDigest(string(content)), + } + asset.Patches = []Patch{patch} + dir := t.TempDir() + path, err := client.DownloadPatch(context.Background(), asset, patch, dir, nil) + if err != nil { + t.Fatal(err) + } + if filepath.Base(path) != "app.zip.0.9.0.patch" { + t.Errorf("file name = %q", filepath.Base(path)) + } + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(got) != string(content) { + t.Errorf("patch = %q", got) + } +} + +func TestDownloadPatchRefusesTheWrongBytes(t *testing.T) { + content := []byte("the patch's bytes") + server, client := downloadFixture(t, content) + asset := testAsset(server, []byte("the full archive")) + patch := Patch{ + FromVersion: "0.9.0", URL: server.URL + "/app.patch", + Size: int64(len(content)), SHA256: strings.Repeat("0", 64), + } + asset.Patches = []Patch{patch} + dir := t.TempDir() + if _, err := client.DownloadPatch(context.Background(), asset, patch, dir, nil); !errors.Is(err, ErrChecksum) { + t.Fatalf("err = %v, want ErrChecksum", err) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 0 { + t.Errorf("a refused patch left %d files", len(entries)) + } + patch.SHA256 = testDigest(string(content)) + patch.Size++ + if _, err := client.DownloadPatch(context.Background(), asset, patch, dir, nil); !errors.Is(err, ErrSize) { + t.Fatalf("err = %v, want ErrSize", err) + } +} + +func TestDownloadPatchRefusesPlaintext(t *testing.T) { + content := []byte("patch") + server, client := downloadFixture(t, content) + asset := testAsset(server, []byte("the full archive")) + patch := Patch{ + FromVersion: "0.9.0", URL: "http://example.com/app.patch", + Size: int64(len(content)), SHA256: testDigest(string(content)), + } + if _, err := client.DownloadPatch(context.Background(), asset, patch, t.TempDir(), nil); !errors.Is(err, ErrInsecureURL) { + t.Fatalf("err = %v, want ErrInsecureURL", err) + } +} diff --git a/update/install.go b/update/install.go index 5ccf93aa0..350487392 100644 --- a/update/install.go +++ b/update/install.go @@ -34,8 +34,15 @@ var ( // Artifact and Asset come from Client.Check and Client.Download; an application // must not build them from somewhere else. type InstallOptions struct { - // Artifact is the file Download returned. + // Artifact is the file Download returned. Exactly one of Artifact and + // Payload is set. Artifact string + // Payload is a new application the caller already made with PatchReader.Apply: + // the staged .app on macOS, or the staged executable on Linux. Install + // replaces the running application with it exactly as it would with an + // unpacked archive, running the same checks. Windows has no patch support, + // so a payload there reports ErrUnsupported. + Payload string // Asset is the archive it came from. Its Format tells Install how to unpack // it, and the format must suit the running platform. Asset Asset @@ -74,31 +81,41 @@ func Install(options InstallOptions, quit func()) error { } func (options InstallOptions) validate() error { - if options.Artifact == "" { - return fmt.Errorf("update: install needs the downloaded artifact") + if (options.Artifact == "") == (options.Payload == "") { + return fmt.Errorf("update: install needs exactly one of the downloaded artifact and a staged payload") } - info, err := os.Lstat(options.Artifact) - if err != nil { - return fmt.Errorf("update: %w", err) - } - if info.Mode()&os.ModeSymlink != 0 { - return fmt.Errorf("%w: %s is a link", ErrManifest, options.Artifact) - } - if !info.Mode().IsRegular() { - return fmt.Errorf("%w: %s is not a regular file", ErrManifest, options.Artifact) - } - // Download verified these bytes, but the file sits on disk between the two - // calls. Hash it again at the moment it is about to be installed. - if options.Asset.Size > 0 && info.Size() != options.Asset.Size { - return fmt.Errorf("%w: %s is %d bytes, the feed declared %d", ErrSize, options.Artifact, info.Size(), options.Asset.Size) - } - if len(options.Asset.SHA256) == 64 { - digest, err := fileSHA256(options.Artifact) + if options.Payload != "" { + info, err := os.Lstat(options.Payload) + if err != nil { + return fmt.Errorf("update: %w", err) + } + if info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("%w: %s is a link", ErrManifest, options.Payload) + } + } else { + info, err := os.Lstat(options.Artifact) if err != nil { return fmt.Errorf("update: %w", err) } - if !strings.EqualFold(digest, options.Asset.SHA256) { - return fmt.Errorf("%w: %s", ErrChecksum, options.Artifact) + if info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("%w: %s is a link", ErrManifest, options.Artifact) + } + if !info.Mode().IsRegular() { + return fmt.Errorf("%w: %s is not a regular file", ErrManifest, options.Artifact) + } + // Download verified these bytes, but the file sits on disk between the two + // calls. Hash it again at the moment it is about to be installed. + if options.Asset.Size > 0 && info.Size() != options.Asset.Size { + return fmt.Errorf("%w: %s is %d bytes, the feed declared %d", ErrSize, options.Artifact, info.Size(), options.Asset.Size) + } + if len(options.Asset.SHA256) == 64 { + digest, err := fileSHA256(options.Artifact) + if err != nil { + return fmt.Errorf("update: %w", err) + } + if !strings.EqualFold(digest, options.Asset.SHA256) { + return fmt.Errorf("%w: %s", ErrChecksum, options.Artifact) + } } } if options.Version == "" { diff --git a/update/install_darwin.go b/update/install_darwin.go index ebf75255a..7e37d68a1 100644 --- a/update/install_darwin.go +++ b/update/install_darwin.go @@ -57,11 +57,20 @@ func install(options InstallOptions, quit func()) error { } }() - options.report("unpacking") - if err := extractZip(options.Artifact, staging); err != nil { - return err + var staged string + if options.Payload != "" { + options.report("copying the patched application") + if err := copyTree(options.Payload, filepath.Join(staging, filepath.Base(options.Payload))); err != nil { + return err + } + staged, err = stagedBundle(staging) + } else { + options.report("unpacking") + if err := extractZip(options.Artifact, staging); err != nil { + return err + } + staged, err = stagedBundle(staging) } - staged, err := stagedBundle(staging) if err != nil { return err } diff --git a/update/install_linux.go b/update/install_linux.go index 6dd999272..edbf73e08 100644 --- a/update/install_linux.go +++ b/update/install_linux.go @@ -65,12 +65,35 @@ func install(options InstallOptions, quit func()) error { _ = os.RemoveAll(staging) } }() - if err := extractTarGz(options.Artifact, staging); err != nil { - return err - } - replacement, err := findProgram(staging, filepath.Base(executable)) - if err != nil { - return err + var replacement string + if options.Payload != "" { + options.report("copying the patched executable") + info, err := os.Lstat(options.Payload) + if err != nil { + return fmt.Errorf("update: %w", err) + } + program := options.Payload + if info.IsDir() { + program, err = findProgram(options.Payload, filepath.Base(executable)) + if err != nil { + return err + } + } else if !info.Mode().IsRegular() { + return fmt.Errorf("%w: the payload is not a regular file", ErrManifest) + } + replacement = filepath.Join(staging, filepath.Base(executable)) + if err := copyRegularFile(program, replacement, 0o755); err != nil { + return fmt.Errorf("update: copying the patched executable: %w", err) + } + } else { + options.report("unpacking") + if err := extractTarGz(options.Artifact, staging); err != nil { + return err + } + replacement, err = findProgram(staging, filepath.Base(executable)) + if err != nil { + return err + } } options.report("replacing") diff --git a/update/install_windows.go b/update/install_windows.go index da88d5ae3..21159c4b5 100644 --- a/update/install_windows.go +++ b/update/install_windows.go @@ -104,6 +104,9 @@ var ( // installed program. It returns only after quit, so the helper can wait for // 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) + } if options.Asset.Format != FormatNSIS { return fmt.Errorf("%w: windows needs an NSIS installer, not %q", ErrManifest, options.Asset.Format) } diff --git a/update/manifest.go b/update/manifest.go index e4dbf6ad7..2edd06b8a 100644 --- a/update/manifest.go +++ b/update/manifest.go @@ -70,6 +70,32 @@ type Asset struct { Size int64 `json:"size"` // SHA256 is the archive's lowercase hexadecimal SHA-256 digest. SHA256 string `json:"sha256"` + // Patches are updates from earlier versions, each a delta against the + // installed payload. A client that does not read them downloads the + // archive. + Patches []Patch `json:"patches,omitempty"` +} + +// Patch is one delta update for an asset. +type Patch struct { + // FromVersion is the installed version the patch applies to. + FromVersion string `json:"from_version"` + // URL is the HTTPS address of the patch file. + URL string `json:"url"` + // Size is the patch's exact length in bytes. + Size int64 `json:"size"` + // SHA256 is the patch's lowercase hexadecimal SHA-256 digest. + SHA256 string `json:"sha256"` +} + +// PatchFrom returns the patch that applies to version, if the feed offers one. +func (asset Asset) PatchFrom(version string) (Patch, bool) { + for _, patch := range asset.Patches { + if patch.FromVersion == version { + return patch, true + } + } + return Patch{}, false } // Asset returns the archive this feed offers for goos and goarch. When a @@ -194,6 +220,38 @@ func (asset Asset) validate() error { if _, err := hex.DecodeString(asset.SHA256); err != nil { return fmt.Errorf("sha256: %v", err) } + seenPatches := make(map[string]bool, len(asset.Patches)) + for _, patch := range asset.Patches { + if err := patch.validate(); err != nil { + return err + } + if seenPatches[patch.FromVersion] { + return fmt.Errorf("patches from %s appear twice", patch.FromVersion) + } + seenPatches[patch.FromVersion] = true + } + return nil +} + +func (patch Patch) validate() error { + if _, err := parseVersion(patch.FromVersion); err != nil { + return fmt.Errorf("patch from_version: %v", err) + } + if patch.FromVersion == "" { + return fmt.Errorf("patch from_version is empty") + } + if err := checkHTTPS(patch.URL); err != nil { + return fmt.Errorf("patch from %s: %w", patch.FromVersion, err) + } + if patch.Size <= 0 { + return fmt.Errorf("patch from %s: size must be positive", patch.FromVersion) + } + if len(patch.SHA256) != 64 || strings.ToLower(patch.SHA256) != patch.SHA256 { + return fmt.Errorf("patch from %s: sha256 must be 64 lowercase hexadecimal digits", patch.FromVersion) + } + if _, err := hex.DecodeString(patch.SHA256); err != nil { + return fmt.Errorf("patch from %s: sha256: %v", patch.FromVersion, err) + } return nil } diff --git a/update/manifest_test.go b/update/manifest_test.go index 4cbd31484..d2ca3e55d 100644 --- a/update/manifest_test.go +++ b/update/manifest_test.go @@ -165,3 +165,48 @@ func TestFeedWithoutExpiryNeverExpires(t *testing.T) { t.Fatalf("a feed with no expires: %v", err) } } + +func TestFeedAcceptsPatches(t *testing.T) { + feed := validFeed() + feed.Latest.Assets[0].Patches = []Patch{{ + FromVersion: "1.4.1", URL: "https://example.com/app.patch", + Size: 4096, SHA256: testDigest("patch"), + }} + if err := feed.validate(); err != nil { + t.Fatalf("valid feed: %v", err) + } + if patch, ok := feed.Latest.Assets[0].PatchFrom("1.4.1"); !ok || patch.FromVersion != "1.4.1" { + t.Fatalf("PatchFrom = %+v, %v", patch, ok) + } + if _, ok := feed.Latest.Assets[0].PatchFrom("1.4.0"); ok { + t.Error("PatchFrom found a patch for a version the feed does not offer") + } +} + +func TestFeedRefusesBadPatches(t *testing.T) { + valid := func() Patch { + return Patch{FromVersion: "1.4.1", URL: "https://example.com/app.patch", Size: 4096, SHA256: testDigest("patch")} + } + tests := map[string]func(*Patch){ + "plaintext": func(p *Patch) { p.URL = "http://example.com/app.patch" }, + "no digest": func(p *Patch) { p.SHA256 = "" }, + "uppercase": func(p *Patch) { p.SHA256 = strings.ToUpper(p.SHA256) }, + "zero size": func(p *Patch) { p.Size = 0 }, + "bad version": func(p *Patch) { p.FromVersion = "1.4" }, + "empty version": func(p *Patch) { p.FromVersion = "" }, + } + for name, change := range tests { + patch := valid() + change(&patch) + feed := validFeed() + feed.Latest.Assets[0].Patches = []Patch{patch} + if err := feed.validate(); !errors.Is(err, ErrManifest) { + t.Errorf("%s: err = %v, want ErrManifest", name, err) + } + } + feed := validFeed() + feed.Latest.Assets[0].Patches = []Patch{valid(), valid()} + if err := feed.validate(); !errors.Is(err, ErrManifest) { + t.Errorf("duplicate patches: err = %v, want ErrManifest", err) + } +} diff --git a/update/patch.go b/update/patch.go new file mode 100644 index 000000000..ccadac9ee --- /dev/null +++ b/update/patch.go @@ -0,0 +1,455 @@ +package update + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "os" + "path" + "path/filepath" + "runtime" + "strings" + + "github.com/vivaui/viva/internal/bsdiff" +) + +// PatchSchema is the only patch format this package reads. +const PatchSchema = 1 + +// patch limits, matching the archive limits in the feed: a patch is not a +// reason to trust a larger document or to fill the disk. +const ( + maxPatchManifest = 4 << 20 + maxPatchFile = 512 << 20 + maxPatchTotal = 2 << 30 +) + +// PatchFile is one file of a patch. Path is relative to the payload root and +// slash-separated. Op is "same" (the file is copied from the old payload), +// "diff" (the blob is a bsdiff against the old file) or "new" (the blob is the +// whole new file). +type PatchFile struct { + Path string `json:"path"` + Mode uint32 `json:"mode"` + Size int64 `json:"size"` + SHA256 string `json:"sha256"` + Op string `json:"op"` + Blob string `json:"blob,omitempty"` +} + +// PatchManifest describes a patch: what it applies to, from where, and every +// file the new payload holds. +type PatchManifest struct { + Schema int `json:"schema"` + App string `json:"app"` + FromVersion string `json:"from_version"` + 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 string `json:"payload"` + Files []PatchFile `json:"files"` +} + +// Patch is an open patch file. Its manifest is read; blobs are applied by +// Apply, which streams them, so a large patch is never held in memory whole. +type PatchReader struct { + manifest PatchManifest + source *tar.Reader + closer io.Closer + byBlob map[string]*PatchFile + done map[string]bool +} + +// ReadPatch opens path and reads its manifest. The caller must Close it. +func ReadPatch(path string) (*PatchReader, error) { + file, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("update: opening the patch: %w", err) + } + patch, err := newPatch(file) + if err != nil { + file.Close() + return nil, err + } + patch.closer = file + return patch, nil +} + +func newPatch(reader io.Reader) (*PatchReader, error) { + gz, err := gzip.NewReader(reader) + if err != nil { + return nil, fmt.Errorf("%w: the patch is not a gzip stream: %v", ErrManifest, err) + } + tarReader := tar.NewReader(gz) + header, err := tarReader.Next() + if err != nil { + return nil, fmt.Errorf("%w: the patch is empty: %v", ErrManifest, err) + } + if header.Name != "patch.json" || header.Typeflag != tar.TypeReg || header.Size > maxPatchManifest { + return nil, fmt.Errorf("%w: the patch does not start with patch.json", ErrManifest) + } + encoded, err := io.ReadAll(io.LimitReader(tarReader, maxPatchManifest+1)) + if err != nil { + return nil, fmt.Errorf("%w: reading patch.json: %v", ErrManifest, err) + } + var manifest PatchManifest + if err := json.Unmarshal(encoded, &manifest); err != nil { + return nil, fmt.Errorf("%w: patch.json: %v", ErrManifest, err) + } + if err := manifest.validate(); err != nil { + return nil, err + } + byBlob := make(map[string]*PatchFile, len(manifest.Files)) + for i := range manifest.Files { + file := &manifest.Files[i] + if file.Blob != "" { + byBlob[file.Blob] = file + } + } + return &PatchReader{manifest: manifest, source: tarReader, closer: gz, byBlob: byBlob, done: map[string]bool{}}, nil +} + +// Manifest returns the patch's description. +func (patch *PatchReader) Manifest() PatchManifest { return patch.manifest } + +// Close closes the patch file. +func (patch *PatchReader) Close() error { + if patch.closer != nil { + return patch.closer.Close() + } + return nil +} + +// Apply writes the new payload into staging, taking unchanged files from +// oldRoot. staging must not exist or must be empty; it is created here. The +// result is verified file by file; on error staging is removed, so a failed +// patch leaves nothing behind. +func (patch *PatchReader) Apply(oldRoot, staging string) error { + if info, statErr := os.Stat(staging); statErr == nil && (!info.IsDir() || !emptyDir(staging)) { + return fmt.Errorf("update: the staging directory %s is not empty", staging) + } + if err := os.MkdirAll(staging, 0o755); err != nil { + return fmt.Errorf("update: creating the staging directory: %w", err) + } + complete := false + defer func() { + if !complete { + _ = os.RemoveAll(staging) + } + }() + + // The files that need no blob are copied first; the tar reader waits at + // the next entry while this happens. + for i := range patch.manifest.Files { + file := &patch.manifest.Files[i] + if file.Op == "same" { + if err := patch.copySame(oldRoot, staging, file); err != nil { + return err + } + } + } + for { + header, err := patch.source.Next() + if err == io.EOF { + break + } + if err != nil { + return fmt.Errorf("%w: reading the patch: %v", ErrManifest, err) + } + if !strings.HasPrefix(header.Name, "files/") { + return fmt.Errorf("%w: unexpected entry %q", ErrManifest, header.Name) + } + file, ok := patch.byBlob[header.Name] + if !ok { + return fmt.Errorf("%w: blob %q is not in the manifest", ErrManifest, header.Name) + } + if header.Typeflag != tar.TypeReg || header.Size < 0 || header.Size > maxPatchFile { + return fmt.Errorf("%w: blob %q has an invalid size", ErrManifest, header.Name) + } + if patch.done[header.Name] { + return fmt.Errorf("%w: blob %q appears twice", ErrManifest, header.Name) + } + if err := patch.applyBlob(oldRoot, staging, file, io.LimitReader(patch.source, header.Size)); err != nil { + return err + } + patch.done[header.Name] = true + } + for i := range patch.manifest.Files { + file := &patch.manifest.Files[i] + if file.Op != "same" && !patch.done[file.Blob] { + return fmt.Errorf("%w: %s has no blob %q", ErrManifest, file.Path, file.Blob) + } + } + complete = true + return nil +} + +func (patch *PatchReader) copySame(oldRoot, staging string, file *PatchFile) error { + source := filepath.Join(oldRoot, filepath.FromSlash(file.Path)) + info, err := os.Lstat(source) + if err != nil { + return fmt.Errorf("%w: reading the old %s: %v", ErrManifest, file.Path, err) + } + if !info.Mode().IsRegular() { + return fmt.Errorf("%w: the installed %s is not a regular file", ErrManifest, file.Path) + } + return copyPatchFile(source, patchDestination(staging, file.Path), file, nil) +} + +func (patch *PatchReader) applyBlob(oldRoot, staging string, file *PatchFile, blob io.Reader) error { + destination := patchDestination(staging, file.Path) + switch file.Op { + case "new": + return copyPatchFile("", destination, file, blob) + case "diff": + encoded, err := io.ReadAll(io.LimitReader(blob, maxPatchFile)) + if err != nil { + return fmt.Errorf("%w: reading the patch for %s: %v", ErrManifest, file.Path, err) + } + oldPath := filepath.Join(oldRoot, filepath.FromSlash(file.Path)) + oldData, err := readRegularFile(oldPath, file.Path) + if err != nil { + return err + } + newData, err := bsdiff.Patch(oldData, encoded) + if err != nil { + return fmt.Errorf("%w: %s: %v", ErrManifest, file.Path, err) + } + if int64(len(newData)) != file.Size { + return fmt.Errorf("%w: %s is %d bytes, want %d", ErrChecksum, file.Path, len(newData), file.Size) + } + sum := sha256.Sum256(newData) + if hex.EncodeToString(sum[:]) != file.SHA256 { + return fmt.Errorf("%w: %s does not match its digest", ErrChecksum, file.Path) + } + if err := writeData(destination, newData, os.FileMode(file.Mode&0o777)); err != nil { + return fmt.Errorf("update: writing %s: %w", file.Path, err) + } + return nil + } + return fmt.Errorf("%w: %s has unknown op %q", ErrManifest, file.Path, file.Op) +} + +func readRegularFile(name, label string) ([]byte, error) { + info, err := os.Lstat(name) + if err != nil { + return nil, fmt.Errorf("%w: reading the old %s: %v", ErrManifest, label, err) + } + if !info.Mode().IsRegular() { + return nil, fmt.Errorf("%w: the installed %s is not a regular file", ErrManifest, label) + } + if info.Size() > maxPatchFile { + return nil, fmt.Errorf("%w: the installed %s is too large", ErrManifest, label) + } + data, err := os.ReadFile(name) + if err != nil { + return nil, fmt.Errorf("%w: reading the old %s: %v", ErrManifest, label, err) + } + return data, nil +} + +func patchDestination(staging, relative string) string { + return filepath.Join(staging, filepath.FromSlash(relative)) +} + +// copyPatchFile writes source (or blob when source is empty) to destination, +// hashing as it goes, and checks the result against the manifest. +func copyPatchFile(source, destination string, file *PatchFile, blob io.Reader) error { + var reader io.Reader = blob + var handle *os.File + if source != "" { + var err error + handle, err = os.Open(source) + if err != nil { + return fmt.Errorf("%w: reading the old %s: %v", ErrManifest, file.Path, err) + } + defer handle.Close() + reader = handle + } + digest := sha256.New() + written, err := writeStream(destination, io.TeeReader(reader, digest), os.FileMode(file.Mode&0o777)) + if err != nil { + return fmt.Errorf("update: writing %s: %w", file.Path, err) + } + if written != file.Size { + return fmt.Errorf("%w: %s is %d bytes, want %d", ErrChecksum, file.Path, written, file.Size) + } + if hex.EncodeToString(digest.Sum(nil)) != file.SHA256 { + return fmt.Errorf("%w: %s does not match its digest", ErrChecksum, file.Path) + } + return nil +} + +// writeStream writes reader to a file that is named only when it is complete. +func writeStream(name string, reader io.Reader, mode os.FileMode) (int64, error) { + if err := os.MkdirAll(filepath.Dir(name), 0o755); err != nil { + return 0, err + } + temporary, err := os.CreateTemp(filepath.Dir(name), "."+filepath.Base(name)+".viva-patch-*") + if err != nil { + return 0, err + } + path := temporary.Name() + defer os.Remove(path) + written, err := io.Copy(temporary, reader) + if err != nil { + temporary.Close() + return 0, err + } + if err := temporary.Chmod(mode); err != nil { + temporary.Close() + return 0, err + } + if err := temporary.Close(); err != nil { + return 0, err + } + if err := os.Rename(path, name); err != nil { + return 0, err + } + return written, nil +} + +func writeData(name string, data []byte, mode os.FileMode) error { + _, err := writeStream(name, bytes.NewReader(data), mode) + return err +} + +func (manifest PatchManifest) validate() error { + if manifest.Schema != PatchSchema { + return fmt.Errorf("%w: patch schema is %d, want %d", ErrManifest, manifest.Schema, PatchSchema) + } + if manifest.App == "" || manifest.FromVersion == "" || manifest.ToVersion == "" { + return fmt.Errorf("%w: the patch does not name the application and both versions", ErrManifest) + } + if _, err := Compare(manifest.FromVersion, manifest.FromVersion); err != nil { + return fmt.Errorf("%w: from_version: %v", ErrManifest, err) + } + 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) + } + if len(manifest.Files) == 0 { + return fmt.Errorf("%w: the patch holds no files", ErrManifest) + } + if len(manifest.Files) > 100000 { + return fmt.Errorf("%w: the patch holds too many files", ErrManifest) + } + seen := make(map[string]bool, len(manifest.Files)) + var total int64 + for i := range manifest.Files { + file := &manifest.Files[i] + clean, err := patchPath(file.Path) + if err != nil { + return err + } + if seen[clean] { + return fmt.Errorf("%w: %s appears twice", ErrManifest, clean) + } + seen[clean] = true + if file.Mode&^0o777 != 0 || file.Mode == 0 { + return fmt.Errorf("%w: %s has mode %o", ErrManifest, clean, file.Mode) + } + if file.Size < 0 || file.Size > maxPatchFile { + return fmt.Errorf("%w: %s has size %d", ErrManifest, clean, file.Size) + } + if len(file.SHA256) != 64 || strings.ToLower(file.SHA256) != file.SHA256 { + return fmt.Errorf("%w: %s has no lowercase SHA-256", ErrManifest, clean) + } + total += file.Size + if total > maxPatchTotal { + return fmt.Errorf("%w: the patched payload is larger than %d bytes", ErrManifest, int64(maxPatchTotal)) + } + switch file.Op { + case "same": + if file.Blob != "" { + return fmt.Errorf("%w: %s is same and has a blob", ErrManifest, clean) + } + case "diff", "new": + if file.Blob == "" || !strings.HasPrefix(file.Blob, "files/") || strings.Contains(file.Blob, "..") { + return fmt.Errorf("%w: %s has an invalid blob name", ErrManifest, clean) + } + default: + return fmt.Errorf("%w: %s has op %q", ErrManifest, clean, file.Op) + } + } + return nil +} + +// patchPath accepts a clean relative slash path inside the payload. +func patchPath(relative string) (string, error) { + if relative == "" || strings.HasPrefix(relative, "/") || strings.Contains(relative, "\\") || + strings.ContainsRune(relative, 0) || strings.Contains(relative, ":") { + return "", fmt.Errorf("%w: %q is not a relative path", ErrManifest, relative) + } + clean := path.Clean(relative) + if clean != relative || clean == "." || clean == ".." || strings.HasPrefix(clean, "../") { + return "", fmt.Errorf("%w: %q is not a clean relative path", ErrManifest, relative) + } + return clean, nil +} + +func emptyDir(dir string) bool { + entries, err := os.ReadDir(dir) + return err == nil && len(entries) == 0 +} + +// locateInstalledPayload is installedPayload, replaceable by tests. +var locateInstalledPayload = installedPayload + +// ApplyPatch applies a downloaded patch to the running application and returns +// a directory holding the new payload, ready for InstallOptions.Payload. app +// may be empty to skip the identity check; the versions, the operating system +// and the architecture the patch names must match. +// +// The installation is not touched: a staging directory is made, and the caller +// removes it when Install fails or is not called. +func ApplyPatch(patchPath, app, fromVersion, toVersion string) (string, error) { + patch, err := ReadPatch(patchPath) + if err != nil { + return "", err + } + defer patch.Close() + manifest := patch.Manifest() + if app != "" && manifest.App != app { + return "", fmt.Errorf("%w: the patch is for %q, not %q", ErrManifest, manifest.App, app) + } + if manifest.FromVersion != fromVersion { + return "", fmt.Errorf("%w: the patch updates from %s, not %s", ErrManifest, manifest.FromVersion, fromVersion) + } + if manifest.ToVersion != toVersion { + return "", fmt.Errorf("%w: the patch updates to %s, not %s", ErrManifest, manifest.ToVersion, toVersion) + } + if manifest.OS != runtime.GOOS || manifest.Arch != runtime.GOARCH { + return "", fmt.Errorf("%w: the patch is for %s/%s, not %s/%s", ErrManifest, manifest.OS, manifest.Arch, runtime.GOOS, runtime.GOARCH) + } + root, kind, err := locateInstalledPayload() + if err != nil { + return "", err + } + if kind != manifest.Payload { + return "", fmt.Errorf("%w: the patch carries a %s payload, but this installation is a %s", ErrManifest, manifest.Payload, kind) + } + staging, err := os.MkdirTemp("", "viva-payload-") + if err != nil { + return "", fmt.Errorf("update: creating the staging directory: %w", err) + } + if err := patch.Apply(root, staging); err != nil { + _ = os.RemoveAll(staging) + return "", err + } + return staging, nil +} diff --git a/update/patch_test.go b/update/patch_test.go new file mode 100644 index 000000000..f67b3ac55 --- /dev/null +++ b/update/patch_test.go @@ -0,0 +1,296 @@ +package update + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/gabstv/go-bsdiff/pkg/bsdiff" +) + +func digest(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +func writePatch(t *testing.T, manifest PatchManifest, blobs map[string][]byte) string { + t.Helper() + var encoded bytes.Buffer + gz := gzip.NewWriter(&encoded) + writer := tar.NewWriter(gz) + manifestData, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + entries := []struct { + name string + data []byte + }{{"patch.json", manifestData}} + names := make([]string, 0, len(blobs)) + for name := range blobs { + names = append(names, name) + } + for i := 0; i < len(names); i++ { + for j := i + 1; j < len(names); j++ { + if names[j] < names[i] { + names[i], names[j] = names[j], names[i] + } + } + } + for _, name := range names { + entries = append(entries, struct { + name string + data []byte + }{name, blobs[name]}) + } + for _, entry := range entries { + header := &tar.Header{Name: entry.name, Mode: 0o644, Size: int64(len(entry.data)), Typeflag: tar.TypeReg} + if err := writer.WriteHeader(header); err != nil { + t.Fatal(err) + } + if _, err := writer.Write(entry.data); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "app.patch") + if err := os.WriteFile(path, encoded.Bytes(), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func fileManifest(path string, data []byte, op, blob string, mode uint32) PatchFile { + return PatchFile{Path: path, Mode: mode, Size: int64(len(data)), SHA256: digest(data), Op: op, Blob: blob} +} + +func TestPatchApply(t *testing.T) { + oldRoot := t.TempDir() + oldData := []byte(strings.Repeat("old content ", 100)) + sameData := []byte("unchanged") + if err := os.WriteFile(filepath.Join(oldRoot, "program"), oldData, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(oldRoot, "same.txt"), sameData, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(oldRoot, "dropped.txt"), []byte("gone"), 0o644); err != nil { + t.Fatal(err) + } + newData := []byte(strings.Repeat("old content ", 100) + " and something new") + addedData := []byte("a new resource") + diff, err := bsdiff.Bytes(oldData, newData) + if err != nil { + t.Fatal(err) + } + manifest := PatchManifest{ + Schema: PatchSchema, App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "linux", Arch: "amd64", Payload: "file", + Files: []PatchFile{ + fileManifest("program", newData, "diff", "files/0001", 0o755), + fileManifest("same.txt", sameData, "same", "", 0o644), + fileManifest("resource/added.txt", addedData, "new", "files/0002", 0o644), + }, + } + patchPath := writePatch(t, manifest, map[string][]byte{"files/0001": diff, "files/0002": addedData}) + + patch, err := ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + 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, + } { + got, err := os.ReadFile(filepath.Join(staging, filepath.FromSlash(name))) + if err != nil { + t.Errorf("%s: %v", name, err) + continue + } + if !bytes.Equal(got, want) { + t.Errorf("%s differs", name) + } + } + 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) + } +} + +func TestPatchRefusesAChangedBase(t *testing.T) { + oldRoot := t.TempDir() + oldData := []byte("the installed file") + newData := []byte("the installed file, updated") + diff, _ := bsdiff.Bytes(oldData, newData) + manifest := PatchManifest{ + Schema: PatchSchema, App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "linux", Arch: "amd64", Payload: "file", + Files: []PatchFile{fileManifest("program", newData, "diff", "files/0001", 0o755)}, + } + patchPath := writePatch(t, manifest, map[string][]byte{"files/0001": diff}) + patch, err := ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(oldRoot, "program"), []byte("something else entirely"), 0o755); err != nil { + t.Fatal(err) + } + staging := filepath.Join(t.TempDir(), "staged") + if err := patch.Apply(oldRoot, staging); !errors.Is(err, ErrChecksum) { + t.Fatalf("err = %v, want ErrChecksum", err) + } + if _, err := os.Stat(staging); !os.IsNotExist(err) { + t.Errorf("staging survived a failed patch: %v", err) + } +} + +func TestPatchRefusesUnsafePaths(t *testing.T) { + for _, path := range []string{"../evil", "/absolute", "a/../../evil", "a\\b", "a:b", "", "."} { + manifest := PatchManifest{ + Schema: PatchSchema, App: "app", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "linux", Arch: "amd64", Payload: "file", + Files: []PatchFile{{Path: path, Mode: 0o644, Size: 1, SHA256: digest([]byte("x")), Op: "new", Blob: "files/0001"}}, + } + patchPath := writePatch(t, manifest, map[string][]byte{"files/0001": []byte("x")}) + if _, err := ReadPatch(patchPath); !errors.Is(err, ErrManifest) { + t.Errorf("%q: err = %v, want ErrManifest", path, err) + } + } +} + +func TestPatchRefusesBadManifests(t *testing.T) { + base := func() PatchManifest { + return PatchManifest{ + Schema: PatchSchema, App: "app", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "linux", Arch: "amd64", Payload: "file", + Files: []PatchFile{{Path: "program", Mode: 0o755, Size: 1, SHA256: digest([]byte("x")), Op: "new", Blob: "files/0001"}}, + } + } + tests := map[string]func(*PatchManifest){ + "schema": func(m *PatchManifest) { m.Schema = 2 }, + "os": func(m *PatchManifest) { m.OS = "windows" }, + "arch": func(m *PatchManifest) { m.Arch = "386" }, + "payload": func(m *PatchManifest) { m.Payload = "dir" }, + "no files": func(m *PatchManifest) { m.Files = nil }, + "bad version": func(m *PatchManifest) { m.FromVersion = "1" }, + "mode setuid": func(m *PatchManifest) { m.Files[0].Mode = 0o4755 }, + "mode zero": func(m *PatchManifest) { m.Files[0].Mode = 0 }, + "bad digest": func(m *PatchManifest) { m.Files[0].SHA256 = "abc" }, + "missing blob": func(m *PatchManifest) { m.Files[0].Blob = "" }, + "unknown op": func(m *PatchManifest) { m.Files[0].Op = "copy" }, + "same with blob": func(m *PatchManifest) { + m.Files[0].Op, m.Files[0].Blob = "same", "files/0001" + }, + } + for name, change := range tests { + 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) + } + } +} + +func TestPatchRefusesANonEmptyStaging(t *testing.T) { + oldRoot := t.TempDir() + data := []byte("x") + manifest := PatchManifest{ + Schema: PatchSchema, App: "app", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "linux", Arch: "amd64", Payload: "file", + Files: []PatchFile{fileManifest("program", data, "new", "files/0001", 0o755)}, + } + patchPath := writePatch(t, manifest, map[string][]byte{"files/0001": data}) + patch, err := ReadPatch(patchPath) + if err != nil { + t.Fatal(err) + } + staging := filepath.Join(t.TempDir(), "staged") + if err := os.MkdirAll(staging, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(staging, "existing"), []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + if err := patch.Apply(oldRoot, staging); err == nil { + t.Fatal("a non-empty staging directory was accepted") + } + if data, err := os.ReadFile(filepath.Join(staging, "existing")); err != nil || string(data) != "keep" { + t.Errorf("the existing staging content was removed: %v", err) + } +} + +func TestApplyPatchChecksNameAndVersions(t *testing.T) { + oldRoot := t.TempDir() + oldData := []byte("old program") + newData := []byte("new program") + if err := os.WriteFile(filepath.Join(oldRoot, "program"), oldData, 0o755); err != nil { + t.Fatal(err) + } + diff, err := bsdiff.Bytes(oldData, newData) + if err != nil { + t.Fatal(err) + } + manifest := PatchManifest{ + Schema: PatchSchema, App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: runtime.GOOS, Arch: runtime.GOARCH, Payload: "file", + 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 } + + staging, err := ApplyPatch(patchPath, "dev.example.notes", "1.0.0", "1.1.0") + if err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(staging, "program")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, newData) { + t.Fatal("the staged program is not the new one") + } + if err := os.RemoveAll(staging); err != nil { + t.Fatal(err) + } + + 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") }, + "wrong to": func() (string, error) { return ApplyPatch(patchPath, "dev.example.notes", "1.0.0", "1.2.0") }, + "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 } + } + 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 } + } +} diff --git a/update/payload_darwin.go b/update/payload_darwin.go new file mode 100644 index 000000000..c61fc6020 --- /dev/null +++ b/update/payload_darwin.go @@ -0,0 +1,21 @@ +//go:build darwin + +package update + +import ( + "fmt" + "os" +) + +// installedPayload returns the .app bundle the running program belongs to. +func installedPayload() (root, kind string, err error) { + executable, err := os.Executable() + if err != nil { + return "", "", fmt.Errorf("update: locating the running program: %w", err) + } + bundle, err := bundleRootFor(executable) + if err != nil { + return "", "", err + } + return bundle, "app", nil +} diff --git a/update/payload_linux.go b/update/payload_linux.go new file mode 100644 index 000000000..3e556399d --- /dev/null +++ b/update/payload_linux.go @@ -0,0 +1,23 @@ +//go:build linux + +package update + +import ( + "fmt" + "os" + "path/filepath" +) + +// installedPayload returns the directory holding the running executable, which +// is all a Linux update installs. +func installedPayload() (root, kind string, err error) { + executable, err := os.Executable() + if err != nil { + return "", "", fmt.Errorf("update: locating the running executable: %w", err) + } + resolved, err := filepath.EvalSymlinks(executable) + if err != nil { + return "", "", fmt.Errorf("update: resolving the running executable: %w", err) + } + return filepath.Dir(resolved), "file", nil +} diff --git a/update/payload_other.go b/update/payload_other.go new file mode 100644 index 000000000..4af4f7419 --- /dev/null +++ b/update/payload_other.go @@ -0,0 +1,9 @@ +//go:build !darwin && !linux && !windows + +package update + +// installedPayload has no application to describe on a target without a native +// executable. +func installedPayload() (root, kind string, err error) { + return "", "", ErrUnsupported +} diff --git a/update/payload_windows.go b/update/payload_windows.go new file mode 100644 index 000000000..e5bc7a03d --- /dev/null +++ b/update/payload_windows.go @@ -0,0 +1,11 @@ +//go:build windows + +package update + +import "fmt" + +// installedPayload has nothing to describe on Windows: the NSIS installer owns +// the installation and patches are not offered there. +func installedPayload() (root, kind string, err error) { + return "", "", fmt.Errorf("%w: Windows installs updates from an installer, not a payload", ErrUnsupported) +} From 7daaafea51e305d6efb84635dcf966d09d2ae51b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 14:43:40 +0800 Subject: [PATCH 34/86] feat(ui): give Select an icon per option MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit components.SelectOptions and SelectItem have had a leading icon slot all along, but ui.Select passed only the labels down, so a page could not give its options a flag or a colour swatch without painting around the control. ui.SelectIcon is Select with one further function, icon func(T) gfx.Icon: the chosen option's icon is painted before the value on the trigger and every option's before its own label in the open list, exactly as the component the select has always been painted by does with the same icons. A select that declares no icons — Select, or a nil icon function — paints what it always painted: the icon table is built in the page's scratch only when a select has one, so warm select frames allocate nothing, icons or not. Box.Icons is the same plumbing at the Frame's layer, where a SelectBase keeps the icons for its caller and paints none of them, as it does the rest of the look. --- ui/elements.go | 32 +++++++++++++++++-- ui/page.go | 3 ++ ui/page_bases.go | 2 +- ui/page_test.go | 30 ++++++++++++++++++ ui/select.go | 22 ++++++++++++- ui/select_test.go | 79 +++++++++++++++++++++++++++++++++++++++++++++++ ui/table_test.go | 14 +++++++++ 7 files changed, 177 insertions(+), 5 deletions(-) diff --git a/ui/elements.go b/ui/elements.go index ac997ed84..c66e4fa9e 100644 --- a/ui/elements.go +++ b/ui/elements.go @@ -153,6 +153,19 @@ func options[T comparable](p *Page, value *T, options []T, label func(T) string) return p.labels[first:len(p.labels):len(p.labels)], selected } +// optionIcons writes the icons of choices into the page's scratch, as options does +// the labels, or returns nil when icon is nil and the select paints none of them. +func optionIcons[T comparable](p *Page, choices []T, icon func(T) gfx.Icon) []gfx.Icon { + if icon == nil { + return nil + } + first := len(p.icons) + for _, choice := range choices { + p.icons = append(p.icons, icon(choice)) + } + return p.icons[first:len(p.icons):len(p.icons)] +} + // pick writes the option a click chose into *value, where the control is declared, // and records whether it did for Changed. func pick[T comparable](c C, b Box, value *T, options []T, index int, ok bool) { @@ -197,11 +210,23 @@ func Tabs[T comparable](c C, value *T, tabs []T, label func(T) string) Box { // it is none of them); picking an option sets it. Whether its list is open is the // Select's own state. func Select[T comparable](c C, value *T, choices []T, label func(T) string) Box { - return selectOf(c, value, choices, label, false) + return selectOf(c, value, choices, label, nil, false) +} + +// SelectIcon is Select with an icon before every option: icon names each option's +// own, painted before the chosen value on the trigger and before each label in the +// open list. It is asked for once per option per paint, as label is; a nil icon +// paints exactly what Select does. +// +// ui.SelectIcon(c, &m.locale, locales, localeName, localeFlag) +func SelectIcon[T comparable](c C, value *T, choices []T, label func(T) string, icon func(T) gfx.Icon) Box { + return selectOf(c, value, choices, label, optionIcons(c.page, choices, icon), false) } -// selectOf is Select, or SelectBase when base is set: the same control without the theme's look. -func selectOf[T comparable](c C, value *T, choices []T, label func(T) string, base bool) Box { +// selectOf is Select (or SelectIcon), or SelectBase when base is set: the same +// control without the theme's look. icons, when SelectIcon's icon function gave +// them, are indexed by option like the labels; nil is the select without icons. +func selectOf[T comparable](c C, value *T, choices []T, label func(T) string, icons []gfx.Icon, base bool) Box { p := c.page scope := p.boundScope(pkSelect, unsafe.Pointer(value)) state := stateIn[SelectState](p, scope, "select") // its open list follows its value @@ -212,6 +237,7 @@ func selectOf[T comparable](c C, value *T, choices []T, label func(T) string, ba } else { b = c.f.Select(scope, state, labels, selected) } + b.Icons(icons) p.selects = append(p.selects, state) index, ok := b.Picked() pick(c, b, value, choices, index, ok) diff --git a/ui/page.go b/ui/page.go index 2934402a6..2bc314ddb 100644 --- a/ui/page.go +++ b/ui/page.go @@ -266,6 +266,7 @@ type Page struct { hoverArea gfx.ID // the scroll area or self-scrolling table the pointer is on selects []*SelectState // the Selects of the last paint, which Wheel scrolls labels []string // scratch for Choice's labels + icons []gfx.Icon // scratch for SelectIcon's icons memos map[gfx.ID]*memoEntry memoBoxes []memoBox memoChecks []memoCheckOf @@ -778,6 +779,8 @@ func (p *Page) paintOnce(canvas *gfx.Canvas, bounds Rect, view func(C)) { clear(p.ctx.stateSeq) clear(p.labels) p.labels = p.labels[:0] + clear(p.icons) + p.icons = p.icons[:0] p.focusPaint = p.focusPaint[:0] for i := range p.held { if id := p.held[i].id; !id.IsZero() && id != canvas.Pressed() && id != canvas.Focused() { diff --git a/ui/page_bases.go b/ui/page_bases.go index 9129b7a2c..3cdacc793 100644 --- a/ui/page_bases.go +++ b/ui/page_bases.go @@ -106,7 +106,7 @@ func SliderBase(c C, state *SliderState) Box { // list.Draw(m.paintPanel) // option i is in sel.Part(i) // } func SelectBase[T comparable](c C, value *T, choices []T, label func(T) string) Box { - return selectOf(c, value, choices, label, true) + return selectOf(c, value, choices, label, nil, true) } // TextFieldBase is TextField without a look: the editable text, with no padding, diff --git a/ui/page_test.go b/ui/page_test.go index 5ffaf8a96..b593f9e7d 100644 --- a/ui/page_test.go +++ b/ui/page_test.go @@ -558,3 +558,33 @@ func TestSelectStaysOpenWhenOneAppearsAbove(t *testing.T) { t.Fatalf("size open=%v, color open=%v", d.has("L"), d.has("Red")) } } + +// SelectIcon opens, chooses and writes back through the option type of the +// application's own, label and icon both named by functions of the option. +func TestSelectIconChoosesAnOption(t *testing.T) { + type locale struct { + name string + flag int + } + flagOf := func(flag int) gfx.Icon { + return gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{gfx.MoveTo(4+float32(flag)*4, 6), gfx.LineTo(14+float32(flag)*4, 18)}} + } + locales := []locale{{"简体中文", 0}, {"English", 1}, {"日本語", 2}} + chosen := locales[1] + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.SelectIcon(c, &chosen, locales, + func(l locale) string { return l.name }, + func(l locale) gfx.Icon { return flagOf(l.flag) }).Placeholder("Language") + }) + }) + d.click("Language") + if !d.has("日本語") { + t.Fatal("the open list does not offer its options") + } + d.click("日本語") + if chosen != locales[2] { + t.Fatalf("chose %+v, want %+v", chosen, locales[2]) + } +} diff --git a/ui/select.go b/ui/select.go index c6cbdb365..2eb3c5723 100644 --- a/ui/select.go +++ b/ui/select.go @@ -165,6 +165,7 @@ type selectDecl struct { scope gfx.Scope state *SelectState labels []string + icons []gfx.Icon selected int canvas *gfx.Canvas popup int32 // the Popup that places the list, or -1 when it is closed @@ -307,6 +308,18 @@ func (b Box) Placeholder(value string) Box { return b } +// Icons sets the icons a Select paints before its chosen value on the trigger and +// before each option's label in the open list, one per option and indexed like the +// labels: what SelectIcon's icon function names. A select given none of them paints +// exactly what it always has; a SelectBase keeps them for its caller and paints +// none, as it does the rest of the look. +func (b Box) Icons(icons []gfx.Icon) Box { + if n := b.n(); n.kind == kindSelect { + b.f.widgets.selects[n.aux].icons = icons + } + return b +} + // Picked reports which option of a Select this paint is delivering a click on, and // keeps the select's state: the trigger opens and closes the list, an option or a press // outside closes it, the arrows move its window. @@ -376,6 +389,9 @@ func (f *frame) paintSelect(n *node) { options.Unpainted = n.flags&flagThemed == 0 if d.selected >= 0 && d.selected < count { options.Value = d.labels[d.selected] + if d.selected < len(d.icons) { + options.Icon = d.icons[d.selected] + } } if options.Label == "" { options.Label = n.text @@ -406,7 +422,11 @@ func (f *frame) paintSelect(n *node) { f.widgets.rows = append(f.widgets.rows, Rect{}) } for index := first; index < first+visible && index < count; index++ { - f.widgets.rows[int(d.rects)+index] = control.AddItem(components.SelectItem{ID: d.scope.At(index), Label: d.labels[index], Selected: index == d.selected}) + item := components.SelectItem{ID: d.scope.At(index), Label: d.labels[index], Selected: index == d.selected} + if index < len(d.icons) { + item.Icon = d.icons[index] + } + f.widgets.rows[int(d.rects)+index] = control.AddItem(item) } if visible < count { control.AddScrollDown(d.scope.At(count+4), first+visible >= count) diff --git a/ui/select_test.go b/ui/select_test.go index 97a26546b..0b3ed30f8 100644 --- a/ui/select_test.go +++ b/ui/select_test.go @@ -16,6 +16,17 @@ var ( selLabels = []string{"Small", "Medium", "Large"} ) +// selIcons are the icons of the three labels, a stroke at each one's own height: +// an icon painted on another option's row shows in the triangles. +var selIcons = []gfx.Icon{ + {ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{gfx.MoveTo(4, 6), gfx.LineTo(20, 6)}}, + {ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{gfx.MoveTo(4, 10), gfx.LineTo(20, 10)}}, + {ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{gfx.MoveTo(4, 14), gfx.LineTo(20, 14)}}, +} + // A Select looks exactly like the components.Select it is painted by, closed and // open, with a value and with a placeholder. func TestSelectIsPaintedLikeTheComponent(t *testing.T) { @@ -59,6 +70,73 @@ func TestSelectIsPaintedLikeTheComponent(t *testing.T) { } } +// A Select with icons is painted exactly like the components.Select an application +// would call with the same icons: the chosen option's before the value on the +// trigger, each option's own before its label on its row — a select that was given +// no icon function paints what TestSelectIsPaintedLikeTheComponent pins above. +func TestSelectWithIconsIsPaintedLikeTheComponent(t *testing.T) { + theme := gfx.LightTheme() + for _, test := range []struct { + open bool + selected int + }{{false, 1}, {false, -1}, {true, 1}, {true, -1}, {true, 2}} { + name := fmt.Sprintf("open=%v selected=%d", test.open, test.selected) + flexed, direct := testCanvas(), testCanvas() + state := SelectState{Open: test.open} + viewport := gfx.Rect{Width: 400, Height: 300} + var view View + view.Draw(flexed, theme, viewport, func(f *Frame) { + f.Column().Pad(10).Children(func() { + f.Select(selScope, &state, selLabels, test.selected).Placeholder("Size").Width(200).Icons(selIcons) + }) + }) + options := components.SelectOptions{ + TriggerID: selScope.At(3), Label: "Size", Placeholder: "Size", Open: test.open, + Layer: 1, Scope: selScope.At(5), DismissID: selScope.At(4), Viewport: viewport, + } + if test.selected >= 0 { + options.Value, options.Icon = selLabels[test.selected], selIcons[test.selected] + } + if test.open { + options.Content = gfx.Rect{X: 10, Y: 10 + 32 + 4, Width: 200, Height: 8 + 32*3} + } + control := components.BeginSelect(direct, theme, gfx.Rect{X: 10, Y: 10, Width: 200}, options) + if test.open { + for i, label := range selLabels { + control.AddItem(components.SelectItem{ID: selScope.At(i), Label: label, Selected: i == test.selected, Icon: selIcons[i]}) + } + } + sameCanvas(t, name, flexed, direct) + } +} + +// Two options that share a label keep their own icon: the rows of a list are not +// interchangeable behind one label. +func TestSelectIconsFollowTheirOwnRows(t *testing.T) { + theme := gfx.LightTheme() + labels := []string{"Same", "Same"} + state := SelectState{Open: true} + flexed, direct := testCanvas(), testCanvas() + viewport := gfx.Rect{Width: 300, Height: 200} + var view View + view.Draw(flexed, theme, viewport, func(f *Frame) { + f.Column().Pad(10).Children(func() { + f.Select(selScope, &state, labels, 0).Placeholder("Pick").Width(200).Icons(selIcons) + }) + }) + options := components.SelectOptions{ + TriggerID: selScope.At(2), Label: "Pick", Placeholder: "Pick", Open: true, + Layer: 1, Scope: selScope.At(4), DismissID: selScope.At(3), Viewport: viewport, + Content: gfx.Rect{X: 10, Y: 10 + 32 + 4, Width: 200, Height: 8 + 32*2}, + Value: "Same", Icon: selIcons[0], + } + control := components.BeginSelect(direct, theme, gfx.Rect{X: 10, Y: 10, Width: 200}, options) + for i, label := range labels { + control.AddItem(components.SelectItem{ID: selScope.At(i), Label: label, Selected: i == 0, Icon: selIcons[i]}) + } + sameCanvas(t, "same-label options", flexed, direct) +} + func TestSelectOpensChoosesAndClosesThroughItsClicks(t *testing.T) { theme := gfx.LightTheme() var state SelectState @@ -165,6 +243,7 @@ func TestSelectAllocatesNothingOnceWarm(t *testing.T) { view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { f.Column().Pad(10).Gap(8).Children(func() { f.Select(selScope, &state, selLabels, 1) + f.Select(selScope, &state, selLabels, 1).Icons(selIcons) f.Select(selScope, &closed, selLabels, -1).Placeholder("Pick").Small() }) }) diff --git a/ui/table_test.go b/ui/table_test.go index 74f2ae46e..a4d1eee89 100644 --- a/ui/table_test.go +++ b/ui/table_test.go @@ -48,6 +48,20 @@ func sameCanvas(t *testing.T, name string, flexed, direct *gfx.Canvas) { } } } + // Triangles are compared without Layer, as the rectangles are: the caller picks + // the layer a component paints its overlay on (ui raises a select's list one + // above the page's widget layer; a direct call names its own). + if a, b := flexed.Triangles(), direct.Triangles(); len(a) != len(b) { + t.Fatalf("%s: ui painted %d triangles, the component %d", name, len(a), len(b)) + } else { + for i := range a { + x, y := a[i], b[i] + if x.Points != y.Points || x.Color != y.Color || x.Shaded != y.Shaded || x.Shade != y.Shade || + x.EdgeMask != y.EdgeMask || x.ClipOf != y.ClipOf || x.HasClip != y.HasClip || x.Order != y.Order { + t.Errorf("%s: triangle %d is %+v, the component's %+v", name, i, x, y) + } + } + } } // A Table looks exactly like the components.Table it is painted by: the same From b63e4a0994d3b8a5efe4736887dd92daf7293c92 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 14:44:30 +0800 Subject: [PATCH 35/86] feat(headless): add a test clock, accessibility queries and notifications Session.Now, Advance, Frame and Transitioning give a test its own clock. Access, AccessByRole and AccessByName read the last frame's accessibility tree as app.AccessNode, and Notifications returns what the application sent: a Driver records notifications instead of showing them. --- app/accessnodes.go | 136 +++++++++++++++++++++++++++ app/driver.go | 12 +++ app/driver_system.go | 20 ++++ app/driver_system_unsupported.go | 2 + app/system.go | 3 + headless/doc.go | 21 +++++ headless/extras_test.go | 91 ++++++++++++++++++ headless/session.go | 55 +++++++++++ website/content/guides/en/testing.md | 34 +++++++ website/content/guides/zh/testing.md | 27 ++++++ 10 files changed, 401 insertions(+) create mode 100644 app/accessnodes.go create mode 100644 headless/extras_test.go diff --git a/app/accessnodes.go b/app/accessnodes.go new file mode 100644 index 000000000..87093ee57 --- /dev/null +++ b/app/accessnodes.go @@ -0,0 +1,136 @@ +package app + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/semantic" +) + +// AccessNode is what assistive technology sees of one control in a frame: the +// same information the platform adapters send to the system, without the +// platform. Driver.Accessibility returns the last frame's tree. +type AccessNode struct { + // ID names the control, as the hit it was made from does. + ID gfx.ID + // Role is the control's role; zero when it is a text without one. + Role gfx.Role + // Bounds is where the control was drawn, in logical pixels. + Bounds gfx.Rect + + // Label is the accessible name, Value the control's value and Hint the + // short instruction usually read after the name. + Label string + Value string + Hint string + // Description is a longer explanation than Hint. + Description string + + Focused bool + Disabled bool + Checked bool + Mixed bool + Selected bool + Expanded bool + Multiline bool + ReadOnly bool + Secure bool + Focusable bool + // Expandable marks a control that opens and closes something, whatever its + // state now. + Expandable bool + + // Level is a heading's level or a tree item's depth; zero when not stated. + Level uint8 + // PosInSet and SetSize place the node among its siblings, counting from 1. + PosInSet, SetSize int32 + // Live marks a region that announces changes to its content. + Live gfx.LiveRegion + // Range is a slider's or progress bar's number. + Range gfx.ValueRange + // Selection is the selected span of a focused text field's Value. + Selection AccessSelection +} + +// AccessSelection is a span of a text node's Value in Unicode code points: +// Start and End are the anchor and the caret, so End < Start for a selection +// made backwards. Valid is false when the node has no caret. +type AccessSelection struct { + Start, End int32 + Valid bool +} + +// Accessibility returns the accessibility tree of the last painted frame, in +// reading order. It is safe to call from the goroutine that drives the Driver +// (the main thread in a test), as Snapshot is. +func (driver *Driver) Accessibility() []AccessNode { + if driver == nil || driver.painter == nil { + return nil + } + nodes := driver.painter.accessibility + if len(nodes) == 0 { + return nil + } + out := make([]AccessNode, len(nodes)) + for index, node := range nodes { + out[index] = AccessNode{ + ID: node.ID, Role: accessRole(semantic.Role(node.Role)), + Bounds: gfx.Rect{X: node.X, Y: node.Y, Width: node.Width, Height: node.Height}, + Label: node.Label, Value: node.Value, Hint: node.Hint, Description: node.Description, + Focused: node.Focused, Disabled: node.Disabled, Checked: node.Checked, Mixed: node.Mixed, + Selected: node.Selected, Expanded: node.Expanded, Multiline: node.Multiline, + ReadOnly: node.ReadOnly, Secure: node.Secure, Focusable: node.Focusable, + Expandable: node.Expandable, Level: node.Level, PosInSet: node.PosInSet, SetSize: node.SetSize, + Live: node.Live, Range: node.Range, + Selection: AccessSelection{Start: node.Selection.Start, End: node.Selection.End, Valid: node.Selection.Valid}, + } + } + return out +} + +// accessRole maps the semantic role the platform adapters receive back to the +// gfx.Role the application declared. Roles that have no gfx counterpart (a +// text, an image, the application itself) are zero. +func accessRole(role semantic.Role) gfx.Role { + switch role { + case semantic.RoleButton: + return gfx.RoleButton + case semantic.RoleLink: + return gfx.RoleLink + case semantic.RoleCheckbox: + return gfx.RoleCheckbox + case semantic.RoleRadio: + return gfx.RoleRadio + case semantic.RoleTab: + return gfx.RoleTab + case semantic.RoleMenuItem: + return gfx.RoleMenuItem + case semantic.RoleCombobox: + return gfx.RoleCombobox + case semantic.RoleSwitch: + return gfx.RoleSwitch + case semantic.RoleTextField: + return gfx.RoleTextField + case semantic.RoleSlider: + return gfx.RoleSlider + case semantic.RoleGroup: + return gfx.RoleGroup + case semantic.RoleMenu: + return gfx.RoleMenu + case semantic.RoleMenubar: + return gfx.RoleMenubar + case semantic.RoleListBox: + return gfx.RoleListBox + case semantic.RoleOption: + return gfx.RoleOption + case semantic.RoleGrid: + return gfx.RoleGrid + case semantic.RoleGridCell: + return gfx.RoleGridCell + case semantic.RoleHeading: + return gfx.RoleHeading + case semantic.RoleStatus: + return gfx.RoleStatus + case semantic.RoleSeparator: + return gfx.RoleSeparator + } + return 0 +} diff --git a/app/driver.go b/app/driver.go index 69cab7f10..6074af20a 100644 --- a/app/driver.go +++ b/app/driver.go @@ -67,6 +67,8 @@ type Driver struct { modifierKeys uint8 clipboard string + notifications []Notification + notificationMu sync.Mutex openedURL string hasOpenedURL bool openedPath string @@ -231,6 +233,16 @@ func (driver *Driver) Transitioning() bool { // Now is the driver's virtual time, which starts at zero. func (driver *Driver) Now() time.Duration { return driver.now } +// Paint processes work other goroutines posted and paints one frame now. A +// test that changed what a view shows from outside it, without input, calls it +// to see the result without moving the clock. +func (driver *Driver) Paint() error { + if err := driver.Pump(); err != nil { + return err + } + return driver.redraw() +} + // Advance moves virtual time forward by duration, repainting at frame cadence // while an animation is in flight and applying background wakes. An idle // application repaints nothing, as in a window. diff --git a/app/driver_system.go b/app/driver_system.go index 2b412c34f..75190a4c5 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -188,6 +188,26 @@ func driverDeleteSecret(service, account string) (error, bool) { return nil, true } +func driverSendNotification(notification Notification) (error, bool) { + system := activeDriverSystem.Load() + if system == nil { + return nil, false + } + system.driver.notificationMu.Lock() + system.driver.notifications = append(system.driver.notifications, notification) + system.driver.notificationMu.Unlock() + return nil, true +} + +// Notifications returns the notifications the application sent in this +// driver-backed run, in order. A Driver has no notification center, so sending +// one records it instead of showing it. +func (driver *Driver) Notifications() []Notification { + driver.notificationMu.Lock() + defer driver.notificationMu.Unlock() + return append([]Notification(nil), driver.notifications...) +} + func driverOpenURL(target string) (error, bool) { system := activeDriverSystem.Load() if system == nil { diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index 89db8d3ed..1f35e4d2f 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -20,6 +20,8 @@ func driverSetClipboardFiles([]string) (error, bool) { return nil, false } func driverSetClipboardHTML(string, string) (error, bool) { return nil, false } +func driverSendNotification(Notification) (error, bool) { return nil, false } + func driverOpenURL(string) (error, bool) { return nil, false } func driverOpenPath(string) (error, bool) { return nil, false } func driverRevealPath(string) (error, bool) { return nil, false } diff --git a/app/system.go b/app/system.go index f5d37334c..621bdbb7e 100644 --- a/app/system.go +++ b/app/system.go @@ -245,6 +245,9 @@ func SendNotification(notification Notification) error { if notification.Title == "" && notification.Body == "" { return fmt.Errorf("app: notification is empty") } + if err, handled := driverSendNotification(notification); handled { + return err + } return nativeSendNotification(notification) } diff --git a/headless/doc.go b/headless/doc.go index 3b0452e96..992b93347 100644 --- a/headless/doc.go +++ b/headless/doc.go @@ -32,6 +32,27 @@ // session.ClickLabel("id:home/auto") // session.Expect("text", "Connected", "within", "5000") // +// The clock belongs to the test: Now returns it, Advance moves it, and Frame +// paints one frame without moving it. Transitioning reports whether the last +// frame asked for the next one, so a test can prove that an animation ended: +// +// session.Advance(200 * time.Millisecond) +// session.Expect("text", "Saved") +// if session.Transitioning() { +// t.Error("the transition is still running") +// } +// +// Access returns the last frame's accessibility tree in reading order: what +// assistive technology is told about every control, with its role, bounds, +// name, value, states and range. AccessByRole and AccessByName find one node, +// as a screen reader or a test would: +// +// node, ok := session.AccessByRole(gfx.RoleCheckbox, "Auto update") +// if !ok || !node.Checked { ... } +// +// A session has no notification center: Notifications returns the ones the +// application sent, in order, instead of showing them. +// // Record plays the animation clock and writes the frames whose pixels changed, // so a transition can be reviewed as a sequence rather than a still: // diff --git a/headless/extras_test.go b/headless/extras_test.go new file mode 100644 index 000000000..187f119f4 --- /dev/null +++ b/headless/extras_test.go @@ -0,0 +1,91 @@ +//go:build darwin || windows || linux + +package headless + +import ( + "testing" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +func TestSessionClockMovesOnlyWhenAsked(t *testing.T) { + session, target := openTestApp(t) + if now := session.Now(); now != 0 { + t.Fatalf("clock starts at %v", now) + } + if session.Transitioning() { + t.Fatal("a still frame reports a transition") + } + if err := session.Advance(100 * time.Millisecond); err != nil { + t.Fatal(err) + } + if now := session.Now(); now != 100*time.Millisecond { + t.Fatalf("clock = %v after advancing 100ms", now) + } + // A frame can be painted without moving the clock, for state changed from + // outside the application. + target.clicks = 3 + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if now := session.Now(); now != 100*time.Millisecond { + t.Fatalf("Frame moved the clock to %v", now) + } + if !session.HasText("Clicks: 3") { + t.Fatalf("frame did not show the change: %q", session.Texts()) + } +} + +func TestSessionAccessReadsTheAccessibilityTree(t *testing.T) { + session := layoutSession(t, func(canvas *gfx.Canvas) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{X: 16, Y: 16, Width: 120, Height: 32}, "Auto update", gfx.HitOptions{ + Role: gfx.RoleCheckbox, Checked: true, Disabled: true, + Description: "Applies updates at night", Level: 2, PosInSet: 2, SetSize: 3, + Live: gfx.LivePolite, + }) + canvas.HitWithOptions(gfx.Item(2), gfx.Rect{X: 16, Y: 64, Width: 200, Height: 24}, "Volume", gfx.HitOptions{ + Role: gfx.RoleSlider, Range: gfx.ValueRange{Now: 0.4, Min: 0, Max: 1, Set: true}, + }) + }) + nodes := session.Access() + if len(nodes) != 2 { + t.Fatalf("accessibility tree = %+v", nodes) + } + check, ok := session.AccessByRole(gfx.RoleCheckbox, "Auto update") + if !ok { + t.Fatalf("no checkbox: %+v", nodes) + } + if !check.Checked || !check.Disabled || check.Description != "Applies updates at night" || + check.Level != 2 || check.PosInSet != 2 || check.SetSize != 3 || check.Live != gfx.LivePolite { + t.Errorf("checkbox = %+v", check) + } + if check.ID != gfx.Item(1) || check.Bounds.Width != 120 { + t.Errorf("checkbox identity or bounds = %+v", check) + } + slider, ok := session.AccessByName("Volume") + if !ok || slider.Role != gfx.RoleSlider || !slider.Range.Set || slider.Range.Now != 0.4 { + t.Errorf("slider = %+v, %v", slider, ok) + } + if _, ok := session.AccessByRole(gfx.RoleButton, ""); ok { + t.Error("AccessByRole found a button that is not there") + } +} + +func TestSessionRecordsNotifications(t *testing.T) { + session, _ := openTestApp(t) + if err := app.SendNotification(app.Notification{Title: "Build", Body: "done"}); err != nil { + t.Fatal(err) + } + if err := app.SendNotification(app.Notification{Title: "Upload", Body: "queued"}); err != nil { + t.Fatal(err) + } + got := session.Notifications() + if len(got) != 2 || got[0].Title != "Build" || got[1].Body != "queued" { + t.Fatalf("notifications = %+v", got) + } + if err := app.SendNotification(app.Notification{}); err == nil { + t.Error("an empty notification was accepted") + } +} diff --git a/headless/session.go b/headless/session.go index a12cc91a7..c4326d824 100644 --- a/headless/session.go +++ b/headless/session.go @@ -187,8 +187,63 @@ func (session *Session) Type(value string) error { func (session *Session) Compose(value string) error { return session.driver.Compose(value) } // Wait advances the animation clock. +// Wait moves the virtual clock forward by duration, running the frames due +// meanwhile; it is Advance under its older name. func (session *Session) Wait(duration time.Duration) error { return session.driver.Advance(duration) } +// Now returns the session's virtual clock, which starts at zero and moves only +// with Advance and Wait. +func (session *Session) Now() time.Duration { return session.driver.Now() } + +// Advance moves the virtual clock forward by duration, running the frames due +// meanwhile and applying work other goroutines posted. Nothing moves unless +// called: an animation sits where the clock left it. +func (session *Session) Advance(duration time.Duration) error { + return session.driver.Advance(duration) +} + +// Transitioning reports whether the last frame asked for the next one: an +// animation or transition is in flight. A frame that only asked for a later +// frame, as a spinner does, does not count. +func (session *Session) Transitioning() bool { return session.driver.Transitioning() } + +// Frame processes work other goroutines posted and paints one frame now, +// without moving the clock. Use it after changing what a view shows from +// outside the application, without input. +func (session *Session) Frame() error { return session.driver.Paint() } + +// Access returns the accessibility tree of the last frame, in reading order: +// what assistive technology is told about every control, with its role, bounds, +// name, value, states and range. +func (session *Session) Access() []app.AccessNode { return session.driver.Accessibility() } + +// AccessByRole returns the first node in the last frame with role and the +// accessible name; an empty name matches any node with that role. It is the +// query a test uses to assert what assistive technology is told. +func (session *Session) AccessByRole(role gfx.Role, name string) (app.AccessNode, bool) { + for _, node := range session.Access() { + if node.Role == role && (name == "" || node.Label == name) { + return node, true + } + } + return app.AccessNode{}, false +} + +// AccessByName returns the first node in the last frame with the accessible +// name, whatever its role. +func (session *Session) AccessByName(name string) (app.AccessNode, bool) { + for _, node := range session.Access() { + if node.Label == name { + return node, true + } + } + return app.AccessNode{}, false +} + +// Notifications returns the notifications the application sent in this run, in +// order. A session has no notification center: sending one records it. +func (session *Session) Notifications() []app.Notification { return session.driver.Notifications() } + // maxRest bounds how long Rest plays animations. const maxRest = 5 * time.Second diff --git a/website/content/guides/en/testing.md b/website/content/guides/en/testing.md index 52971203b..bc5573711 100644 --- a/website/content/guides/en/testing.md +++ b/website/content/guides/en/testing.md @@ -74,6 +74,40 @@ func TestClickCounts(t *testing.T) { The test finds controls by the name a user and a screen reader know them by (`Hit.Label`), not by coordinates. A page names its elements itself, as paths such as `page/~k1/#0` in its tree; `c.Part("word")` gives an element a name of yours, which a test or the headless driver can address by path. +## headless.Session + +`headless.Open` wraps that driver in a session that finds controls by their +accessible name and owns the clock. `Now`, `Advance` and `Frame` move time and +paint, `Transitioning` says whether anything is still moving, `Access` returns +the accessibility tree of the last frame, and `Notifications` returns what the +application sent: + +```go +session, err := headless.Open(config, nil, headless.Options{}) +if err != nil { + t.Fatal(err) +} +defer session.Close() + +node, ok := session.AccessByRole(gfx.RoleCheckbox, "Auto update") +if !ok || !node.Checked { + t.Fatalf("checkbox = %+v", node) +} +session.ClickLabel("Install") +session.Advance(200 * time.Millisecond) +if session.Transitioning() { + t.Error("the progress bar is still moving") +} +if got := session.Notifications(); len(got) != 1 || got[0].Title != "Installed" { + t.Errorf("notifications = %+v", got) +} +``` + +`Access` reports what assistive technology is told: the role, bounds, name, +value, description, states, range and live region of every control, in reading +order. It is the same tree the platform adapters send to the system, without the +platform. + ## Mistakes that compile A page can compile and still do the wrong thing: a `Button` with the same label in every row of a loop whose rows have no Key can take a click meant for another row when a row is added above. `viva vet` finds it without running anything: diff --git a/website/content/guides/zh/testing.md b/website/content/guides/zh/testing.md index eede34724..163d28613 100644 --- a/website/content/guides/zh/testing.md +++ b/website/content/guides/zh/testing.md @@ -74,6 +74,33 @@ func TestClickCounts(t *testing.T) { 测试按用户和读屏器认识控件的名字(`Hit.Label`)找控件,而不是按坐标。页面自己为元素命名,在它的树里是 `page/~k1/#0` 这样的路径;`c.Part("word")` 给元素起一个你自己的名字,测试和无头驱动可以按路径定位。 +## headless.Session + +`headless.Open` 把那个 driver 包成一个 session:按可访问名称查找控件,并拥有自己的时钟。`Now`、`Advance` 和 `Frame` 控制时间与绘制,`Transitioning` 说明是否还有东西在动,`Access` 返回最后一帧的无障碍树,`Notifications` 返回应用发出的通知: + +```go +session, err := headless.Open(config, nil, headless.Options{}) +if err != nil { + t.Fatal(err) +} +defer session.Close() + +node, ok := session.AccessByRole(gfx.RoleCheckbox, "Auto update") +if !ok || !node.Checked { + t.Fatalf("checkbox = %+v", node) +} +session.ClickLabel("Install") +session.Advance(200 * time.Millisecond) +if session.Transitioning() { + t.Error("the progress bar is still moving") +} +if got := session.Notifications(); len(got) != 1 || got[0].Title != "Installed" { + t.Errorf("notifications = %+v", got) +} +``` + +`Access` 报告辅助技术看到的内容:每个控件的角色、边界、名称、值、描述、状态、数值范围和 live region,按阅读顺序排列。它和平台适配器交给系统的是同一棵树,只是不含平台。 + ## 能编译却做错事的写法 页面可能能编译却做错事:循环里每一行都有同名 `Button`、行又没加 Key 时,上方新增一行后,点击可能落到别的行上。`viva vet` 不运行程序就能找出它: From e703e62580709725d0b1e17ffc8782d8dd04e6b8 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 15:40:58 +0800 Subject: [PATCH 36/86] feat(update): patch a Windows installation from the portable payload A patch carries 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; the portable data folder is excluded at generation. Install copies the staged files over the install directory with a PowerShell helper that keeps a backup and restores it when the new program fails to start. A machine-wide installation falls back to the full installer. Tested on the Windows VM, including the rollback. --- cmd/viva/feed.go | 23 +++-- cmd/viva/feed_test.go | 81 +++++++++++++++++ cmd/viva/help.go | 2 +- docs/updating.md | 31 ++++--- tools/patchgen/patchgen.go | 43 +++++++-- tools/patchgen/patchgen_test.go | 61 +++++++++++++ update/doc.go | 8 +- update/install_windows.go | 112 +++++++++++++++++++++++- update/install_windows_test.go | 149 ++++++++++++++++++++++++++++++++ update/patch.go | 24 +++-- update/patch_test.go | 87 ++++++++++++++++++- update/payload_windows.go | 22 ++++- 12 files changed, 601 insertions(+), 42 deletions(-) diff --git a/cmd/viva/feed.go b/cmd/viva/feed.go index 33ee0cd41..7129c99cc 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 { @@ -482,8 +491,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..87e6dd21d 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,83 @@ 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"), + }) + 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) != 1 || len(feed.Latest.Assets[0].Patches) != 1 { + t.Fatalf("feed = %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..bd19426f2 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -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/docs/updating.md b/docs/updating.md index 5daf4e513..c4e559731 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,7 +271,7 @@ 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 | +| 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` installed by dpkg, a read-only directory | A program that a package manager installed is not updated by itself. Linux @@ -332,9 +342,10 @@ 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 @@ -342,9 +353,9 @@ warning. - **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 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/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/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_windows.go b/update/install_windows.go index 21159c4b5..415958622 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,116 @@ 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)) + 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("$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..3cb4c6839 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,149 @@ 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 := t.TempDir() + install := t.TempDir() + 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")) + copyWindowsFile(t, systemExecutable(t, "cmd.exe"), filepath.Join(payload, "app.exe")) + 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{"/c", "exit 1"}) + runPayloadHelper(t, script, 1) + 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) + } +} 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..aa49e508a 100644 --- a/update/patch_test.go +++ b/update/patch_test.go @@ -252,16 +252,23 @@ func TestApplyPatchChecksNameAndVersions(t *testing.T) { if err != nil { t.Fatal(err) } + payload := "file" + switch runtime.GOOS { + case "darwin": + payload = "app" + case "windows": + payload = "dir" + } 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: runtime.GOOS, Arch: runtime.GOARCH, 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" + located := payload locateInstalledPayload = func() (string, string, error) { return oldRoot, located, nil } staging, err := ApplyPatch(patchPath, "dev.example.notes", "1.0.0", "1.1.0") @@ -279,6 +286,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 +297,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 } From 83f5a45d61cf4d86bdbfbad7d243069223766c3c Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 15:43:33 +0800 Subject: [PATCH 37/86] fix(feed): patch only the portable Windows zip A Windows release carries an NSIS setup and a portable zip for each architecture. The setup is an installer, not a payload; only the zip gets a patch, so a --patch-from for Windows no longer tries to diff the setup. --- cmd/viva/feed.go | 8 ++++++++ cmd/viva/feed_test.go | 20 +++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/cmd/viva/feed.go b/cmd/viva/feed.go index 7129c99cc..f104d5d30 100644 --- a/cmd/viva/feed.go +++ b/cmd/viva/feed.go @@ -480,6 +480,14 @@ func addPatches(assets []update.Asset, froms []patchFrom, excludes []string, dir 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) diff --git a/cmd/viva/feed_test.go b/cmd/viva/feed_test.go index 87e6dd21d..cb5ccc533 100644 --- a/cmd/viva/feed_test.go +++ b/cmd/viva/feed_test.go @@ -660,6 +660,9 @@ func TestFeedAddsAWindowsPortablePatch(t *testing.T) { "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"), @@ -686,9 +689,24 @@ func TestFeedAddsAWindowsPortablePatch(t *testing.T) { if err := json.Unmarshal(data, &feed); err != nil { t.Fatal(err) } - if len(feed.Latest.Assets) != 1 || len(feed.Latest.Assets[0].Patches) != 1 { + 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 { From 5b177b73a89f63908b15909d79295a84725becb2 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 16:44:12 +0800 Subject: [PATCH 38/86] feat(tools): teach iconcompile use elements and vertex markers --- tools/iconcompile/compile.go | 538 ++++++++++++++++++++++--- tools/iconcompile/compile_test.go | 231 +++++++++++ tools/iconcompile/testdata/flag-cn.svg | 11 + tools/iconcompile/testdata/flag-kr.svg | 24 ++ tools/iconcompile/testdata/flag-us.svg | 9 + 5 files changed, 762 insertions(+), 51 deletions(-) create mode 100644 tools/iconcompile/testdata/flag-cn.svg create mode 100644 tools/iconcompile/testdata/flag-kr.svg create mode 100644 tools/iconcompile/testdata/flag-us.svg 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 @@ + + + + + + + + + From 878e446aa52d8bba94a14769c169d1b1344c118a Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 18:24:16 +0800 Subject: [PATCH 39/86] feat(ui): report a table's painted cell rectangles TableState.CellRect answers where a source cell was painted by the last paint, in window coordinates, mirroring RowID: rows and columns are source indices, so scrolling and sorting do not renumber them. The rectangle is the whole cell, not the part the clip leaves visible, so an overlay can cover it. The records come from the same components.TableCellBounds layout the rows are painted from, once per table per frame, into state kept across frames: a warm table records them without allocating. Frozen columns answer at the band's pinned origin, the rest at the painted offset. A header is not a source cell and has no rectangle. --- ui/table.go | 16 ++- ui/tablecell.go | 71 +++++++++++++ ui/tablecell_test.go | 230 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 315 insertions(+), 2 deletions(-) create mode 100644 ui/tablecell.go create mode 100644 ui/tablecell_test.go 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") + } +} From 819f1b5a266a0a7fcf2420b4f3bb8a66d35313f7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 18:38:40 +0800 Subject: [PATCH 40/86] feat(components): draw italic runs in the code editor CodeEditorRun now carries Italic, and gridRuns passes it to the gfx.TextRun of the range, so a highlighter can slant a comment the way an editor does. Runs that differ only in slant are not merged into one upright run, and the sanitizer keeps the bit. Every fixed-pitch backend already reads TextRun.Italic (darwin slant, linux Pango, windows DirectWrite/GDI, web CSS), so the grid path needs no new platform code. The component demo draws its comments italic, and the darwin italic regression test proves that a grid run's slant changes the pixels. --- cmd/viva/templates/code_editor.go.txt | 8 +- cmd/viva/templates/code_editor_layout.go.txt | 11 +- components/code_editor.go | 8 +- components/code_editor_layout.go | 11 +- components/code_editor_test.go | 110 ++++++++++++++++++ gfx/canvas.go | 7 +- gfx/label_runs_test.go | 10 +- internal/componentdemo/code_editor.go | 7 +- .../darwin/text_italic_regression_test.go | 48 ++++++++ 9 files changed, 197 insertions(+), 23 deletions(-) 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/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_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/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/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/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) + } +} From 479721c8962d596be8cc477668c4c1ff5a6a0c97 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 18:50:23 +0800 Subject: [PATCH 41/86] fix(ui): float Select popups outside ancestor scroll clips A Select list is declared during the page paint, inside whatever clips its ancestors push, so a list opened near the bottom of a scroll area was cut to the few pixels left inside it. The workaround was to leave room under it. Give the popup the same viewport-scoped float components.SingleSelect and MultiSelect already use: SelectOptions.Viewport, when set, suspends the ancestor clips for the length of the surface, each row and the scrollbar with Canvas.PushOverlayClip, so the list paints and hit-tests whole over the page. The scroll position, focus scope, Escape target, dismiss backdrop and the Unpainted path are unchanged. A component called without a viewport keeps its ancestor clips, as before. The row and scrollbar clipping lives in menuSurface, shared by Select, Combobox, the menus and the command list; only Select sets the new viewport, so none of the others change. ui.Select passes the frame bounds, from which the list was already clipped and placed. --- cmd/viva/templates/dropdown_menu.go.txt | 26 ++++++ cmd/viva/templates/select.go.txt | 15 ++++ components/dropdown_menu.go | 26 ++++++ components/select.go | 15 ++++ components/select_test.go | 92 +++++++++++++++++++++ components/single_select_test.go | 46 +++++++++++ ui/select.go | 3 +- ui/select_test.go | 102 ++++++++++++++++++++++++ 8 files changed, 324 insertions(+), 1 deletion(-) diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index 973533a97..c84e29f6c 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -703,6 +703,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 @@ -813,9 +819,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 { @@ -1080,6 +1104,7 @@ 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 !scroll.BarID.IsZero() { @@ -1087,6 +1112,7 @@ func (menu *menuSurface) end() { "Scroll", gfx.HitOptions{Role: gfx.RoleSlider, SkipFocus: true}) } menu.popOverlay() + menu.popClip() } if menu.animated { menu.canvas.EndPresence() 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/components/dropdown_menu.go b/components/dropdown_menu.go index 4fd14679b..c67ee28cd 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -703,6 +703,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 @@ -813,9 +819,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 { @@ -1080,6 +1104,7 @@ 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 !scroll.BarID.IsZero() { @@ -1087,6 +1112,7 @@ func (menu *menuSurface) end() { "Scroll", gfx.HitOptions{Role: gfx.RoleSlider, SkipFocus: true}) } menu.popOverlay() + menu.popClip() } if menu.animated { menu.canvas.EndPresence() 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/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") + } +} From a823813bb28d764e7aecb654041895dcc478e1fb Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 19:29:42 +0800 Subject: [PATCH 42/86] feat(text): support multiple selections in an editor text.Editor keeps a CodeMirror-shaped selection set: one primary selection, which Selection and Caret still report, plus secondary ones. Selections, SelectionsInto and SelectionSpansInto read the set, AddSelection and SetSelections write it and merge overlaps, and ClearSecondarySelections goes back to the primary alone. Insert and Delete apply to every selection as one undo unit through ReplaceRangesWith, so the text changes in a single buffer replacement and no later selection's offset is ever read after an earlier one moved it; each selection becomes a caret after what it replaced. A composition, restricted editor, overwriting editor, movement, Undo/Redo and the single-range and line commands end with the primary alone, as before. InputSnapshot, TextareaSnapshot and ui.Field paint SelectionRanges, so a field or code editor driven from an editor's SelectionSpansInto paints every selection, with the caret only on the primary. The single selection path is unchanged. --- cmd/viva/templates/input.go.txt | 61 ++- cmd/viva/templates/textarea.go.txt | 26 +- .../code_editor_editor_multiselection_test.go | 67 +++ components/input.go | 61 ++- components/input_multiselection_test.go | 78 ++++ components/textarea.go | 26 +- components/textarea_multiselection_test.go | 49 ++ text/code.go | 12 +- text/editing.go | 2 + text/editor.go | 43 +- text/multi_replace.go | 3 + text/multiselection.go | 427 ++++++++++++++++++ text/multiselection_test.go | 206 +++++++++ text/multiselection_verbs_test.go | 116 +++++ text/transaction.go | 3 + ui/field.go | 12 + ui/field_multiselection_test.go | 63 +++ 17 files changed, 1208 insertions(+), 47 deletions(-) create mode 100644 components/code_editor_editor_multiselection_test.go create mode 100644 components/input_multiselection_test.go create mode 100644 components/textarea_multiselection_test.go create mode 100644 text/multiselection.go create mode 100644 text/multiselection_test.go create mode 100644 text/multiselection_verbs_test.go create mode 100644 ui/field_multiselection_test.go 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/textarea.go.txt b/cmd/viva/templates/textarea.go.txt index 3303cc24c..904f44cb2 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 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/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/textarea.go b/components/textarea.go index b5363bf43..a9de9ea3e 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 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/text/code.go b/text/code.go index 2882ecd57..09ae4276f 100644 --- a/text/code.go +++ b/text/code.go @@ -102,6 +102,9 @@ 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. + editor.clearSecondary() before := editor.selectionState() change := editor.replace(target, string(replacement), false) editor.anchor = clamp(anchor, 0, len(editor.runes)) @@ -462,7 +465,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 +513,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,6 +684,7 @@ 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.clearSecondary() // one range replaced, one caret left target = normalizeRange(target, len(editor.runes)) before := editor.selectionState() change := editor.replace(target, value, false) diff --git a/text/editing.go b/text/editing.go index 74902501a..3c709c680 100644 --- a/text/editing.go +++ b/text/editing.go @@ -118,6 +118,7 @@ func WordRange(value string, index int) Range { // 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 +161,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/editor.go b/text/editor.go index 1e7a950d6..1430e286d 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 @@ -219,6 +223,7 @@ func (editor *Editor) SetSelection(selection Range) { } editor.anchor = anchor editor.caret = caret + editor.clearSecondary() editor.composing = false editor.releaseCompositionHistory() } @@ -226,7 +231,8 @@ 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.BreakUndoGroup() index = clamp(index, 0, len(editor.runes)) @@ -235,6 +241,7 @@ func (editor *Editor) MoveTo(index int, extend bool) { } else { editor.collapse(index) } + editor.clearSecondary() editor.composing = false editor.releaseCompositionHistory() } @@ -245,8 +252,13 @@ 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 { @@ -284,6 +296,11 @@ func (editor *Editor) Paste(value string) { // text. selected is relative to the marked text, matching native IME APIs. func (editor *Editor) SetMarkedText(value string, selected Range) { wasComposing := editor.composing + if !wasComposing { + // The input method composes at the caret: a multi-selection ends here, as + // it does for any edit made through one selection. + editor.clearSecondary() + } target := editor.Selection() if wasComposing { target = editor.composition @@ -361,8 +378,12 @@ 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 { + if editor.multiDelete(false) { + return true + } if editor.deleteSelectionOrComposition() { return true } @@ -383,8 +404,12 @@ 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 { + if editor.multiDelete(true) { + return true + } if editor.deleteSelectionOrComposition() { return true } @@ -406,6 +431,7 @@ func (editor *Editor) DeleteForward() bool { // UAX #9 displays it in. func (editor *Editor) MoveLeft(extend bool) bool { editor.BreakUndoGroup() + editor.clearSecondary() // a movement moves the primary selection alone editor.composing = false editor.releaseCompositionHistory() selection := editor.Selection() @@ -430,6 +456,7 @@ func (editor *Editor) MoveLeft(extend bool) bool { // (see MoveLeft). func (editor *Editor) MoveRight(extend bool) bool { editor.BreakUndoGroup() + editor.clearSecondary() // see MoveLeft editor.composing = false editor.releaseCompositionHistory() selection := editor.Selection() @@ -507,6 +534,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 @@ -659,6 +687,7 @@ 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() } diff --git a/text/multi_replace.go b/text/multi_replace.go index 2646be7ac..c2ea5dc3a 100644 --- a/text/multi_replace.go +++ b/text/multi_replace.go @@ -155,6 +155,9 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang func (editor *Editor) commitBatch(target Range, replacement string, primitives []Edit, contexts []lineContext, after *Range) { target = normalizeRange(target, len(editor.runes)) + // 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 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/transaction.go b/text/transaction.go index a003da02f..5916f0b19 100644 --- a/text/transaction.go +++ b/text/transaction.go @@ -54,6 +54,9 @@ 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 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) + } +} From 83fe4f5ca5e9f268bca7007447e69433bcbb1330 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 21:41:19 +0800 Subject: [PATCH 43/86] fix(app): resolve a missing path's icon from its type on macOS Refs: t8y2/motty#854 --- app/file_icon_darwin_test.go | 26 ++++++++++++++++++++ docs/system-integrations.md | 2 +- internal/platform/darwin/file_icon_darwin.go | 2 +- internal/platform/darwin/file_icon_darwin.h | 10 +++++--- internal/platform/darwin/file_icon_darwin.m | 24 +++++++++++++++++- 5 files changed, 57 insertions(+), 7 deletions(-) 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/docs/system-integrations.md b/docs/system-integrations.md index 5eec83a39..ac2d8c640 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -25,7 +25,7 @@ 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 | 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; From cee05b936a534d162fbbf8a97764589f90d624a3 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:26:04 +0800 Subject: [PATCH 44/86] fix(update): repair patch test portability and Windows payload paths --- update/install_windows.go | 3 +++ update/install_windows_test.go | 28 ++++++++++++++++++++++++---- update/patch_test.go | 34 +++++++++++++++++++++++++++++----- 3 files changed, 56 insertions(+), 9 deletions(-) diff --git a/update/install_windows.go b/update/install_windows.go index 415958622..dbf6985a1 100644 --- a/update/install_windows.go +++ b/update/install_windows.go @@ -213,8 +213,11 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, 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") diff --git a/update/install_windows_test.go b/update/install_windows_test.go index 3cb4c6839..38fc35fd1 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -321,8 +321,8 @@ func runPayloadHelper(t *testing.T, script string, wantExit int) { } func TestPayloadHelperReplacesTheApplication(t *testing.T) { - payload := t.TempDir() - install := t.TempDir() + 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 { @@ -356,12 +356,21 @@ func TestPayloadHelperRollsBackAFailedStart(t *testing.T) { payload := t.TempDir() install := t.TempDir() original := copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(install, "app.exe")) - copyWindowsFile(t, systemExecutable(t, "cmd.exe"), filepath.Join(payload, "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{"/c", "exit 1"}) + 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) @@ -373,3 +382,14 @@ func TestPayloadHelperRollsBackAFailedStart(t *testing.T) { 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_test.go b/update/patch_test.go index aa49e508a..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) @@ -259,9 +266,15 @@ func TestApplyPatchChecksNameAndVersions(t *testing.T) { 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: payload, + 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}) @@ -269,9 +282,20 @@ func TestApplyPatchChecksNameAndVersions(t *testing.T) { original := locateInstalledPayload defer func() { locateInstalledPayload = original }() located := payload - locateInstalledPayload = func() (string, string, error) { return oldRoot, located, nil } + 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) } From db50fd0d9b3716e05fa6a51875a79ae1d0856a62 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:26:18 +0800 Subject: [PATCH 45/86] fix(ibus): preserve preedit mode and visibility provenance --- .github/workflows/text-input.yml | 5 + internal/ibus/ibus.go | 75 +++++++++--- internal/ibus/ibus_test.go | 172 +++++++++++++++++++++++++-- internal/platform/linux/ime_linux.go | 6 +- 4 files changed, 229 insertions(+), 29 deletions(-) diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 53228c65a..40cfd27f2 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -5,11 +5,13 @@ on: paths: - 'app/**' - 'internal/platform/**' + - 'internal/ibus/**' - '.github/workflows/text-input.yml' pull_request: paths: - 'app/**' - 'internal/platform/**' + - 'internal/ibus/**' - '.github/workflows/text-input.yml' workflow_dispatch: @@ -42,6 +44,9 @@ jobs: cache: true - name: Application input lifecycle run: go test ./app -count=1 + - 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: Windows IME lifecycle if: runner.os == 'Windows' run: go test ./internal/platform/windows -run 'TestComposition|TestDynamicTextInput' -count=1 diff --git a/internal/ibus/ibus.go b/internal/ibus/ibus.go index 6b9f63089..4c4dbedcf 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 @@ -123,9 +148,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 @@ -408,27 +431,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..f707f2cf4 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" ) @@ -99,8 +101,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 { @@ -211,8 +221,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 +249,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 +364,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 +384,60 @@ 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") +} + +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 +492,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, "你好") @@ -496,15 +645,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/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, From 190ecfed7aa2b85e1843d2641e8f2b3488ca948b Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:28:04 +0800 Subject: [PATCH 46/86] fix(ibus): retire input contexts through the native service --- internal/ibus/ibus.go | 13 ++- internal/ibus/ibus_test.go | 172 +++++++++++++++++++++++++++++++++++++ 2 files changed, 181 insertions(+), 4 deletions(-) diff --git a/internal/ibus/ibus.go b/internal/ibus/ibus.go index 4c4dbedcf..1ded91c5a 100644 --- a/internal/ibus/ibus.go +++ b/internal/ibus/ibus.go @@ -353,7 +353,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 { @@ -369,7 +369,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 @@ -418,10 +418,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) { diff --git a/internal/ibus/ibus_test.go b/internal/ibus/ibus_test.go index f707f2cf4..7f3c26a38 100644 --- a/internal/ibus/ibus_test.go +++ b/internal/ibus/ibus_test.go @@ -147,6 +147,103 @@ 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 TestKeyAnswersArriveInTheOrderTheKeysWereTyped(t *testing.T) { bus, context, transport := newTestBus(t, Handler{}) var order []string @@ -556,6 +653,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 { @@ -586,6 +737,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", From dfc25d161177540742e0260aaa0cff673a763f44 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:28:18 +0800 Subject: [PATCH 47/86] fix(linux): detach GTK input methods before window destruction --- .github/workflows/text-input.yml | 3 + internal/platform/linux/gtk_app_linux.go | 7 +- internal/platform/linux/gtk_window_linux.go | 5 + .../linux/gtk_window_teardown_linux_test.go | 129 ++++++++++++++++++ 4 files changed, 142 insertions(+), 2 deletions(-) create mode 100644 internal/platform/linux/gtk_window_teardown_linux_test.go diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 40cfd27f2..95097b209 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -56,6 +56,9 @@ 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 # 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/internal/platform/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go index 65ed1c15c..4ba7f024c 100644 --- a/internal/platform/linux/gtk_app_linux.go +++ b/internal/platform/linux/gtk_app_linux.go @@ -374,8 +374,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 }), diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index bc64ff2b9..a8104776b 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -363,6 +363,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..4a26c0b0c --- /dev/null +++ b/internal/platform/linux/gtk_window_teardown_linux_test.go @@ -0,0 +1,129 @@ +//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 + g.objectUnref = func(uintptr) {} + 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 { + 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) + } +} + +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) + } + }) + } +} From 7c5f74bd7a86323ae503287608cb66c2d4c1bdfb Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 22:29:28 +0800 Subject: [PATCH 48/86] fix(components): size menu rows by the theme's control height --- cmd/viva/templates/context_menu.go.txt | 9 +++--- cmd/viva/templates/dropdown_menu.go.txt | 22 ++++++++++--- components/context_menu.go | 9 +++--- components/context_menu_test.go | 43 +++++++++++++++++++++++++ components/dropdown_menu.go | 22 ++++++++++--- 5 files changed, 89 insertions(+), 16 deletions(-) diff --git a/cmd/viva/templates/context_menu.go.txt b/cmd/viva/templates/context_menu.go.txt index 2ae972f61..f08c54736 100644 --- a/cmd/viva/templates/context_menu.go.txt +++ b/cmd/viva/templates/context_menu.go.txt @@ -68,9 +68,10 @@ 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 } @@ -121,7 +122,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) } diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index c84e29f6c..fbddc306e 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -237,8 +237,8 @@ func BeginDropdownMenu(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, opt // 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 +606,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) @@ -675,7 +677,8 @@ 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 } @@ -857,6 +860,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 } @@ -956,7 +970,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) diff --git a/components/context_menu.go b/components/context_menu.go index 17b2baf7c..d917b8265 100644 --- a/components/context_menu.go +++ b/components/context_menu.go @@ -68,9 +68,10 @@ 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 } @@ -121,7 +122,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) } 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 c67ee28cd..23005a114 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -237,8 +237,8 @@ func BeginDropdownMenu(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, opt // 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 +606,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) @@ -675,7 +677,8 @@ 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 } @@ -857,6 +860,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 } @@ -956,7 +970,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) From 63475931bd9cedc9af4ec049ac6107b2c3f40e4d Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:36:17 +0800 Subject: [PATCH 49/86] fix(linux): preserve text state across callback reentry --- .github/workflows/text-input.yml | 6 + .../linux/text_callback_linux_test.go | 350 ++++++++++++++++++ internal/platform/linux/text_input_linux.go | 54 ++- 3 files changed, 409 insertions(+), 1 deletion(-) create mode 100644 internal/platform/linux/text_callback_linux_test.go diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 95097b209..721a274b5 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -47,6 +47,12 @@ jobs: - 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: 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 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. From 7a00b92a6ce0bfbfa9ea6363f08c16543f8cd138 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:36:34 +0800 Subject: [PATCH 50/86] fix(textcache): protect reused lines from sketch collisions --- internal/textcache/admission_test.go | 98 +++ .../testdata/adverse-scan-traces.json | 788 ++++++++++++++++++ internal/textcache/textcache.go | 46 +- 3 files changed, 924 insertions(+), 8 deletions(-) create mode 100644 internal/textcache/admission_test.go create mode 100644 internal/textcache/testdata/adverse-scan-traces.json 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 From 9301d117c3321e6cf3511f3eaa36ec95455f74dd Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 22:36:56 +0800 Subject: [PATCH 51/86] fix(update): stage the macOS payload under the running bundle name --- update/install.go | 4 ++- update/install_darwin.go | 17 ++++++++--- update/install_darwin_test.go | 57 +++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/update/install.go b/update/install.go index 350487392..dd764f61c 100644 --- a/update/install.go +++ b/update/install.go @@ -38,7 +38,9 @@ type InstallOptions struct { // Payload is set. Artifact string // Payload is a new application the caller already made with PatchReader.Apply: - // the staged .app on macOS, or the staged executable on Linux. Install + // the staged .app on macOS, or the staged executable on Linux. On macOS the + // directory's own name does not matter, so the one ApplyPatch returns can be + // passed as it is: the copy takes the running bundle's name. Install // replaces the running application with it exactly as it would with an // unpacked archive, running the same checks. Windows has no patch support, // so a payload there reports ErrUnsupported. diff --git a/update/install_darwin.go b/update/install_darwin.go index 7e37d68a1..d628aaaa9 100644 --- a/update/install_darwin.go +++ b/update/install_darwin.go @@ -60,10 +60,7 @@ func install(options InstallOptions, quit func()) error { var staged string if options.Payload != "" { options.report("copying the patched application") - if err := copyTree(options.Payload, filepath.Join(staging, filepath.Base(options.Payload))); err != nil { - return err - } - staged, err = stagedBundle(staging) + staged, err = stagePayload(options.Payload, staging, filepath.Base(bundle)) } else { options.report("unpacking") if err := extractZip(options.Artifact, staging); err != nil { @@ -153,6 +150,18 @@ func isDirectory(path string) bool { // stagedBundle returns the one application bundle at the top of staging. An // archive that holds none, several, or a file with the .app suffix is refused. +// stagePayload copies a patched application into staging as name, the running +// bundle's directory name, and returns the copy. ApplyPatch builds the payload +// in a temporary directory whose own name has no .app suffix, so the copy cannot +// keep it; the helper moves the copy over the running bundle under that name +// anyway. +func stagePayload(payload, staging, name string) (string, error) { + if err := copyTree(payload, filepath.Join(staging, name)); err != nil { + return "", err + } + return stagedBundle(staging) +} + func stagedBundle(staging string) (string, error) { entries, err := os.ReadDir(staging) if err != nil { diff --git a/update/install_darwin_test.go b/update/install_darwin_test.go index 8adba212f..f39507c2a 100644 --- a/update/install_darwin_test.go +++ b/update/install_darwin_test.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "slices" "strings" "testing" @@ -375,3 +376,59 @@ func TestInstallShellQuote(t *testing.T) { } } } + +// TestInstallStagesAnAppliedPatch follows the documented order: ApplyPatch +// rebuilds the bundle in a directory named viva-payload-*, and Install has to +// find that copy as an application bundle. +func TestInstallStagesAnAppliedPatch(t *testing.T) { + oldRoot := filepath.Join(t.TempDir(), "My App.app") + program := []byte("program") + if err := os.MkdirAll(filepath.Join(oldRoot, "Contents", "MacOS"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(oldRoot, "Contents", "MacOS", "My App"), program, 0o755); err != nil { + t.Fatal(err) + } + oldPlist := []byte(strings.Replace(fixtureInfoPlist, "1.2.3", "1.0.0", 1)) + if err := os.WriteFile(filepath.Join(oldRoot, "Contents", "Info.plist"), oldPlist, 0o644); err != nil { + t.Fatal(err) + } + newPlist := []byte(strings.Replace(fixtureInfoPlist, "1.2.3", "1.1.0", 1)) + manifest := PatchManifest{ + Schema: PatchSchema, App: "dev.viva.gallery", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: runtime.GOOS, Arch: runtime.GOARCH, Payload: "app", + Files: []PatchFile{ + fileManifest("Contents/MacOS/My App", program, "same", "", 0o755), + fileManifest("Contents/Info.plist", newPlist, "new", "files/0001", 0o644), + }, + } + patchPath := writePatch(t, manifest, map[string][]byte{"files/0001": newPlist}) + + original := locateInstalledPayload + defer func() { locateInstalledPayload = original }() + locateInstalledPayload = func() (string, string, error) { return oldRoot, "app", nil } + + payload, err := ApplyPatch(patchPath, "dev.viva.gallery", "1.0.0", "1.1.0") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(payload) + staging := t.TempDir() + staged, err := stagePayload(payload, staging, filepath.Base(oldRoot)) + if err != nil { + t.Fatalf("stagePayload: %v", err) + } + if want := filepath.Join(staging, "My App.app"); staged != want { + t.Errorf("staged = %q, want %q", staged, want) + } + info, err := readBundleInfo(staged) + if err != nil { + t.Fatal(err) + } + if info.Identifier != "dev.viva.gallery" || info.Version != "1.1.0" { + t.Errorf("staged bundle = %+v, want dev.viva.gallery 1.1.0", info) + } + if got, err := os.ReadFile(filepath.Join(staged, "Contents", "MacOS", "My App")); err != nil || !slices.Equal(got, program) { + t.Errorf("staged program = %q, %v", got, err) + } +} From 7edc953710d5b409928bbf3390df1fe67709752a Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:41:29 +0800 Subject: [PATCH 52/86] fix(linux): restore clipboard and graphics contract gates --- .github/workflows/text-input.yml | 7 +++ .../linux/clipboard_html_linux_test.go | 61 ++++++++++++++++--- .../linux/clipboard_html_write_linux.go | 4 ++ .../linux/gtk_clipboard_html_linux_test.go | 3 +- internal/platform/linux/layers_test.go | 30 ++++++++- .../platform/linux/window_icon_linux_test.go | 18 ++++-- 6 files changed, 106 insertions(+), 17 deletions(-) diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 721a274b5..0d111bc5e 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -4,14 +4,18 @@ on: push: paths: - 'app/**' + - 'internal/iconshape/**' - 'internal/platform/**' - 'internal/ibus/**' + - 'internal/render/**' - '.github/workflows/text-input.yml' pull_request: paths: - 'app/**' + - 'internal/iconshape/**' - 'internal/platform/**' - 'internal/ibus/**' + - 'internal/render/**' - '.github/workflows/text-input.yml' workflow_dispatch: @@ -65,6 +69,9 @@ jobs: - 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/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_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/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/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 } From ca3f6dfa8ee4d3b3f8bc8b77b07b06e3f68ce39c Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 22:56:11 +0800 Subject: [PATCH 53/86] docs(release): v0.6.4 notes --- docs/releases/0.6.4.md | 87 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 docs/releases/0.6.4.md 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 From 77c8ba3dece6ebea23dd2aebeaef01a8d1506b46 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 23:03:09 +0800 Subject: [PATCH 54/86] docs: point at v0.6.4 --- README.md | 2 +- README.zh-CN.md | 2 +- website/content/guides/en/getting-started.md | 2 +- website/content/guides/zh/getting-started.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3c79b1eb6..87769b96b 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 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/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` 指向检出目录: From ebe264aac42695a7e956dd22fe45645c1b1110d4 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 23:07:29 +0800 Subject: [PATCH 55/86] feat(app): keep the machine awake while work needs it PreventSleep holds an idle-sleep inhibitor named by the work: an IOKit assertion on macOS, a power request on Windows, and logind's inhibitor on Linux, whose lock arrives as a unix file descriptor and therefore extends the D-Bus client to receive descriptors. The call starts no goroutine or timer; the request ends with its release or the process. The capability is reusable desktop behavior and lives in Viva; which work is worth keeping a machine awake for is the application's policy. Motty holds one request while a file transfer moves bytes, as the companion change in that repository. --- README.md | 4 + app/capabilities.go | 3 + app/capabilities_native.go | 3 +- app/driver_system.go | 43 ++++++++ app/driver_system_unsupported.go | 2 + app/keepawake.go | 54 +++++++++++ app/keepawake_darwin.go | 18 ++++ app/keepawake_driver_test.go | 39 ++++++++ app/keepawake_js.go | 7 ++ app/keepawake_linux.go | 18 ++++ app/keepawake_test.go | 14 +++ app/keepawake_unsupported.go | 5 + app/keepawake_windows.go | 18 ++++ docs/system-integrations.md | 1 + internal/dbus/conn.go | 74 +++++++++++++- internal/dbus/doc.go | 9 +- internal/dbus/fd_test.go | 97 +++++++++++++++++++ internal/dbus/fd_unix.go | 24 +++++ internal/dbus/message.go | 14 +++ internal/dbus/wire.go | 8 +- internal/platform/darwin/sleep_darwin.go | 42 ++++++++ internal/platform/darwin/sleep_darwin.h | 12 +++ internal/platform/darwin/sleep_darwin.m | 44 +++++++++ internal/platform/darwin/sleep_darwin_test.go | 14 +++ internal/platform/linux/sleep_linux.go | 55 +++++++++++ internal/platform/linux/sleep_linux_test.go | 23 +++++ internal/platform/windows/sleep_windows.go | 77 +++++++++++++++ .../platform/windows/sleep_windows_test.go | 20 ++++ 28 files changed, 731 insertions(+), 11 deletions(-) create mode 100644 app/keepawake.go create mode 100644 app/keepawake_darwin.go create mode 100644 app/keepawake_driver_test.go create mode 100644 app/keepawake_js.go create mode 100644 app/keepawake_linux.go create mode 100644 app/keepawake_test.go create mode 100644 app/keepawake_unsupported.go create mode 100644 app/keepawake_windows.go create mode 100644 internal/dbus/fd_test.go create mode 100644 internal/dbus/fd_unix.go create mode 100644 internal/platform/darwin/sleep_darwin.go create mode 100644 internal/platform/darwin/sleep_darwin.h create mode 100644 internal/platform/darwin/sleep_darwin.m create mode 100644 internal/platform/darwin/sleep_darwin_test.go create mode 100644 internal/platform/linux/sleep_linux.go create mode 100644 internal/platform/linux/sleep_linux_test.go create mode 100644 internal/platform/windows/sleep_windows.go create mode 100644 internal/platform/windows/sleep_windows_test.go diff --git a/README.md b/README.md index 87769b96b..6be966ff3 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,10 @@ 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. - `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/app/capabilities.go b/app/capabilities.go index 56761c77d..a51e86607 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -36,6 +36,9 @@ 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 ) // Capabilities is a set of platform integrations. diff --git a/app/capabilities_native.go b/app/capabilities_native.go index 5cb9a2890..f71d2afc8 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -30,7 +30,8 @@ func nativeCapabilities() Capabilities { CapabilityFullscreen | CapabilityWindowFrame | CapabilityWindowMinimize | - CapabilityReduceMotion + CapabilityReduceMotion | + CapabilityPreventSleep if runtime.GOOS == "darwin" { capabilities |= CapabilityNativeAppearance } else { diff --git a/app/driver_system.go b/app/driver_system.go index 75190a4c5..fcfa5a226 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 1f35e4d2f..3826d0750 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -50,3 +50,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/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/docs/system-integrations.md b/docs/system-integrations.md index ac2d8c640..b970ddd4e 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -30,6 +30,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | 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 | | 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/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/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/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/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") + } +} From 94c3710944090240b6a9d9427976ebf8beb2dfb3 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 23:12:57 +0800 Subject: [PATCH 56/86] fix(windows): color the window border to match the window edge Windows 11 composites the border that DwmExtendFrameIntoClientArea draws around a custom-titlebar window against the desktop, not against the window's own pixels, so the background shows through a 1 DIP ring that grows with the display scale. Add Config.WindowBorderColor, read with every frame, and give the border the application's edge color through DWMWA_BORDER_COLOR, defaulting to ClearColor when the application names none. Material-backed and transparent windows keep the system border. The companion Motty commit passes each window's theme color so the border follows a light or dark switch. --- app/app.go | 9 +++ app/run.go | 1 + app/run_canvas.go | 18 ++++- internal/platform/contract.go | 9 +++ internal/platform/windows/border_windows.go | 66 +++++++++++++++++ .../platform/windows/border_windows_test.go | 74 +++++++++++++++++++ internal/platform/windows/window_windows.go | 8 +- 7 files changed, 182 insertions(+), 3 deletions(-) create mode 100644 internal/platform/windows/border_windows.go create mode 100644 internal/platform/windows/border_windows_test.go diff --git a/app/app.go b/app/app.go index 1118c2284..427853d90 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/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/internal/platform/contract.go b/internal/platform/contract.go index 02ee5a0eb..060999389 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 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/window_windows.go b/internal/platform/windows/window_windows.go index 3fd088f18..33feea52b 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -140,7 +140,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] @@ -381,6 +385,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) @@ -944,6 +949,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) From 477614e763690efddaf441b552e47108a6425fab Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 23:42:38 +0800 Subject: [PATCH 57/86] feat(api): enforce the typed page boundary Every Base now has a contract test that it paints no surface and declares the role and state assistive technology reads. The page guide names the controls that paint their own surface and the four steps to restyle one, from theme tokens to a Base and recipe, parts, and Control. tools/apicheck fails the build when an exported symbol in ui, components, app or gfx names any or interface{} or imports reflect, with an allowlist for ui.Textf's format arguments. CI runs it beside gofmt and vet. --- .github/workflows/ci.yml | 5 + tools/apicheck/allow.txt | 8 + tools/apicheck/apicheck_test.go | 97 +++++++++++ tools/apicheck/main.go | 275 ++++++++++++++++++++++++++++++++ ui/base_contract_test.go | 53 ++++++ ui/doc.go | 12 ++ 6 files changed, 450 insertions(+) create mode 100644 tools/apicheck/allow.txt create mode 100644 tools/apicheck/apicheck_test.go create mode 100644 tools/apicheck/main.go create mode 100644 ui/base_contract_test.go 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/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/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/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 From 1687747326ecb1d8d9630738b6c3c74d666320f0 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 23:59:32 +0800 Subject: [PATCH 58/86] feat(ui): let a page replace its recipes and paint its menus Styles gives a page one place to replace the button, checkbox, switch and text-entry recipes, and a nil field keeps the theme's. The components' recipe overrides make the same look reach the buttons a component paints. A menu can be declared Unpainted: the menu keeps its size, hits, focus, keyboard, dismissal and submenu behavior, while DrawPanel and DrawItem paint the surface and rows from the rectangles the menu lays out. --- components/button.go | 20 ++++++ components/checkbox.go | 12 ++++ components/context_menu.go | 6 ++ components/dropdown_menu.go | 137 +++++++++++++++++++++++++++++------- components/switch.go | 15 ++++ ui/frame.go | 1 + ui/menu.go | 87 +++++++++++++++++++++++ ui/menu_parts_test.go | 56 +++++++++++++++ ui/page.go | 6 ++ ui/paint.go | 9 +++ ui/recipe.go | 16 ++++- ui/styles.go | 33 +++++++++ ui/styles_test.go | 77 ++++++++++++++++++++ 13 files changed, 448 insertions(+), 27 deletions(-) create mode 100644 ui/menu_parts_test.go create mode 100644 ui/styles.go create mode 100644 ui/styles_test.go 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/context_menu.go b/components/context_menu.go index d917b8265..ced040f27 100644 --- a/components/context_menu.go +++ b/components/context_menu.go @@ -73,6 +73,11 @@ type ContextMenuOptions struct { // 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. @@ -146,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/dropdown_menu.go b/components/dropdown_menu.go index 23005a114..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,6 +239,7 @@ 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, })} } @@ -656,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 @@ -680,6 +712,11 @@ type menuSurfaceOptions struct { // 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 @@ -773,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 } @@ -888,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, @@ -901,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) }) @@ -979,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 @@ -1003,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 @@ -1095,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, @@ -1120,7 +1207,9 @@ func (menu *menuSurface) end() { 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}) 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/ui/frame.go b/ui/frame.go index 5687eb37e..8c285b79d 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 nodes []node inputs []components.InputSnapshot addons []fieldAddons // the icons and buttons inside fields, by 1 + extra.addons diff --git a/ui/menu.go b/ui/menu.go index 67ab6c115..8f5d7fc43 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -109,6 +109,9 @@ func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, an 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 @@ -150,6 +153,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 } @@ -283,6 +287,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 { @@ -504,6 +589,7 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer 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, + Unpainted: m.unpainted, PaintPanel: m.panelPainter, PaintItem: m.itemPainter, }) for i := range m.items { switch row := &m.items[i]; row.kind { @@ -536,6 +622,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/page.go b/ui/page.go index 2bc314ddb..fd87add25 100644 --- a/ui/page.go +++ b/ui/page.go @@ -206,6 +206,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 } // Page is a window's declaration: one tree for the whole window. A Page lives @@ -788,6 +793,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 p.ctx.page, p.ctx.f, p.ctx.nextSet = p, f, false p.nodes = append(p.nodes[:0], protoNode{scope: p.root, named: true, parentNode: -1}) // node 0, the root column 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/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())) + } +} From 83c0ec82671a783564070337ce2034d5f7c25304 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 14 Nov 2026 23:59:33 +0800 Subject: [PATCH 59/86] feat(app): read the desktop's proxy settings SystemProxy reports the proxy the desktop selects for an HTTP URL: the environment first, then CFNetwork on macOS (a PAC policy is an error, not a silent direct connection) and WinHTTP's automatic proxy on Windows. Linux reads the environment; a proxy kept in GSettings is documented as unread rather than guessed. CapabilitySystemProxy reports the target. --- README.md | 4 + app/capabilities.go | 4 + app/capabilities_native.go | 3 +- app/proxy.go | 66 ++++++++ app/proxy_darwin.go | 19 +++ app/proxy_js.go | 7 + app/proxy_linux.go | 11 ++ app/proxy_test.go | 63 +++++++ app/proxy_unsupported.go | 7 + app/proxy_windows.go | 19 +++ docs/system-integrations.md | 1 + internal/platform/darwin/proxy_darwin.go | 50 ++++++ internal/platform/darwin/proxy_darwin.h | 10 ++ internal/platform/darwin/proxy_darwin.m | 93 ++++++++++ internal/platform/darwin/proxy_darwin_test.go | 17 ++ internal/platform/windows/proxy_windows.go | 159 ++++++++++++++++++ .../platform/windows/proxy_windows_test.go | 15 ++ 17 files changed, 547 insertions(+), 1 deletion(-) create mode 100644 app/proxy.go create mode 100644 app/proxy_darwin.go create mode 100644 app/proxy_js.go create mode 100644 app/proxy_linux.go create mode 100644 app/proxy_test.go create mode 100644 app/proxy_unsupported.go create mode 100644 app/proxy_windows.go create mode 100644 internal/platform/darwin/proxy_darwin.go create mode 100644 internal/platform/darwin/proxy_darwin.h create mode 100644 internal/platform/darwin/proxy_darwin.m create mode 100644 internal/platform/darwin/proxy_darwin_test.go create mode 100644 internal/platform/windows/proxy_windows.go create mode 100644 internal/platform/windows/proxy_windows_test.go diff --git a/README.md b/README.md index 6be966ff3..10f935904 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,10 @@ WebView and no bundled rendering runtime. 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. +- `app.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/app/capabilities.go b/app/capabilities.go index a51e86607..28cbb6cc1 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -39,6 +39,10 @@ const ( // 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 SystemProxy can read the desktop's proxy + // settings. Linux reads the environment only, and macOS reports a PAC + // policy as ErrSystemProxyUnavailable. + CapabilitySystemProxy ) // Capabilities is a set of platform integrations. diff --git a/app/capabilities_native.go b/app/capabilities_native.go index f71d2afc8..31281cb49 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -31,7 +31,8 @@ func nativeCapabilities() Capabilities { CapabilityWindowFrame | CapabilityWindowMinimize | CapabilityReduceMotion | - CapabilityPreventSleep + CapabilityPreventSleep | + CapabilitySystemProxy if runtime.GOOS == "darwin" { capabilities |= CapabilityNativeAppearance } else { diff --git a/app/proxy.go b/app/proxy.go new file mode 100644 index 000000000..57a46a12a --- /dev/null +++ b/app/proxy.go @@ -0,0 +1,66 @@ +package app + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "os" +) + +// ErrSystemProxyUnavailable 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 ErrSystemProxyUnavailable = 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 +// ErrSystemProxyUnavailable: 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", ErrSystemProxyUnavailable, err) + } + return proxy, err +} + +// errSystemProxyUnavailable is what a platform reports for a policy it cannot +// evaluate; SystemProxy turns it into ErrSystemProxyUnavailable. +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_darwin.go b/app/proxy_darwin.go new file mode 100644 index 000000000..5e0ee101b --- /dev/null +++ b/app/proxy_darwin.go @@ -0,0 +1,19 @@ +//go:build darwin + +package app + +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_js.go b/app/proxy_js.go new file mode 100644 index 000000000..50114f570 --- /dev/null +++ b/app/proxy_js.go @@ -0,0 +1,7 @@ +//go:build js && wasm + +package app + +import "net/url" + +func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrSystemProxyUnavailable } diff --git a/app/proxy_linux.go b/app/proxy_linux.go new file mode 100644 index 000000000..c1a300656 --- /dev/null +++ b/app/proxy_linux.go @@ -0,0 +1,11 @@ +//go:build linux + +package app + +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_test.go b/app/proxy_test.go new file mode 100644 index 000000000..3944335c3 --- /dev/null +++ b/app/proxy_test.go @@ -0,0 +1,63 @@ +package app + +import ( + "net/url" + "os" + "os/exec" + "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 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/proxy_unsupported.go b/app/proxy_unsupported.go new file mode 100644 index 000000000..d576f2e03 --- /dev/null +++ b/app/proxy_unsupported.go @@ -0,0 +1,7 @@ +//go:build !darwin && !windows && !linux && !(js && wasm) + +package app + +import "net/url" + +func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrSystemProxyUnavailable } diff --git a/app/proxy_windows.go b/app/proxy_windows.go new file mode 100644 index 000000000..77beb1e28 --- /dev/null +++ b/app/proxy_windows.go @@ -0,0 +1,19 @@ +//go:build windows + +package app + +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/docs/system-integrations.md b/docs/system-integrations.md index b970ddd4e..d76326175 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -31,6 +31,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | 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 | +| System 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/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/windows/proxy_windows.go b/internal/platform/windows/proxy_windows.go new file mode 100644 index 000000000..6d47aab8f --- /dev/null +++ b/internal/platform/windows/proxy_windows.go @@ -0,0 +1,159 @@ +//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) + options := winHTTPAutoproxyOptions{ + Flags: winHTTPAutoproxyAutoDetect | winHTTPAutoproxyConfigURL, + AutoDetectFlags: winHTTPAutoDetectDHCP | winHTTPAutoDetectDNS, + AutoConfigURL: config.AutoConfigURL, + AutoLogonIfChallenged: 1, + } + 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 { + return nil, fmt.Errorf("%w: WinHttpGetProxyForUrl: %v", ErrProxyUnavailable, callErr) + } + defer freeWinHTTPString(info.Proxy) + defer freeWinHTTPString(info.ProxyBypass) + if info.AccessType == winHTTPAccessTypeNoProxy || info.Proxy == nil { + return nil, nil + } + return parseWinHTTPProxy(utf16PtrToString(info.Proxy), 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..85617c078 --- /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.Skipf("this session's WinHTTP cannot answer: %v", err) + } + if proxy != nil && proxy.Host == "" { + t.Fatalf("proxy = %+v, want a host", proxy) + } +} From cef90445e4a349b435445978e216a57c583e8f25 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 00:02:51 +0800 Subject: [PATCH 60/86] fix(windows): answer direct when proxy auto-detection finds nothing WinHttpGetProxyForUrl answers ERROR_WINHTTP_AUTODETECTION_FAILED on a machine with no WPAD server, which is the normal answer there, not an unavailable policy. The fallback now uses the static per-user proxy when one is set, and otherwise goes direct; only a PAC script that fails is reported as ErrSystemProxyUnavailable. Found by running the same WinHTTP sequence on a Windows 11 machine: the structures are 32, 24 and 32 bytes, and auto-detection with an empty PAC URL returns 87, then 12180 without WPAD. --- internal/platform/windows/proxy_windows.go | 35 ++++++++++++++++--- .../platform/windows/proxy_windows_test.go | 2 +- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/internal/platform/windows/proxy_windows.go b/internal/platform/windows/proxy_windows.go index 6d47aab8f..3fce8ef23 100644 --- a/internal/platform/windows/proxy_windows.go +++ b/internal/platform/windows/proxy_windows.go @@ -73,12 +73,23 @@ func SystemProxy(target string) (*url.URL, error) { 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 | winHTTPAutoproxyConfigURL, + Flags: winHTTPAutoproxyAutoDetect, AutoDetectFlags: winHTTPAutoDetectDHCP | winHTTPAutoDetectDNS, - AutoConfigURL: config.AutoConfigURL, 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) @@ -88,14 +99,28 @@ func SystemProxy(target string) (*url.URL, error) { session, uintptr(unsafe.Pointer(pointer)), uintptr(unsafe.Pointer(&options)), uintptr(unsafe.Pointer(&info)), ); ok == 0 { - return nil, fmt.Errorf("%w: WinHttpGetProxyForUrl: %v", ErrProxyUnavailable, callErr) + // 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 || info.Proxy == nil { + if info.AccessType == winHTTPAccessTypeNoProxy { return nil, nil } - return parseWinHTTPProxy(utf16PtrToString(info.Proxy), target) + 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. diff --git a/internal/platform/windows/proxy_windows_test.go b/internal/platform/windows/proxy_windows_test.go index 85617c078..ed9d8fc09 100644 --- a/internal/platform/windows/proxy_windows_test.go +++ b/internal/platform/windows/proxy_windows_test.go @@ -7,7 +7,7 @@ import "testing" func TestSystemProxyAnswersForAURL(t *testing.T) { proxy, err := SystemProxy("https://example.com/") if err != nil { - t.Skipf("this session's WinHTTP cannot answer: %v", err) + 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) From 3a0c050e2b6035667cb483f321fbe37c1dc3d15b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 00:12:03 +0800 Subject: [PATCH 61/86] fix(viva): regenerate the component installer templates The components gained the recipe overrides and the menu paint hooks, so viva add's generated sources no longer matched their reference components; the darwin, Linux and wasm test jobs failed on TestInstalledRecipesMatchReferenceSource. go generate ./cmd/viva refreshes them. --- .../native_darwin.go} | 0 app/{proxy_js.go => proxy/native_js.go} | 0 app/{proxy_linux.go => proxy/native_linux.go} | 0 .../native_unsupported.go} | 0 .../native_windows.go} | 0 app/{ => proxy}/proxy.go | 0 app/{ => proxy}/proxy_test.go | 0 cmd/viva/templates/button.go.txt | 20 +++ cmd/viva/templates/checkbox.go.txt | 12 ++ cmd/viva/templates/context_menu.go.txt | 6 + cmd/viva/templates/dropdown_menu.go.txt | 137 +++++++++++++++--- cmd/viva/templates/switch.go.txt | 15 ++ 12 files changed, 166 insertions(+), 24 deletions(-) rename app/{proxy_darwin.go => proxy/native_darwin.go} (100%) rename app/{proxy_js.go => proxy/native_js.go} (100%) rename app/{proxy_linux.go => proxy/native_linux.go} (100%) rename app/{proxy_unsupported.go => proxy/native_unsupported.go} (100%) rename app/{proxy_windows.go => proxy/native_windows.go} (100%) rename app/{ => proxy}/proxy.go (100%) rename app/{ => proxy}/proxy_test.go (100%) diff --git a/app/proxy_darwin.go b/app/proxy/native_darwin.go similarity index 100% rename from app/proxy_darwin.go rename to app/proxy/native_darwin.go diff --git a/app/proxy_js.go b/app/proxy/native_js.go similarity index 100% rename from app/proxy_js.go rename to app/proxy/native_js.go diff --git a/app/proxy_linux.go b/app/proxy/native_linux.go similarity index 100% rename from app/proxy_linux.go rename to app/proxy/native_linux.go diff --git a/app/proxy_unsupported.go b/app/proxy/native_unsupported.go similarity index 100% rename from app/proxy_unsupported.go rename to app/proxy/native_unsupported.go diff --git a/app/proxy_windows.go b/app/proxy/native_windows.go similarity index 100% rename from app/proxy_windows.go rename to app/proxy/native_windows.go diff --git a/app/proxy.go b/app/proxy/proxy.go similarity index 100% rename from app/proxy.go rename to app/proxy/proxy.go diff --git a/app/proxy_test.go b/app/proxy/proxy_test.go similarity index 100% rename from app/proxy_test.go rename to app/proxy/proxy_test.go 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/context_menu.go.txt b/cmd/viva/templates/context_menu.go.txt index f08c54736..8aa65ab90 100644 --- a/cmd/viva/templates/context_menu.go.txt +++ b/cmd/viva/templates/context_menu.go.txt @@ -73,6 +73,11 @@ type ContextMenuOptions struct { // 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. @@ -146,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 fbddc306e..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,6 +239,7 @@ 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, })} } @@ -656,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 @@ -680,6 +712,11 @@ type menuSurfaceOptions struct { // 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 @@ -773,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 } @@ -888,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, @@ -901,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) }) @@ -979,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 @@ -1003,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 @@ -1095,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, @@ -1120,7 +1207,9 @@ func (menu *menuSurface) end() { 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}) 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) From 134a178057428cf12a47184ea97fa6a2f76965ef Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 00:12:03 +0800 Subject: [PATCH 62/86] refactor(app): move the proxy reader into its own package Importing net/http from app linked net/http and its TLS stack into every application, including ones that never ask for a proxy: hello darwin/arm64 grew from 4.19 MB to 5.58 MB, past the size alarm. app/proxy is opt-in, so an application that does not import it pays nothing; CapabilitySystemProxy stays in app, and the documentation names the package. --- README.md | 2 +- app/capabilities.go | 6 +++--- app/proxy/native_darwin.go | 2 +- app/proxy/native_js.go | 4 ++-- app/proxy/native_linux.go | 2 +- app/proxy/native_unsupported.go | 4 ++-- app/proxy/native_windows.go | 2 +- app/proxy/proxy.go | 16 ++++++++++------ app/proxy/proxy_test.go | 2 +- docs/system-integrations.md | 2 +- 10 files changed, 23 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 10f935904..1335ef29f 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ WebView and no bundled rendering runtime. 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. -- `app.SystemProxy` reports the proxy the desktop selects for an HTTP URL: +- `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. diff --git a/app/capabilities.go b/app/capabilities.go index 28cbb6cc1..12b6c3012 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -39,9 +39,9 @@ const ( // 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 SystemProxy can read the desktop's proxy - // settings. Linux reads the environment only, and macOS reports a PAC - // policy as ErrSystemProxyUnavailable. + // 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 ) diff --git a/app/proxy/native_darwin.go b/app/proxy/native_darwin.go index 5e0ee101b..b88aa6eea 100644 --- a/app/proxy/native_darwin.go +++ b/app/proxy/native_darwin.go @@ -1,6 +1,6 @@ //go:build darwin -package app +package proxy import ( "errors" diff --git a/app/proxy/native_js.go b/app/proxy/native_js.go index 50114f570..3b5c6f503 100644 --- a/app/proxy/native_js.go +++ b/app/proxy/native_js.go @@ -1,7 +1,7 @@ //go:build js && wasm -package app +package proxy import "net/url" -func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrSystemProxyUnavailable } +func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrUnavailable } diff --git a/app/proxy/native_linux.go b/app/proxy/native_linux.go index c1a300656..f4b0a3e86 100644 --- a/app/proxy/native_linux.go +++ b/app/proxy/native_linux.go @@ -1,6 +1,6 @@ //go:build linux -package app +package proxy import "net/url" diff --git a/app/proxy/native_unsupported.go b/app/proxy/native_unsupported.go index d576f2e03..5488aa63a 100644 --- a/app/proxy/native_unsupported.go +++ b/app/proxy/native_unsupported.go @@ -1,7 +1,7 @@ //go:build !darwin && !windows && !linux && !(js && wasm) -package app +package proxy import "net/url" -func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrSystemProxyUnavailable } +func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrUnavailable } diff --git a/app/proxy/native_windows.go b/app/proxy/native_windows.go index 77beb1e28..ead6795bc 100644 --- a/app/proxy/native_windows.go +++ b/app/proxy/native_windows.go @@ -1,6 +1,6 @@ //go:build windows -package app +package proxy import ( "errors" diff --git a/app/proxy/proxy.go b/app/proxy/proxy.go index 57a46a12a..6cef6ffcc 100644 --- a/app/proxy/proxy.go +++ b/app/proxy/proxy.go @@ -1,4 +1,8 @@ -package app +// 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" @@ -8,12 +12,12 @@ import ( "os" ) -// ErrSystemProxyUnavailable reports that the desktop's proxy settings could not +// 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 ErrSystemProxyUnavailable = errors.New("app: the system proxy settings cannot be 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, @@ -27,7 +31,7 @@ var ErrSystemProxyUnavailable = errors.New("app: the system proxy settings canno // package does not start a D-Bus or GIO session to find it. // // A macOS system whose policy is a PAC script returns -// ErrSystemProxyUnavailable: evaluating the script is asynchronous and needs a +// 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 @@ -42,13 +46,13 @@ func SystemProxy(target *url.URL) (*url.URL, error) { } proxy, err := nativeSystemProxy(target) if errors.Is(err, errSystemProxyUnavailable) { - return nil, fmt.Errorf("%w: %v", ErrSystemProxyUnavailable, err) + 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 ErrSystemProxyUnavailable. +// 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. diff --git a/app/proxy/proxy_test.go b/app/proxy/proxy_test.go index 3944335c3..3efe13fce 100644 --- a/app/proxy/proxy_test.go +++ b/app/proxy/proxy_test.go @@ -1,4 +1,4 @@ -package app +package proxy import ( "net/url" diff --git a/docs/system-integrations.md b/docs/system-integrations.md index d76326175..e1e72fd19 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -31,7 +31,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | 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 | -| System 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` | +| 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 | From 0fc452c83077ee8ab82f610535cbdf491fdfa4ab Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 00:16:58 +0800 Subject: [PATCH 63/86] fix(proxy): skip the child-process test under the wasm runtime The environment test starts a helper process to read a fresh environment; a js/wasm test cannot start one, so the web job failed with 'pipe: not implemented on js'. The test now skips there, and the rest of the package still runs under wasm. --- app/proxy/proxy_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/proxy/proxy_test.go b/app/proxy/proxy_test.go index 3efe13fce..5d37a1cdf 100644 --- a/app/proxy/proxy_test.go +++ b/app/proxy/proxy_test.go @@ -4,6 +4,7 @@ import ( "net/url" "os" "os/exec" + "runtime" "strings" "testing" ) @@ -27,6 +28,9 @@ func TestSystemProxyNeedsAnHTTPURL(t *testing.T) { // 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 { From 53de03c9547f5a26c030189c5985909fbeba4b75 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 00:33:18 +0800 Subject: [PATCH 64/86] feat(text): select the word or line a multi-click press lands on placeCaret now honors ClickCount for fields that lay their rows out themselves: a double press takes the word under the pointer, a triple press its line, and a drag while held extends the selection by that unit. A double press on whitespace leaves the caret alone instead of selecting the newlines. text.LineRange provides the line range both the framework and its tests use. --- app/painter.go | 71 ++++++++++++++++++++++++++++++++++++++---- app/place_unit_test.go | 47 ++++++++++++++++++++++++++++ text/editing.go | 22 +++++++++++++ text/editing_test.go | 6 ++++ 4 files changed, 140 insertions(+), 6 deletions(-) create mode 100644 app/place_unit_test.go diff --git a/app/painter.go b/app/painter.go index 8e7c0e9a0..63dc6cc1f 100644 --- a/app/painter.go +++ b/app/painter.go @@ -7,6 +7,7 @@ import ( "math" "slices" "time" + "unicode" "unicode/utf8" "unsafe" @@ -41,10 +42,14 @@ type painter struct { activeText *TextInput onTextEvent platform.TextHandler // 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 @@ -419,10 +424,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) @@ -439,6 +469,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 { 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/text/editing.go b/text/editing.go index 3c709c680..8ae9d32f0 100644 --- a/text/editing.go +++ b/text/editing.go @@ -114,6 +114,28 @@ 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) { 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 { From 87c3a8755fd4e4a13a721374af2cf956780e66a1 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 01:55:43 +0800 Subject: [PATCH 65/86] feat(ui): open a context menu at a point the application captured MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ContextMenuAt serves a surface without a hit target — a canvas cell, a column header, an editor — with the ContextMenu look and a dense RowHeight, and it clamps at the window edge instead of flipping to the other side of the pointer. components.ClampOverlay is that placement without the anchor. A context menu opened by its target keeps its own open state, so choosing a row or dismissing it closes it. Tests cover the captured origin, the 24px rows and the edge clamp; the full ui and components suites pass. --- components/popover.go | 8 ++++ ui/contextmenu_geometry_test.go | 55 +++++++++++++++++++++++ ui/menu.go | 79 ++++++++++++++++++++++++++------- ui/menu_test.go | 1 + 4 files changed, 126 insertions(+), 17 deletions(-) create mode 100644 ui/contextmenu_geometry_test.go 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/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/menu.go b/ui/menu.go index 8f5d7fc43..03864a30c 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -51,7 +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) + p.declareMenu(c, menu, scope, open, anchor.i, nil, body) } // ContextMenu shows the items body declares at the pointer when target is pressed @@ -68,6 +68,27 @@ func Menu(c C, anchor Box, 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 @@ -75,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 { @@ -104,7 +144,7 @@ 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 @@ -115,6 +155,9 @@ func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, an 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() @@ -136,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) @@ -217,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)) } @@ -270,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 @@ -446,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 @@ -588,7 +633,7 @@ 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 { diff --git a/ui/menu_test.go b/ui/menu_test.go index 85cc91bec..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 } From 60223b6010ba63636e7a8cbd89e3abae2e86c0f3 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 02:00:15 +0800 Subject: [PATCH 66/86] fix(viva): regenerate the popover installer template ClampOverlay is part of the popover component source that viva add installs, and the generated template still described the file without it, so the recipe tests failed on every platform. --- cmd/viva/templates/popover.go.txt | 8 ++++++++ 1 file changed, 8 insertions(+) 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 { From c1bcfe6cefe56e6057044893880ec7f2b6c933e3 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 02:14:43 +0800 Subject: [PATCH 67/86] feat(app): run posted work on the event-loop thread Application.Post hands work from any goroutine to the thread that owns the windows and the retained scene, in the order it was accepted, without starting a goroutine, timer or blocking wait. Each adapter uses the wake it already has: the main queue on macOS, a coalesced thread message on Windows, the existing command channel on X11 and idle source on GTK; a headless session runs it where it was posted. There is deliberately no call-the-loop-and-wait form: waiting on the loop from the loop deadlocks, and pumping the native event loop to avoid it (as an immediate-mode framework does) would put a platform detail in the public API. Results belong where the next wake or paint reads them. --- README.md | 3 ++ app/application.go | 23 ++++++++++ app/application_native.go | 2 + app/application_test.go | 21 +++++++++ headless/application.go | 8 ++++ internal/platform/contract.go | 4 ++ internal/platform/darwin/post_darwin.go | 46 +++++++++++++++++++ internal/platform/darwin/post_darwin.h | 7 +++ internal/platform/darwin/post_darwin.m | 11 +++++ internal/platform/darwin/post_darwin_test.go | 33 +++++++++++++ internal/platform/linux/gtk_app_linux.go | 8 ++++ internal/platform/linux/post_linux.go | 33 +++++++++++++ internal/platform/linux/post_linux_test.go | 29 ++++++++++++ internal/platform/linux/status_item_linux.go | 2 + internal/platform/linux/window_linux.go | 7 +++ internal/platform/windows/post_windows.go | 33 +++++++++++++ .../platform/windows/post_windows_test.go | 29 ++++++++++++ .../platform/windows/status_item_windows.go | 4 +- internal/platform/windows/window_windows.go | 9 ++++ 19 files changed, 311 insertions(+), 1 deletion(-) create mode 100644 internal/platform/darwin/post_darwin.go create mode 100644 internal/platform/darwin/post_darwin.h create mode 100644 internal/platform/darwin/post_darwin.m create mode 100644 internal/platform/darwin/post_darwin_test.go create mode 100644 internal/platform/linux/post_linux.go create mode 100644 internal/platform/linux/post_linux_test.go create mode 100644 internal/platform/windows/post_windows.go create mode 100644 internal/platform/windows/post_windows_test.go diff --git a/README.md b/README.md index 1335ef29f..8ccd954a7 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,9 @@ WebView and no bundled rendering runtime. 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.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 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..c30773ee2 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -130,6 +130,8 @@ func (host nativeHost) SetProgress(fraction float32) { host.native.SetProgress(f 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/headless/application.go b/headless/application.go index 92133282e..6f0f90d34 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/platform/contract.go b/internal/platform/contract.go index 060999389..08a775469 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -226,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 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/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go index 4ba7f024c..ee0d7d2cd 100644 --- a/internal/platform/linux/gtk_app_linux.go +++ b/internal/platform/linux/gtk_app_linux.go @@ -151,6 +151,14 @@ func (a *gtkApplication) enqueue(function func()) { a.g.idleAdd(callbacks().task, a.tasks.add(function)) } +// 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 { 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/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/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/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/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 33feea52b..465ccc477 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -178,6 +178,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 { @@ -266,6 +271,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) { From fa315dfa3dc23339af04e51ce69e5952e9f647ab Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 02:22:16 +0800 Subject: [PATCH 68/86] feat(app): give an application its own macOS menu bar Application.SetMenuBar installs the application's File, Edit and View menus between the system's application menu and its Window menu: key equivalents from a character chord, enablement, check marks, submenus, and loop-thread actions. A C bridge builds the NSMenus and one Go-exported dispatcher runs the entry's action; the standard Hide and Window items keep AppKit's behaviour and Command+W stays with the application. Windows and Linux return ErrUnsupported rather than faking a system menu bar; their applications keep using components.Menubar. The Darwin test compiles the real Objective-C and checks order, shortcuts, state, submenus and action dispatch. --- README.md | 4 + app/application_native.go | 13 +++ app/menu_bar.go | 102 ++++++++++++++++++ app/menu_bar_test.go | 42 ++++++++ docs/system-integrations.md | 1 + internal/platform/darwin/main_menu_darwin.m | 63 +++++++++-- .../platform/darwin/main_menu_darwin_test.go | 2 +- internal/platform/darwin/menu_bar_darwin.go | 89 +++++++++++++++ internal/platform/darwin/menu_bar_darwin.h | 23 ++++ internal/platform/darwin/menu_bar_darwin.m | 60 +++++++++++ internal/platform/darwin/testdata/main_menu.m | 85 ++++++++++++++- internal/platform/menu_bar.go | 21 ++++ 12 files changed, 490 insertions(+), 15 deletions(-) create mode 100644 app/menu_bar.go create mode 100644 app/menu_bar_test.go create mode 100644 internal/platform/darwin/menu_bar_darwin.go create mode 100644 internal/platform/darwin/menu_bar_darwin.h create mode 100644 internal/platform/darwin/menu_bar_darwin.m create mode 100644 internal/platform/menu_bar.go diff --git a/README.md b/README.md index 8ccd954a7..d47429375 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,10 @@ WebView and no bundled rendering runtime. 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. diff --git a/app/application_native.go b/app/application_native.go index c30773ee2..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,6 +129,18 @@ 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) } 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/docs/system-integrations.md b/docs/system-integrations.md index e1e72fd19..b78776cbb 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -31,6 +31,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | 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 | 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/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/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() +} From 0f7305cc0ba9a9b6c37fe66c9a711ab68865b492 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 02:28:00 +0800 Subject: [PATCH 69/86] feat(document): save a file atomically and detect outside changes Read returns a file's bytes and the SHA-256 revision that names them; Save writes a temporary file in the same directory, syncs it, checks once more that the file is still the expected revision, renames over it and syncs the directory, keeping the old mode; Changed reports whether another program replaced, wrote or removed it. Symbolic links and non-regular files are refused, and a missing file is created only from the zero revision. The editor, its format and its autosave policy stay the application's; this is the storage half both a Viva editor and an application's own document model share. --- document/document.go | 147 ++++++++++++++++++++++++++++++++++ document/document_test.go | 151 +++++++++++++++++++++++++++++++++++ document/sync_dir_unix.go | 17 ++++ document/sync_dir_windows.go | 7 ++ 4 files changed, 322 insertions(+) create mode 100644 document/document.go create mode 100644 document/document_test.go create mode 100644 document/sync_dir_unix.go create mode 100644 document/sync_dir_windows.go 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) {} From 167de96c059bd3c8b4f06f600ac10b6c7d75bf16 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 02:30:45 +0800 Subject: [PATCH 70/86] docs: record the macOS application menu bar in conformance --- docs/conformance.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conformance.md b/docs/conformance.md index f93a29065..1affa16d5 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -91,7 +91,7 @@ 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. | From cd4a6248f0c673c7bdca29c21a0331c18ee48463 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 11:35:52 +0800 Subject: [PATCH 71/86] docs(testenv): describe the Linux desktop container The machine is a Debian 12 x86_64 desktop container with Xvnc at 1920x1080 and DISPLAY=:1, with no Vulkan device or discrete GPU: rendering is software. The user and password stay in the git-ignored local.sh. --- tools/testenv/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 From 31251d143b6c6c6a662eb760432c94a3c7e48b67 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 11:39:14 +0800 Subject: [PATCH 72/86] test(conformance): assert wake coalescing, not a display rate The flood scenario bounded wakes by a 120 Hz frame grid, but a window presenting to a software surface (a Windows virtual machine's WARP, a CPU fallback) legitimately runs faster than a monitor. The invariant is now what the scenario is about: at least one wake, and far fewer wakes than the Invalidate calls that asked for them. --- cmd/viva-conformance/main.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) 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 }) From 1887f03c164f0e1d2d92f56979e0ecaf82a858fd Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 11:46:38 +0800 Subject: [PATCH 73/86] fix(windows): repair the CF_HTML header and the grabbing cursor cache cfHTML wrote the offsets without their field names (the fixed-width header constant was never used), so a paste target could not parse a rich copy; it now formats StartHTML, EndHTML, StartFragment and EndFragment with ten digits. closeGrabbingCursor destroyed the handle but left the sync.Once done, so the rest of the process asked for a destroyed cursor; the cache can be built again, and the test asserts a live handle rather than comparing opaque values. The compositing test's expectation put layer 2's text before its shape, contradicting the paint order the label's ShapesBefore records; the algorithm and the expectation now agree. All found by running internal/platform/windows on the Windows test VM, which CI does not run. --- .../windows/clipboard_html_windows.go | 22 +++++----------- .../platform/windows/cursor_image_windows.go | 26 ++++++++++++------- .../platform/windows/cursor_windows_test.go | 4 +-- .../platform/windows/renderer_windows_test.go | 4 ++- 4 files changed, 27 insertions(+), 29 deletions(-) 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/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) From 1eacfe2c96935ffdf353d20b5d807c814105f3ed Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 12:35:42 +0800 Subject: [PATCH 74/86] fix(input): name shifted Control chords by their base character KeyEvent.Text is the character without any modifier applied, with what was held reported in Modifiers. The XCB, GTK and macOS raw-key paths applied Shift to that character, so Control+Shift+C arrived as "C"; a terminal that identifies its copy chord by "c" then encoded it as Control+C instead. --- internal/platform/darwin/native.m | 26 +++++++++++++++++---- internal/platform/linux/gtk_input_linux.go | 4 +++- internal/platform/linux/input_linux.go | 4 +++- internal/platform/linux/input_linux_test.go | 26 +++++++++++++++++++++ 4 files changed, 53 insertions(+), 7 deletions(-) diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 592de6340..92baf645f 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; @@ -4611,7 +4625,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, @@ -4671,9 +4685,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), @@ -4701,7 +4717,7 @@ - (void)keyDown:(NSEvent *)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), 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/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{ From f465bad718ad38d09152bb2cabca582eee489dbf Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:35:52 +0800 Subject: [PATCH 75/86] feat(text): retain optional LF labels through undo history --- text/code.go | 5 +- text/edit_journal.go | 6 + text/editor.go | 81 ++++- text/lf_labels.go | 363 +++++++++++++++++++ text/lf_labels_batch.go | 70 ++++ text/lf_labels_batch_test.go | 578 +++++++++++++++++++++++++++++++ text/lf_labels_budget.go | 57 +++ text/lf_labels_composition.go | 99 ++++++ text/lf_labels_lifecycle_test.go | 444 ++++++++++++++++++++++++ text/lf_labels_revision_test.go | 75 ++++ text/lf_labels_test.go | 259 ++++++++++++++ text/line_journal.go | 1 + text/multi_replace.go | 38 +- text/transaction.go | 24 +- 14 files changed, 2078 insertions(+), 22 deletions(-) create mode 100644 text/lf_labels.go create mode 100644 text/lf_labels_batch.go create mode 100644 text/lf_labels_batch_test.go create mode 100644 text/lf_labels_budget.go create mode 100644 text/lf_labels_composition.go create mode 100644 text/lf_labels_lifecycle_test.go create mode 100644 text/lf_labels_revision_test.go create mode 100644 text/lf_labels_test.go diff --git a/text/code.go b/text/code.go index 09ae4276f..9a309ef3c 100644 --- a/text/code.go +++ b/text/code.go @@ -104,12 +104,13 @@ func (editor *Editor) column(index, tabWidth int) int { 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. - editor.clearSecondary() 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) } @@ -684,11 +685,11 @@ 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.clearSecondary() // one range replaced, one caret left target = normalizeRange(target, len(editor.runes)) before := editor.selectionState() change := editor.replace(target, value, false) editor.collapse(target.Start + len(change.inserted)) editor.composing = false + editor.releaseCompositionHistory() editor.record(change, before, editor.selectionState(), editSeparate) } diff --git a/text/edit_journal.go b/text/edit_journal.go index 75bd3b72f..fc927a590 100644 --- a/text/edit_journal.go +++ b/text/edit_journal.go @@ -18,6 +18,7 @@ type editJournal struct { oldest int unlimited bool tracking bool + private bool savePoint *int lines *lineJournal } @@ -151,6 +152,11 @@ func (editor *Editor) recordBatchEdits(primitives []Edit, contexts []lineContext func (editor *Editor) replaceHistory(edit *historyEdit, inverse bool) { journal := editor.journal + if labels := editor.lfLabelState(); labels != nil { + labels.replaying = true + defer func() { labels.replaying = false }() + labels.ops.replay(labels, lfLabelHistoryKey(edit), inverse) + } contexts := editor.lineBatchContexts(edit.primitives) if len(edit.primitives) > 0 { editor.journal = nil diff --git a/text/editor.go b/text/editor.go index 1430e286d..b8e28b769 100644 --- a/text/editor.go +++ b/text/editor.go @@ -296,11 +296,6 @@ func (editor *Editor) Paste(value string) { // text. selected is relative to the marked text, matching native IME APIs. func (editor *Editor) SetMarkedText(value string, selected Range) { wasComposing := editor.composing - if !wasComposing { - // The input method composes at the caret: a multi-selection ends here, as - // it does for any edit made through one selection. - editor.clearSecondary() - } target := editor.Selection() if wasComposing { target = editor.composition @@ -308,6 +303,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 @@ -319,6 +317,9 @@ 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) + } } inserted := len(change.inserted) if inserted == 0 && value != "" { @@ -354,7 +355,15 @@ func (editor *Editor) CancelComposition() bool { 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 @@ -582,6 +591,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 @@ -611,6 +623,9 @@ func (editor *Editor) Undo() bool { if !editor.CanUndo() { return false } + if labels := editor.lfLabelState(); labels != nil && labels.mapping { + panic("text: LF label mapper reentered Undo") + } editor.historyIndex-- edit := &editor.history[editor.historyIndex] editor.replaceHistory(edit, true) @@ -638,13 +653,22 @@ func (editor *Editor) Redo() bool { func (editor *Editor) BreakUndoGroup() { editor.coalescing = 0 } func (editor *Editor) clearHistory() { + if labels := editor.lfLabelState(); labels != nil && labels.mapping { + panic("text: LF label mapper reentered history reset") + } 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 point := editor.savePointIndex(); point != nil { *point = 0 @@ -656,6 +680,9 @@ func (editor *Editor) clearHistory() { // while it is called cannot bring back cleared units. func (editor *Editor) ClearHistory() { editor.clearHistory() + if labels := editor.lfLabelState(); labels != nil { + labels.ops.discard(labels) + } editor.compositionHistoryIndex = 0 editor.compositionHistoryRunes = 0 editor.compositionCoalescing = 0 @@ -663,6 +690,9 @@ func (editor *Editor) ClearHistory() { } func (editor *Editor) releaseCompositionHistory() { + if labels := editor.lfLabelState(); labels != nil { + labels.ops.release(labels) + } if !editor.compositionHistoryHeld { return } @@ -693,7 +723,7 @@ func (editor *Editor) restoreSelection(selection editorSelection) { } 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) && (len(change.removed) == 0 || editor.savePointIndex() == nil) && !editor.pendingLFLabels() { return } editor.dropRedo() @@ -712,7 +742,7 @@ 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.savePointIndex() == nil && !editor.pendingLFLabels() { return } editor.dropRedo() @@ -726,7 +756,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 { @@ -746,6 +779,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 { @@ -779,9 +819,21 @@ func (editor *Editor) merge(change textChange, before, after editorSelection, ki return false } 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)) + } + return cost +} + func (editor *Editor) dropRedo() { if editor.historyIndex < len(editor.history) { editor.discardRedo() @@ -793,7 +845,10 @@ 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] @@ -805,7 +860,10 @@ func (editor *Editor) trimHistory() { remove := 0 for len(editor.history)-remove > 1 && (len(editor.history)-remove > maxHistoryEntries || editor.historyRunes > 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 { @@ -842,6 +900,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/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..494e74272 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 diff --git a/text/multi_replace.go b/text/multi_replace.go index c2ea5dc3a..28e379697 100644 --- a/text/multi_replace.go +++ b/text/multi_replace.go @@ -22,7 +22,7 @@ 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. + // Without save-point mode equal text and LF labels add no Undo unit and preserve Redo. // SetSavePoint opts into retaining those actual replacements in history. ApplyUnchanged bool } @@ -70,8 +70,9 @@ 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 or save-point mode 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 +90,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,14 +133,31 @@ 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 { - return 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 + } + } + if !changed && editor.savePointIndex() == nil && (labelPlan == nil || !labelPlan.changed) { + labelPlan = nil + if !options.ApplyUnchanged { + return nil + } } if options.Forward { shift := 0 @@ -149,11 +169,11 @@ 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)) // A batch leaves the one selection it names; the multi-selection paths // reinstall their set after the call. @@ -163,6 +183,10 @@ func (editor *Editor) commitBatch(target Range, replacement string, primitives [ 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/transaction.go b/text/transaction.go index 5916f0b19..b8c6c5531 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, 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)} @@ -61,6 +72,13 @@ func (editor *Editor) Transact(apply func(*Editor) error) error { 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 } From e88cee5b5c42ed79580eac6307af67ef340626cc Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:40:08 +0800 Subject: [PATCH 76/86] feat(text): expose opt-in complete history metadata --- text/edit_journal.go | 36 +- text/editor.go | 59 +++- text/history_frames_bench_test.go | 50 +++ text/history_frames_test.go | 570 ++++++++++++++++++++++++++++++ text/history_journal.go | 436 +++++++++++++++++++++++ text/history_link.go | 66 ++++ text/line_journal.go | 4 +- text/multi_replace.go | 29 +- text/savepoint.go | 22 ++ text/transaction.go | 2 +- 10 files changed, 1240 insertions(+), 34 deletions(-) create mode 100644 text/history_frames_bench_test.go create mode 100644 text/history_frames_test.go create mode 100644 text/history_journal.go create mode 100644 text/history_link.go diff --git a/text/edit_journal.go b/text/edit_journal.go index fc927a590..d4a1e4772 100644 --- a/text/edit_journal.go +++ b/text/edit_journal.go @@ -13,14 +13,17 @@ type Edit struct { const EditJournalLimit = 1024 type editJournal struct { - revision uint64 - entries []Edit - oldest int - unlimited bool - tracking bool - private 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 + history *historyJournal } // TrackEdits enables a bounded mutation journal and returns its current cursor. @@ -53,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 @@ -78,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) @@ -157,8 +163,10 @@ func (editor *Editor) replaceHistory(edit *historyEdit, inverse bool) { defer func() { labels.replaying = false }() labels.ops.replay(labels, lfLabelHistoryKey(edit), inverse) } - contexts := editor.lineBatchContexts(edit.primitives) - if len(edit.primitives) > 0 { + batch := edit.kind == editSeparate && len(edit.primitives) > 0 + var contexts []lineContext + if batch { + contexts = editor.lineBatchContexts(edit.primitives) editor.journal = nil } if inverse { @@ -167,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/editor.go b/text/editor.go index b8e28b769..e7ed805cb 100644 --- a/text/editor.go +++ b/text/editor.go @@ -295,6 +295,7 @@ 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.invalidateHistoryFrom(0) wasComposing := editor.composing target := editor.Selection() if wasComposing { @@ -631,6 +632,9 @@ func (editor *Editor) Undo() bool { editor.replaceHistory(edit, true) editor.restoreSelection(edit.before) editor.BreakUndoGroup() + if history := editor.historyState(); history != nil { + history.ops.replay(history, editor.historyIndex, true) + } return true } @@ -644,6 +648,9 @@ func (editor *Editor) Redo() bool { editor.restoreSelection(edit.after) editor.historyIndex++ editor.BreakUndoGroup() + if history := editor.historyState(); history != nil { + history.ops.replay(history, editor.historyIndex-1, false) + } return true } @@ -652,10 +659,13 @@ 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") } + 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 @@ -678,8 +688,10 @@ 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) } @@ -723,18 +735,28 @@ func (editor *Editor) restoreSelection(selection editorSelection) { } func (editor *Editor) record(change textChange, before, after editorSelection, kind editKind) { - if runesEqual(change.removed, change.inserted) && (len(change.removed) == 0 || editor.savePointIndex() == nil) && !editor.pendingLFLabels() { + if runesEqual(change.removed, change.inserted) && !editor.pendingLFLabels() && (len(change.removed) == 0 || !editor.retainEqualEdits()) { return } 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) { @@ -742,10 +764,13 @@ 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 && !editor.pendingLFLabels() { + if runesEqual(change.removed, change.inserted) && !editor.pendingLFLabels() && !editor.retainEqualEdits() { return } 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, @@ -768,7 +793,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 } @@ -818,6 +843,11 @@ 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)) @@ -831,6 +861,9 @@ func (editor *Editor) historyUnitRunes(edit *historyEdit) int { 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 } @@ -855,10 +888,13 @@ func (editor *Editor) discardRedo() { } func (editor *Editor) trimHistory() { + 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 -= editor.historyUnitRunes(&edit) + editor.forgetLineBatch(&editor.history[remove]) if labels := editor.lfLabelState(); labels != nil { @@ -866,8 +902,8 @@ func (editor *Editor) trimHistory() { } 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 } @@ -876,6 +912,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 { 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..d1443b553 --- /dev/null +++ b/text/history_journal.go @@ -0,0 +1,436 @@ +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 +} + +const historyHeaderRunes = 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 journal != nil && journal.history != nil { + history := journal.history + 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.history = history + 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) { + 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) + 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 + } + return append(steps, HistoryStep{HistoryForward, primitive, position, length, before, after, history.context(boundary+1, boundary+1)}) +} + +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) { + 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 + } + tail := steps[len(steps)-1].Context.RetainedTo + 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.history != nil { + cost += editor.journal.history.cost + } + 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) captureHistoryReplay(edit *historyEdit, inverse bool) { + history := editor.historyState() + if history == nil { + return + } + 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)) + } + 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..11c0acb94 --- /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.history + 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/line_journal.go b/text/line_journal.go index 494e74272..bbb9b425a 100644 --- a/text/line_journal.go +++ b/text/line_journal.go @@ -74,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 @@ -169,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 28e379697..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 and LF labels add no Undo unit and preserve 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 } @@ -71,7 +72,8 @@ 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 and LF labels -// are also a no-op unless ApplyUnchanged or save-point mode is enabled; +// 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 { @@ -153,11 +155,10 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang return err } } - if !changed && editor.savePointIndex() == nil && (labelPlan == nil || !labelPlan.changed) { + retained := len(primitives) > 0 && editor.retainEqualEdits() + if !changed && !options.ApplyUnchanged && !retained && editor.savePointIndex() == nil && (labelPlan == nil || !labelPlan.changed) { labelPlan = nil - if !options.ApplyUnchanged { - return nil - } + return nil } if options.Forward { shift := 0 @@ -175,6 +176,20 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang 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() 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/transaction.go b/text/transaction.go index b8c6c5531..2f5bf89e6 100644 --- a/text/transaction.go +++ b/text/transaction.go @@ -27,7 +27,7 @@ func (editor *Editor) Transact(apply func(*Editor) error) error { 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, private: true} + recorder := &editJournal{unlimited: true, tracking: true, retainEqual: editor.retainEqualEdits(), private: true} if editor.journal != nil && editor.journal.lines != nil { recorder.lines = &lineJournal{} } From a91cb75d0cad11c65e009fffd3e4aba74eb13b4c Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:42:04 +0800 Subject: [PATCH 77/86] feat(text): add opt-in tentative composition transactions --- text/code.go | 2 + text/composition.go | 1027 +++++++++++++++++++++++++++++ text/composition_history.go | 206 ++++++ text/composition_link.go | 111 ++++ text/composition_retention.go | 306 +++++++++ text/edit_journal.go | 2 +- text/editor.go | 74 ++- text/editor_sidecar.go | 58 ++ text/history_journal.go | 59 +- text/history_link.go | 2 +- text/tentative_core_bench_test.go | 53 ++ text/tentative_core_test.go | 655 ++++++++++++++++++ 12 files changed, 2537 insertions(+), 18 deletions(-) create mode 100644 text/composition.go create mode 100644 text/composition_history.go create mode 100644 text/composition_link.go create mode 100644 text/composition_retention.go create mode 100644 text/editor_sidecar.go create mode 100644 text/tentative_core_bench_test.go create mode 100644 text/tentative_core_test.go diff --git a/text/code.go b/text/code.go index 9a309ef3c..3e973df99 100644 --- a/text/code.go +++ b/text/code.go @@ -685,9 +685,11 @@ 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() diff --git a/text/composition.go b/text/composition.go new file mode 100644 index 000000000..c70682471 --- /dev/null +++ b/text/composition.go @@ -0,0 +1,1027 @@ +package text + +import ( + "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 +} + +// 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 + 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 + 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, + 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 +} + +// 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_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 d4a1e4772..988dded9f 100644 --- a/text/edit_journal.go +++ b/text/edit_journal.go @@ -23,7 +23,7 @@ type editJournal struct { private bool savePoint *int lines *lineJournal - history *historyJournal + optional *editorSidecar } // TrackEdits enables a bounded mutation journal and returns its current cursor. diff --git a/text/editor.go b/text/editor.go index e7ed805cb..a946dc67a 100644 --- a/text/editor.go +++ b/text/editor.go @@ -84,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 @@ -157,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]...) @@ -181,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 } @@ -216,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 { @@ -234,6 +242,7 @@ func (editor *Editor) SetSelection(selection Range) { // 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 { @@ -262,6 +271,8 @@ func (editor *Editor) Insert(value string) { target := editor.Selection() wasComposing := editor.composing if wasComposing { + editor.sealTentativeHistory() + editor.invalidateHistoryFrom(0) target = editor.composition } overwrite := editor.overwrite && !wasComposing && target.Start == target.End @@ -287,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() @@ -295,6 +307,7 @@ 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() @@ -321,6 +334,7 @@ func (editor *Editor) SetMarkedText(value string, selected Range) { if labels := editor.lfLabelState(); labels != nil { labels.ops.hold(labels, change) } + editor.legacyComposition = true } inserted := len(change.inserted) if inserted == 0 && value != "" { @@ -342,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() @@ -355,6 +370,12 @@ 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 { @@ -368,6 +389,7 @@ func (editor *Editor) CancelComposition() bool { 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 = "" @@ -391,6 +413,7 @@ func (editor *Editor) CancelComposition() bool { // 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 } @@ -417,6 +440,7 @@ func (editor *Editor) DeleteBackward() bool { // 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 } @@ -440,6 +464,7 @@ 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 @@ -465,6 +490,7 @@ 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 @@ -553,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 { @@ -621,12 +652,16 @@ 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) @@ -635,14 +670,21 @@ func (editor *Editor) Undo() bool { 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) @@ -651,6 +693,9 @@ func (editor *Editor) Redo() bool { 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 } @@ -663,7 +708,13 @@ func (editor *Editor) clearHistory(manual bool) { if labels := editor.lfLabelState(); labels != nil && labels.mapping { panic("text: LF label mapper reentered history reset") } - if history := editor.historyState(); history != nil { + 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 { @@ -680,6 +731,14 @@ func (editor *Editor) clearHistory(manual bool) { 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 } @@ -705,6 +764,9 @@ func (editor *Editor) releaseCompositionHistory() { if labels := editor.lfLabelState(); labels != nil { labels.ops.release(labels) } + if !editor.composing { + editor.legacyComposition = false + } if !editor.compositionHistoryHeld { return } @@ -738,6 +800,7 @@ func (editor *Editor) record(change textChange, before, after editorSelection, k if runesEqual(change.removed, change.inserted) && !editor.pendingLFLabels() && (len(change.removed) == 0 || !editor.retainEqualEdits()) { return } + editor.recordRetiresCompleted() editor.dropRedo() var primitive Edit owned := false @@ -764,9 +827,10 @@ func (editor *Editor) recordWithPrimitives(change textChange, before, after edit editor.record(change, before, after, kind) return } - if runesEqual(change.removed, change.inserted) && !editor.pendingLFLabels() && !editor.retainEqualEdits() { + 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) @@ -888,6 +952,10 @@ func (editor *Editor) discardRedo() { } 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) } 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_journal.go b/text/history_journal.go index d1443b553..5e1ae4e14 100644 --- a/text/history_journal.go +++ b/text/history_journal.go @@ -79,7 +79,8 @@ type historyJournal struct { oldest uint16 } -const historyHeaderRunes = int((unsafe.Sizeof(historyJournal{}) + unsafe.Sizeof(rune(0)) - 1) / unsafe.Sizeof(rune(0))) +// 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 @@ -92,8 +93,11 @@ func (editor *Editor) TrackHistory() (HistoryCursor, int, bool) { return HistoryCursor{}, 0, false } journal := editor.journal - if journal != nil && journal.history != nil { - history := journal.history + 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 } @@ -130,7 +134,8 @@ func (editor *Editor) TrackHistory() (HistoryCursor, int, bool) { epoch: HistoryCursor{source: source, generation: 1}, bootstrapBytes: size, bytes: size, cost: historyHeaderRunes, available: true, } - journal.history = history + journal.setHistoryJournal(history) + editor.chargeCompositionCapacity() return history.epoch, size, true } @@ -201,6 +206,10 @@ func historyRuneBytes(value []rune) int { } 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 @@ -224,6 +233,15 @@ func (editor *Editor) captureHistoryPrimitives(primitives []Edit) { 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 { @@ -232,7 +250,6 @@ func (editor *Editor) appendForwardHistoryStep(history *historyJournal, steps [] } else if history.detach != -1 && history.detach > boundary { history.detach = boundary } - return append(steps, HistoryStep{HistoryForward, primitive, position, length, before, after, history.context(boundary+1, boundary+1)}) } func (editor *Editor) captureHistorySave() { @@ -247,6 +264,13 @@ func (editor *Editor) captureHistorySave() { } 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 @@ -270,7 +294,6 @@ func (editor *Editor) appendHistoryFrame(steps []HistoryStep, before, after, cur } running = step.AfterBytes } - tail := steps[len(steps)-1].Context.RetainedTo if running != after || current < history.retainedFrom || current < 0 || current > tail { editor.invalidateHistoryFrom(0) return @@ -315,9 +338,10 @@ func (history *historyJournal) dropOldestFrame() { func (editor *Editor) historyCost() int { cost := editor.historyRunes - if editor.journal != nil && editor.journal.history != nil { - cost += editor.journal.history.cost + if editor.journal != nil && editor.journal.historyJournal() != nil { + cost += editor.journal.historyJournal().cost } + cost += editor.compositionCost() return cost } @@ -339,11 +363,7 @@ type historyReplayPrimitive struct { position, length int } -func (editor *Editor) captureHistoryReplay(edit *historyEdit, inverse bool) { - history := editor.historyState() - if history == nil { - return - } +func (editor *Editor) historyReplayPrimitives(edit *historyEdit) []historyReplayPrimitive { primitives := make([]historyReplayPrimitive, 0, len(edit.primitives)*2) appendPrimitive := func(position, removed, inserted int) { if removed > 0 { @@ -360,6 +380,19 @@ func (editor *Editor) captureHistoryReplay(edit *historyEdit, inverse bool) { } 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 diff --git a/text/history_link.go b/text/history_link.go index 11c0acb94..da3f1dc2f 100644 --- a/text/history_link.go +++ b/text/history_link.go @@ -16,7 +16,7 @@ func (editor *Editor) historyState() *historyJournal { if editor == nil || editor.journal == nil { return nil } - history := editor.journal.history + history := editor.journal.historyJournal() if history == nil || history.owner != editor || !history.available { return nil } 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") + } + }) + } + } +} From 4c47ada587e2b48f569e60da43a3222efb94579d Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:42:58 +0800 Subject: [PATCH 78/86] feat(app): bridge opt-in composition phases and native input ownership --- app/composition_dispatch_reentry_test.go | 115 ++++ app/composition_dispatch_test.go | 544 ++++++++++++++++++ app/painter.go | 59 +- app/run_canvas_js_test.go | 46 ++ app/text_input.go | 76 ++- app/text_input_js.go | 21 - .../platform/composition_dispatch_test.go | 174 ++++++ internal/platform/contract.go | 39 +- text/composition.go | 45 +- text/composition_identity_test.go | 129 +++++ 10 files changed, 1179 insertions(+), 69 deletions(-) create mode 100644 app/composition_dispatch_reentry_test.go create mode 100644 app/composition_dispatch_test.go create mode 100644 internal/platform/composition_dispatch_test.go create mode 100644 text/composition_identity_test.go 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/painter.go b/app/painter.go index 63dc6cc1f..56c0011ed 100644 --- a/app/painter.go +++ b/app/painter.go @@ -41,6 +41,7 @@ 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. placeUnit is the click // unit a multi-click press took (2 a word, 3 a line) and placeUnitRange the @@ -1267,6 +1268,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { if !painter.textEnabled { return platform.TextInputUpdate{} } + painter.textEpoch++ painter.textEnabled = false return platform.TextInputUpdate{Changed: true} } @@ -1305,6 +1307,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { if !painter.textEnabled { return platform.TextInputUpdate{} } + painter.textEpoch++ painter.textEnabled = false return platform.TextInputUpdate{Changed: true} } @@ -1335,13 +1338,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 { @@ -1354,6 +1351,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{} } @@ -1368,21 +1371,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 @@ -1392,8 +1398,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) @@ -1403,15 +1409,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/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..f85c10a9a 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. @@ -232,11 +242,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 +287,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/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 08a775469..8758c0fcf 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -949,11 +949,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 @@ -1045,6 +1050,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. @@ -1056,7 +1066,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 { @@ -1137,6 +1161,7 @@ func (event TextEvent) Apply(editor *text.Editor) { editor.DeleteToLineBoundary(true) } } + return true } // actsOnActiveComposition reports whether the event updates or commits the @@ -1186,11 +1211,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/text/composition.go b/text/composition.go index c70682471..d1e032692 100644 --- a/text/composition.go +++ b/text/composition.go @@ -1,6 +1,7 @@ package text import ( + "sync/atomic" "unicode/utf8" "unsafe" ) @@ -37,14 +38,31 @@ type CompositionEvent struct { 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 - ops compositionOps - event *historyEvent - cost int + 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. @@ -103,6 +121,7 @@ func (editor *Editor) EnableTentativeComposition() (ok bool) { } state.enabled = true state.passive = false + state.identity = nextCompositionIdentity() return true } if editor.composing || editor.accept != nil || editor.maxRunes > 0 { @@ -126,6 +145,7 @@ func (editor *Editor) EnableTentativeComposition() (ok bool) { 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, @@ -198,6 +218,23 @@ func (editor *Editor) TentativeCompositionEnabled() bool { 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) { 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") + } +} From 856ff6664dcc1a8426e8330e841468fb53f31b5e Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:43:44 +0800 Subject: [PATCH 79/86] fix(ibus): preserve daemon order during native engine selection --- .github/workflows/text-input.yml | 13 ++ internal/ibus/ibus.go | 75 ++++++-- internal/ibus/ibus_test.go | 158 +++++++++++++++- internal/ibus/native_test.go | 201 +++++++++++++++++++++ internal/ibus/testdata/native-daemon.sh | 44 +++++ internal/ibus/testdata/native-service.sh | 34 ++++ internal/ibus/testdata/reference-client.py | 87 +++++++++ 7 files changed, 589 insertions(+), 23 deletions(-) create mode 100644 internal/ibus/native_test.go create mode 100644 internal/ibus/testdata/native-daemon.sh create mode 100644 internal/ibus/testdata/native-service.sh create mode 100644 internal/ibus/testdata/reference-client.py diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 0d111bc5e..2626cb7ef 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -5,6 +5,7 @@ on: paths: - 'app/**' - 'internal/iconshape/**' + - 'internal/dbus/**' - 'internal/platform/**' - 'internal/ibus/**' - 'internal/render/**' @@ -13,6 +14,7 @@ on: paths: - 'app/**' - 'internal/iconshape/**' + - 'internal/dbus/**' - 'internal/platform/**' - 'internal/ibus/**' - 'internal/render/**' @@ -51,6 +53,17 @@ jobs: - 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 diff --git a/internal/ibus/ibus.go b/internal/ibus/ibus.go index 1ded91c5a..50dfb82b0 100644 --- a/internal/ibus/ibus.go +++ b/internal/ibus/ibus.go @@ -126,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 { @@ -295,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) } - case dbus.TypeReturn, dbus.TypeError: - bus.answer(message) + if bus.err != nil { + return bus.err + } + } + // 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 @@ -391,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) } diff --git a/internal/ibus/ibus_test.go b/internal/ibus/ibus_test.go index 7f3c26a38..b133f5a13 100644 --- a/internal/ibus/ibus_test.go +++ b/internal/ibus/ibus_test.go @@ -17,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 } @@ -41,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) } @@ -244,6 +251,146 @@ func TestNativeContextRetirement(t *testing.T) { } } +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 @@ -526,6 +673,7 @@ func BenchmarkPreeditSignalDispatch(b *testing.B) { } 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) { 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() From 5301d4642ec6f4c109fa6909d2696cff89479a5c Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:44:36 +0800 Subject: [PATCH 80/86] fix(linux): bind GTK input contexts to focused targets --- .github/workflows/text-input.yml | 9 + internal/platform/linux/gtk_app_linux.go | 54 +- internal/platform/linux/gtk_ime_linux.go | 122 ++++- .../linux/gtk_ime_native_linux_test.go | 471 ++++++++++++++++++ internal/platform/linux/gtk_library_linux.go | 6 + .../linux/gtk_window_teardown_linux_test.go | 46 +- 6 files changed, 672 insertions(+), 36 deletions(-) create mode 100644 internal/platform/linux/gtk_ime_native_linux_test.go diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 2626cb7ef..93a201319 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -50,6 +50,15 @@ 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 diff --git a/internal/platform/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go index ee0d7d2cd..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,27 @@ 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()) { @@ -288,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 ( @@ -462,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 @@ -498,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_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_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_teardown_linux_test.go b/internal/platform/linux/gtk_window_teardown_linux_test.go index 4a26c0b0c..68167ff57 100644 --- a/internal/platform/linux/gtk_window_teardown_linux_test.go +++ b/internal/platform/linux/gtk_window_teardown_linux_test.go @@ -18,7 +18,44 @@ func TestGTKDestroyDetachesInputMethodBeforeNativeWidget(t *testing.T) { w := >kWindow{app: a, g: g, toplevel: 17} w.ime = >kIME{w: w, g: g, ctx: 23, active: true} detached, destroyed := false, 0 - g.objectUnref = func(uintptr) {} + 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") @@ -33,7 +70,7 @@ func TestGTKDestroyDetachesInputMethodBeforeNativeWidget(t *testing.T) { } g.widgetDestroy = func(window uintptr) { destroyed++ - if window != 17 || !detached || w.ime != nil { + if window != 17 || !detached || w.ime != nil || references != 1 || !retired { t.Error("native widget destruction preceded input-method detachment") } } @@ -42,6 +79,11 @@ func TestGTKDestroyDetachesInputMethodBeforeNativeWidget(t *testing.T) { 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) { From c6115765879e8c319b526e1c38f12a049909c803 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 13:45:36 +0800 Subject: [PATCH 81/86] feat(app): open a local file in the default browser --- app/driver.go | 16 +- app/driver_system.go | 10 + app/driver_system_unsupported.go | 1 + app/open_in_browser.go | 53 +++ app/open_in_browser_test.go | 62 ++++ app/open_in_browser_unsupported.go | 9 + app/system_darwin.go | 2 + app/system_linux.go | 4 + app/system_windows.go | 2 + docs/system-integrations.md | 1 + internal/platform/browser.go | 314 ++++++++++++++++++ internal/platform/browser_test.go | 153 +++++++++ internal/platform/darwin/system_darwin.go | 22 ++ internal/platform/darwin/system_darwin.h | 3 + internal/platform/darwin/system_darwin.m | 20 ++ .../platform/linux/open_in_browser_linux.go | 93 ++++++ .../windows/open_in_browser_windows.go | 73 ++++ .../content/guides/en/system-integration.md | 3 +- .../content/guides/zh/system-integration.md | 3 +- 19 files changed, 839 insertions(+), 5 deletions(-) create mode 100644 app/open_in_browser.go create mode 100644 app/open_in_browser_test.go create mode 100644 app/open_in_browser_unsupported.go create mode 100644 internal/platform/browser.go create mode 100644 internal/platform/browser_test.go create mode 100644 internal/platform/linux/open_in_browser_linux.go create mode 100644 internal/platform/windows/open_in_browser_windows.go diff --git a/app/driver.go b/app/driver.go index 6074af20a..db2655304 100644 --- a/app/driver.go +++ b/app/driver.go @@ -75,9 +75,12 @@ type Driver struct { hasOpenedPath bool openedWith [2]string hasOpenedWith bool - releases []func() - closed bool - appearanceOpen bool + // openedInBrowser is the file OpenPathInBrowser was last given. + openedInBrowser string + hasOpenedInBrowser bool + releases []func() + closed bool + appearanceOpen bool system driverSystem openFilesResponses [driverOpenFilesQueueSize]driverOpenFilesResponse @@ -979,6 +982,13 @@ func (driver *Driver) LastOpenedWith() (executable, path string, ok bool) { return driver.openedWith[0], driver.openedWith[1], driver.hasOpenedWith } +// LastOpenedInBrowser returns the most recent file passed to OpenPathInBrowser +// while this driver was active. Driver-backed runs record the request and start +// no browser. +func (driver *Driver) LastOpenedInBrowser() (string, bool) { + return driver.openedInBrowser, driver.hasOpenedInBrowser +} + // PrimitiveKind says what a Primitive is. type PrimitiveKind uint8 diff --git a/app/driver_system.go b/app/driver_system.go index fcfa5a226..163b0f834 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -324,6 +324,16 @@ func driverOpenWith(executable, path string) (error, bool) { return nil, true } +func driverOpenInBrowser(path string) (error, bool) { + system := activeDriverSystem.Load() + if system == nil { + return nil, false + } + system.driver.openedInBrowser = path + system.driver.hasOpenedInBrowser = true + return nil, true +} + func driverOpenFiles(options OpenFileOptions) ([]string, error, bool) { system := activeDriverSystem.Load() if system == nil { diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index 3826d0750..809e936d4 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -28,6 +28,7 @@ func driverRevealPath(string) (error, bool) { return nil, false } func driverOpenWith(string, string) (error, bool) { return nil, false } +func driverOpenInBrowser(string) (error, bool) { return nil, false } func driverOpenFiles(OpenFileOptions) ([]string, error, bool) { return nil, nil, false diff --git a/app/open_in_browser.go b/app/open_in_browser.go new file mode 100644 index 000000000..2755f32b0 --- /dev/null +++ b/app/open_in_browser.go @@ -0,0 +1,53 @@ +package app + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/vivaui/viva/internal/platform" +) + +// ErrNoBrowser is returned by OpenPathInBrowser when the system has no default +// web browser to give the file to. +var ErrNoBrowser = errors.New("app: no default web browser") + +// OpenPathInBrowser opens a local file in the user's default web browser, the +// application the system opens http and https links with, whatever application +// the file's own type is associated with. It is for pages an application wrote +// or previews: an .html file is often associated with an editor, where OpenPath +// would open it. The browser is given the file's URL, so it shows the file and +// does not run it. The path must be absolute and name a regular file, not a +// link or a directory. A system with no default browser returns ErrNoBrowser; +// one where a browser cannot be started, as on the Web target, ErrUnsupported. +// Driver-backed runs record the request without starting a browser. A native +// call can wait for the browser to take the file, so callers on an interactive +// window thread should run it away from that thread. +func OpenPathInBrowser(path string) error { + if strings.IndexByte(path, 0) >= 0 { + return fmt.Errorf("app: path contains NUL") + } + if !filepath.IsAbs(path) { + return fmt.Errorf("app: %q is not an absolute path", path) + } + path = filepath.Clean(path) + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return fmt.Errorf("app: %q is not a regular file", path) + } + if err, handled := driverOpenInBrowser(path); handled { + return err + } + if err := nativeOpenInBrowser(path); err != nil { + if errors.Is(err, platform.ErrNoBrowser) { + return ErrNoBrowser + } + return err + } + return nil +} diff --git a/app/open_in_browser_test.go b/app/open_in_browser_test.go new file mode 100644 index 000000000..1f139ec14 --- /dev/null +++ b/app/open_in_browser_test.go @@ -0,0 +1,62 @@ +//go:build darwin || windows || linux + +package app + +import ( + "os" + "path/filepath" + "testing" +) + +func TestOpenPathInBrowserValidatesBeforeAskingTheSystem(t *testing.T) { + dir := t.TempDir() + page := filepath.Join(dir, "page.html") + if err := os.WriteFile(page, []byte("

x

"), 0o644); err != nil { + t.Fatal(err) + } + for _, path := range []string{"relative.html", filepath.Join(dir, "missing.html"), dir, page + "\x00"} { + if err := OpenPathInBrowser(path); err == nil { + t.Errorf("%q was accepted", path) + } + } + link := filepath.Join(dir, "link.html") + if err := os.Symlink(page, link); err == nil { + if err := OpenPathInBrowser(link); err == nil { + t.Error("a symbolic link was accepted") + } + } +} + +// TestDriverRecordsOpenPathInBrowserAndStartsNothing pins that the browser +// request is its own record: a page that goes to the browser is neither an +// OpenPath nor an OpenURL, so a test can tell which way the file left. +func TestDriverRecordsOpenPathInBrowserAndStartsNothing(t *testing.T) { + driver, err := NewDriver(Config{}, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + dir := t.TempDir() + page := filepath.Join(dir, "my page.html") + if err := os.WriteFile(page, []byte("

x

"), 0o644); err != nil { + t.Fatal(err) + } + if err := OpenPathInBrowser(dir); err == nil { + t.Fatal("a directory was accepted") + } + if _, ok := driver.LastOpenedInBrowser(); ok { + t.Fatal("a refused path reached the driver") + } + if err := OpenPathInBrowser(page); err != nil { + t.Fatal(err) + } + if opened, ok := driver.LastOpenedInBrowser(); !ok || opened != page { + t.Fatalf("LastOpenedInBrowser = %q, %t", opened, ok) + } + if _, ok := driver.LastOpenedPath(); ok { + t.Fatal("OpenPathInBrowser was recorded as OpenPath") + } + if _, ok := driver.LastOpenedURL(); ok { + t.Fatal("OpenPathInBrowser was recorded as OpenURL") + } +} diff --git a/app/open_in_browser_unsupported.go b/app/open_in_browser_unsupported.go new file mode 100644 index 000000000..a0d0bc2a7 --- /dev/null +++ b/app/open_in_browser_unsupported.go @@ -0,0 +1,9 @@ +//go:build !windows && !darwin && !linux + +package app + +import "fmt" + +func nativeOpenInBrowser(string) error { + return fmt.Errorf("%w: OpenPathInBrowser", ErrUnsupported) +} diff --git a/app/system_darwin.go b/app/system_darwin.go index ce78d83a2..f5732795f 100644 --- a/app/system_darwin.go +++ b/app/system_darwin.go @@ -106,6 +106,8 @@ func nativeOpenWith(executable, path string) error { return darwinplatform.OpenWith(executable, path) } +func nativeOpenInBrowser(path string) error { return darwinplatform.OpenInBrowser(path) } + func nativePlaySystemSound(sound SystemSound) error { return darwinplatform.PlaySystemSound(uint8(sound)) } diff --git a/app/system_linux.go b/app/system_linux.go index 0129924c1..baa0dd927 100644 --- a/app/system_linux.go +++ b/app/system_linux.go @@ -124,6 +124,10 @@ func nativeOpenWith(executable, path string) error { return linuxSystemError(linuxplatform.OpenWith(executable, path)) } +func nativeOpenInBrowser(path string) error { + return linuxSystemError(linuxplatform.OpenInBrowser(path)) +} + func nativePlaySystemSound(sound SystemSound) error { return linuxSystemError(linuxplatform.PlaySystemSound(uint8(sound))) } diff --git a/app/system_windows.go b/app/system_windows.go index 716398a12..54c6cb67f 100644 --- a/app/system_windows.go +++ b/app/system_windows.go @@ -94,6 +94,8 @@ func nativeRevealPath(path string) error { return windowsplatform.RevealPath(pat func nativeOpenWith(executable, path string) error { return windowsplatform.OpenWith(executable, path) } + +func nativeOpenInBrowser(path string) error { return windowsplatform.OpenInBrowser(path) } func nativePlaySystemSound(sound SystemSound) error { return windowsplatform.PlaySystemSound(uint8(sound)) } diff --git a/docs/system-integrations.md b/docs/system-integrations.md index b78776cbb..7864a0cf7 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -19,6 +19,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Open directory | `NSOpenPanel` | `IFileOpenDialog` | the desktop portal's `FileChooser` | `ErrUnsupported` | | File drop (`OnFileDrop`) | AppKit drag destination, with paths | `WM_DROPFILES`, with paths | XDND / GTK drop, with paths | DOM drag events; `gfx.FileDropEvent.Files` carries the browser files and `Paths` is empty | | Open external URL | `NSWorkspace` | `ShellExecuteW` | installed `xdg-open` or `gio` | `window.open`; popup rejection is `ErrUserGestureRequired` | +| Open a local file in the default browser (`OpenPathInBrowser`) | the application LaunchServices opens `https` links in, through `open -a` | the `http` protocol's command from `AssocQueryStringW`, started with the file's `file:` URL and no shell | the desktop entry `xdg-settings get default-web-browser` names (`xdg-mime` for `x-scheme-handler/https` without it), its `Exec` line run with the file's URL; a terminal browser is `ErrUnsupported` | `ErrUnsupported` | | System sound | AppKit system sounds | `MessageBeep` | `canberra-gtk-play` or X11 bell | `ErrUnsupported` | | Notification | UserNotifications; app bundle ID and permission required | shell notification icon; running window required | the desktop's `org.freedesktop.Notifications` service, under the executable's name; installed `notify-send` without one; no click callback | only when Notification permission is already granted; `RequestNotificationPermission` asks for it asynchronously | | Secret store (`StoreSecretAsync`, `LoadSecretAsync`, `DeleteSecretAsync`) | Keychain | Credential Manager | Secret Service (GNOME Keyring, KWallet) | AES-GCM through WebCrypto with a non-extractable key held in IndexedDB; synchronous calls return `ErrSecretStoreUnavailable` | diff --git a/internal/platform/browser.go b/internal/platform/browser.go new file mode 100644 index 000000000..9ab30d0d8 --- /dev/null +++ b/internal/platform/browser.go @@ -0,0 +1,314 @@ +package platform + +import ( + "errors" + "fmt" + "net/url" + "strings" +) + +// ErrNoBrowser is what a backend returns when the system names no default web +// browser to open a file in. +var ErrNoBrowser = errors.New("platform: no default web browser") + +// FileURL is the file URL a browser is given for an absolute local path. A +// Windows path (windows true) has its separators turned and its drive written +// as file:///C:/..., and a UNC share as file://///host/share/..., the form +// browsers on Windows resolve back to the share; the \\?\ prefix of a long +// path is dropped first. Every space, quote and percent sign comes out escaped, +// so the URL is one word on any command line. +func FileURL(path string, windows bool) string { + if windows { + switch { + case strings.HasPrefix(path, `\\?\UNC\`): + path = `\\` + path[len(`\\?\UNC\`):] + case strings.HasPrefix(path, `\\?\`): + path = path[len(`\\?\`):] + } + // C:/dir becomes /C:/dir and //host/share ///host/share, which a URL + // with no host writes as file:///C:/dir and file://///host/share. + path = "/" + strings.ReplaceAll(path, `\`, "/") + } + return (&url.URL{Scheme: "file", Path: path}).String() +} + +// BrowserCommandLine turns the command Windows registers for a protocol, such +// as `"C:\Program Files\Browser\browser.exe" -url "%1"`, into the program to +// start and the command line to start it with for target, the way the shell +// fills it in: %1 and %L become target and %* nothing, and a command with +// neither %1 nor %L gets target appended. A program path the registry left +// unquoted though it has spaces is taken up to the first space at which exists +// reports a file. target goes in as it is, so it must be one word, as a FileURL +// is. +func BrowserCommandLine(command, target string, exists func(string) bool) (program, commandLine string, err error) { + if target == "" || strings.ContainsAny(target, " \t\"\x00") { + return "", "", fmt.Errorf("platform: browser target %q is not one word", target) + } + command = strings.TrimSpace(command) + var rest string + if strings.HasPrefix(command, `"`) { + end := strings.IndexByte(command[1:], '"') + if end < 0 { + return "", "", fmt.Errorf("platform: browser command %q has an unterminated quote", command) + } + program, rest = command[1:1+end], command[2+end:] + } else { + program, rest = command, "" + if space := strings.IndexByte(command, ' '); space >= 0 { + program, rest = command[:space], command[space:] + } + for index := range command { + if command[index] == ' ' && exists(command[:index]) { + program, rest = command[:index], command[index:] + break + } + } + } + if program == "" { + return "", "", fmt.Errorf("platform: browser command %q names no program", command) + } + var line strings.Builder + line.WriteString(`"` + program + `"`) + placed := false + for index := 0; index < len(rest); index++ { + if rest[index] == '%' && index+1 < len(rest) { + switch rest[index+1] { + case '1', 'L', 'l': + line.WriteString(target) + placed = true + index++ + continue + case '*': + index++ + continue + } + } + line.WriteByte(rest[index]) + } + if !placed { + line.WriteString(" " + target) + } + return program, line.String(), nil +} + +// DesktopEntry is what a freedesktop.org desktop entry file says about starting +// its application: the keys of its [Desktop Entry] group that a launcher needs. +type DesktopEntry struct { + Path string // the file the entry was read from, for %k + Name string + Icon string + Exec string + Hidden bool // the entry was deleted + Terminal bool // the program runs in a terminal +} + +// ParseDesktopEntry reads the [Desktop Entry] group of a desktop entry file, +// undoing the string escapes of the values it keeps; localized keys and other +// groups are ignored. +func ParseDesktopEntry(path string, data []byte) DesktopEntry { + entry := DesktopEntry{Path: path} + inGroup := false + for _, line := range strings.Split(string(data), "\n") { + line = strings.TrimSpace(line) + if line == "" || line[0] == '#' { + continue + } + if line[0] == '[' { + inGroup = line == "[Desktop Entry]" + continue + } + key, value, ok := strings.Cut(line, "=") + if !inGroup || !ok { + continue + } + value = desktopString(strings.TrimSpace(value)) + switch strings.TrimSpace(key) { + case "Name": + entry.Name = value + case "Icon": + entry.Icon = value + case "Exec": + entry.Exec = value + case "Hidden": + entry.Hidden = value == "true" + case "Terminal": + entry.Terminal = value == "true" + } + } + return entry +} + +// desktopString undoes the escapes of a desktop entry string value. +func desktopString(value string) string { + if !strings.Contains(value, `\`) { + return value + } + var out strings.Builder + for index := 0; index < len(value); index++ { + char := value[index] + if char == '\\' && index+1 < len(value) { + index++ + switch value[index] { + case 's': + char = ' ' + case 'n': + char = '\n' + case 't': + char = '\t' + case 'r': + char = '\r' + case '\\': + char = '\\' + default: + index-- + } + } + out.WriteByte(char) + } + return out.String() +} + +// Arguments is the program and arguments the entry's Exec starts to open one +// file, by the Desktop Entry Specification's quoting rules and field codes: %u +// and %U become uri, %f and %F path, %c the name, %k the entry's own file, %i +// --icon and the icon when there is one, and %% a percent sign; the deprecated +// codes are dropped. An Exec with no file code gets uri appended, since a +// browser that leaves the code out still takes a URL. +func (entry DesktopEntry) Arguments(uri, path string) ([]string, error) { + words, err := desktopExecWords(entry.Exec) + if err != nil { + return nil, err + } + var arguments []string + placed := false + for _, word := range words { + switch word { + case "%u", "%U": + arguments, placed = append(arguments, uri), true + continue + case "%f", "%F": + arguments, placed = append(arguments, path), true + continue + case "%i": + if entry.Icon != "" { + arguments = append(arguments, "--icon", entry.Icon) + } + continue + } + var expanded strings.Builder + for index := 0; index < len(word); index++ { + if word[index] != '%' || index+1 == len(word) { + expanded.WriteByte(word[index]) + continue + } + index++ + switch word[index] { + case '%': + expanded.WriteByte('%') + case 'u', 'U': + expanded.WriteString(uri) + placed = true + case 'f', 'F': + expanded.WriteString(path) + placed = true + case 'c': + expanded.WriteString(entry.Name) + case 'k': + expanded.WriteString(entry.Path) + case 'i': + expanded.WriteString(entry.Icon) + case 'd', 'D', 'n', 'N', 'v', 'm': + default: + expanded.WriteByte('%') + expanded.WriteByte(word[index]) + } + } + if expanded.Len() == 0 && word != "" { + continue + } + arguments = append(arguments, expanded.String()) + } + if len(arguments) == 0 { + return nil, fmt.Errorf("platform: desktop entry %s has no program to run", entry.Path) + } + if !placed { + arguments = append(arguments, uri) + } + return arguments, nil +} + +// desktopExecWords splits an Exec value into its arguments: spaces separate +// them, and inside double quotes a backslash keeps the next quote, backquote, +// dollar sign or backslash. +func desktopExecWords(value string) ([]string, error) { + var words []string + var word strings.Builder + inWord, quoted := false, false + for index := 0; index < len(value); index++ { + char := value[index] + switch { + case quoted && char == '\\' && index+1 < len(value) && strings.IndexByte("\"`$\\", value[index+1]) >= 0: + word.WriteByte(value[index+1]) + index++ + case quoted && char == '"': + quoted = false + case quoted: + word.WriteByte(char) + case char == '"': + quoted, inWord = true, true + case char == ' ' || char == '\t': + if inWord { + words = append(words, word.String()) + word.Reset() + inWord = false + } + default: + word.WriteByte(char) + inWord = true + } + } + if quoted { + return nil, fmt.Errorf("platform: desktop entry Exec %q has an unterminated quote", value) + } + if inWord { + words = append(words, word.String()) + } + return words, nil +} + +// DesktopEntryCandidates lists, in the order a launcher looks, the files a +// desktop file ID such as "org.example.Browser.desktop" can be: under +// applications in the user's data directory and then in each system one, as +// the ID itself and then with its dashes taken for subdirectories. dataHome and +// dataDirs are $XDG_DATA_HOME and $XDG_DATA_DIRS, with their defaults when +// unset; an ID that is not a plain .desktop file name has no candidates. +func DesktopEntryCandidates(id, dataHome, dataDirs, home string) []string { + if !strings.HasSuffix(id, ".desktop") || strings.ContainsAny(id, "/\x00") || strings.HasPrefix(id, ".") { + return nil + } + var roots []string + if strings.HasPrefix(dataHome, "/") { + roots = append(roots, dataHome) + } else if strings.HasPrefix(home, "/") { + roots = append(roots, strings.TrimSuffix(home, "/")+"/.local/share") + } + if dataDirs == "" { + dataDirs = "/usr/local/share:/usr/share" + } + for _, root := range strings.Split(dataDirs, ":") { + if strings.HasPrefix(root, "/") { + roots = append(roots, root) + } + } + names := []string{id} + if nested := strings.ReplaceAll(id, "-", "/"); nested != id { + names = append(names, nested) + } + var candidates []string + for _, root := range roots { + for _, name := range names { + candidates = append(candidates, strings.TrimSuffix(root, "/")+"/applications/"+name) + } + } + return candidates +} diff --git a/internal/platform/browser_test.go b/internal/platform/browser_test.go new file mode 100644 index 000000000..6eb5cdd61 --- /dev/null +++ b/internal/platform/browser_test.go @@ -0,0 +1,153 @@ +package platform + +import ( + "reflect" + "strings" + "testing" +) + +func TestFileURLIsOneWordABrowserResolvesBackToThePath(t *testing.T) { + cases := []struct { + path string + windows bool + want string + }{ + {"/tmp/my page #1.html", false, "file:///tmp/my%20page%20%231.html"}, + {`/tmp/"quoted" 100%.html`, false, "file:///tmp/%22quoted%22%20100%25.html"}, + {"/tmp/页面.html", false, "file:///tmp/%E9%A1%B5%E9%9D%A2.html"}, + {`C:\Users\me\my page.html`, true, "file:///C:/Users/me/my%20page.html"}, + {`\\server.local\share\dir\report.html`, true, "file://///server.local/share/dir/report.html"}, + {`\\?\C:\very\long.html`, true, "file:///C:/very/long.html"}, + {`\\?\UNC\server\share\a.html`, true, "file://///server/share/a.html"}, + } + for _, test := range cases { + got := FileURL(test.path, test.windows) + if got != test.want { + t.Errorf("FileURL(%q, %t) = %q, want %q", test.path, test.windows, got, test.want) + } + if strings.ContainsAny(got, " \t\"") { + t.Errorf("FileURL(%q) = %q is more than one word", test.path, got) + } + } +} + +func TestBrowserCommandLineFillsInTheRegisteredCommand(t *testing.T) { + const target = "file:///C:/a%20b.html" + installed := map[string]bool{`C:\Program Files\Browser\browser.exe`: true} + exists := func(path string) bool { return installed[path] } + cases := []struct { + command, program, line string + }{ + {`"C:\Program Files\Browser\browser.exe" -osint -url "%1"`, `C:\Program Files\Browser\browser.exe`, + `"C:\Program Files\Browser\browser.exe" -osint -url "file:///C:/a%20b.html"`}, + {`"C:\Program Files\Browser\browser.exe" --single-argument %1`, `C:\Program Files\Browser\browser.exe`, + `"C:\Program Files\Browser\browser.exe" --single-argument file:///C:/a%20b.html`}, + {`"C:\Program Files\Browser\browser.exe" "%L" %*`, `C:\Program Files\Browser\browser.exe`, + `"C:\Program Files\Browser\browser.exe" "file:///C:/a%20b.html" `}, + {`"C:\Program Files\Browser\browser.exe"`, `C:\Program Files\Browser\browser.exe`, + `"C:\Program Files\Browser\browser.exe" file:///C:/a%20b.html`}, + {`C:\Program Files\Browser\browser.exe -- "%1"`, `C:\Program Files\Browser\browser.exe`, + `"C:\Program Files\Browser\browser.exe" -- "file:///C:/a%20b.html"`}, + {`C:\Tools\browser.exe %1`, `C:\Tools\browser.exe`, `"C:\Tools\browser.exe" file:///C:/a%20b.html`}, + {`C:\Tools\browser.exe`, `C:\Tools\browser.exe`, `"C:\Tools\browser.exe" file:///C:/a%20b.html`}, + {`"C:\Tools\browser.exe" -url %1 -- %2`, `C:\Tools\browser.exe`, `"C:\Tools\browser.exe" -url file:///C:/a%20b.html -- %2`}, + } + for _, test := range cases { + program, line, err := BrowserCommandLine(test.command, target, exists) + if err != nil || program != test.program || line != test.line { + t.Errorf("BrowserCommandLine(%q) = %q, %q, %v\nwant %q, %q", test.command, program, line, err, test.program, test.line) + } + } + for _, command := range []string{`"C:\Program Files\browser.exe -url %1`, `""`, ``} { + if _, _, err := BrowserCommandLine(command, target, exists); err == nil { + t.Errorf("BrowserCommandLine(%q) was accepted", command) + } + } + for _, unsafe := range []string{"", "a b", `a"b`} { + if _, _, err := BrowserCommandLine(`"C:\b.exe" %1`, unsafe, exists); err == nil { + t.Errorf("target %q was accepted", unsafe) + } + } +} + +func TestDesktopEntryKeepsOnlyItsOwnGroup(t *testing.T) { + entry := ParseDesktopEntry("/usr/share/applications/browser.desktop", []byte(`# a comment +[Desktop Entry] +Name=Web\sBrowser +Name[fr]=Navigateur +Icon = browser +Exec=browser %u +Terminal=false + +[Desktop Action new-window] +Exec=browser --new-window %u +Hidden=true +`)) + want := DesktopEntry{Path: "/usr/share/applications/browser.desktop", Name: "Web Browser", Icon: "browser", Exec: "browser %u"} + if entry != want { + t.Fatalf("entry = %+v, want %+v", entry, want) + } + hidden := ParseDesktopEntry("", []byte("[Desktop Entry]\nHidden=true\nTerminal=true\n")) + if !hidden.Hidden || !hidden.Terminal { + t.Fatalf("hidden entry = %+v", hidden) + } +} + +func TestDesktopEntryArgumentsFollowTheSpecification(t *testing.T) { + const uri, path = "file:///tmp/a%20b.html", "/tmp/a b.html" + cases := []struct { + exec string + want []string + }{ + {"firefox %u", []string{"firefox", uri}}, + {"/usr/bin/chromium --enable-features=X %U", []string{"/usr/bin/chromium", "--enable-features=X", uri}}, + {"viewer %f", []string{"viewer", path}}, + {"browser", []string{"browser", uri}}, + {"env BAMF_DESKTOP_FILE_HINT=/x.desktop /snap/bin/firefox %u", []string{"env", "BAMF_DESKTOP_FILE_HINT=/x.desktop", "/snap/bin/firefox", uri}}, + {"/usr/bin/flatpak run --file-forwarding org.example.Browser @@u %u @@", []string{"/usr/bin/flatpak", "run", "--file-forwarding", "org.example.Browser", "@@u", uri, "@@"}}, + {`"/opt/My Browser/browser" --name="%c" %i %m %u`, []string{"/opt/My Browser/browser", "--name=Web Browser", "--icon", "browser", uri}}, + {`sh -c "echo \"\$1\" \\\\" %k 100%% %u`, []string{"sh", "-c", `echo "$1" \\`, "/apps/browser.desktop", "100%", uri}}, + {`browser "" %u`, []string{"browser", "", uri}}, + {"browser --url=%u", []string{"browser", "--url=" + uri}}, + } + for _, test := range cases { + entry := DesktopEntry{Path: "/apps/browser.desktop", Name: "Web Browser", Icon: "browser", Exec: test.exec} + got, err := entry.Arguments(uri, path) + if err != nil || !reflect.DeepEqual(got, test.want) { + t.Errorf("Exec=%s: %q, %v\nwant %q", test.exec, got, err, test.want) + } + } + for _, exec := range []string{`browser "%u`, "", "%m"} { + if got, err := (DesktopEntry{Exec: exec}).Arguments(uri, path); err == nil { + t.Errorf("Exec=%s was accepted: %q", exec, got) + } + } + if got, _ := (DesktopEntry{Exec: "browser %i %u"}).Arguments(uri, path); !reflect.DeepEqual(got, []string{"browser", uri}) { + t.Errorf("%%i without an icon = %q", got) + } +} + +func TestDesktopEntryCandidatesFollowTheDataDirectories(t *testing.T) { + got := DesktopEntryCandidates("kde-browser.desktop", "", "/opt/share/:relative:/usr/share", "/home/me") + want := []string{ + "/home/me/.local/share/applications/kde-browser.desktop", + "/home/me/.local/share/applications/kde/browser.desktop", + "/opt/share/applications/kde-browser.desktop", + "/opt/share/applications/kde/browser.desktop", + "/usr/share/applications/kde-browser.desktop", + "/usr/share/applications/kde/browser.desktop", + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("candidates = %q\nwant %q", got, want) + } + got = DesktopEntryCandidates("firefox.desktop", "/data", "", "/home/me") + want = []string{"/data/applications/firefox.desktop", "/usr/local/share/applications/firefox.desktop", "/usr/share/applications/firefox.desktop"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("defaults = %q\nwant %q", got, want) + } + for _, id := range []string{"firefox", "../evil.desktop", "a/b.desktop", ".desktop", "a\x00.desktop"} { + if got := DesktopEntryCandidates(id, "", "", "/home/me"); got != nil { + t.Errorf("%q has candidates %q", id, got) + } + } +} diff --git a/internal/platform/darwin/system_darwin.go b/internal/platform/darwin/system_darwin.go index 3f04e1b6d..4577f0f5e 100644 --- a/internal/platform/darwin/system_darwin.go +++ b/internal/platform/darwin/system_darwin.go @@ -12,6 +12,8 @@ import "C" import ( "errors" "fmt" + "os/exec" + "path/filepath" "runtime" "strings" "sync/atomic" @@ -411,6 +413,26 @@ func SchemeHandlerAvailable(scheme string) (bool, error) { return status == 1, nil } +// OpenInBrowser opens the file at path in the default browser, the application +// https links open in, through open, whose exit status reports whether the +// handoff worked. Without a default browser it returns platform.ErrNoBrowser. +func OpenInBrowser(path string) error { + var nativePath, nativeError *C.char + switch C.viva_system_default_browser(&nativePath, &nativeError) { + case 0: + return fmt.Errorf("darwin: open in browser: %w", platform.ErrNoBrowser) + case 1: + default: + return systemError("look up the default browser", nativeError) + } + browser := C.GoString(nativePath) + C.viva_system_free(unsafe.Pointer(nativePath)) + if err := exec.Command("/usr/bin/open", "-a", browser, path).Run(); err != nil { + return fmt.Errorf("darwin: open in %s: %w", filepath.Base(browser), err) + } + return nil +} + func PlaySystemSound(sound uint8) error { var nativeError *C.char if C.viva_system_play_sound(C.uint8_t(sound), &nativeError) != 0 { diff --git a/internal/platform/darwin/system_darwin.h b/internal/platform/darwin/system_darwin.h index b55e5755b..a0b9d930b 100644 --- a/internal/platform/darwin/system_darwin.h +++ b/internal/platform/darwin/system_darwin.h @@ -73,6 +73,9 @@ int viva_system_reveal_path(const char *path, char **error_message); // Whether any application is registered for the URL scheme (no trailing colon): // 1 yes, 0 no, -1 failure with *error_message. int viva_system_scheme_handler(const char *scheme, char **error_message); +// The application https links open in, the default browser: 1 with *path set, +// 0 when there is none, -1 failure with *error_message. +int viva_system_default_browser(char **path, char **error_message); int viva_system_reduce_motion(void); char *viva_system_preferred_languages(void); int viva_system_dark_appearance(void); diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m index 04a685674..4addd74dd 100644 --- a/internal/platform/darwin/system_darwin.m +++ b/internal/platform/darwin/system_darwin.m @@ -1117,6 +1117,26 @@ int viva_system_scheme_handler(const char *scheme, char **error_message) { } } +int viva_system_default_browser(char **path, char **error_message) { + // Like the scheme lookup, LaunchServices answers this from any thread. + @autoreleasepool { + NSURL *probe = [NSURL URLWithString:@"https://example.invalid/"]; + NSURL *browser = [NSWorkspace.sharedWorkspace URLForApplicationToOpenURL:probe]; + if (browser == nil) { + return 0; + } + NSString *value = browser.path; + if (value.length == 0) { + if (error_message != NULL) { + *error_message = viva_copy_utf8(@"the default browser has no file path"); + } + return -1; + } + *path = viva_copy_utf8(value); + return 1; + } +} + int viva_system_play_sound(uint8_t sound, char **error_message) { __block int status = 0; __block char *failure = NULL; diff --git a/internal/platform/linux/open_in_browser_linux.go b/internal/platform/linux/open_in_browser_linux.go new file mode 100644 index 000000000..02b927b5b --- /dev/null +++ b/internal/platform/linux/open_in_browser_linux.go @@ -0,0 +1,93 @@ +package linux + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "github.com/vivaui/viva/internal/platform" +) + +// browserQueryTimeout bounds asking xdg-settings or xdg-mime for the default +// browser, which are shell scripts that can hang on a broken session. +const browserQueryTimeout = 5 * time.Second + +// OpenInBrowser opens the file at path in the default browser: the desktop +// entry xdg-settings names as the default web browser, or the one xdg-mime +// gives https links to, is started with the file's URL by its Exec line, +// without a shell, and reaped in the background once it exits. Without a +// default browser it returns platform.ErrNoBrowser. +func OpenInBrowser(path string) error { + id, err := defaultBrowserID() + if err != nil { + return err + } + entry, err := readDesktopEntry(id) + if err != nil { + return err + } + if entry.Hidden { + return fmt.Errorf("linux: open in browser: %s is hidden: %w", id, platform.ErrNoBrowser) + } + if entry.Terminal { + return unsupported(fmt.Sprintf("the default browser %s runs in a terminal", id)) + } + arguments, err := entry.Arguments(platform.FileURL(path, false), path) + if err != nil { + return fmt.Errorf("linux: open in browser: %w", err) + } + if err := platform.StartReaped(exec.Command(arguments[0], arguments[1:]...)); err != nil { + return fmt.Errorf("linux: launch %s: %w", filepath.Base(arguments[0]), err) + } + return nil +} + +// defaultBrowserID is the desktop file ID of the default browser. +func defaultBrowserID() (string, error) { + queries := []desktopCommand{ + {name: "xdg-settings", arguments: []string{"get", "default-web-browser"}}, + {name: "xdg-mime", arguments: []string{"query", "default", "x-scheme-handler/https"}}, + } + asked := false + for _, query := range queries { + program, err := exec.LookPath(query.name) + if err != nil { + continue + } + asked = true + ctx, cancel := context.WithTimeout(context.Background(), browserQueryTimeout) + output, err := exec.CommandContext(ctx, program, query.arguments...).Output() + cancel() + if err != nil { + continue + } + id, _, _ := strings.Cut(strings.TrimSpace(string(output)), ";") + if id = strings.TrimSpace(id); id != "" { + return id, nil + } + } + if !asked { + return "", unsupported("opening a file in the browser requires xdg-settings or xdg-mime") + } + return "", fmt.Errorf("linux: open in browser: %w", platform.ErrNoBrowser) +} + +func readDesktopEntry(id string) (platform.DesktopEntry, error) { + home, _ := os.UserHomeDir() + for _, candidate := range platform.DesktopEntryCandidates(id, os.Getenv("XDG_DATA_HOME"), os.Getenv("XDG_DATA_DIRS"), home) { + data, err := os.ReadFile(candidate) + if err == nil { + return platform.ParseDesktopEntry(candidate, data), nil + } + if !errors.Is(err, fs.ErrNotExist) { + return platform.DesktopEntry{}, fmt.Errorf("linux: read %s: %w", candidate, err) + } + } + return platform.DesktopEntry{}, fmt.Errorf("linux: open in browser: the default browser %q has no desktop entry: %w", id, platform.ErrNoBrowser) +} diff --git a/internal/platform/windows/open_in_browser_windows.go b/internal/platform/windows/open_in_browser_windows.go new file mode 100644 index 000000000..3328d8f06 --- /dev/null +++ b/internal/platform/windows/open_in_browser_windows.go @@ -0,0 +1,73 @@ +//go:build windows + +package windows + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND): the protocol has no key at all, as +// hresultNoAssociation means it has no command. +const hresultFileNotFound = 0x80070002 + +// OpenInBrowser opens the file at path in the default browser by starting the +// command Windows registers for http links with the file's URL, without a +// shell, as the shell itself fills the command in; the browser is reaped in the +// background once it exits. Without a default browser it returns +// platform.ErrNoBrowser. +func OpenInBrowser(path string) error { + command, err := browserCommand() + if err != nil { + return err + } + program, commandLine, err := platform.BrowserCommandLine(command, platform.FileURL(path, true), regularFile) + if err != nil { + return fmt.Errorf("windows: open in browser: %w", err) + } + browser := exec.Command(program) + browser.SysProcAttr = &syscall.SysProcAttr{CmdLine: commandLine} + if err := platform.StartReaped(browser); err != nil { + return fmt.Errorf("windows: launch %s: %w", filepath.Base(program), err) + } + return nil +} + +// browserCommand is the command line Windows starts http links with, the +// default browser's. +func browserCommand() (string, error) { + protocol, _ := syscall.UTF16PtrFromString("http") + var length uint32 + status, _, _ := assocQueryString.Call(assocfIsProtocol, assocStrCommand, uintptr(unsafe.Pointer(protocol)), 0, 0, uintptr(unsafe.Pointer(&length))) + if code := uint32(status); code == hresultNoAssociation || code == hresultFileNotFound { + return "", fmt.Errorf("windows: open in browser: %w", platform.ErrNoBrowser) + } + if err := hresult(status); err != nil { + return "", fmt.Errorf("windows: look up the default browser: %w", err) + } + if length == 0 { + return "", fmt.Errorf("windows: open in browser: %w", platform.ErrNoBrowser) + } + buffer := make([]uint16, length) + status, _, _ = assocQueryString.Call(assocfIsProtocol, assocStrCommand, uintptr(unsafe.Pointer(protocol)), 0, uintptr(unsafe.Pointer(&buffer[0])), uintptr(unsafe.Pointer(&length))) + if err := hresult(status); err != nil { + return "", fmt.Errorf("windows: look up the default browser: %w", err) + } + command := strings.TrimSpace(syscall.UTF16ToString(buffer)) + if command == "" { + return "", fmt.Errorf("windows: open in browser: %w", platform.ErrNoBrowser) + } + return command, nil +} + +func regularFile(path string) bool { + info, err := os.Stat(path) + return err == nil && info.Mode().IsRegular() +} diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md index e4aad5ece..b89cd1ed1 100644 --- a/website/content/guides/en/system-integration.md +++ b/website/content/guides/en/system-integration.md @@ -13,6 +13,7 @@ The `app` package exposes a small, synchronous set of system integrations. An op | File dialogs | `app.OpenFiles`, `app.OpenDirectory`, `app.SaveFile` | | Open a URL | `app.OpenURL` | | Open a local document in its default application (never a program) | `app.OpenPath` | +| Open a local file, such as an HTML page, in the default browser whatever opens its type | `app.OpenPathInBrowser` | | Notifications and sounds | `app.SendNotification`, `app.PlaySystemSound` | | Cursor | `app.SetCursor` | | Preferred languages | `app.PreferredLanguages` | @@ -27,7 +28,7 @@ The `app` package exposes a small, synchronous set of system integrations. An op ## What each platform uses -Each function maps to the platform's own API: `NSPasteboard`, `NSOpenPanel` and `NSWorkspace` on macOS; the Win32 clipboard, `IFileOpenDialog` and `ShellExecuteW` on Windows; X11 selections on Linux, with the desktop portal's file chooser and the notification service over D-Bus (`zenity`, `kdialog` and `notify-send` when a desktop has neither), and `xdg-open` or `gio` for URLs. Secrets go to the Keychain, Credential Manager or Secret Service. +Each function maps to the platform's own API: `NSPasteboard`, `NSOpenPanel` and `NSWorkspace` on macOS; the Win32 clipboard, `IFileOpenDialog` and `ShellExecuteW` on Windows; X11 selections on Linux, with the desktop portal's file chooser and the notification service over D-Bus (`zenity`, `kdialog` and `notify-send` when a desktop has neither), and `xdg-open` or `gio` for URLs. The default browser is the application LaunchServices opens `https` links in on macOS, the `http` protocol's registered command on Windows, and on Linux the desktop entry `xdg-settings` names. Secrets go to the Keychain, Credential Manager or Secret Service. The full table, including the cases where a platform cannot do something, is the repository's `docs/system-integrations.md`. diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md index 938020ad6..17c93ca3c 100644 --- a/website/content/guides/zh/system-integration.md +++ b/website/content/guides/zh/system-integration.md @@ -13,6 +13,7 @@ group: guides | 文件对话框 | `app.OpenFiles`、`app.OpenDirectory`、`app.SaveFile` | | 打开 URL | `app.OpenURL` | | 用默认应用打开本地文档(绝不运行程序) | `app.OpenPath` | +| 用默认浏览器打开本地文件(如 HTML 页面),不论该类型关联到哪个应用 | `app.OpenPathInBrowser` | | 通知与声音 | `app.SendNotification`、`app.PlaySystemSound` | | 光标 | `app.SetCursor` | | 系统首选语言 | `app.PreferredLanguages` | @@ -27,7 +28,7 @@ group: guides ## 各平台用什么实现 -每个函数都映射到平台自己的接口:macOS 上是 `NSPasteboard`、`NSOpenPanel` 和 `NSWorkspace`;Windows 上是 Win32 剪贴板、`IFileOpenDialog` 和 `ShellExecuteW`;Linux 上是 X11 选区,文件对话框使用 `zenity` 或 `kdialog`,打开 URL 使用 `xdg-open` 或 `gio`,通知使用 `notify-send`。密钥存入钥匙串、凭据管理器或 Secret Service。 +每个函数都映射到平台自己的接口:macOS 上是 `NSPasteboard`、`NSOpenPanel` 和 `NSWorkspace`;Windows 上是 Win32 剪贴板、`IFileOpenDialog` 和 `ShellExecuteW`;Linux 上是 X11 选区,文件对话框使用 `zenity` 或 `kdialog`,打开 URL 使用 `xdg-open` 或 `gio`,通知使用 `notify-send`。默认浏览器在 macOS 上是 LaunchServices 打开 `https` 链接所用的应用,在 Windows 上是 `http` 协议登记的命令,在 Linux 上是 `xdg-settings` 给出的桌面文件。密钥存入钥匙串、凭据管理器或 Secret Service。 完整的表格,包括某个平台做不到某件事的情形,见仓库中的 `docs/system-integrations.md`。 From 68ce694cdcf0a38e76f7118fef217786e1388d2f Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 13:46:35 +0800 Subject: [PATCH 82/86] fix(ui): scroll TextArea content with the mouse wheel --- components/textarea.go | 20 ++++++++++++++ components/textarea_wheel_test.go | 45 +++++++++++++++++++++++++++++++ ui/page.go | 7 +++++ 3 files changed, 72 insertions(+) create mode 100644 components/textarea_wheel_test.go diff --git a/components/textarea.go b/components/textarea.go index a9de9ea3e..d03a4f803 100644 --- a/components/textarea.go +++ b/components/textarea.go @@ -569,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_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/ui/page.go b/ui/page.go index fd87add25..d6e565b7a 100644 --- a/ui/page.go +++ b/ui/page.go @@ -1127,6 +1127,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 From 4de3c5dde4730cffb9fb1b1f27d23be2a4165b8d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 13:46:59 +0800 Subject: [PATCH 83/86] fix(components): regenerate the TextArea recipe for wheel support --- cmd/viva/templates/textarea.go.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/cmd/viva/templates/textarea.go.txt b/cmd/viva/templates/textarea.go.txt index 904f44cb2..80e291a52 100644 --- a/cmd/viva/templates/textarea.go.txt +++ b/cmd/viva/templates/textarea.go.txt @@ -569,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 From e2c8db254e90bd8777ed6499a39185de29db287c Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 13:47:55 +0800 Subject: [PATCH 84/86] feat(package): write .rpm packages for Fedora, RHEL and openSUSE --- cmd/viva/help.go | 2 +- cmd/viva/package.go | 4 +- cmd/viva/package_tarball.go | 43 ++- cmd/viva/package_tarball_test.go | 20 +- docs/conformance.md | 2 +- docs/updating.md | 9 +- tools/rpmpkg/rpmpkg.go | 530 +++++++++++++++++++++++++++++++ tools/rpmpkg/rpmpkg_test.go | 147 +++++++++ update/install_linux.go | 15 + update/install_linux_test.go | 53 ++++ 10 files changed, 807 insertions(+), 18 deletions(-) create mode 100644 tools/rpmpkg/rpmpkg.go create mode 100644 tools/rpmpkg/rpmpkg_test.go diff --git a/cmd/viva/help.go b/cmd/viva/help.go index bd19426f2..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" + 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/docs/conformance.md b/docs/conformance.md index 1affa16d5..dd02cf7f2 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -94,7 +94,7 @@ mistakes an absence for an oversight. Items marked *measured* were tried or size | 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/updating.md b/docs/updating.md index c4e559731..54ba6414d 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -272,10 +272,10 @@ error nothing has been changed and `quit` was not called. | 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 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` installed by dpkg, a read-only directory | +| 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 @@ -350,8 +350,9 @@ warning. 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, and a patch only writes a writable directory. A `[windows] scope = "machine"` installation under `Program Files` cannot be 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..173098fe6 --- /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 info := run("-qpi", path); !strings.Contains(info, "Summary : A test application") { + t.Fatalf("rpm -qpi lacks the summary:\n%s", info) + } + 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/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"}, From 1fc64444f57073cb4fe2d27942cb9c8cd6c2a21b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 13:35:03 +0800 Subject: [PATCH 85/86] test(rpmpkg): read the rpm summary with a query format --- tools/rpmpkg/rpmpkg_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/rpmpkg/rpmpkg_test.go b/tools/rpmpkg/rpmpkg_test.go index 173098fe6..fe87ada41 100644 --- a/tools/rpmpkg/rpmpkg_test.go +++ b/tools/rpmpkg/rpmpkg_test.go @@ -124,8 +124,8 @@ func TestWriteVerifiesWithRPMTools(t *testing.T) { 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 info := run("-qpi", path); !strings.Contains(info, "Summary : A test application") { - t.Fatalf("rpm -qpi lacks the summary:\n%s", info) + 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"} { From 1fc84f6ff1d3a4020277b509fecab86527c0494f Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 14:33:04 +0800 Subject: [PATCH 86/86] feat(darwin): keep the input method off surfaces that disable it A text input that sets DisableIME (a surface showing another machine's remote desktop) still sent its keys through the host's text system on macOS, so the local input method composed and showed its candidates over the picture. The flag was honored on Windows only. macOS now never exposes such a surface to the text system: the input context is deactivated, printable keys reach a terminal-role surface as raw presses with their base character and the text they type, named keys keep their existing route, and an ordinary field takes what the layout types as a text event. A composition held when the flag turns on is discarded, and the flag joins the presentation comparison so turning it on is never mistaken for the field only moving. Motty's remote desktop already declares the flag, so its keys now reach the input method of the machine on the other side. --- app/text_input.go | 3 +- internal/platform/contract.go | 3 +- internal/platform/darwin/native.h | 4 + internal/platform/darwin/native.m | 101 +++++++++++------ internal/platform/darwin/platform.go | 4 +- .../platform/darwin/testdata/text_selection.m | 102 +++++++++++++++++- internal/platform/darwin/text_test.go | 21 ++++ 7 files changed, 200 insertions(+), 38 deletions(-) diff --git a/app/text_input.go b/app/text_input.go index f85c10a9a..0c3d79cd3 100644 --- a/app/text_input.go +++ b/app/text_input.go @@ -212,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 diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 8758c0fcf..68642d24c 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -903,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 diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 6beed09b9..4cc50c82e 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 92baf645f..44fe66e21 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -3851,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; @@ -4064,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; @@ -4376,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; @@ -4591,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; @@ -4634,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]; @@ -4710,12 +4727,14 @@ - (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 = [viva_key_base_characters(event) dataUsingEncoding:NSUTF8StringEncoding]; NSData *typedText = [typed dataUsingEncoding:NSUTF8StringEncoding]; @@ -4726,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]; @@ -5054,6 +5076,7 @@ - (void)shutdownTextInput { _hasMarkedText = NO; _textAltSendsEscape = NO; _textKeyReleases = NO; + _textDisableIME = NO; } - (void)detachCallbacks { @@ -5533,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]; @@ -5571,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; @@ -5583,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; @@ -5594,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 ee9146391..eeda0a4b2 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -260,6 +260,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() } @@ -268,7 +269,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 } @@ -838,6 +839,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/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_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.