From 9f2eb0f905108ba5b5380fd9e719eb0187167dc5 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 27 Nov 2026 17:50:26 +0800 Subject: [PATCH 01/29] fix(components): draw a focus ring on unfilled buttons as a halo A button's focus ring was painted as a disc under its surface, which the button's own fill covered; a ghost, link or translucent-filled button left the disc visible through its middle, so a keyboard-focused ghost button read as a filled square. Paint the halo as a line whenever the look paints no opaque fill, in the canvas button, the button group and the frame's ring. PaintButtonSurface is now the surface half of BeginButton's paint, next to PaintButtonContent, so a page that draws a button's content itself paints a button surface instead of a copy of this logic. Motty's tools window takes this surface in its own commit. --- base/button_node_test.go | 14 ++++++++ base/style.go | 12 ++++--- components/button.go | 64 +++++++++++++++++++++------------ components/button_group.go | 11 +++++- components/button_group_test.go | 27 ++++++++++++++ components/button_test.go | 36 +++++++++++++++++-- components/doc.go | 5 +-- components/recipes_test.go | 16 +-------- style/look.go | 4 +-- 9 files changed, 140 insertions(+), 49 deletions(-) diff --git a/base/button_node_test.go b/base/button_node_test.go index fca19723f..da6a10dfe 100644 --- a/base/button_node_test.go +++ b/base/button_node_test.go @@ -273,3 +273,17 @@ func TestButtonIsOneRectangleWhateverItIsGiven(t *testing.T) { } } } + +// A ghost button holds the keyboard too: its focus ring is a halo around it, and its +// middle still shows the page rather than the ring's disc. +func TestFocusedGhostButtonKeepsItsMiddleClear(t *testing.T) { + focused := func(c *gfx.Canvas) { c.SetInteraction(gfx.ID{}, gfx.ID{}, save, true) } + p := probeButton(t, focused, func(f *Frame) Box { return f.Button(save, "Save").Ghost() }) + center := gfx.Point{X: p.box.X + p.box.Width/2, Y: p.box.Y + p.box.Height/2} + for _, rectangle := range p.canvas.Rectangles() { + box := rectangle.Bounds + if center.X > box.X && center.X < box.X+box.Width && center.Y > box.Y && center.Y < box.Y+box.Height { + t.Fatalf("the focus ring fills the ghost button's middle: %+v", rectangle) + } + } +} diff --git a/base/style.go b/base/style.go index e3bfdfa67..cabbf459f 100644 --- a/base/style.go +++ b/base/style.go @@ -355,9 +355,10 @@ type resolved struct { // and then the line over it even where one shape could paint both. borderWidth float32 splitBorder bool - // ringFilled paints the ring as a disc under the element rather than a line around - // it, and a nonzero ringLine is the width the line is drawn at: how a control's - // recipe draws its focus ring over an opaque page and over a translucent one. + // ringFilled paints the ring as a disc under an element whose opaque background + // covers its middle rather than as a line around it, and a nonzero ringLine is the + // width the line is drawn at: how a control's recipe draws its focus ring over an + // opaque page and over a translucent one. ringFilled bool ringLine float32 } @@ -464,11 +465,14 @@ func (f *Frame) paintRing(r Rect, Radius float32, s *resolved) { Radius += w } switch { - case s.ringFilled: + case s.ringFilled && s.Background.Alpha*f.Opacity >= 1: + // The surface covers the middle of the disc, leaving the halo outside it. f.Surface.Rounded(outer, Radius, color) case s.ringLine > 0: f.Surface.RoundedOutline(outer, Radius, s.ringLine, color) default: + // Nothing over the middle (a ghost or link button's transparent surface, or a + // disabled one) would cover a disc: the halo is only its line. f.Surface.RoundedOutline(outer, Radius, w, color) } } diff --git a/components/button.go b/components/button.go index 2c8c1809a..b2920c14c 100644 --- a/components/button.go +++ b/components/button.go @@ -377,26 +377,7 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { 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 - } - if look.RingWidth > 0 { - if look.RingOutline { - button.canvas.RoundedOutline(expand(button.bounds, look.RingWidth), look.RingRadius, 2, look.Ring) - } else { - button.canvas.Rounded(expand(button.bounds, look.RingWidth), look.RingRadius, look.Ring) - } - } - style := buttonStyle{ - background: look.Background, foreground: look.Foreground, border: look.Border, - filled: look.Filled, bordered: look.Bordered, underlined: look.Underlined, - } - if style.bordered && style.filled { - paintBordered(button.canvas, button.theme, button.bounds, radius, style.border, style.background) - } else if style.filled { - button.canvas.Rounded(button.bounds, radius, style.background) - } + PaintButtonSurface(button.canvas, button.theme, button.bounds, look) area := button.bounds _, padding, _, _ := button.geometry() if !iconOnly && padding > 0 { @@ -415,8 +396,8 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { } hint := PaintButtonContent(button.canvas, area, ButtonContent{ Label: label, Icon: button.icon, IconTransform: button.iconTransform, - FontSize: fontSize, Weight: gfx.WeightMedium, Color: style.foreground, - Gap: buttonIconGap, Height: height, IconOnly: iconOnly, Underlined: style.underlined, + FontSize: fontSize, Weight: gfx.WeightMedium, Color: look.Foreground, + Gap: buttonIconGap, Height: height, IconOnly: iconOnly, Underlined: look.Underlined, }) if !button.id.IsZero() { button.canvas.HitWithOptions(button.id, button.bounds, label, gfx.HitOptions{ @@ -646,6 +627,45 @@ type ButtonContent struct { // function, not a closure made in each paint, which would allocate. type ButtonLoadingPainter func(canvas *gfx.Canvas, theme *gfx.Theme, bounds gfx.Rect, color gfx.Color, phase uint8) +// PaintButtonSurface paints a button's surface in bounds: its shadow, its focus +// ring, its fill and its border, for a look the caller resolved itself with +// ButtonRecipe or with a recipe of its own. It is the surface half of the paint +// BeginButton does, so a control that draws content of its own on a button's +// surface paints the same surface as a declared button; PaintButtonContent is +// the content half. +// +// The focus ring is a halo that reaches RingWidth beyond bounds. Under an opaque +// fill only the part outside the bounds can be seen, so the whole halo is painted +// with the fill over it; a button that paints no opaque fill (ghost or link, or +// one that is disabled) gets the halo as a line, since nothing would cover the +// middle of the disc. +func PaintButtonSurface(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, look ButtonLook) { + if canvas == nil || bounds.Width <= 0 || bounds.Height <= 0 { + return + } + radius := look.Radius + if look.Shadow != gfx.ShadowNone { + canvas.Elevate(bounds, radius, look.Shadow) // shadow-xs + } + if look.RingWidth > 0 { + halo := expand(bounds, look.RingWidth) + switch { + case look.RingOutline: + canvas.RoundedOutline(halo, look.RingRadius, 2, look.Ring) + case look.Filled && look.Background.Alpha >= 1: + canvas.Rounded(halo, look.RingRadius, look.Ring) + default: + canvas.RoundedOutline(halo, look.RingRadius, look.RingWidth, look.Ring) + } + } + switch { + case look.Bordered && look.Filled: + paintBordered(canvas, theme, bounds, radius, look.Border, look.Background) + case look.Filled: + canvas.Rounded(bounds, radius, look.Background) + } +} + // PaintButtonContent paints a button's icon and label centered in area and returns the // hint an icon-only button gives assistive technology, which is its label. It is the // content half of the paint the Button does: the same placement, the same shrinking of diff --git a/components/button_group.go b/components/button_group.go index d5977ddf1..c3a62bfb4 100644 --- a/components/button_group.go +++ b/components/button_group.go @@ -95,7 +95,16 @@ func (group ButtonGroup) Paint() ButtonGroupResult { framed = framed || option.Variant == ButtonOutline || option.Variant == ButtonDestructiveOutline if !group.disabled && !option.Disabled && !option.ID.IsZero() && group.canvas.FocusVisible() == option.ID { ring, _ := buttonRing(&group.theme, option.Variant, false) - group.canvas.Rounded(expand(group.optionBounds(index, float32(count)), 3), radius+3, ring) + halo := expand(group.optionBounds(index, float32(count)), 3) + // The halo is a disc under an action that paints an opaque fill; an action + // with no fill of its own gets it as a line, or the disc would fill the + // action's whole surface. + style := buttonStyleFor(&group.theme, option.Variant, group.canvas.Hovered() == option.ID, group.canvas.Pressed() == option.ID) + if style.filled && style.background.Alpha >= 1 { + group.canvas.Rounded(halo, radius+3, ring) + } else { + group.canvas.RoundedOutline(halo, radius+3, 3, ring) + } } } // The outline goes down first and the actions are painted inside it. diff --git a/components/button_group_test.go b/components/button_group_test.go index 2d092b853..c9562b7bc 100644 --- a/components/button_group_test.go +++ b/components/button_group_test.go @@ -121,3 +121,30 @@ func hasRectangleColor(canvas *gfx.Canvas, color gfx.Color) bool { } return false } + +// A ghost action in a group holds the keyboard like any other: its focus ring is a halo +// around it, and the disc a filled action hides under itself would fill the ghost's +// whole surface. +func TestFocusedGhostGroupActionKeepsItsMiddleClear(t *testing.T) { + options := [...]ButtonGroupOption{ + {ID: gfx.Item(61), Label: "Save", Variant: ButtonDefault}, + {ID: gfx.Item(62), Label: "More", Variant: ButtonGhost}, + } + var canvas gfx.Canvas + canvas.SetInteraction(gfx.ID{}, gfx.ID{}, gfx.Item(62), true) + BeginButtonGroup(&canvas, gfx.LightTheme(), gfx.Rect{Width: 240}, options[:]).Paint() + if len(canvas.Hits()) != len(options) { + t.Fatalf("hits = %+v", canvas.Hits()) + } + ghost := canvas.Hits()[1].Bounds + center := gfx.Point{X: ghost.X + ghost.Width/2, Y: ghost.Y + ghost.Height/2} + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color.Alpha <= 0 { + continue + } + box := rectangle.Bounds + if center.X > box.X && center.X < box.X+box.Width && center.Y > box.Y && center.Y < box.Y+box.Height { + t.Fatalf("the focus ring fills the ghost action's middle: %+v", rectangle) + } + } +} diff --git a/components/button_test.go b/components/button_test.go index 10549ab82..b95e84ac2 100644 --- a/components/button_test.go +++ b/components/button_test.go @@ -160,11 +160,17 @@ func TestButtonFocusAndInvalidRingsUseOfficialTokensInDark(t *testing.T) { if focusRing.Color != wantFocus || focusRing.Bounds != (gfx.Rect{X: 1, Y: 1, Width: 106, Height: 38}) { t.Fatalf("focus ring = %+v, want Ring/50 expanded 3px", focusRing) } - invalidRing := invalid.Rectangles()[0] + // The dark outline's surface is a translucent input tint, so nothing covers the + // middle of a ring disc: the invalid ring is the danger token drawn as a line, and + // the border keeps its own token. + ring := invalid.Triangles() wantInvalid := withAlpha(theme.Danger, 0.40) wantBorder := invalidBorder(&theme).Over(theme.Background) - if invalidRing.Color != wantInvalid || invalid.Rectangles()[1].Color != wantBorder { - t.Fatalf("invalid ring/border = %+v / %+v", invalidRing, invalid.Rectangles()[1]) + if len(ring) == 0 || ring[0].Color != wantInvalid { + t.Fatalf("invalid ring = %+v, want the danger/40 line", ring) + } + if invalid.Rectangles()[0].Color != wantBorder { + t.Fatalf("invalid border = %+v, want %+v", invalid.Rectangles()[0], wantBorder) } } @@ -315,3 +321,27 @@ func TestButtonFontSizeChangesOnlyTheLabel(t *testing.T) { t.Errorf("a bigger label fit in %v, no wider than %v", large, small) } } + +// A focused button that paints no fill keeps its middle: the focus ring is a halo +// around the button, and a disc under it would show through the surface. +func TestFocusedButtonRingDoesNotFillAnUnpaintedSurface(t *testing.T) { + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 20, Y: 20, Width: 40, Height: 32} + center := gfx.Point{X: bounds.X + bounds.Width/2, Y: bounds.Y + bounds.Height/2} + for _, variant := range []ButtonVariant{ButtonGhost, ButtonLink} { + var canvas gfx.Canvas + BeginButton(&canvas, theme, gfx.Item(1), bounds).WithState(ButtonState{Focused: true}).paint("Open", variant) + if len(canvas.Triangles()) == 0 { + t.Fatalf("%v: a focused button drew no ring", variant) + } + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color.Alpha <= 0 { + continue + } + box := rectangle.Bounds + if center.X > box.X && center.X < box.X+box.Width && center.Y > box.Y && center.Y < box.Y+box.Height { + t.Fatalf("%v: the ring fills the button's middle: %+v", variant, rectangle) + } + } + } +} diff --git a/components/doc.go b/components/doc.go index 3abe264ff..f17601d23 100644 --- a/components/doc.go +++ b/components/doc.go @@ -74,9 +74,10 @@ // - Button: `BeginButton` paints a labeled control with Default, Secondary, // Outline, and Ghost variants; hover, press, and focus states, metrics- // scaled geometry, and the hit declaration are built in. -// `ButtonRecipe` is the look of a variant in a state as plain values, and +// `ButtonRecipe` is the look of a variant in a state as plain values; +// `PaintButtonSurface` paints that look's surface alone, and // `PaintButtonContent` paints a button's icon and label alone, centered in -// the area a surface the caller painted leaves for them. +// the area the surface leaves for them. // - Icon hover: `IconHover` plays one short gesture after an icon-only // control's pointer rests, and `Button.IconTransform` paints the resulting // transform inside the button's hit region. diff --git a/components/recipes_test.go b/components/recipes_test.go index b8d2e4894..3b5be6c2a 100644 --- a/components/recipes_test.go +++ b/components/recipes_test.go @@ -185,21 +185,7 @@ func TestButtonRecipePaintsTheSurfaceAsTheComponentDoes(t *testing.T) { var got gfx.Canvas look := ButtonRecipe(theme, variant, state) - if look.Shadow != gfx.ShadowNone { - got.Elevate(bounds, look.Radius, look.Shadow) - } - if look.RingWidth > 0 { - if look.RingOutline { - got.RoundedOutline(expand(bounds, look.RingWidth), look.RingRadius, 2, look.Ring) - } else { - got.Rounded(expand(bounds, look.RingWidth), look.RingRadius, look.Ring) - } - } - if look.Bordered && look.Filled { - paintBordered(&got, theme, bounds, look.Radius, look.Border, look.Background) - } else if look.Filled { - got.Rounded(bounds, look.Radius, look.Background) - } + PaintButtonSurface(&got, theme, bounds, look) // The underline of a hovered link belongs to the label, which this test has none of. var surface []gfx.Rectangle for _, r := range want.Rectangles() { diff --git a/style/look.go b/style/look.go index 9052e6127..9d4a30269 100644 --- a/style/look.go +++ b/style/look.go @@ -17,8 +17,8 @@ type ButtonLook struct { // Shadow is the elevation under the surface; only the outline variant has one. Shadow gfx.ShadowLevel // Ring is the halo of a focused or invalid button, transparent with a zero RingWidth - // when there is none. RingOutline says it is drawn as a line over a translucent theme - // rather than a disc under the surface. + // when there is none. RingOutline says it is drawn as a line over a translucent theme. + // A surface with no opaque fill is not covered by a disc either, so its halo is a line. Ring gfx.Color RingWidth, RingRadius float32 RingOutline bool From 7022eddcbfe0d01cf1230ae3058a318f82396583 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 27 Nov 2026 22:50:03 +0800 Subject: [PATCH 02/29] fix(input): scroll a page notch by the region's own screen Windows reports the "one screen per notch" setting as a screen of the window, so a list, menu or dialog smaller than the window moved by the window's screen and skipped the rows in between. The scroll event now says how many screens it is, and each scroll region moves that many of its own screens, following whole visible rows where it scrolls rows. ScrollState, menus, selects, text areas, the code editor, the code diff, the time picker and the editable tabs resolve their own page; a wheel that is not set to screens keeps its old distance. Refs: t8y2/motty#1672 --- app/driver.go | 2 +- app/painter.go | 2 +- base/list.go | 11 ++++- base/menu_state.go | 3 ++ base/scroll.go | 8 ++++ base/scroll_test.go | 23 +++++++++ base/select.go | 2 +- base/textarea.go | 3 ++ components/code_diff.go | 12 +++-- components/code_editor_layout.go | 2 +- gfx/input.go | 55 ++++++++++++++++++++-- gfx/scroll_test.go | 33 +++++++++++++ internal/platform/contract.go | 7 ++- internal/platform/windows/wheel_windows.go | 13 ++++- internal/reloadwire/codec.go | 3 +- ui/editabletabs/editabletabs.go | 6 +++ ui/timepicker/timepicker.go | 6 ++- 17 files changed, 174 insertions(+), 17 deletions(-) diff --git a/app/driver.go b/app/driver.go index b0aabe2da..37551cc59 100644 --- a/app/driver.go +++ b/app/driver.go @@ -534,7 +534,7 @@ func (driver *Driver) Scroll(event gfx.ScrollEvent) error { } _, err := driver.painter.scroll(platform.ScrollEvent{ Modifiers: event.Modifiers | driver.heldModifiers(), X: event.X, Y: event.Y, - DeltaX: event.DeltaX, DeltaY: event.DeltaY, Precise: event.Precise, + DeltaX: event.DeltaX, DeltaY: event.DeltaY, Pages: event.Pages, Precise: event.Precise, }) return err } diff --git a/app/painter.go b/app/painter.go index d312cf628..a475a19c3 100644 --- a/app/painter.go +++ b/app/painter.go @@ -942,7 +942,7 @@ func (painter *painter) applyScroll(event platform.ScrollEvent) bool { if painter.onScroll != nil { response = painter.onScroll(gfx.ScrollEvent{ Phase: event.Phase, Modifiers: gfx.Modifiers(event.Modifiers), X: event.X, Y: event.Y, - DeltaX: event.DeltaX, DeltaY: event.DeltaY, Viewport: painter.size, Target: target, Precise: event.Precise, + DeltaX: event.DeltaX, DeltaY: event.DeltaY, Pages: event.Pages, Viewport: painter.size, Target: target, Precise: event.Precise, }) } focusChanged := painter.applyEventResult(response) diff --git a/base/list.go b/base/list.go index 10cff5e65..6c40cde31 100644 --- a/base/list.go +++ b/base/list.go @@ -1255,7 +1255,9 @@ func (p *Page) ListKey(event gfx.KeyEvent) (gfx.EventResult, bool) { func (p *Page) ListWheelX(event gfx.ScrollEvent) (moved, only bool) { dx, only := event.DeltaX, event.DeltaY == 0 if dx == 0 && event.Modifiers&gfx.ModifierShift != 0 { - dx, only = event.DeltaY, true + // The vertical wheel turned sideways: its page is sideways too. + event.DeltaX, event.DeltaY = event.DeltaY, 0 + dx, only = event.DeltaX, true } if dx == 0 { return false, false @@ -1264,7 +1266,7 @@ func (p *Page) ListWheelX(event gfx.ScrollEvent) (moved, only bool) { if f := p.View.Frame; f != nil { panel = f.wheelPanel(event.X, event.Y) } - dx = wheelStep(dx, event.Precise) // a notch moves at least a line, as down the list + step := wheelStep(dx, event.Precise) // a notch moves at least a line, as down the list for _, s := range p.listStates { in := &s.list if s.RowWidth <= 0 || in.f == nil || !in.f.ContainsPoint(int(in.area), event.X, event.Y) || !in.f.within(in.area, panel) { @@ -1274,6 +1276,11 @@ func (p *Page) ListWheelX(event gfx.ScrollEvent) (moved, only bool) { if room <= 0 { continue } + // A screen per notch is a screen of this list's width. + dx := step + if event.Pages != 0 { + dx = event.StepXIn(1, in.View.Width) + } before := s.ScrollX() in.scrollX = min(max(before+dx, 0), room) return in.scrollX != before, only diff --git a/base/menu_state.go b/base/menu_state.go index f0453e254..12c15c419 100644 --- a/base/menu_state.go +++ b/base/menu_state.go @@ -85,6 +85,9 @@ func (scroll *MenuScroll) Max() float32 { return scroll.MaxValue } // A notch of a wheel (a gesture that is not Precise) moves at least 24 pixels. func (scroll *MenuScroll) Wheel(event gfx.ScrollEvent) bool { step := event.DeltaY + if event.Pages != 0 { + step = event.StepYIn(1, scroll.View) + } if !event.Precise { if step > 0 && step < 24 { step = 24 diff --git a/base/scroll.go b/base/scroll.go index ffe72e475..a164d3a7d 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -210,6 +210,14 @@ func (s *ScrollState) canScroll(dx, dy float32) bool { // wheelSteps is how far a scroll event moves the area, right and down. A Sideways area // takes the wheel with Shift held, and no horizontal delta, as a horizontal wheel. func (s *ScrollState) wheelSteps(event gfx.ScrollEvent) (dx, dy float32) { + if event.Pages != 0 { + // The system asks for whole screens: the area moves one of its own, not + // one of the window's, which the event's delta is measured in. + if s.sideways && event.DeltaX == 0 && event.Modifiers&gfx.ModifierShift != 0 { + return event.StepYIn(1, s.ViewportWidth), 0 + } + return event.StepXIn(1, s.ViewportWidth), event.StepYIn(1, s.Viewport) + } dx, dy = event.DeltaX, event.DeltaY if s.sideways && dx == 0 && event.Modifiers&gfx.ModifierShift != 0 { dx, dy = dy, 0 diff --git a/base/scroll_test.go b/base/scroll_test.go index 945fbff5d..f183d14a6 100644 --- a/base/scroll_test.go +++ b/base/scroll_test.go @@ -362,3 +362,26 @@ func TestScrollStateFollowingAndPrepend(t *testing.T) { t.Fatal("ScrollToEnd did not reattach the follow") } } + +func TestAWheelPageMovesTheAreasOwnPage(t *testing.T) { + var view View + logPage(&view, false, 20) // 600 of rows in a 100-tall area + state := view.ScrollState(listID) + window := gfx.Size{Width: 800, Height: 1000} + // The system asks for a screen per notch: the event's delta is a screen of + // the window, and the area moves a screen of its own instead. + if result := state.Wheel(gfx.ScrollEvent{DeltaY: 1000, Pages: 1, Viewport: window}); !result.Handled { + t.Fatal("a page notch was not handled") + } + if state.Offset != 100 { + t.Fatalf("one page notch moved the area to %v, want its own page 100, not the window's", state.Offset) + } + state.Wheel(gfx.ScrollEvent{DeltaY: 1000, Pages: 1, Viewport: window}) + if state.Offset != 200 { + t.Fatalf("the second page notch left the area at %v, want 200", state.Offset) + } + state.Wheel(gfx.ScrollEvent{DeltaY: -1000, Pages: -1, Viewport: window}) + if state.Offset != 100 { + t.Fatalf("a page notch up left the area at %v, want 100", state.Offset) + } +} diff --git a/base/select.go b/base/select.go index 3ca6873ab..ca9f743fb 100644 --- a/base/select.go +++ b/base/select.go @@ -103,7 +103,7 @@ func (s *SelectState) Wheel(event gfx.ScrollEvent) gfx.EventResult { return gfx.EventResult{} } last := len(s.labels) - s.Visible - step := event.DeltaY / selectItem + step := event.StepYIn(selectItem, float32(s.Visible)*selectItem) / selectItem if !event.Precise { switch { case event.DeltaY > 0: diff --git a/base/textarea.go b/base/textarea.go index 2aa8bfaab..b8d02edde 100644 --- a/base/textarea.go +++ b/base/textarea.go @@ -307,6 +307,9 @@ func (layout *TextareaLayout) Wheel(event gfx.ScrollEvent) bool { return false } dy := event.DeltaY + if event.Pages != 0 { + dy = event.StepYIn(1, content.Height) + } if !event.Precise && dy > 0 && dy < 24 { dy = 24 } else if !event.Precise && dy < 0 && dy > -24 { diff --git a/components/code_diff.go b/components/code_diff.go index e1934a12b..512ccffc9 100644 --- a/components/code_diff.go +++ b/components/code_diff.go @@ -866,12 +866,16 @@ func (diff *CodeDiff) linesForValue(value string) ([]string, []int) { // Scroll applies a wheel or touchpad scroll to both panes. Horizontal deltas use // horizontal movement; Shift turns vertical delta into horizontal movement. func (diff *CodeDiff) Scroll(event gfx.ScrollEvent) gfx.EventResult { - diff.scrollX += event.DeltaX + dy := event.DeltaY + if event.Pages != 0 { + dy = event.StepYIn(1, float32(diff.visibleRows)*diff.rowHeight) + } + dx := event.DeltaX if event.Modifiers&gfx.ModifierShift != 0 { - diff.scrollX += event.DeltaY - } else { - diff.scrollY += event.DeltaY + dx, dy = dx+dy, 0 // Shift turns the vertical travel sideways } + diff.scrollX += dx + diff.scrollY += dy diff.clampScroll() return gfx.EventResult{Handled: true, Repaint: true} } diff --git a/components/code_editor_layout.go b/components/code_editor_layout.go index ea9a9696c..15a10ce61 100644 --- a/components/code_editor_layout.go +++ b/components/code_editor_layout.go @@ -705,7 +705,7 @@ func (editor *CodeEditor) Scroll(event gfx.ScrollEvent) gfx.EventResult { if !editor.painted { return gfx.EventResult{} } - dx, dy := event.StepX(editor.cellWidth), event.StepY(editor.lineHeight) + dx, dy := event.StepXIn(editor.cellWidth, editor.content.Width), event.StepYIn(editor.lineHeight, editor.content.Height) if event.Modifiers&gfx.ModifierShift != 0 && dx == 0 { dx, dy = dy, 0 } diff --git a/gfx/input.go b/gfx/input.go index 558e0a813..4bdc1eeed 100644 --- a/gfx/input.go +++ b/gfx/input.go @@ -252,9 +252,16 @@ type ScrollEvent struct { Y float32 DeltaX float32 DeltaY float32 - Viewport Size - Target ID - Precise bool + // Pages is how many screens the gesture is when the system's wheel setting + // asks for whole screens per notch, zero otherwise, and in the same + // direction as the delta of its axis. DeltaX and DeltaY are that many + // screens of the window, which is right only for what the window scrolls: + // a scroll region moves Pages of its own page instead, as StepYIn and + // StepXIn give it. + Pages float32 + Viewport Size + Target ID + Precise bool } // ScrollPhase is what a scroll event comes from. A wheel or a touchpad is the zero value @@ -281,15 +288,57 @@ const ( // which the pixel scale turns into a distance far below one row, so without the // floor several notches would pass before anything moves. A precise delta is // the distance the finger moved and is returned as it is. +// +// It is the whole window's step. A scroll region smaller than the window takes +// StepYIn instead, so a page notch is one of its pages and not one of the +// window's. func (e ScrollEvent) StepY(unit float32) float32 { return wheelStep(e.DeltaY, unit, e.Precise) } +// StepYIn is StepY for content of unit-sized rows inside a scroll region whose +// visible height is viewport. When the system asks for whole screens, the notch +// moves as many of the region's pages as Pages says, rounded down to whole rows, +// rather than the window-sized distance DeltaY carries; that is one screen of +// the region, which is a screen of the rows a user sees in it. +func (e ScrollEvent) StepYIn(unit, viewport float32) float32 { + if e.Pages == 0 || unit <= 0 || e.DeltaY == 0 { + return e.StepY(unit) + } + return pageStep(e.DeltaY, e.Pages, unit, viewport) +} + // StepX is StepY for DeltaX. func (e ScrollEvent) StepX(unit float32) float32 { return wheelStep(e.DeltaX, unit, e.Precise) } +// StepXIn is StepX for a sideways region whose visible width is viewport, as +// StepYIn is for a tall one. +func (e ScrollEvent) StepXIn(unit, viewport float32) float32 { + if e.Pages == 0 || unit <= 0 || e.DeltaX == 0 { + return e.StepX(unit) + } + return pageStep(e.DeltaX, e.Pages, unit, viewport) +} + +// pageStep is how far pages of a region of viewport units-by-unit move it in the +// direction of delta. +func pageStep(delta, pages, unit, viewport float32) float32 { + if pages < 0 { + pages = -pages + } + units := float32(int(pages * viewport / unit)) + if units < 1 { + units = 1 + } + step := units * unit + if delta < 0 { + return -step + } + return step +} + func wheelStep(delta, unit float32, precise bool) float32 { switch { case precise || delta == 0 || unit <= 0: diff --git a/gfx/scroll_test.go b/gfx/scroll_test.go index 7308be5e9..cd05518fb 100644 --- a/gfx/scroll_test.go +++ b/gfx/scroll_test.go @@ -23,3 +23,36 @@ func TestScrollStepRaisesClassicWheelToOneUnit(t *testing.T) { t.Errorf("StepX = %v, want -8", got) } } + +func TestPageStepMovesOnePageOfTheRegion(t *testing.T) { + // A page notch reports the window as pixels and the region's own page is + // what moves: whole rows that fit in the region, not the window's. + cases := []struct { + name string + event ScrollEvent + unit float32 + view float32 + want float32 + }{ + {"a page down in a short list", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 300, 300}, + {"a page up in a short list", ScrollEvent{DeltaY: -900, Pages: -1}, 30, 300, -300}, + {"rows that do not fit whole are left out", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 305, 300}, + {"two pages", ScrollEvent{DeltaY: 1800, Pages: 2}, 24, 200, 384}, + {"half a page of a trackpad setting", ScrollEvent{DeltaY: 450, Pages: 0.5}, 24, 200, 96}, + {"a region shorter than one row still moves a row", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 10, 30}, + {"a line notch is not a page", ScrollEvent{DeltaY: 48}, 30, 300, 48}, + {"a zero viewport keeps a row", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 0, 30}, + } + for _, c := range cases { + if got := c.event.StepYIn(c.unit, c.view); got != c.want { + t.Errorf("%s: StepYIn(%v, %v) = %v, want %v", c.name, c.unit, c.view, got, c.want) + } + } + if got := (ScrollEvent{DeltaX: 900, Pages: 1}).StepXIn(10, 50); got != 50 { + t.Errorf("StepXIn = %v, want 50", got) + } + // A page setting does not turn a horizontal delta into a vertical page. + if got := (ScrollEvent{DeltaY: 900, Pages: 1}).StepXIn(10, 50); got != 0 { + t.Errorf("StepXIn on a vertical page = %v, want 0", got) + } +} diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 6004a6987..bc6541ad4 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -746,7 +746,12 @@ type ScrollEvent struct { Y float32 DeltaX float32 DeltaY float32 - Precise bool + // Pages is how many screens the gesture is, when the user's wheel setting + // is whole screens per notch; zero otherwise. DeltaX and DeltaY carry the + // same distance against the window, which is the page only for the window's + // own scrolling: a scroll region moves Pages of its own page instead. + Pages float32 + Precise bool } // ScrollHandler applies one scroll gesture and returns an optional repaint. diff --git a/internal/platform/windows/wheel_windows.go b/internal/platform/windows/wheel_windows.go index c84a720f6..148b61dc3 100644 --- a/internal/platform/windows/wheel_windows.go +++ b/internal/platform/windows/wheel_windows.go @@ -43,7 +43,8 @@ func (state *windowState) wheelEvent(horizontal bool, first, second uintptr) pla if horizontal { units, extent = state.wheel.chars, state.pageExtent(true) } - pixels, precise := platform.WheelPixels(int(int16(first>>16)), units, extent) + wheelDelta := int16(first >> 16) + pixels, precise := platform.WheelPixels(int(wheelDelta), units, extent) event := platform.ScrollEvent{ Modifiers: modifiers(), X: float32(position.X) / state.scale, Y: float32(position.Y) / state.scale, Precise: precise, @@ -53,6 +54,16 @@ func (state *windowState) wheelEvent(horizontal bool, first, second uintptr) pla } else { event.DeltaY = -pixels } + if units == platform.WheelPageScroll { + // The system asks for whole screens, and extent is only the window's: the + // region the pointer is over moves Pages of its own page. A notch away + // from the user is up, as a negative DeltaY. + pages := float32(wheelDelta) / platform.WheelNotch + if !horizontal { + pages = -pages + } + event.Pages = pages + } return event } diff --git a/internal/reloadwire/codec.go b/internal/reloadwire/codec.go index cc6dc4bb8..4a206244a 100644 --- a/internal/reloadwire/codec.go +++ b/internal/reloadwire/codec.go @@ -403,6 +403,7 @@ func encodeScrollEvent(value gfx.ScrollEvent) []byte { result.f32(value.Y) result.f32(value.DeltaX) result.f32(value.DeltaY) + result.f32(value.Pages) result.f32(value.Viewport.Width) result.f32(value.Viewport.Height) result.id(value.Target) @@ -414,7 +415,7 @@ func decodeScrollEvent(data []byte) (gfx.ScrollEvent, error) { value := decoder{data: data} result := gfx.ScrollEvent{ Modifiers: gfx.Modifiers(value.u8()), X: value.f32(), Y: value.f32(), - DeltaX: value.f32(), DeltaY: value.f32(), Viewport: gfx.Size{Width: value.f32(), Height: value.f32()}, Target: value.id(), Precise: value.bool(), + DeltaX: value.f32(), DeltaY: value.f32(), Pages: value.f32(), Viewport: gfx.Size{Width: value.f32(), Height: value.f32()}, Target: value.id(), Precise: value.bool(), } if err := value.finish(); err != nil { return gfx.ScrollEvent{}, err diff --git a/ui/editabletabs/editabletabs.go b/ui/editabletabs/editabletabs.go index c30d4f002..10e9c4a67 100644 --- a/ui/editabletabs/editabletabs.go +++ b/ui/editabletabs/editabletabs.go @@ -200,6 +200,12 @@ func (t *EditableTabs) scroll(event gfx.ScrollEvent) gfx.EventResult { if math.Abs(float64(event.DeltaY)) > math.Abs(float64(event.DeltaX)) { delta = event.DeltaY } + if event.Pages != 0 { + delta = event.StepXIn(1, t.width) + if math.Abs(float64(event.DeltaY)) > math.Abs(float64(event.DeltaX)) { + delta = event.StepYIn(1, t.width) + } + } if delta == 0 { return gfx.EventResult{} } diff --git a/ui/timepicker/timepicker.go b/ui/timepicker/timepicker.go index ceb02264e..ea1862d1c 100644 --- a/ui/timepicker/timepicker.go +++ b/ui/timepicker/timepicker.go @@ -237,7 +237,11 @@ func (t *TimePicker) scroll(event gfx.ScrollEvent) gfx.EventResult { } rows, _ := t.size(column) limit := max(float32(rows*rowHeight)-visibleRows*rowHeight, 0) - t.offsets[column] = min(max(t.offsets[column]-event.DeltaY, 0), limit) + step := event.DeltaY + if event.Pages != 0 { + step = event.StepYIn(rowHeight, visibleRows*rowHeight) + } + t.offsets[column] = min(max(t.offsets[column]-step, 0), limit) return gfx.EventResult{Handled: true, Repaint: true} } From 4178eeee7cf3799b033e3ad92e0cd7476c10f6e2 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:12:18 +0800 Subject: [PATCH 03/29] fix(cli): regenerate button focus ring recipes --- cmd/viva/templates/button.go.txt | 64 +++++++++++++++++--------- cmd/viva/templates/button_group.go.txt | 11 ++++- 2 files changed, 52 insertions(+), 23 deletions(-) diff --git a/cmd/viva/templates/button.go.txt b/cmd/viva/templates/button.go.txt index 967446a24..828f26b75 100644 --- a/cmd/viva/templates/button.go.txt +++ b/cmd/viva/templates/button.go.txt @@ -377,26 +377,7 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { 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 - } - if look.RingWidth > 0 { - if look.RingOutline { - button.canvas.RoundedOutline(expand(button.bounds, look.RingWidth), look.RingRadius, 2, look.Ring) - } else { - button.canvas.Rounded(expand(button.bounds, look.RingWidth), look.RingRadius, look.Ring) - } - } - style := buttonStyle{ - background: look.Background, foreground: look.Foreground, border: look.Border, - filled: look.Filled, bordered: look.Bordered, underlined: look.Underlined, - } - if style.bordered && style.filled { - paintBordered(button.canvas, button.theme, button.bounds, radius, style.border, style.background) - } else if style.filled { - button.canvas.Rounded(button.bounds, radius, style.background) - } + PaintButtonSurface(button.canvas, button.theme, button.bounds, look) area := button.bounds _, padding, _, _ := button.geometry() if !iconOnly && padding > 0 { @@ -415,8 +396,8 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { } hint := PaintButtonContent(button.canvas, area, ButtonContent{ Label: label, Icon: button.icon, IconTransform: button.iconTransform, - FontSize: fontSize, Weight: gfx.WeightMedium, Color: style.foreground, - Gap: buttonIconGap, Height: height, IconOnly: iconOnly, Underlined: style.underlined, + FontSize: fontSize, Weight: gfx.WeightMedium, Color: look.Foreground, + Gap: buttonIconGap, Height: height, IconOnly: iconOnly, Underlined: look.Underlined, }) if !button.id.IsZero() { button.canvas.HitWithOptions(button.id, button.bounds, label, gfx.HitOptions{ @@ -646,6 +627,45 @@ type ButtonContent struct { // function, not a closure made in each paint, which would allocate. type ButtonLoadingPainter func(canvas *gfx.Canvas, theme *gfx.Theme, bounds gfx.Rect, color gfx.Color, phase uint8) +// PaintButtonSurface paints a button's surface in bounds: its shadow, its focus +// ring, its fill and its border, for a look the caller resolved itself with +// ButtonRecipe or with a recipe of its own. It is the surface half of the paint +// BeginButton does, so a control that draws content of its own on a button's +// surface paints the same surface as a declared button; PaintButtonContent is +// the content half. +// +// The focus ring is a halo that reaches RingWidth beyond bounds. Under an opaque +// fill only the part outside the bounds can be seen, so the whole halo is painted +// with the fill over it; a button that paints no opaque fill (ghost or link, or +// one that is disabled) gets the halo as a line, since nothing would cover the +// middle of the disc. +func PaintButtonSurface(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, look ButtonLook) { + if canvas == nil || bounds.Width <= 0 || bounds.Height <= 0 { + return + } + radius := look.Radius + if look.Shadow != gfx.ShadowNone { + canvas.Elevate(bounds, radius, look.Shadow) // shadow-xs + } + if look.RingWidth > 0 { + halo := expand(bounds, look.RingWidth) + switch { + case look.RingOutline: + canvas.RoundedOutline(halo, look.RingRadius, 2, look.Ring) + case look.Filled && look.Background.Alpha >= 1: + canvas.Rounded(halo, look.RingRadius, look.Ring) + default: + canvas.RoundedOutline(halo, look.RingRadius, look.RingWidth, look.Ring) + } + } + switch { + case look.Bordered && look.Filled: + paintBordered(canvas, theme, bounds, radius, look.Border, look.Background) + case look.Filled: + canvas.Rounded(bounds, radius, look.Background) + } +} + // PaintButtonContent paints a button's icon and label centered in area and returns the // hint an icon-only button gives assistive technology, which is its label. It is the // content half of the paint the Button does: the same placement, the same shrinking of diff --git a/cmd/viva/templates/button_group.go.txt b/cmd/viva/templates/button_group.go.txt index d71bbdb5c..f948a11a4 100644 --- a/cmd/viva/templates/button_group.go.txt +++ b/cmd/viva/templates/button_group.go.txt @@ -95,7 +95,16 @@ func (group ButtonGroup) Paint() ButtonGroupResult { framed = framed || option.Variant == ButtonOutline || option.Variant == ButtonDestructiveOutline if !group.disabled && !option.Disabled && !option.ID.IsZero() && group.canvas.FocusVisible() == option.ID { ring, _ := buttonRing(&group.theme, option.Variant, false) - group.canvas.Rounded(expand(group.optionBounds(index, float32(count)), 3), radius+3, ring) + halo := expand(group.optionBounds(index, float32(count)), 3) + // The halo is a disc under an action that paints an opaque fill; an action + // with no fill of its own gets it as a line, or the disc would fill the + // action's whole surface. + style := buttonStyleFor(&group.theme, option.Variant, group.canvas.Hovered() == option.ID, group.canvas.Pressed() == option.ID) + if style.filled && style.background.Alpha >= 1 { + group.canvas.Rounded(halo, radius+3, ring) + } else { + group.canvas.RoundedOutline(halo, radius+3, 3, ring) + } } } // The outline goes down first and the actions are painted inside it. From c1785affed12382941b5845602a5c2303b317d2d Mon Sep 17 00:00:00 2001 From: mirakyux <45783208+mirakyux@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:12:27 +0800 Subject: [PATCH 04/29] fix(render): keep thin stroke coverage uniform across clips --- app/driver.go | 9 ++ gfx/canvas.go | 14 +++ gfx/embed.go | 5 + gfx/icon_cache.go | 7 ++ gfx/icon_clip.go | 14 ++- gfx/icon_clip_raster_test.go | 59 +++++++++ gfx/path.go | 11 +- gfx/path_test.go | 4 +- gfx/presence.go | 7 ++ gfx/replay.go | 15 ++- headless/convert.go | 7 ++ headless/vector_aa_test.go | 113 ++++++++++++++++++ internal/framebuild/framebuild.go | 44 ++++++- internal/platform/darwin/callback.go | 12 +- internal/platform/darwin/shaders/scene.metal | 73 ++++++++--- .../platform/darwin/shaders/scene.metallib | Bin 23190 -> 24006 bytes internal/platform/triangle.go | 20 ++++ internal/platform/vulkan/shaders/scene.frag | 54 +++++++-- .../platform/vulkan/shaders/scene.frag.spv | Bin 10240 -> 12164 bytes internal/platform/vulkan/shaders/scene.vert | 24 ++-- .../platform/vulkan/shaders/scene.vert.spv | Bin 9120 -> 9816 bytes .../platform/vulkan/vulkan_scene_linux.go | 8 +- internal/platform/web/glpack.go | 11 +- internal/platform/web/shaders/scene.frag.glsl | 54 +++++++-- internal/platform/web/shaders/scene.vert.glsl | 24 ++-- internal/platform/windows/renderer_windows.go | 7 +- .../platform/windows/shaders/manifest.json | 16 +-- .../windows/shaders/rectangleFragment.dxbc | Bin 9660 -> 11308 bytes .../windows/shaders/rectangleVertex.dxbc | Bin 6612 -> 6808 bytes internal/platform/windows/shaders/scene.hlsl | 76 +++++++++--- .../windows/shaders/textFragment.dxbc | Bin 2576 -> 2576 bytes .../platform/windows/shaders/textVertex.dxbc | Bin 2152 -> 2164 bytes internal/raster/raster_test.go | 31 +++++ internal/raster/shapes.go | 63 ++++++++-- internal/reloadwire/codec.go | 18 ++- internal/reloadwire/reloadwire_test.go | 6 + internal/render/store.go | 39 +++++- internal/render/store_test.go | 30 ++++- internal/render/validate.go | 28 ++++- internal/scene/scene.go | 54 ++++++--- internal/scene/scene_test.go | 16 +-- 41 files changed, 809 insertions(+), 164 deletions(-) create mode 100644 gfx/icon_clip_raster_test.go create mode 100644 internal/platform/triangle.go diff --git a/app/driver.go b/app/driver.go index 37551cc59..db7e68d46 100644 --- a/app/driver.go +++ b/app/driver.go @@ -1123,6 +1123,8 @@ type Primitive struct { Layer uint16 // EdgeMask selects the boundary edges feathered for TrianglePrimitive. EdgeMask uint8 + // Coverage carries the original silhouette for a clipped stroke quad. + Coverage *gfx.StrokeCoverage // Shaded gives a TrianglePrimitive the colors Shade[0] and Shade[1] at // Points[1] and Points[2], Color being that of Points[0]; the color varies // linearly between them. @@ -1318,6 +1320,13 @@ func (driver *Driver) Snapshot() Snapshot { if rectangle.Kind == scene.KindTriangle { primitive.Kind = TrianglePrimitive primitive.EdgeMask = rectangle.EdgeMask + if source, ok := rectangle.StrokeCoverage(); ok { + coverage := &gfx.StrokeCoverage{EdgeMask: source.EdgeMask} + for index, point := range source.Points { + coverage.Points[index] = gfx.Point(point) + } + primitive.Coverage = coverage + } if rectangle.Shade.On { primitive.Shaded = true for index, color := range rectangle.Shade.Colors { diff --git a/gfx/canvas.go b/gfx/canvas.go index 8bfd38730..2e9bf0f16 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -124,6 +124,13 @@ var shadowLayers = [...][2]struct { ShadowLG: {{ShadowStyle{OffsetY: 10, Blur: 15, Spread: -3}, 0.10}, {ShadowStyle{OffsetY: 4, Blur: 6, Spread: -4}, 0.10}}, } +// StrokeCoverage describes the uncut triangle of a stroke quad. All pieces +// cut from the same triangle use these coordinates for edge feathering. +type StrokeCoverage struct { + Points [3]Point + EdgeMask uint8 +} + // Triangle is one solid vector-mesh primitive. Paths are tessellated into // triangles so native backends need no SVG parser or general geometry engine. type Triangle struct { @@ -141,7 +148,14 @@ type Triangle struct { // boundary. Bit 0 is Points[0]→Points[1], bit 1 is Points[1]→Points[2], // and bit 2 is Points[2]→Points[0]. Renderers feather only these edges; // shared tessellation edges stay fully covered. + // Bit 3 marks one half of a stroke quad: the long edge is 0→1 when bit 0 + // is set, otherwise 2→0. Its opposite boundary is parallel through the + // remaining point. Both boundaries constrain coverage, whichever half the + // quad's internal diagonal assigns a pixel to. EdgeMask uint8 + // Coverage, when present, gives a flat clipped stroke its original + // silhouette. Points and EdgeMask still control which pixels it owns. + Coverage *StrokeCoverage ClipOf Rect HasClip bool // Order is where the triangle was painted among every primitive of the diff --git a/gfx/embed.go b/gfx/embed.go index a3483198c..cee227f3e 100644 --- a/gfx/embed.go +++ b/gfx/embed.go @@ -86,6 +86,11 @@ func (canvas *Canvas) Embed(child *Canvas, origin Point, mount Scope) { triangle.Points[index].X += origin.X triangle.Points[index].Y += origin.Y } + if triangle.Coverage != nil { + coverage := *triangle.Coverage + coverage.Points = translatePoints(coverage.Points, origin) + triangle.Coverage = &coverage + } triangle.Layer += layer triangle.Order += orderBase triangle.ClipOf, triangle.HasClip = embedClip(triangle.ClipOf, triangle.HasClip, origin, outer, hasOuter) diff --git a/gfx/icon_cache.go b/gfx/icon_cache.go index 92bf58aa6..ada4f42ad 100644 --- a/gfx/icon_cache.go +++ b/gfx/icon_cache.go @@ -251,6 +251,7 @@ func (canvas *Canvas) drawIconTrianglesPlaced(triangles []iconTriangle, icon Ico place.apply(cached.points[1]), place.apply(cached.points[2]), } + var coverage *StrokeCoverage emit := func(points [3]Point, edges uint8, weights [3][3]float32) { triangle := Triangle{ Points: points, Color: tint, Layer: state.layer, EdgeMask: edges, @@ -259,6 +260,12 @@ func (canvas *Canvas) drawIconTrianglesPlaced(triangles []iconTriangle, icon Ico if cached.layer >= 0 && !shadeIconTriangleAt(icon, tint, cached, weights, &triangle) { return } + if cached.edges&triangleStrokeQuad != 0 && edges&triangleStrokeQuad == 0 { + if coverage == nil { + coverage = &StrokeCoverage{Points: source, EdgeMask: cached.edges} + } + triangle.Coverage = coverage + } triangle.Order = canvas.nextOrder() canvas.triangles = append(canvas.triangles, triangle) } diff --git a/gfx/icon_clip.go b/gfx/icon_clip.go index eb3d43e8a..34ced99fa 100644 --- a/gfx/icon_clip.go +++ b/gfx/icon_clip.go @@ -123,6 +123,7 @@ func (shape iconClipShape) eachTriangle( // fixed vertex array, once per edge and per triangle. var polygons [2]iconClipPolygon current := 0 + unchanged := true for index := range points { var weights [3]float32 weights[index] = 1 @@ -139,6 +140,7 @@ func (shape iconClipShape) eachTriangle( to := cur.vertices[(vertex+1)%cur.count] fromInside := insideIconClip(a, b, from.point, sign) toInside := insideIconClip(a, b, to.point, sign) + unchanged = unchanged && fromInside if fromInside { next.add(from.point, from.boundary, from.weights) if !toInside { @@ -152,7 +154,13 @@ func (shape iconClipShape) eachTriangle( } current = 1 - current } - emitIconClipTriangles(&polygons[current], emit) + var sourceFlags uint8 + if unchanged { + // The stroke quad flag describes the original corners. A cut cannot + // reconstruct the opposite edge from its new corners. + sourceFlags = edges &^ triangleAllEdges + } + emitIconClipTriangles(&polygons[current], sourceFlags, emit) } // iconClipWeights interpolates barycentric weights along from→to. @@ -192,7 +200,7 @@ func iconClipIntersection(a, b Point, from, to iconClipVertex) (Point, float64) // pointer because the fan compacts the shared corner list in place, and a copy // of the fixed vertex array per clipped triangle is the cost that made a rounded // clip an order of magnitude slower than the other transforms. -func emitIconClipTriangles(polygon *iconClipPolygon, emit func([3]Point, uint8, [3][3]float32)) { +func emitIconClipTriangles(polygon *iconClipPolygon, sourceFlags uint8, emit func([3]Point, uint8, [3][3]float32)) { count := 0 for index := 0; index < polygon.count; index++ { next := polygon.vertices[(index+1)%polygon.count] @@ -211,7 +219,7 @@ func emitIconClipTriangles(polygon *iconClipPolygon, emit func([3]Point, uint8, if !clipFiniteArea(a.point, b.point, c.point) || cross > -1e-5 && cross < 1e-5 { continue } - var edges uint8 + edges := sourceFlags if index == 1 && a.boundary { edges |= 1 } diff --git a/gfx/icon_clip_raster_test.go b/gfx/icon_clip_raster_test.go new file mode 100644 index 000000000..c693c62f8 --- /dev/null +++ b/gfx/icon_clip_raster_test.go @@ -0,0 +1,59 @@ +package gfx_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" + "github.com/vivaui/viva/internal/raster" + "github.com/vivaui/viva/internal/render" +) + +func TestIconClipPreservesThinStrokeCoverage(t *testing.T) { + icon := gfx.Icon{ + ViewBox: 32, Stroke: 1, Cap: gfx.CapButt, + Commands: []gfx.PathCommand{gfx.MoveTo(12.25, 4), gfx.LineTo(12.25, 28)}, + } + bounds := gfx.Rect{Width: 32, Height: 32} + for _, test := range []struct { + name string + clip *gfx.IconClip + from int + to int + }{ + {name: "unclipped", from: 5, to: 27}, + {name: "contained", clip: &gfx.IconClip{Bounds: bounds}, from: 5, to: 27}, + {name: "cut", clip: &gfx.IconClip{Bounds: gfx.Rect{Y: 6, Width: 32, Height: 20}}, from: 6, to: 26}, + {name: "cut-rounded", clip: &gfx.IconClip{Bounds: gfx.Rect{Y: 6, Width: 24, Height: 20}, Radius: 10}, from: 6, to: 26}, + {name: "cut-across-width", clip: &gfx.IconClip{Bounds: gfx.Rect{X: 12, Y: 6, Width: 2, Height: 20}}, from: 6, to: 26}, + {name: "cut-away-both-edges", clip: &gfx.IconClip{Bounds: gfx.Rect{X: 12.375, Y: 6, Width: 0.25, Height: 20}}, from: 6, to: 26}, + } { + t.Run(test.name, func(t *testing.T) { + var canvas gfx.Canvas + canvas.DrawIconTransformed(icon, bounds, gfx.Color{Red: 1, Alpha: 1}, gfx.IconTransform{Clip: test.clip}) + instances := make([]render.Rectangle, 0, len(canvas.Triangles())) + for _, triangle := range canvas.Triangles() { + instances = append(instances, framebuild.SceneTriangle(triangle)) + } + pixels := raster.NewCanvas(32, 32) + var renderer raster.Rasterizer + renderer.Draw(pixels, raster.Params{Scale: 1}, instances, nil) + for y := test.from; y < test.to; y++ { + // The center at x=12.5 is a quarter pixel from the right + // stroke edge, giving 75% coverage regardless of the cut. + if got := pixels.Pix[y*pixels.Stride+12*4+3]; got < 190 || got > 192 { + t.Fatalf("alpha at (12, %d) = %d, want 191", y, got) + } + } + if test.from == 6 { + for _, y := range []int{5, 26} { + for x := 11; x <= 12; x++ { + if got := pixels.Pix[y*pixels.Stride+x*4+3]; got != 0 { + t.Fatalf("alpha outside clip at (%d, %d) = %d, want 0", x, y, got) + } + } + } + } + }) + } +} diff --git a/gfx/path.go b/gfx/path.go index 655d56728..e138999e6 100644 --- a/gfx/path.go +++ b/gfx/path.go @@ -366,7 +366,10 @@ func (canvas *Canvas) dashStrokeContours(opaque bool, half float32, cap StrokeCa } } -const triangleAllEdges = uint8(1<<3 - 1) +const ( + triangleAllEdges = uint8(1<<3 - 1) + triangleStrokeQuad = uint8(1 << 3) +) func canonicalEdge(a, b Point) [4]uint32 { ax, ay := pointBits(a) @@ -529,6 +532,8 @@ func mergeCollinear(destination []Point, points []Point, closed bool, epsilon fl // appendStrokeQuad adds one offset rectangle for the segment from→to. The long // sides are always visible union boundaries. A cross edge is a boundary only // at an open butt cap; joins and explicit cap geometry cover every other one. +// Both triangles retain the stroke-quad flag so each fragment can account for +// the opposite long edge, including where the internal diagonal owns its fringe. func (canvas *Canvas) appendStrokeQuad(from, to Point, half float32, color Color, startCap, endCap bool) { dir := direction(from, to) normal := Point{X: -dir.Y * half, Y: dir.X * half} @@ -536,8 +541,8 @@ func (canvas *Canvas) appendStrokeQuad(from, to Point, half float32, color Color b := Point{X: to.X + normal.X, Y: to.Y + normal.Y} c := Point{X: to.X - normal.X, Y: to.Y - normal.Y} d := Point{X: from.X - normal.X, Y: from.Y - normal.Y} - firstMask := uint8(1 << 0) - secondMask := uint8(1 << 2) + firstMask := triangleStrokeQuad | 1<<0 + secondMask := triangleStrokeQuad | 1<<2 if startCap { firstMask |= 1 << 2 } diff --git a/gfx/path_test.go b/gfx/path_test.go index 9a50138a0..3526d4ea3 100644 --- a/gfx/path_test.go +++ b/gfx/path_test.go @@ -166,8 +166,8 @@ func TestDrawPathOpaqueStrokeDoesNotFeatherItsTriangleDiagonal(t *testing.T) { if len(triangles) != 2 { t.Fatalf("stroke triangles = %d, want 2", len(triangles)) } - if triangles[0].EdgeMask != 1<<0|1<<2 || triangles[1].EdgeMask != 1<<1|1<<2 { - t.Fatalf("stroke edge masks = %03b, %03b; shared diagonal must stay opaque", triangles[0].EdgeMask, triangles[1].EdgeMask) + if triangles[0].EdgeMask != triangleStrokeQuad|1<<0|1<<2 || triangles[1].EdgeMask != triangleStrokeQuad|1<<1|1<<2 { + t.Fatalf("stroke edge masks = %04b, %04b; both halves must retain the quad while the shared diagonal stays opaque", triangles[0].EdgeMask, triangles[1].EdgeMask) } } diff --git a/gfx/presence.go b/gfx/presence.go index 47114972e..50d0f0ead 100644 --- a/gfx/presence.go +++ b/gfx/presence.go @@ -648,6 +648,13 @@ func (transform presenceTransform) apply(canvas *Canvas, open presenceOpen, fade for corner := range triangle.Points { triangle.Points[corner] = transform.point(triangle.Points[corner]) } + if triangle.Coverage != nil { + coverage := *triangle.Coverage + for corner := range coverage.Points { + coverage.Points[corner] = transform.point(coverage.Points[corner]) + } + triangle.Coverage = &coverage + } if fade { triangle.Color = transform.color(triangle.Color) triangle.Shade[0] = transform.color(triangle.Shade[0]) diff --git a/gfx/replay.go b/gfx/replay.go index a17c7a677..12e741aff 100644 --- a/gfx/replay.go +++ b/gfx/replay.go @@ -374,9 +374,18 @@ func (canvas *Canvas) SameAsPrevious(span, prev Span, dx, dy float32) bool { // part painted ignores it: the copy's place among the other primitives is // checked by the span it lands in, not by the numbers. func sameRectangle(a, b Rectangle) bool { a.Order, b.Order = 0, 0; return a == b } -func sameTriangle(a, b Triangle) bool { a.Order, b.Order = 0, 0; return a == b } -func sameShadow(a, b Shadow) bool { a.Order, b.Order = 0, 0; return a == b } -func sameText(a, b Text) bool { a.Order, b.Order = 0, 0; return a == b } +func sameTriangle(a, b Triangle) bool { + if a.Coverage != b.Coverage { + if a.Coverage == nil || b.Coverage == nil || *a.Coverage != *b.Coverage { + return false + } + a.Coverage = b.Coverage + } + a.Order, b.Order = 0, 0 + return a == b +} +func sameShadow(a, b Shadow) bool { a.Order, b.Order = 0, 0; return a == b } +func sameText(a, b Text) bool { a.Order, b.Order = 0, 0; return a == b } func sameImage(a, b Image) bool { return a.Source == b.Source && a.Bounds == b.Bounds && a.Layer == b.Layer && a.ClipOf == b.ClipOf && a.HasClip == b.HasClip && diff --git a/headless/convert.go b/headless/convert.go index e2ff33f48..8bfb2fb2c 100644 --- a/headless/convert.go +++ b/headless/convert.go @@ -34,6 +34,13 @@ func scenery(snapshot app.Snapshot) ([]render.Rectangle, []platform.TextLabel, * if primitive.Shaded { rectangle.Shade = scene.Shade{On: true, Colors: [2]scene.Color{scene.Color(primitive.Shade[0]), scene.Color(primitive.Shade[1])}} } + if source := primitive.Coverage; source != nil { + coverage := scene.StrokeCoverage{EdgeMask: source.EdgeMask} + for point, position := range source.Points { + coverage.Points[point] = scene.Point(position) + } + rectangle.SetStrokeCoverage(coverage) + } for point := range rectangle.Points { rectangle.Points[point] = scene.Point{X: primitive.Points[point].X, Y: primitive.Points[point].Y} } diff --git a/headless/vector_aa_test.go b/headless/vector_aa_test.go index 8819b6fa5..02616b5dd 100644 --- a/headless/vector_aa_test.go +++ b/headless/vector_aa_test.go @@ -104,3 +104,116 @@ func TestVectorCoverageAtDeviceScales(t *testing.T) { }) } } + +// A stroke's internal diagonal must not change the coverage of either long edge, +// even near the ends where the triangle owning a pixel carries the opposite edge. +func TestVectorStrokeQuadCoverageIsUniform(t *testing.T) { + if !rendererAvailable { + t.Skip("native screenshots need the platform headless renderer") + } + r := newRenderer() + defer r.close() + for _, scale := range []float64{1, 1.25, 1.5, 2} { + for _, width := range []float64{1, 1.25, 2, 3} { + for _, reverse := range []bool{false, true} { + for _, cap := range []gfx.StrokeCap{gfx.CapButt, gfx.CapRound} { + t.Run(fmt.Sprintf("%gx/%gpx/reverse=%t/cap=%d", scale, width, reverse, cap), func(t *testing.T) { + const center = 12.25 + from, to := float32(4/scale), float32(28/scale) + if reverse { + from, to = to, from + } + var canvas gfx.Canvas + canvas.SetPixelScale(float32(scale)) + driver, err := app.NewDriver(app.Config{ + Title: "stroke coverage", Width: 32, Height: 32, ClearColor: app.Color{Alpha: 1}, + Paint: func(canvas *gfx.Canvas, size gfx.Size) { + path := canvas.PathBuilder() + path.MoveTo(float32(center/scale), from) + path.LineTo(float32(center/scale), to) + canvas.DrawPath(path.Path(size.Width, size.Height), gfx.Rect{Width: size.Width, Height: size.Height}, gfx.PathStyle{ + Stroke: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, StrokeWidth: float32(width / scale), Cap: cap, + }) + }, + }, &canvas) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + pixels, err := r.render(driver.Snapshot(), scale) + if err != nil { + t.Fatal(err) + } + for x := 9; x <= 15; x++ { + // Coverage is the width of the intersection of this pixel and the stroke. + coverage := min(float64(x+1), center+width/2) - max(float64(x), center-width/2) + want := math.Round(255 * max(0, coverage)) + // Both cap styles end at least two device pixels outside this band. + for y := 6; y < 26; y++ { + if got := pixels.RGBAAt(x, y).R; math.Abs(float64(got)-want) > 2 { + t.Fatalf("stroke coverage at (%d,%d) = %d, want %g", x, y, got, want) + } + } + } + }) + } + } + } + } +} + +func TestVectorClippedStrokeCoverage(t *testing.T) { + if !rendererAvailable { + t.Skip("native screenshots need the platform headless renderer") + } + renderer := newRenderer() + defer renderer.close() + icon := gfx.Icon{ + ViewBox: 32, Stroke: 1, Cap: gfx.CapButt, + Commands: []gfx.PathCommand{gfx.MoveTo(12.25, 4), gfx.LineTo(12.25, 28)}, + } + bounds := gfx.Rect{Width: 32, Height: 32} + for _, tc := range []struct { + name string + clip gfx.IconClip + leftCoverage float64 + }{ + {name: "ends", clip: gfx.IconClip{Bounds: gfx.Rect{Y: 6, Width: 32, Height: 20}}, leftCoverage: 64}, + {name: "ends and side", clip: gfx.IconClip{Bounds: gfx.Rect{X: 12, Y: 6, Width: 2, Height: 20}}}, + {name: "rounded", clip: gfx.IconClip{Bounds: gfx.Rect{Y: 6, Width: 24, Height: 20}, Radius: 10}, leftCoverage: 64}, + } { + t.Run(tc.name, func(t *testing.T) { + driver, err := app.NewDriver(app.Config{ + Title: "clipped stroke coverage", Width: 32, Height: 32, ClearColor: app.Color{Alpha: 1}, + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.DrawIconTransformed(icon, bounds, gfx.Color{Red: 1, Alpha: 1}, gfx.IconTransform{Clip: &tc.clip}) + }, + }, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + pixels, err := renderer.render(driver.Snapshot(), 1) + if err != nil { + t.Fatal(err) + } + near := func(x, y int, want float64) { + t.Helper() + if got := pixels.RGBAAt(x, y).R; math.Abs(float64(got)-want) > 2 { + t.Fatalf("stroke coverage at (%d,%d) = %d, want %g", x, y, got, want) + } + } + // The 1px stroke spans x=11.75 to 12.75. The clipping side + // at x=12 removes the quarter pixel on the left. + for y := 6; y < 26; y++ { + near(11, y, tc.leftCoverage) + near(12, y, 191) + near(13, y, 0) + } + for _, y := range []int{5, 26} { + near(11, y, 0) + near(12, y, 0) + } + }) + } +} diff --git a/internal/framebuild/framebuild.go b/internal/framebuild/framebuild.go index 1e34fee67..269a0fd85 100644 --- a/internal/framebuild/framebuild.go +++ b/internal/framebuild/framebuild.go @@ -572,8 +572,11 @@ func min32(a, b float32) float32 { func (builder *Builder) drawnBy(stored *render.Rectangle, ref shapeRef) bool { if ref.triangle { triangle := &builder.clippedPaths[ref.index] + coverage, hasCoverage := stored.StrokeCoverage() return stored.Kind == scene.KindTriangle && stored.Color == scene.Color(triangle.Color) && - stored.EdgeMask == triangle.EdgeMask && stored.Shade == sceneShade(*triangle) && + stored.EdgeMask == triangle.EdgeMask && stored.Shade.On == triangle.Shaded && + (!triangle.Shaded || stored.Shade == sceneShade(*triangle)) && + strokeCoverageMatches(coverage, hasCoverage, triangle.Coverage) && stored.Points[0] == scene.Point(triangle.Points[0]) && stored.Points[1] == scene.Point(triangle.Points[1]) && stored.Points[2] == scene.Point(triangle.Points[2]) @@ -652,8 +655,9 @@ func (builder *Builder) syncShapes() { // setShape makes an existing node draw a shape, whatever it drew before. func (builder *Builder) setShape(id scene.ID, ref shapeRef) { if ref.triangle { - value := SceneTriangle(builder.clippedPaths[ref.index]) - builder.graph.SetTriangle(id, value.Points, value.Color, value.EdgeMask, value.Shade) + triangle := builder.clippedPaths[ref.index] + value := sceneTriangleGeometry(triangle) + builder.graph.SetTriangle(id, value.Points, value.Color, value.EdgeMask, value.Shade, sceneStrokeCoverage(triangle.Coverage)) return } if ref.shadow { @@ -667,8 +671,9 @@ func (builder *Builder) setShape(id scene.ID, ref shapeRef) { // insertShape adds a node drawing a shape right after previous. func (builder *Builder) insertShape(root, previous scene.ID, ref shapeRef) scene.ID { if ref.triangle { - value := SceneTriangle(builder.clippedPaths[ref.index]) - id, _ := builder.graph.InsertTriangle(root, previous, value.Points, value.Color, value.EdgeMask, value.Shade) + triangle := builder.clippedPaths[ref.index] + value := sceneTriangleGeometry(triangle) + id, _ := builder.graph.InsertTriangle(root, previous, value.Points, value.Color, value.EdgeMask, value.Shade, sceneStrokeCoverage(triangle.Coverage)) return id } if ref.shadow { @@ -947,6 +952,14 @@ func SceneRectangle(rectangle gfx.Rectangle) render.Rectangle { // SceneTriangle converts a canvas triangle to its render instance shape. func SceneTriangle(triangle gfx.Triangle) render.Rectangle { + rectangle := sceneTriangleGeometry(triangle) + if source := triangle.Coverage; source != nil { + rectangle.SetStrokeCoverage(*sceneStrokeCoverage(source)) + } + return rectangle +} + +func sceneTriangleGeometry(triangle gfx.Triangle) render.Rectangle { return render.Rectangle{ Kind: scene.KindTriangle, Points: [3]scene.Point{ @@ -964,6 +977,27 @@ func SceneTriangle(triangle gfx.Triangle) render.Rectangle { } } +func sceneStrokeCoverage(source *gfx.StrokeCoverage) *scene.StrokeCoverage { + if source == nil { + return nil + } + coverage := &scene.StrokeCoverage{EdgeMask: source.EdgeMask} + for index, point := range source.Points { + coverage.Points[index] = scene.Point(point) + } + return coverage +} + +func strokeCoverageMatches(stored scene.StrokeCoverage, hasCoverage bool, canvas *gfx.StrokeCoverage) bool { + if !hasCoverage || canvas == nil { + return !hasCoverage && canvas == nil + } + return stored.EdgeMask == canvas.EdgeMask && + stored.Points[0] == scene.Point(canvas.Points[0]) && + stored.Points[1] == scene.Point(canvas.Points[1]) && + stored.Points[2] == scene.Point(canvas.Points[2]) +} + // sceneShade is the vertex colors of a shaded triangle, and the zero Shade for a // flat one, whatever stale colors its Shade array holds. func sceneShade(triangle gfx.Triangle) scene.Shade { diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index e948c923b..7f5ea9b28 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -1233,15 +1233,13 @@ func updateLabels(view unsafe.Pointer, labels []TextLabel) error { // layout: float4 bounds, float4 color, float4 style, float4 shade1, float4 // shade2. A shadow keeps its blur in the third style value and its offset and // spread in shade1 (see the Metal vertex shader). Triangles reuse the slot as bounds=(p0, p1), style=(p2.x, layer, p2.y, -// edgeMask+1), color, shade1 and shade2 being the colors of p0, p1 and p2. Zero -// continues to identify rectangles while values 1..8 identify triangles and -// their three independently feathered boundary edges. +// edgeFlags+1). PackTriangleCoverage defines the shade slots and edge flags. func makeNativeRectangle(rectangle render.Rectangle) C.viva_rectangle { if rectangle.Kind == scene.KindTriangle { - colors := rectangle.VertexColors() + marker, shade1, shade2 := platform.PackTriangleCoverage(rectangle) return C.viva_rectangle{ - shade1_red: C.float(colors[1].Red), shade1_green: C.float(colors[1].Green), shade1_blue: C.float(colors[1].Blue), shade1_alpha: C.float(colors[1].Alpha), - shade2_red: C.float(colors[2].Red), shade2_green: C.float(colors[2].Green), shade2_blue: C.float(colors[2].Blue), shade2_alpha: C.float(colors[2].Alpha), + shade1_red: C.float(shade1[0]), shade1_green: C.float(shade1[1]), shade1_blue: C.float(shade1[2]), shade1_alpha: C.float(shade1[3]), + shade2_red: C.float(shade2[0]), shade2_green: C.float(shade2[1]), shade2_blue: C.float(shade2[2]), shade2_alpha: C.float(shade2[3]), x: C.float(rectangle.Points[0].X), y: C.float(rectangle.Points[0].Y), width: C.float(rectangle.Points[1].X), @@ -1253,7 +1251,7 @@ func makeNativeRectangle(rectangle render.Rectangle) C.viva_rectangle { corner_radius: C.float(rectangle.Points[2].X), reserved0: C.float(rectangle.Layer), reserved1: C.float(rectangle.Points[2].Y), - reserved2: C.float(rectangle.EdgeMask + 1), + reserved2: C.float(marker), } } native := C.viva_rectangle{ diff --git a/internal/platform/darwin/shaders/scene.metal b/internal/platform/darwin/shaders/scene.metal index 2926a0140..21ccf7af8 100644 --- a/internal/platform/darwin/shaders/scene.metal +++ b/internal/platform/darwin/shaders/scene.metal @@ -20,12 +20,15 @@ struct VertexOutput { float2 triA [[flat]]; float2 triB [[flat]]; float2 triC [[flat]]; + float2 coverageC [[flat]]; float pixelSize [[flat]]; uint triangleMask [[flat]]; }; // Low bits retain edgeMask+1; this bit is local to the rasterizer varyings. constant uint boundedTriangleFlag = 1u << 8; +constant uint strokeQuadEdgeMask = 1u << 3; +constant uint coverageSourceFlag = 1u << 4; static float cross2(float2 a, float2 b) { return a.x*b.y - a.y*b.x; } static float segmentDistance(float2 p, float2 a, float2 b) { @@ -68,6 +71,7 @@ vertex VertexOutput viva_rectangle_vertex( float2 triA = 0.0; float2 triB = 0.0; float2 triC = 0.0; + float2 coverageC = 0.0; uint triangleMask = 0; float4 color = instance.color; if (isTriangle) { @@ -81,7 +85,9 @@ vertex VertexOutput viva_rectangle_vertex( instance.bounds.zw, instance.style.xz, }; - uint edgeMask = (uint(instance.style.w + 0.5) - 1u) & 7u; + uint edgeFlags = uint(instance.style.w + 0.5) - 1u; + uint edgeMask = edgeFlags & 7u; + bool hasCoverageSource = (edgeFlags & coverageSourceFlag) != 0u; float2 ab = points[1] - points[0], ac = points[2] - points[0]; float2 bc = points[2] - points[1]; float area = cross2(ab, ac); @@ -94,7 +100,7 @@ vertex VertexOutput viva_rectangle_vertex( // scales because hardware snaps geometry to its own subpixel grid. // Above this aspect ratio the miter displacement is at most eight // device pixels. Below it the quad avoids both overflow and overdraw. - bool bounded = valid && (edgeMask != 7u || abs(area) < longest2 * 0.125); + bool bounded = valid && (hasCoverageSource || edgeMask != 7u || abs(area) < longest2 * 0.125); uint index = vertexID < 3 ? vertexID : 0u; uint previous = (index + 2u) % 3u; if (!valid) { @@ -107,18 +113,20 @@ vertex VertexOutput viva_rectangle_vertex( pixel = fringeVertex(points[previous], points[index], points[(index + 1u) % 3u], 1u << previous, 1u << index, edgeMask, viewportSize.z); } // Extrapolate corner colors so interpolation stays on the original mesh. - if (valid) { + if (valid && !hasCoverageSource) { float2 delta = pixel - points[0]; color = instance.color + cross2(delta, ac) / area * (instance.shade1 - instance.color) + cross2(ab, delta) / area * (instance.shade2 - instance.color); } - localPixel = 0.0; - size = 0.0; - radius = 0.0; + // A clipped flat stroke sends its antialiasing face in the shade slots. + localPixel = hasCoverageSource ? instance.shade1.xy : float2(0.0); + size = hasCoverageSource ? instance.shade1.zw : float2(0.0); + coverageC = hasCoverageSource ? instance.shade2.xy : float2(0.0); + radius = hasCoverageSource ? instance.shade2.z : 0.0; triA = points[0]; triB = points[1]; triC = points[2]; - triangleMask = (edgeMask + 1u) | (bounded ? boundedTriangleFlag : 0u); + triangleMask = (edgeFlags + 1u) | (bounded ? boundedTriangleFlag : 0u); } else if (instance.style.z > 0.0) { // Shadow slots: bounds and style.x are the rounded rectangle that casts // the shadow, style.z its blur, shade1 = (offset.x, offset.y, spread). The @@ -150,6 +158,7 @@ vertex VertexOutput viva_rectangle_vertex( output.triA = triA; output.triB = triB; output.triC = triC; + output.coverageC = coverageC; output.pixelSize = viewportSize.z; output.triangleMask = triangleMask; return output; @@ -207,7 +216,8 @@ fragment float4 viva_rectangle_fragment(VertexOutput input [[stage_in]]) { float area2 = (input.triB.x - input.triA.x) * (input.triC.y - input.triA.y) - (input.triB.y - input.triA.y) * (input.triC.x - input.triA.x); float sign = area2 > 0.0 ? 1.0 : -1.0; - uint edgeMask = (input.triangleMask & ~boundedTriangleFlag) - 1u; + uint edgeFlags = (input.triangleMask & ~boundedTriangleFlag) - 1u; + uint edgeMask = edgeFlags & 7u; // Use the actual sample position, not interpolation over an acute face. float2 p = input.position.xy * input.pixelSize; float pixel = input.pixelSize; @@ -244,18 +254,47 @@ fragment float4 viva_rectangle_fragment(VertexOutput input [[stage_in]]) { } } } - float d0 = (edgeMask & 1u) != 0u ? sign * edgeDistance(p, input.triA, input.triB) : 1e6; - float d1 = (edgeMask & 2u) != 0u ? sign * edgeDistance(p, input.triB, input.triC) : 1e6; - float d2 = (edgeMask & 4u) != 0u ? sign * edgeDistance(p, input.triC, input.triA) : 1e6; + // The clipped face owns the sample. Its original outline determines + // the feathering, even when clipping removed every silhouette edge. + float2 coverageA = input.triA, coverageB = input.triB, coverageC = input.triC; + uint coverageFlags = edgeFlags; + float coverageSign = sign; + if ((edgeFlags & coverageSourceFlag) != 0u) { + coverageA = input.localPosition; + coverageB = input.size; + coverageC = input.coverageC; + coverageFlags = uint(input.radius + 0.5); + coverageSign = cross2(coverageB - coverageA, coverageC - coverageA) > 0.0 ? 1.0 : -1.0; + } + uint coverageMask = coverageFlags & 7u; + float d0 = (coverageMask & 1u) != 0u ? coverageSign * edgeDistance(p, coverageA, coverageB) : 1e6; + float d1 = (coverageMask & 2u) != 0u ? coverageSign * edgeDistance(p, coverageB, coverageC) : 1e6; + float d2 = (coverageMask & 4u) != 0u ? coverageSign * edgeDistance(p, coverageC, coverageA) : 1e6; float inside = min(d0, min(d1, d2)); + bool strokeQuad = (coverageFlags & strokeQuadEdgeMask) != 0u; + float2 oppositeStart, oppositeEnd; + if (strokeQuad) { + // The shared diagonal decides ownership, but coverage depends on both long edges. + bool firstHalf = (coverageMask & 1u) != 0u; + float2 from = firstHalf ? coverageA : coverageC; + float2 to = firstHalf ? coverageB : coverageA; + oppositeStart = firstHalf ? coverageC : coverageB; + oppositeEnd = oppositeStart + (to - from); + float primary = firstHalf ? d0 : d2; + inside = min(inside, coverageSign * edgeDistance(oppositeStart, from, to) - primary); + } if (inside < 0.0) { - // Acute offset-line miters must not paint beyond the actual ends. - float s0 = (edgeMask & 1u) != 0u ? segmentDistance(p, input.triA, input.triB) : 1e6; - float s1 = (edgeMask & 2u) != 0u ? segmentDistance(p, input.triB, input.triC) : 1e6; - float s2 = (edgeMask & 4u) != 0u ? segmentDistance(p, input.triC, input.triA) : 1e6; - inside = -min(s0, min(s1, s2)); + // Use the visible edge segments for the outward fringe. A clipped + // stroke's original edges may extend beyond the cut. + bool clippedStroke = (edgeFlags & coverageSourceFlag) != 0u; + uint fringeMask = clippedStroke ? edgeMask : coverageMask; + float s0 = (fringeMask & 1u) != 0u ? segmentDistance(p, input.triA, input.triB) : 1e6; + float s1 = (fringeMask & 2u) != 0u ? segmentDistance(p, input.triB, input.triC) : 1e6; + float s2 = (fringeMask & 4u) != 0u ? segmentDistance(p, input.triC, input.triA) : 1e6; + float opposite = strokeQuad && !clippedStroke ? segmentDistance(p, oppositeStart, oppositeEnd) : 1e6; + inside = -min(min(s0, s1), min(s2, opposite)); } - float coverage = edgeMask == 0 ? 1.0 : saturate(0.5 + inside / pixel); + float coverage = coverageMask == 0 ? 1.0 : saturate(0.5 + inside / pixel); float4 shade = saturate(input.color); return float4(shade.rgb, shade.a * coverage); } diff --git a/internal/platform/darwin/shaders/scene.metallib b/internal/platform/darwin/shaders/scene.metallib index 17f2c0d83dd0fbca49ca146b9c90db3f3dba4d42..3ebf7620bbb8f3d93acf46dc285e44fe6b0ef887 100644 GIT binary patch delta 7331 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 G7x}++|4hpO delta 6450 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 Ky8J`{vi}1f^%YqF diff --git a/internal/platform/triangle.go b/internal/platform/triangle.go new file mode 100644 index 000000000..d449bcaef --- /dev/null +++ b/internal/platform/triangle.go @@ -0,0 +1,20 @@ +package platform + +import "github.com/vivaui/viva/internal/render" + +// PackTriangleCoverage returns the triangle marker and the two shade slots in +// the instance format shared by the GPU renderers. A clipped flat stroke uses +// the shade slots to carry its original coverage edges. +func PackTriangleCoverage(rectangle render.Rectangle) (marker float32, shade1, shade2 [4]float32) { + const coverageSourceFlag = 1 << 4 + if coverage, ok := rectangle.StrokeCoverage(); ok { + a, b, c := coverage.Points[0], coverage.Points[1], coverage.Points[2] + return float32((rectangle.EdgeMask | coverageSourceFlag) + 1), + [4]float32{a.X, a.Y, b.X, b.Y}, + [4]float32{c.X, c.Y, float32(coverage.EdgeMask), 0} + } + colors := rectangle.VertexColors() + return float32(rectangle.EdgeMask + 1), + [4]float32{colors[1].Red, colors[1].Green, colors[1].Blue, colors[1].Alpha}, + [4]float32{colors[2].Red, colors[2].Green, colors[2].Blue, colors[2].Alpha} +} diff --git a/internal/platform/vulkan/shaders/scene.frag b/internal/platform/vulkan/shaders/scene.frag index a495c9989..e85f88842 100644 --- a/internal/platform/vulkan/shaders/scene.frag +++ b/internal/platform/vulkan/shaders/scene.frag @@ -4,7 +4,7 @@ layout(location = 0) in vec4 inColor; layout(location = 1) in vec2 inLocal; layout(location = 2) in vec2 inSize; layout(location = 3) in float inRadius; -layout(location = 4) in vec2 inFragment; +layout(location = 4) flat in vec2 inCoverageC; layout(location = 5) in vec2 inTriangleA; layout(location = 6) in vec2 inTriangleB; layout(location = 7) in vec2 inTriangleC; @@ -22,6 +22,8 @@ layout(location = 0) out vec4 outColor; // Low bits keep edgeMask+1; this bit is local to the rasterizer. #define boundedTriangleFlag (1u << 8) +#define strokeQuadEdgeMask (1u << 3) +#define coverageSourceFlag (1u << 4) float edgeDistance(vec2 point, vec2 from, vec2 to) { vec2 edge = to - from; @@ -80,7 +82,8 @@ void main() { float area = (inTriangleB.x - inTriangleA.x) * (inTriangleC.y - inTriangleA.y) - (inTriangleB.y - inTriangleA.y) * (inTriangleC.x - inTriangleA.x); float orientation = area > 0.0 ? 1.0 : -1.0; - uint edgeMask = (inTriangleMask & ~boundedTriangleFlag) - 1u; + uint edgeFlags = (inTriangleMask & ~boundedTriangleFlag) - 1u; + uint edgeMask = edgeFlags & 7u; // The actual sample in the content's device pixels, as D3D and Metal // take it: the interpolated face would put a sample that lies exactly on // a shared edge on either side by rounding. @@ -125,18 +128,47 @@ void main() { } } } - float distance0 = (edgeMask & 1u) != 0u ? orientation * edgeDistance(p, inTriangleA, inTriangleB) : 1e6; - float distance1 = (edgeMask & 2u) != 0u ? orientation * edgeDistance(p, inTriangleB, inTriangleC) : 1e6; - float distance2 = (edgeMask & 4u) != 0u ? orientation * edgeDistance(p, inTriangleC, inTriangleA) : 1e6; + // The clipped face owns the sample. Its original outline determines + // the feathering, even when clipping removed every silhouette edge. + vec2 coverageA = inTriangleA, coverageB = inTriangleB, coverageC = inTriangleC; + uint coverageFlags = edgeFlags; + float coverageSign = orientation; + if ((edgeFlags & coverageSourceFlag) != 0u) { + coverageA = inLocal; + coverageB = inSize; + coverageC = inCoverageC; + coverageFlags = uint(inRadius + 0.5); + coverageSign = cross2(coverageB - coverageA, coverageC - coverageA) > 0.0 ? 1.0 : -1.0; + } + uint coverageMask = coverageFlags & 7u; + float distance0 = (coverageMask & 1u) != 0u ? coverageSign * edgeDistance(p, coverageA, coverageB) : 1e6; + float distance1 = (coverageMask & 2u) != 0u ? coverageSign * edgeDistance(p, coverageB, coverageC) : 1e6; + float distance2 = (coverageMask & 4u) != 0u ? coverageSign * edgeDistance(p, coverageC, coverageA) : 1e6; float inside = min(distance0, min(distance1, distance2)); + bool strokeQuad = (coverageFlags & strokeQuadEdgeMask) != 0u; + vec2 oppositeStart, oppositeEnd; + if (strokeQuad) { + // The shared diagonal decides ownership, but coverage depends on both long edges. + bool firstHalf = (coverageMask & 1u) != 0u; + vec2 from = firstHalf ? coverageA : coverageC; + vec2 to = firstHalf ? coverageB : coverageA; + oppositeStart = firstHalf ? coverageC : coverageB; + oppositeEnd = oppositeStart + (to - from); + float primary = firstHalf ? distance0 : distance2; + inside = min(inside, coverageSign * edgeDistance(oppositeStart, from, to) - primary); + } if (inside < 0.0) { - // Acute offset-line miters must not paint beyond the actual ends. - float s0 = (edgeMask & 1u) != 0u ? segmentDistance(p, inTriangleA, inTriangleB) : 1e6; - float s1 = (edgeMask & 2u) != 0u ? segmentDistance(p, inTriangleB, inTriangleC) : 1e6; - float s2 = (edgeMask & 4u) != 0u ? segmentDistance(p, inTriangleC, inTriangleA) : 1e6; - inside = -min(s0, min(s1, s2)); + // Use the visible edge segments for the outward fringe. A clipped + // stroke's original edges may extend beyond the cut. + bool clippedStroke = (edgeFlags & coverageSourceFlag) != 0u; + uint fringeMask = clippedStroke ? edgeMask : coverageMask; + float s0 = (fringeMask & 1u) != 0u ? segmentDistance(p, inTriangleA, inTriangleB) : 1e6; + float s1 = (fringeMask & 2u) != 0u ? segmentDistance(p, inTriangleB, inTriangleC) : 1e6; + float s2 = (fringeMask & 4u) != 0u ? segmentDistance(p, inTriangleC, inTriangleA) : 1e6; + float opposite = strokeQuad && !clippedStroke ? segmentDistance(p, oppositeStart, oppositeEnd) : 1e6; + inside = -min(min(s0, s1), min(s2, opposite)); } - float coverage = edgeMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); + float coverage = coverageMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); vec4 shade = clamp(inColor, 0.0, 1.0); float alpha = shade.a * coverage; outColor = vec4(shade.rgb * alpha, alpha); diff --git a/internal/platform/vulkan/shaders/scene.frag.spv b/internal/platform/vulkan/shaders/scene.frag.spv index cdc5266553b70007eb72b2f2b97419d5281fcf6b..1bfadc9854d7223171790cdc89b4bef13db845f0 100644 GIT binary patch literal 12164 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 literal 10240 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 diff --git a/internal/platform/vulkan/shaders/scene.vert b/internal/platform/vulkan/shaders/scene.vert index 21f858f63..4dbcd15f6 100644 --- a/internal/platform/vulkan/shaders/scene.vert +++ b/internal/platform/vulkan/shaders/scene.vert @@ -11,6 +11,7 @@ layout(location = 4) in vec4 inShade2; // Low bits keep edgeMask+1; this bit is local to the rasterizer. #define boundedTriangleFlag (1u << 8) +#define coverageSourceFlag (1u << 4) layout(push_constant) uniform Frame { vec2 viewport; @@ -24,7 +25,7 @@ layout(location = 0) out vec4 outColor; layout(location = 1) out vec2 outLocal; layout(location = 2) out vec2 outSize; layout(location = 3) out float outRadius; -layout(location = 4) out vec2 outFragment; +layout(location = 4) flat out vec2 outCoverageC; layout(location = 5) out vec2 outTriangleA; layout(location = 6) out vec2 outTriangleB; layout(location = 7) out vec2 outTriangleC; @@ -59,6 +60,7 @@ void main() { vec2 localPixel; vec2 size = inBounds.zw; float radius = inStyle.x; + vec2 coverageC = vec2(0.0); vec2 triangleA = vec2(0.0); vec2 triangleB = vec2(0.0); vec2 triangleC = vec2(0.0); @@ -67,7 +69,9 @@ void main() { if (inStyle.w > 0.5) { vec2 points[3] = vec2[](inBounds.xy, inBounds.zw, inStyle.xz); uint index = gl_VertexIndex < 3 ? uint(gl_VertexIndex) : 0u; - uint edgeMask = uint(inStyle.w + 0.5) - 1u; + uint edgeFlags = uint(inStyle.w + 0.5) - 1u; + uint edgeMask = edgeFlags & 7u; + bool hasCoverageSource = (edgeFlags & coverageSourceFlag) != 0u; uint previous = (index + 2u) % 3u; vec2 ab = points[1] - points[0], ac = points[2] - points[0]; vec2 bc = points[2] - points[1]; @@ -81,7 +85,7 @@ void main() { // scales because hardware snaps geometry to its own subpixel grid. // Above this aspect ratio the miter displacement is at most eight // device pixels; below it the quad avoids both overflow and overdraw. - bool bounded = valid && (edgeMask != 7u || abs(area) < longest2 * 0.125); + bool bounded = valid && (hasCoverageSource || edgeMask != 7u || abs(area) < longest2 * 0.125); if (!valid) { pixel = vec2(0.0); } else if (bounded) { @@ -92,18 +96,20 @@ void main() { pixel = fringeVertex(points[previous], points[index], points[(index + 1u) % 3u], 1u << previous, 1u << index, edgeMask); } // Extrapolate corner colors so interpolation stays on the original mesh. - if (valid) { + if (valid && !hasCoverageSource) { vec2 delta = pixel - points[0]; color = inColor + cross2(delta, ac) / area * (inShade1 - inColor) + cross2(ab, delta) / area * (inShade2 - inColor); } - localPixel = vec2(0.0); - size = vec2(0.0); - radius = 0.0; + // A clipped flat stroke sends its antialiasing face in the shade slots. + localPixel = hasCoverageSource ? inShade1.xy : vec2(0.0); + size = hasCoverageSource ? inShade1.zw : vec2(0.0); + coverageC = hasCoverageSource ? inShade2.xy : vec2(0.0); + radius = hasCoverageSource ? inShade2.z : 0.0; triangleA = points[0]; triangleB = points[1]; triangleC = points[2]; - triangleMask = edgeMask + 1u + (bounded ? boundedTriangleFlag : 0u); + triangleMask = edgeFlags + 1u + (bounded ? boundedTriangleFlag : 0u); } else if (inStyle.z > 0.0) { // A soft shadow: inBounds and inStyle.x are the rounded rectangle that // casts it, inStyle.z its blur, inShade1 = (offset.x, offset.y, spread). The @@ -127,7 +133,7 @@ void main() { outLocal = localPixel; outSize = size; outRadius = radius; - outFragment = pixel; + outCoverageC = coverageC; outTriangleA = triangleA; outTriangleB = triangleB; outTriangleC = triangleC; diff --git a/internal/platform/vulkan/shaders/scene.vert.spv b/internal/platform/vulkan/shaders/scene.vert.spv index 76341185905f0fe1db1be391a7a51b5775ca32e2..cb996ef353d3c9d0953ca4d3c235175560f00db6 100644 GIT binary patch literal 9816 zcmZwMd(f3t6$bDVS1$-&0(Ddd`HU1CB=LfyfP{jI1`alrR^uf?#|xO|J-L)AX8zHb z*^JgyiinzHmf-!%QK`fvD>coUL`AdG)bf_r^E=3pcOd1s5xJ^ee~wpFKJm`=Ds-G1iba}OVX#+hFjzt`RqI1KIdIr16S8II}< zh@5)dNvFZfBP%1fM}9?*<86_N{W_g#k%J;LB8Nt1MUIHfjvN^|Dl#+iPszBz&LN$F zT^!iy@lRTD=ErT);*7x!X>qc}Z5f%FOyxH+qS56_Hpirw zS$npMZ6D|Z8@oNB4{CJ#L(hTf)@iRQ7R+WZw#n>KJ3D7q^TH#7#2FRYHZzJrXB!pW zI2`$K*kS31hu<#!sE9VM(R=#Tjry4A){$Mzqa$ap9k*xc^P+2|&+lrBrV z7V+qwjf#g~8xgPKKNBow>CXmx4olw<>Ykl1f`E1nP4fM)) zJtaby_YlQ(ItR*sLNIPj#MyIC)VW|I=G`;BHD)(2-Q9{~-#ggZk{f+$W2>`7cMq5U z^ak@6kM3S!FWtRT{)aSJuIzO8Oxxex($?KAZQb3{*4-_1`Oa;y^C>>v{ldOa&URqf zzJ_}%%)s<~o!Q<<)nbp%jdm_eLqnji6inl7*b68{U2sXxZS7YuB#^0H^!_wc?#hs43>CMb|PkQa0%)xed z7FXV31#5%(Xm-W_vX9+lZXu3&Pv;$0B0A9o`srer+B9uj~f@bFu-(h+*CNE=dm7 z{>g~7v~H(1@&C~9OXFkwQxV*l$eM=xQ^UKzid)}s&!)ezsqwjBym=QlV_yuG(}wiR z8t$cF{OX8(-z5FZk>1F{h&3FX{%;X{`TQfeH{xC_pI3tMUriiiUX2)suW_#j_eR{G zHSUdIeChuVZpV2uIv;%byc66W^PlMQtGV9`=7T>n`3y>bYz~f`wBn8rC%*G{QR8<) zIKFJ zTt1y$BgXJ4+pw0+9DHldwh6YbmH&d|gVV0gJ`YQOUO4=UMn69o=Q&xNUh|ybFNokg z2kRB&l3?-H1@jfld|ytlnUBxu5uEwps^g4cbtt9kxF{UH z>iBvvPTX&#*TltN9KneTR~^fO+c7SUj#EeZ>#L5-g2j^?U$OXB&ie8_D_Bj7BgTm% zw-L>L$c@kN=s3B-wU^rmJMXmy--<6zt2MYL9KP1zd%-yK{3yL<9{l$sIP<`@20sXH z$M|7%oVv=s0zhzrO0YC0IPU@fC}2<*YB??*^;MIv6Jo-`Y2Q`R)*GU!4Wx z#8Jmi3Qn^he0GfB)B)GNj|z70)q4Fb<8fN8S8q6ct=G?kaprj_y=ET#{Slmb;99Q- zg4;13jE+-R`Rl8$HNoP^m9JRlyDNRo$7fXpXFj;p-1Fp4rD!3iv>F78)m%qMp zekNEvdGHmBZ{?>i-(7>{uV&-Kk=xkll^dVkA~?ChRo`FY@4Kt&dp0^wj1B2427Y}6 zCk9;gJs;eT@j`T*oXcNdIlmYzo;>)9#kca)m+$ys`K#GDapX23dgaDvj|fg~@Q{3C z`_A4oIG;RqeS2_k-UEF1O$^C)bg;Q=tiI;nD_Cs#@E6zIlhSLRWj^~xaOQ^VU2y+k z?~UFWmpAhs5Y9UyTdn!zV7%B<(`#bmr$lgK!&TR`;CwdLRqsIug|rvbBdeP^4-V$f zrq+t5uUcmW%R&D9&BeFs(wFbdV0Bw7z>^cpJMP?I?^LCKGP>{O(mxg5eeL~>|EHtp)A>k*FMHWO)3S-n*L$ zXM990V)C(%_RSvItNPuuDA@0wG4Ze8J&VKP{qA`nx%s`dG&&!@iHiGL!x>*Wemz`o z<5xLe91dST%Nif!%IDH>`0}}|@sUgUd@~sD4DOe)+PlF$>EFtoqc(l*<-5V+n!mXB z!-<2h@7F1b#aAotz;Jxyw($&23&)qO{H6yR%dfbD!x^j9`I`}rFI)ZgnHel5TiqG` zgT-u(oB zg3UiKV{d5g=`Et;=Z8BnVy`@ZL&JUW`5P7vU-fSp?D@kNw{Cet>fLV zVxJpqocXK~->PABuo^rcRYOlWd{1~aj0@J(z_v?dY{a~9)i5TwUBj-?s|IJRYS=A2 zUv@c*FP4~X9bYw^7i^sQ)WG-h<}R8LEWSF6n;2}}jH~BquVB7xb+7Id?Cg+Bnt1yL z^JQDoaFc>Phir1(FTI@ga&(`a-}pGI{N>NL?lOJ(ekC^dU-$bcSRB6f{iQG83u3z^ z@ed1UoH+IU`0Zfd|JNr^&)JpHeP813-Bsx|d&l;j2u|*B-B(u!``)Ovx+c1L@pV_s zijLQ6FFz3ue|*-u{N^-%T+456IQ;zh)tz!wbmQ5qy|a2<2I0Nm%I(^4*N0mkF^+yi zFm6?_{l=|~jyK+(;cjev*eZ`>68qT1mP>KR2G0wpj>_%0;I41_%IznKgKy{d({Q&% zD!1E%aqZkzMaLUoxvdWF=9k{S*PiI@yZkTDT;ezj{Oy-Ly(hh9PoGPFcl6$fJ%wxC z?hUqX_4n8Nf^kICnOi(##c1pJI)fJ`7vsfu7WvBM!Sq_?@<8-oM8tzDmxqGexvYtf zBU$=H>YH0UW5tk5>H5lLQJjqzUoL#*@<@8Ea#y` zR*bfeuUr-<7vsg33tzeXKD}1C{4V;F5%FN(M>od)c(7bH1k2Ae@I-XHImI!?*tU+B z1OFw-!5DGfjeNy&Cp{h9ejj`$di#Cw&(XaP`rh>J^j!3rk@b@vton8*stP|T`BO`Ml#D**OE5XiBJNB#5@%1;; ze+K8%eV1i3hv&^2y%ycPd@APa!D6bj*8Yv?`1($JGZ}C6J%Vu7_RZo_uTN9r;$Nj=xpIAhTY2)|Y01sIs?yA92 z2SzuBP5leP4GQ*uEZ*q{2cMZB>hu2zn?%R)sq?jIFuv~6p}|8U=Bn@5VZnGJe{*jc zydpiDvAC^*#bYbKt%K#sR(X#I#>-tE?#gY0t$nSsSNGK&xhvG~*>Yd0xooRqvu^*-c2jKDoy|P$ahJqqKiJg4*1jX$ z73Ofi+#O$ciTkT3dONo}V{;#|$*pZ$9hVA zJK6jnYJ1$x;eF4rST-@@k_PujV3CEYs z{W(7($Enc|j7*Hk(HW)lho_}iJA6>EHG*dZTTA%RU~3M~3br@!5yAElo*itj;Uj~c Q3E2P7J3H^?Nt_hs;qt*L7dd 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 0 { // The casting rectangle keeps the slot's bounds and radius; the blur is the diff --git a/internal/platform/web/glpack.go b/internal/platform/web/glpack.go index ef8138072..ec1cfa721 100644 --- a/internal/platform/web/glpack.go +++ b/internal/platform/web/glpack.go @@ -1,6 +1,7 @@ package web import ( + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" ) @@ -35,18 +36,18 @@ func packInstance(dst []float32, instance render.Rectangle) { for index := 0; index < 20; index++ { dst[index] = 0 } - colors := instance.VertexColors() setColor := func(at int, color scene.Color) { dst[at], dst[at+1], dst[at+2], dst[at+3] = color.Red, color.Green, color.Blue, color.Alpha } switch instance.Kind { case scene.KindTriangle: points := instance.Points + marker, shade1, shade2 := platform.PackTriangleCoverage(instance) dst[0], dst[1], dst[2], dst[3] = points[0].X, points[0].Y, points[1].X, points[1].Y - dst[8], dst[9], dst[10], dst[11] = points[2].X, float32(instance.Layer), points[2].Y, float32(instance.EdgeMask)+1 - setColor(4, colors[0]) - setColor(12, colors[1]) - setColor(16, colors[2]) + dst[8], dst[9], dst[10], dst[11] = points[2].X, float32(instance.Layer), points[2].Y, marker + setColor(4, instance.Color) + copy(dst[12:16], shade1[:]) + copy(dst[16:20], shade2[:]) case scene.KindShadow: dst[0], dst[1], dst[2], dst[3] = instance.Bounds.X, instance.Bounds.Y, instance.Bounds.Width, instance.Bounds.Height dst[8], dst[9], dst[10], dst[11] = instance.Radius, 0, instance.Shadow.Blur, 0 diff --git a/internal/platform/web/shaders/scene.frag.glsl b/internal/platform/web/shaders/scene.frag.glsl index 3d1ae728b..095797d49 100644 --- a/internal/platform/web/shaders/scene.frag.glsl +++ b/internal/platform/web/shaders/scene.frag.glsl @@ -6,7 +6,7 @@ in vec4 vColor; in vec2 vLocal; in vec2 vSize; in float vRadius; -in vec2 vFragment; +flat in vec2 vCoverageC; in vec2 vTriangleA; in vec2 vTriangleB; in vec2 vTriangleC; @@ -19,6 +19,8 @@ uniform float uPixelSize; out vec4 outColor; #define boundedTriangleFlag (1u << 8) +#define strokeQuadEdgeMask (1u << 3) +#define coverageSourceFlag (1u << 4) float edgeDistance(vec2 point, vec2 from, vec2 to) { vec2 edge = to - from; @@ -82,7 +84,8 @@ void main() { float area = (vTriangleB.x - vTriangleA.x) * (vTriangleC.y - vTriangleA.y) - (vTriangleB.y - vTriangleA.y) * (vTriangleC.x - vTriangleA.x); float orientation = area > 0.0 ? 1.0 : -1.0; - uint edgeMask = (vTriangleMask & ~boundedTriangleFlag) - 1u; + uint edgeFlags = (vTriangleMask & ~boundedTriangleFlag) - 1u; + uint edgeMask = edgeFlags & 7u; // Marked edges are supporting lines: only their half-pixel neighborhood // of the triangle itself is coverage. Without this cut a sliver paints // its lines across the window. @@ -121,18 +124,47 @@ void main() { } } } - float distance0 = (edgeMask & 1u) != 0u ? orientation * edgeDistance(p, vTriangleA, vTriangleB) : 1e6; - float distance1 = (edgeMask & 2u) != 0u ? orientation * edgeDistance(p, vTriangleB, vTriangleC) : 1e6; - float distance2 = (edgeMask & 4u) != 0u ? orientation * edgeDistance(p, vTriangleC, vTriangleA) : 1e6; + // The clipped face owns the sample. Its original outline determines + // the feathering, even when clipping removed every silhouette edge. + vec2 coverageA = vTriangleA, coverageB = vTriangleB, coverageC = vTriangleC; + uint coverageFlags = edgeFlags; + float coverageSign = orientation; + if ((edgeFlags & coverageSourceFlag) != 0u) { + coverageA = vLocal; + coverageB = vSize; + coverageC = vCoverageC; + coverageFlags = uint(vRadius + 0.5); + coverageSign = cross2(coverageB - coverageA, coverageC - coverageA) > 0.0 ? 1.0 : -1.0; + } + uint coverageMask = coverageFlags & 7u; + float distance0 = (coverageMask & 1u) != 0u ? coverageSign * edgeDistance(p, coverageA, coverageB) : 1e6; + float distance1 = (coverageMask & 2u) != 0u ? coverageSign * edgeDistance(p, coverageB, coverageC) : 1e6; + float distance2 = (coverageMask & 4u) != 0u ? coverageSign * edgeDistance(p, coverageC, coverageA) : 1e6; float inside = min(distance0, min(distance1, distance2)); + bool strokeQuad = (coverageFlags & strokeQuadEdgeMask) != 0u; + vec2 oppositeStart, oppositeEnd; + if (strokeQuad) { + // The shared diagonal decides ownership, but coverage depends on both long edges. + bool firstHalf = (coverageMask & 1u) != 0u; + vec2 from = firstHalf ? coverageA : coverageC; + vec2 to = firstHalf ? coverageB : coverageA; + oppositeStart = firstHalf ? coverageC : coverageB; + oppositeEnd = oppositeStart + (to - from); + float primary = firstHalf ? distance0 : distance2; + inside = min(inside, coverageSign * edgeDistance(oppositeStart, from, to) - primary); + } if (inside < 0.0) { - // Acute offset-line miters must not paint beyond the actual ends. - float s0 = (edgeMask & 1u) != 0u ? segmentDistance(p, vTriangleA, vTriangleB) : 1e6; - float s1 = (edgeMask & 2u) != 0u ? segmentDistance(p, vTriangleB, vTriangleC) : 1e6; - float s2 = (edgeMask & 4u) != 0u ? segmentDistance(p, vTriangleC, vTriangleA) : 1e6; - inside = -min(s0, min(s1, s2)); + // Use the visible edge segments for the outward fringe. A clipped + // stroke's original edges may extend beyond the cut. + bool clippedStroke = (edgeFlags & coverageSourceFlag) != 0u; + uint fringeMask = clippedStroke ? edgeMask : coverageMask; + float s0 = (fringeMask & 1u) != 0u ? segmentDistance(p, vTriangleA, vTriangleB) : 1e6; + float s1 = (fringeMask & 2u) != 0u ? segmentDistance(p, vTriangleB, vTriangleC) : 1e6; + float s2 = (fringeMask & 4u) != 0u ? segmentDistance(p, vTriangleC, vTriangleA) : 1e6; + float opposite = strokeQuad && !clippedStroke ? segmentDistance(p, oppositeStart, oppositeEnd) : 1e6; + inside = -min(min(s0, s1), min(s2, opposite)); } - float coverage = edgeMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); + float coverage = coverageMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); vec4 shade = clamp(vColor, 0.0, 1.0); float alpha = shade.a * coverage; outColor = vec4(shade.rgb * alpha, alpha); diff --git a/internal/platform/web/shaders/scene.vert.glsl b/internal/platform/web/shaders/scene.vert.glsl index 0f919b76b..cb0ff5994 100644 --- a/internal/platform/web/shaders/scene.vert.glsl +++ b/internal/platform/web/shaders/scene.vert.glsl @@ -13,12 +13,13 @@ uniform float uPixelSize; // Low bits keep edgeMask+1; this bit is local to the rasterizer. #define boundedTriangleFlag (1u << 8) +#define coverageSourceFlag (1u << 4) out vec4 vColor; out vec2 vLocal; out vec2 vSize; out float vRadius; -out vec2 vFragment; +flat out vec2 vCoverageC; out vec2 vTriangleA; out vec2 vTriangleB; out vec2 vTriangleC; @@ -54,6 +55,7 @@ void main() { vec2 localPixel; vec2 size = inBounds.zw; float radius = inStyle.x; + vec2 coverageC = vec2(0.0); vec2 triangleA = vec2(0.0); vec2 triangleB = vec2(0.0); vec2 triangleC = vec2(0.0); @@ -62,7 +64,9 @@ void main() { if (inStyle.w > 0.5) { vec2 points[3] = vec2[](inBounds.xy, inBounds.zw, inStyle.xz); uint index = gl_VertexID < 3 ? uint(gl_VertexID) : 0u; - uint edgeMask = uint(inStyle.w + 0.5) - 1u; + uint edgeFlags = uint(inStyle.w + 0.5) - 1u; + uint edgeMask = edgeFlags & 7u; + bool hasCoverageSource = (edgeFlags & coverageSourceFlag) != 0u; uint previous = (index + 2u) % 3u; vec2 ab = points[1] - points[0], ac = points[2] - points[0]; vec2 bc = points[2] - points[1]; @@ -74,7 +78,7 @@ void main() { // its finite support instead. Every face with a shared edge uses this // path: mixing hardware and analytic edge ownership cracks at fractional // scales because hardware snaps geometry to its own subpixel grid. - bool bounded = valid && (edgeMask != 7u || abs(area) < longest2 * 0.125); + bool bounded = valid && (hasCoverageSource || edgeMask != 7u || abs(area) < longest2 * 0.125); if (!valid) { pixel = vec2(0.0); } else if (bounded) { @@ -85,18 +89,20 @@ void main() { pixel = fringeVertex(points[previous], points[index], points[(index + 1u) % 3u], 1u << previous, 1u << index, edgeMask); } // Extrapolate corner colors so interpolation stays on the original mesh. - if (valid) { + if (valid && !hasCoverageSource) { vec2 delta = pixel - points[0]; color = inColor + cross2(delta, ac) / area * (inShade1 - inColor) + cross2(ab, delta) / area * (inShade2 - inColor); } - localPixel = vec2(0.0); - size = vec2(0.0); - radius = 0.0; + // A clipped flat stroke sends its antialiasing face in the shade slots. + localPixel = hasCoverageSource ? inShade1.xy : vec2(0.0); + size = hasCoverageSource ? inShade1.zw : vec2(0.0); + coverageC = hasCoverageSource ? inShade2.xy : vec2(0.0); + radius = hasCoverageSource ? inShade2.z : 0.0; triangleA = points[0]; triangleB = points[1]; triangleC = points[2]; - triangleMask = edgeMask + 1u + (bounded ? boundedTriangleFlag : 0u); + triangleMask = edgeFlags + 1u + (bounded ? boundedTriangleFlag : 0u); } else if (inStyle.z > 0.0) { // A soft shadow: inBounds and inStyle.x are the rounded rectangle that // casts it, inStyle.z its blur, inShade1 = (offset.x, offset.y, spread). @@ -118,7 +124,7 @@ void main() { vLocal = localPixel; vSize = size; vRadius = radius; - vFragment = pixel; + vCoverageC = coverageC; vTriangleA = triangleA; vTriangleB = triangleB; vTriangleC = triangleC; diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 28d4d47b1..770453f5c 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -540,10 +540,9 @@ func makeRectangleInstance(rectangle render.Rectangle) rectangleInstance { // Same triangle slot convention as the Metal backend: // bounds=(p0, p1), style=(p2.x, layer, p2.y, edgeMask+1). instance.Bounds = [4]float32{rectangle.Points[0].X, rectangle.Points[0].Y, rectangle.Points[1].X, rectangle.Points[1].Y} - instance.Style = [4]float32{rectangle.Points[2].X, float32(rectangle.Layer), rectangle.Points[2].Y, float32(rectangle.EdgeMask + 1)} - colors := rectangle.VertexColors() - instance.Shade1 = [4]float32{colors[1].Red, colors[1].Green, colors[1].Blue, colors[1].Alpha} - instance.Shade2 = [4]float32{colors[2].Red, colors[2].Green, colors[2].Blue, colors[2].Alpha} + marker, shade1, shade2 := platform.PackTriangleCoverage(rectangle) + instance.Style = [4]float32{rectangle.Points[2].X, float32(rectangle.Layer), rectangle.Points[2].Y, marker} + instance.Shade1, instance.Shade2 = shade1, shade2 } if rectangle.Kind == scene.KindShadow && rectangle.Shadow.Blur > 0 { // The casting rectangle keeps the slot's bounds and radius; the blur is the diff --git a/internal/platform/windows/shaders/manifest.json b/internal/platform/windows/shaders/manifest.json index 462c7f3ac..01bfa63c6 100644 --- a/internal/platform/windows/shaders/manifest.json +++ b/internal/platform/windows/shaders/manifest.json @@ -1,30 +1,30 @@ { - "source_sha256": "5083c9723999eac26132facf2b8ce704824dfc4719b56fe9b8974de7d91b2524", + "source_sha256": "0a87c0024b7eaed6bfd77f1c47843e77dff754954839ed9156a029358f8ed548", "compiler": "d3dcompiler_47.dll", "flags": 34816, "entries": [ { "name": "rectangleVertex", "profile": "vs_5_0", - "sha256": "edf06eb99b4bbbc8f0386f1ddc0fbce58e20e61721c2c810073b7ab040873a03", - "bytes": 6612 + "sha256": "cf2f256447720e809e81cdc38b6f015b8ac72cee432324dba946f781558e8129", + "bytes": 6808 }, { "name": "rectangleFragment", "profile": "ps_5_0", - "sha256": "820e508861cefb20e957f6cd042110ab33f63220ee6a134c59b8c84f1ed60db1", - "bytes": 9660 + "sha256": "568dc12dba9084a4e72eff46fd01022b8fe4fb9397cfa258e84f134bdb46709e", + "bytes": 11308 }, { "name": "textVertex", "profile": "vs_5_0", - "sha256": "701be5fdd0a737b4f23d8807f92451955d587b0e91b4c6e8423b70236a3195c7", - "bytes": 2152 + "sha256": "9aae8cd4ab52b16ee24a465887e7c92d178dd950068b6f1db6d564f1b7fb4178", + "bytes": 2164 }, { "name": "textFragment", "profile": "ps_5_0", - "sha256": "43278ce7f746c6d9b366868be6388938e5dec229a01d4c4e78be043236954542", + "sha256": "2d79ce8be175bfdae8f807268157325e7122e72d57185b202dff778293d25007", "bytes": 2576 } ] diff --git a/internal/platform/windows/shaders/rectangleFragment.dxbc b/internal/platform/windows/shaders/rectangleFragment.dxbc index 261e021d9c82ec9407d38d3a2b6220f7c8db4156..c1683f99937e634c33345a2362cde078d1ce5fe0 100644 GIT binary patch literal 11308 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 literal 9660 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 rectangles : register(t0); Texture2D labelTexture : register(t1); SamplerState labelSampler : register(s0); -struct Vertex { float4 position : SV_Position; float4 color : COLOR; float2 local : LOCAL; float2 size : SIZE; float radius : RADIUS; float2 uv : TEXCOORD; float2 frag : FRAG; float2 triA : TRIA; float2 triB : TRIB; float2 triC : TRIC; nointerpolation uint triangleMask : TRIMASK; }; +struct Vertex { float4 position : SV_Position; float4 color : COLOR; float2 local : LOCAL; float2 size : SIZE; float radius : RADIUS; float2 uv : TEXCOORD; nointerpolation float2 coverageC : COVERC; float2 triA : TRIA; float2 triB : TRIB; float2 triC : TRIC; nointerpolation uint triangleMask : TRIMASK; }; // Low bits keep edgeMask+1; this bit is local to the rasterizer. #define boundedTriangleFlag (1u << 8) +#define strokeQuadFlag (1u << 3) +#define coverageSourceFlag (1u << 4) float2 corner(uint vertex) { const float2 corners[6] = {float2(0,0),float2(1,0),float2(0,1),float2(0,1),float2(1,0),float2(1,1)}; return corners[vertex]; @@ -46,6 +48,7 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) float2 local; float2 size = rectangle.bounds.zw; float radius = rectangle.style.x; + float2 coverageC = 0; float2 triA = 0, triB = 0, triC = 0; uint triangleMask = 0; float4 color = rectangle.color; @@ -60,7 +63,9 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) rectangle.style.xz, }; uint index = vertex < 3 ? vertex : 0; - uint edgeMask = (uint)(rectangle.style.w + 0.5) - 1; + uint edgeFlags = (uint)(rectangle.style.w + 0.5) - 1; + uint edgeMask = edgeFlags & 7u; + bool hasCoverageSource = (edgeFlags & coverageSourceFlag) != 0; uint previous = (index + 2) % 3; float2 ab = points[1] - points[0], ac = points[2] - points[0]; float2 bc = points[2] - points[1]; @@ -74,7 +79,7 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) // scales because hardware snaps geometry to its own subpixel grid. // Above this aspect ratio the miter displacement is at most eight // device pixels; below it the quad avoids both overflow and overdraw. - bool bounded = valid && (edgeMask != 7 || abs(area) < longest2 * 0.125); + bool bounded = valid && (hasCoverageSource || edgeMask != 7 || abs(area) < longest2 * 0.125); if (!valid) { pixel = 0; } else if (bounded) { @@ -85,18 +90,20 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) pixel = fringeVertex(points[previous], points[index], points[(index + 1) % 3], 1u << previous, 1u << index, edgeMask); } // Extrapolate corner colors so interpolation stays on the original mesh. - if (valid) { + if (valid && !hasCoverageSource) { float2 delta = pixel - points[0]; color = rectangle.color + cross2(delta, ac) / area * (rectangle.shade1 - rectangle.color) + cross2(ab, delta) / area * (rectangle.shade2 - rectangle.color); } - local = 0; - size = 0; - radius = 0; + // A clipped flat stroke sends its antialiasing face in the shade slots. + local = hasCoverageSource ? rectangle.shade1.xy : 0; + size = hasCoverageSource ? rectangle.shade1.zw : 0; + coverageC = hasCoverageSource ? rectangle.shade2.xy : 0; + radius = hasCoverageSource ? rectangle.shade2.z : 0; triA = points[0]; triB = points[1]; triC = points[2]; - triangleMask = edgeMask + 1 + (bounded ? boundedTriangleFlag : 0); + triangleMask = edgeFlags + 1 + (bounded ? boundedTriangleFlag : 0); } else if (rectangle.style.z > 0) { // A soft shadow: bounds and style.x are the rounded rectangle that casts it, // style.z its blur, shade1 = (offset.x, offset.y, spread). The quad grows by @@ -119,7 +126,7 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) output.size = size; output.radius = radius; output.uv = corner(vertex); - output.frag = pixel; + output.coverageC = coverageC; output.triA = triA; output.triB = triB; output.triC = triC; @@ -169,7 +176,8 @@ float4 rectangleFragment(Vertex input) : SV_Target { float area2 = (input.triB.x-input.triA.x)*(input.triC.y-input.triA.y) - (input.triB.y-input.triA.y)*(input.triC.x-input.triA.x); float sign = area2 > 0 ? 1 : -1; - uint edgeMask = (input.triangleMask & ~boundedTriangleFlag) - 1; + uint edgeFlags = (input.triangleMask & ~boundedTriangleFlag) - 1; + uint edgeMask = edgeFlags & 7u; // The actual sample, not the interpolated face: over a sliver's long // support the interpolant cannot say which pixel it is. float2 p = input.position.xy * pixelSize; @@ -211,18 +219,48 @@ float4 rectangleFragment(Vertex input) : SV_Target { } } } - float d0 = (edgeMask & 1u) != 0 ? sign * edgeDistance(p, input.triA, input.triB) : 1e6; - float d1 = (edgeMask & 2u) != 0 ? sign * edgeDistance(p, input.triB, input.triC) : 1e6; - float d2 = (edgeMask & 4u) != 0 ? sign * edgeDistance(p, input.triC, input.triA) : 1e6; + // The clipped face owns the sample. Its original outline determines + // the feathering, even when clipping removed every silhouette edge. + float2 coverageA = input.triA, coverageB = input.triB, coverageC = input.triC; + uint coverageFlags = edgeFlags; + float coverageSign = sign; + if ((edgeFlags & coverageSourceFlag) != 0u) { + coverageA = input.local; + coverageB = input.size; + coverageC = input.coverageC; + coverageFlags = uint(input.radius + 0.5); + coverageSign = cross2(coverageB - coverageA, coverageC - coverageA) > 0.0 ? 1.0 : -1.0; + } + uint coverageMask = coverageFlags & 7u; + float d0 = (coverageMask & 1u) != 0 ? coverageSign * edgeDistance(p, coverageA, coverageB) : 1e6; + float d1 = (coverageMask & 2u) != 0 ? coverageSign * edgeDistance(p, coverageB, coverageC) : 1e6; + float d2 = (coverageMask & 4u) != 0 ? coverageSign * edgeDistance(p, coverageC, coverageA) : 1e6; float inside = min(d0, min(d1, d2)); + float2 oppositeStart = 0, oppositeEnd = 0; + bool strokeQuad = (coverageFlags & strokeQuadFlag) != 0; + if (strokeQuad) { + // The diagonal assigns this sample to one triangle, but coverage is + // measured against both long edges of the original stroke quad. + bool firstHalf = (coverageMask & 1u) != 0; + float2 start = firstHalf ? coverageA : coverageC; + float2 end = firstHalf ? coverageB : coverageA; + oppositeStart = firstHalf ? coverageC : coverageB; + oppositeEnd = oppositeStart + (end - start); + float opposite = -coverageSign * edgeDistance(p, oppositeStart, oppositeEnd); + inside = min(inside, opposite); + } if (inside < 0) { - // Acute offset-line miters must not paint beyond the actual ends. - float s0 = (edgeMask & 1u) != 0 ? segmentDistance(p, input.triA, input.triB) : 1e6; - float s1 = (edgeMask & 2u) != 0 ? segmentDistance(p, input.triB, input.triC) : 1e6; - float s2 = (edgeMask & 4u) != 0 ? segmentDistance(p, input.triC, input.triA) : 1e6; - inside = -min(s0, min(s1, s2)); + // Use the visible edge segments for the outward fringe. A clipped + // stroke's original edges may extend beyond the cut. + bool clippedStroke = (edgeFlags & coverageSourceFlag) != 0u; + uint fringeMask = clippedStroke ? edgeMask : coverageMask; + float s0 = (fringeMask & 1u) != 0 ? segmentDistance(p, input.triA, input.triB) : 1e6; + float s1 = (fringeMask & 2u) != 0 ? segmentDistance(p, input.triB, input.triC) : 1e6; + float s2 = (fringeMask & 4u) != 0 ? segmentDistance(p, input.triC, input.triA) : 1e6; + float opposite = strokeQuad && !clippedStroke ? segmentDistance(p, oppositeStart, oppositeEnd) : 1e6; + inside = -min(opposite, min(s0, min(s1, s2))); } - float coverage = edgeMask == 0 ? 1 : saturate(0.5 + inside / pixel); + float coverage = coverageMask == 0 ? 1 : saturate(0.5 + inside / pixel); float4 shade = saturate(input.color); return float4(shade.rgb*coverage*shade.a, shade.a*coverage); } diff --git a/internal/platform/windows/shaders/textFragment.dxbc b/internal/platform/windows/shaders/textFragment.dxbc index d11331f54bfdd84dda5fe70cd93a77865aaaeb80..eabaace9a75ba3a739dd95d3ac5db91f9bc2302e 100644 GIT binary patch delta 127 zcmbOrGC@SdCBn%$V{>fh?w#`jznM1D0~~;uEFe6&mqnbF8OREp zJds6QGz>`%NR$nTnJ4dMF_3fi4|5H2W(W!L^mPpO2GNcn!U;q;Gi>H&Wn~2bOOP4M delta 131 zcmbOrGC@SdCBn)1cEWqTJ-@tL7ud9F9h?`1KNa|?2GX9x-MbOaGjAi^0$_&NrAGpt^{nVXfB6#$++ B8sGo` diff --git a/internal/platform/windows/shaders/textVertex.dxbc b/internal/platform/windows/shaders/textVertex.dxbc index 6e01f92827ac42a32d69bda17fc7eda6d176b49a..9fad70a40c16bd5383682b9812baeebba20de0fe 100644 GIT binary patch delta 222 zcmaDM@I}DTCBn&>BUL7xTYbd>O%G}R0=j0_A6B^(S4tU%fXhy$1z7+Qe%1q%bi zjg5xfEQT&1B~Soj0wow&xEUCHki>x+z$P&BFfas8&Seo73qzA-1FB%=nLLX{U&q-$ z%r(fFAtcDt*D=@|L_2~AClKMxusYboHR1&m&?O9v47(eB a#-hoU>~?G%MhXH9Y?JS@iBCSkz5oDxuP74$ delta 223 zcmew&@It`QCBn&h$?@fyB?h-yO2J46(a)!Lk0%}11pd=0pb8=28I?Oe!;@P zaAu<+H;bVYNC^}GB^ZDb3_L)FJDNDi1ZExv2A|2fEaGB;NU|U%8xS+{O`gS~uj3Zv z=*|!l 0 { orientation = 1 } + coveragePoints, coverageFlags := pts, rc.EdgeMask + coverageOrientation := orientation + source, hasSource := rc.StrokeCoverage() + if hasSource { + coveragePoints, coverageFlags = source.Points, source.EdgeMask + a, b, c := coveragePoints[0], coveragePoints[1], coveragePoints[2] + if cross2(b.X-a.X, b.Y-a.Y, c.X-a.X, c.Y-a.Y) > 0 { + coverageOrientation = 1 + } else { + coverageOrientation = -1 + } + } + strokeQuad := coverageFlags&scene.StrokeQuadEdgeMask != 0 + coverageEdges := coverageFlags & 7 + fa, fb, fc := coveragePoints[0], coveragePoints[1], coveragePoints[2] + var strokeWidth, oppositeX, oppositeY, oppositeEndX, oppositeEndY float32 + firstHalf := coverageEdges&1 != 0 + if strokeQuad { + if firstHalf { + strokeWidth = coverageOrientation * edgeDistance(fc.X, fc.Y, fa.X, fa.Y, fb.X, fb.Y) + oppositeX, oppositeY = fc.X, fc.Y + oppositeEndX, oppositeEndY = fc.X+(fb.X-fa.X), fc.Y+(fb.Y-fa.Y) + } else { + strokeWidth = coverageOrientation * edgeDistance(fb.X, fb.Y, fc.X, fc.Y, fa.X, fa.Y) + oppositeX, oppositeY = fb.X, fb.Y + oppositeEndX, oppositeEndY = fb.X+(fa.X-fc.X), fb.Y+(fa.Y-fc.Y) + } + } px := [3][2]float32{{ax, ay}, {bx, by}, {cx, cy}} for y := box.Top; y < box.Bottom; y++ { dy := float32(y) + 0.5 @@ -249,18 +277,29 @@ func drawTriangle(c *Canvas, area render.Scissor, rc *render.Rectangle, scale fl } const far = 1e6 d0, d1, d2 := float32(far), float32(far), float32(far) - if edgeMask&1 != 0 { - d0 = orientation * edgeDistance(ppx, py, ax, ay, bx, by) + if coverageEdges&1 != 0 { + d0 = coverageOrientation * edgeDistance(ppx, py, fa.X, fa.Y, fb.X, fb.Y) } - if edgeMask&2 != 0 { - d1 = orientation * edgeDistance(ppx, py, bx, by, cx, cy) + if coverageEdges&2 != 0 { + d1 = coverageOrientation * edgeDistance(ppx, py, fb.X, fb.Y, fc.X, fc.Y) } - if edgeMask&4 != 0 { - d2 = orientation * edgeDistance(ppx, py, cx, cy, ax, ay) + if coverageEdges&4 != 0 { + d2 = coverageOrientation * edgeDistance(ppx, py, fc.X, fc.Y, fa.X, fa.Y) } inside := min(d0, min(d1, d2)) + if strokeQuad { + // The internal diagonal determines ownership only. The opposite + // side can be closer to a pixel center even in this half. + longEdge := d2 + if firstHalf { + longEdge = d0 + } + inside = min(inside, strokeWidth-longEdge) + } if inside < 0 { - // An acute offset line must not paint past the actual ends. + // The clipped mesh still supplies the visible line segments + // for outward feathering. The source's longer segments could + // extend a fringe past the end of the cut. s0, s1, s2 := float32(far), float32(far), float32(far) if edgeMask&1 != 0 { s0 = segmentDistance(ppx, py, ax, ay, bx, by) @@ -271,10 +310,14 @@ func drawTriangle(c *Canvas, area render.Scissor, rc *render.Rectangle, scale fl if edgeMask&4 != 0 { s2 = segmentDistance(ppx, py, cx, cy, ax, ay) } - inside = -min(s0, min(s1, s2)) + outside := min(s0, min(s1, s2)) + if strokeQuad && !hasSource { + outside = min(outside, segmentDistance(ppx, py, oppositeX, oppositeY, oppositeEndX, oppositeEndY)) + } + inside = -outside } coverage := float32(1) - if edgeMask != 0 { + if coverageEdges != 0 { coverage = clamp01(0.5 + inside/ps) } // The color at this point of a shaded face (flat when the three are equal). diff --git a/internal/reloadwire/codec.go b/internal/reloadwire/codec.go index 4a206244a..ad42907a4 100644 --- a/internal/reloadwire/codec.go +++ b/internal/reloadwire/codec.go @@ -9,7 +9,7 @@ import ( ) const ( - ProtocolVersion = 30 + ProtocolVersion = 31 MaxFrameBytes = 32 << 20 MaxStateBytes = 8 << 20 maxItems = 200_000 @@ -496,6 +496,14 @@ func encodeCanvas(value CanvasSnapshot) ([]byte, error) { result.bool(triangle.Shaded) result.u16(triangle.Layer) result.u8(triangle.EdgeMask) + result.bool(triangle.Coverage != nil) + if coverage := triangle.Coverage; coverage != nil { + for _, point := range coverage.Points { + result.f32(point.X) + result.f32(point.Y) + } + result.u8(coverage.EdgeMask) + } encodeRect(&result, triangle.ClipOf) result.bool(triangle.HasClip) result.u32(triangle.Order) @@ -635,6 +643,14 @@ func decodeCanvas(data []byte) (CanvasSnapshot, error) { triangle.Shaded = value.bool() triangle.Layer = value.u16() triangle.EdgeMask = value.u8() + if value.bool() { + coverage := new(gfx.StrokeCoverage) + for point := range coverage.Points { + coverage.Points[point] = gfx.Point{X: value.f32(), Y: value.f32()} + } + coverage.EdgeMask = value.u8() + triangle.Coverage = coverage + } triangle.ClipOf, triangle.HasClip = decodeRect(&value), value.bool() triangle.Order = value.u32() result.Triangles[index] = triangle diff --git a/internal/reloadwire/reloadwire_test.go b/internal/reloadwire/reloadwire_test.go index cf7f26bc3..d54a86108 100644 --- a/internal/reloadwire/reloadwire_test.go +++ b/internal/reloadwire/reloadwire_test.go @@ -21,6 +21,12 @@ func TestCanvasCodecPreservesRetainedOutput(t *testing.T) { Points: [3]gfx.Point{{X: 0, Y: 0}, {X: 12, Y: 0}, {X: 0, Y: 9}}, Color: gfx.Color{Red: 1, Alpha: 0.5}, EdgeMask: 1, }) + canvas.DrawIconTransformed(gfx.Icon{ + ViewBox: 24, Stroke: 1, Cap: gfx.CapButt, + Commands: []gfx.PathCommand{gfx.MoveTo(12.25, 2), gfx.LineTo(12.25, 22)}, + }, gfx.Rect{Width: 24, Height: 24}, gfx.Color{Red: 1, Alpha: 1}, gfx.IconTransform{ + Clip: &gfx.IconClip{Bounds: gfx.Rect{Y: 4, Width: 24, Height: 16}}, + }) canvas.Elevate(gfx.Rect{X: 1, Y: 2, Width: 80, Height: 30}, 6, gfx.ShadowMD) canvas.Rounded(gfx.Rect{X: 1, Y: 2, Width: 80, Height: 30}, 6, gfx.Color{Red: 0.2, Green: 0.3, Blue: 0.4, Alpha: 1}) canvas.AppendTriangle(gfx.Triangle{ diff --git a/internal/render/store.go b/internal/render/store.go index b9cfa11ae..c850d78c9 100644 --- a/internal/render/store.go +++ b/internal/render/store.go @@ -17,9 +17,12 @@ type Rectangle struct { Points [3]scene.Point Layer uint16 // EdgeMask selects the triangle edges that receive boundary feathering. - EdgeMask uint8 + // scene.StrokeQuadEdgeMask also enables coverage from the opposite edge. + EdgeMask uint8 + hasStrokeCoverage bool // Shade, when On, gives the triangle the colors of its second and third - // corner; Color is the first's. + // corner; Color is the first's. Flat clipped strokes reuse the same + // slots for coverage coordinates, keeping the instance pointer-free. Shade scene.Shade // Shadow places and blurs a KindShadow instance: Bounds and Radius are the // rectangle that casts it. @@ -32,6 +35,28 @@ type Rectangle struct { Clip scene.Rect } +// SetStrokeCoverage stores a flat clipped stroke's original feathering edges. +func (rectangle *Rectangle) SetStrokeCoverage(coverage scene.StrokeCoverage) { + a, b, c := coverage.Points[0], coverage.Points[1], coverage.Points[2] + rectangle.hasStrokeCoverage = true + rectangle.Shade.Colors = [2]scene.Color{ + {Red: a.X, Green: a.Y, Blue: b.X, Alpha: b.Y}, + {Red: c.X, Green: c.Y, Blue: float32(coverage.EdgeMask)}, + } +} + +// StrokeCoverage returns the original feathering edges of a flat clipped stroke. +func (rectangle Rectangle) StrokeCoverage() (scene.StrokeCoverage, bool) { + if !rectangle.hasStrokeCoverage { + return scene.StrokeCoverage{}, false + } + ab, c := rectangle.Shade.Colors[0], rectangle.Shade.Colors[1] + return scene.StrokeCoverage{ + Points: [3]scene.Point{{X: ab.Red, Y: ab.Green}, {X: ab.Blue, Y: ab.Alpha}, {X: c.Red, Y: c.Green}}, + EdgeMask: uint8(c.Blue), + }, true +} + // VertexColors is the color at each corner of a triangle: all Color for a flat // one, so a renderer that interpolates colors across the face needs no special // case for either. @@ -421,7 +446,7 @@ func rectangleOf(change scene.Change) Rectangle { if change.Shape != nil { shape = *change.Shape } - return Rectangle{ + rectangle := Rectangle{ ID: change.ID, Kind: change.Kind, Bounds: change.Bounds, @@ -432,6 +457,10 @@ func rectangleOf(change scene.Change) Rectangle { Shade: shape.Shade, Shadow: shape.Shadow, } + if shape.Coverage != nil { + rectangle.SetStrokeCoverage(*shape.Coverage) + } + return rectangle } // reindexFrom repoints every slot whose instance is at or after index, @@ -495,10 +524,14 @@ func (store *Store) upsert(change scene.Change) (bool, int, error) { rectangle.Bounds = change.Bounds rectangle.Color = change.Color rectangle.Radius = change.Radius + rectangle.hasStrokeCoverage = false if change.Shape != nil { rectangle.Points = change.Shape.Points rectangle.Shade = change.Shape.Shade rectangle.Shadow = change.Shape.Shadow + if change.Shape.Coverage != nil { + rectangle.SetStrokeCoverage(*change.Shape.Coverage) + } } rectangle.EdgeMask = change.EdgeMask } diff --git a/internal/render/store_test.go b/internal/render/store_test.go index efeec5411..d012e4a6d 100644 --- a/internal/render/store_test.go +++ b/internal/render/store_test.go @@ -214,7 +214,7 @@ func TestStoreInsertsInTheMiddleAlongsideAChangeToItsSuccessor(t *testing.T) { } graph.SetRectangle(second, scene.Rect{X: 20}, scene.Color{Red: 1}) // queued before the insert - inserted, _ := graph.InsertTriangle(graph.Root(), first, [3]scene.Point{{X: 1}, {X: 2}, {X: 3}}, scene.Color{Green: 1}, 5, scene.Shade{}) + inserted, _ := graph.InsertTriangle(graph.Root(), first, [3]scene.Point{{X: 1}, {X: 2}, {X: 3}}, scene.Color{Green: 1}, 5, scene.Shade{}, nil) update, err := store.Apply(graph.DrainChanges(nil)) if err != nil { t.Fatal(err) @@ -248,7 +248,13 @@ func TestStoreKeepsPlaceWhenAShapeChangesKind(t *testing.T) { var store Store store.Apply(graph.DrainChanges(nil)) - graph.SetTriangle(flip, [3]scene.Point{{X: 5}, {X: 6}, {X: 7}}, scene.Color{Blue: 1}, 3, scene.Shade{}) + points := [3]scene.Point{{X: 5}, {X: 6}, {X: 7}} + color := scene.Color{Blue: 1} + coverage := scene.StrokeCoverage{ + Points: [3]scene.Point{{X: 5}, {X: 5, Y: 10}, {X: 7}}, + EdgeMask: scene.StrokeQuadEdgeMask | 1, + } + graph.SetTriangle(flip, points, color, 3, scene.Shade{}, &coverage) update, err := store.Apply(graph.DrainChanges(nil)) if err != nil { t.Fatal(err) @@ -256,14 +262,30 @@ func TestStoreKeepsPlaceWhenAShapeChangesKind(t *testing.T) { if update != (Update{First: 1, Count: 1}) { t.Fatalf("kind change update = %+v", update) } - if got := store.Rectangles()[1]; got.ID != flip || got.Kind != scene.KindTriangle || got.Points[1].X != 6 || got.Bounds != (scene.Rect{}) || got.EdgeMask != 3 { + if got := store.Rectangles()[1]; got.ID != flip || got.Kind != scene.KindTriangle || got.Points != points || got.Bounds != (scene.Rect{}) || + got.EdgeMask != 3 { t.Fatalf("flipped shape = %+v", got) } + if got, ok := store.Rectangles()[1].StrokeCoverage(); !ok || got != coverage { + t.Fatalf("retained coverage = %v, want %+v", got, coverage) + } + updatedCoverage := coverage + if graph.SetTriangle(flip, points, color, 3, scene.Shade{}, &updatedCoverage) { + t.Fatal("identical coverage queued an update") + } + updatedCoverage.Points[1].Y++ + graph.SetTriangle(flip, points, color, 3, scene.Shade{}, &updatedCoverage) + if update, err := store.Apply(graph.DrainChanges(nil)); err != nil || update != (Update{First: 1, Count: 1}) { + t.Fatalf("coverage update = %+v, error = %v", update, err) + } + if got, ok := store.Rectangles()[1].StrokeCoverage(); !ok || got != updatedCoverage { + t.Fatalf("retained coverage = %v, want %+v", got, updatedCoverage) + } graph.SetRoundedRectangle(flip, scene.Rect{X: 8}, scene.Color{}, 3) if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { t.Fatal(err) } - if got := store.Rectangles()[1]; got.Kind != scene.KindRectangle || got.Bounds.X != 8 || got.Radius != 3 { + if got := store.Rectangles()[1]; got.Kind != scene.KindRectangle || got.Bounds.X != 8 || got.Radius != 3 || got.hasStrokeCoverage { t.Fatalf("flipped back = %+v", got) } } diff --git a/internal/render/validate.go b/internal/render/validate.go index 008df193b..b1bc0dc82 100644 --- a/internal/render/validate.go +++ b/internal/render/validate.go @@ -33,14 +33,40 @@ func ValidateRectangles(rectangles []Rectangle) error { return fmt.Errorf("render: triangle %d point %d is non-finite", index, pointIndex) } } - if rectangle.EdgeMask > 7 { + if !validTriangleEdgeMask(rectangle.EdgeMask) { return fmt.Errorf("render: triangle %d has invalid edge mask %d", index, rectangle.EdgeMask) } + if source, ok := rectangle.StrokeCoverage(); ok { + if rectangle.Shade.On || rectangle.EdgeMask > 7 || + source.EdgeMask&scene.StrokeQuadEdgeMask == 0 || !validTriangleEdgeMask(source.EdgeMask) { + return fmt.Errorf("render: triangle %d has invalid stroke coverage", index) + } + for pointIndex, point := range source.Points { + if !finiteFloat(point.X) || !finiteFloat(point.Y) { + return fmt.Errorf("render: triangle %d stroke coverage point %d is non-finite", index, pointIndex) + } + } + } } } return nil } +func validTriangleEdgeMask(mask uint8) bool { + if mask <= 7 { + return true + } + // The first half has long edge 0→1 and an optional start cap 2→0. + // The second has long edge 2→0 and an optional end cap 1→2. + switch mask { + case scene.StrokeQuadEdgeMask | 0b001, scene.StrokeQuadEdgeMask | 0b101, + scene.StrokeQuadEdgeMask | 0b100, scene.StrokeQuadEdgeMask | 0b110: + return true + default: + return false + } +} + func finiteFloat(value float32) bool { return !math.IsNaN(float64(value)) && !math.IsInf(float64(value), 0) } diff --git a/internal/scene/scene.go b/internal/scene/scene.go index 5d7e451ea..324100a4d 100644 --- a/internal/scene/scene.go +++ b/internal/scene/scene.go @@ -46,6 +46,19 @@ type Point struct { Y float32 } +// StrokeQuadEdgeMask marks a triangle as one half of a parallelogram stroke. +// Its long edge is 0→1 when bit 0 is set, or 2→0 otherwise. The opposite edge +// is parallel and passes through the remaining point. Both contribute to +// coverage even though the diagonal gives each pixel to just one triangle. +const StrokeQuadEdgeMask uint8 = 1 << 3 + +// StrokeCoverage is the original half of a stroke quad after clipping has +// divided it into triangles with their own geometry and edge masks. +type StrokeCoverage struct { + Points [3]Point + EdgeMask uint8 +} + // Shade makes a triangle vary from its Color at Points[0] to Colors[0] at // Points[1] and Colors[1] at Points[2], linearly across its face. The zero Shade // leaves the triangle one flat color. @@ -81,9 +94,10 @@ func abs32(value float32) float32 { // Shape is the geometry only a triangle or a shadow carries. Rectangle // changes leave Change.Shape nil, so the common change is small. type Shape struct { - Points [3]Point - Shade Shade - Shadow Shadow + Points [3]Point + Shade Shade + Shadow Shadow + Coverage *StrokeCoverage } // Change is one renderer-facing incremental scene update. @@ -116,6 +130,7 @@ type node struct { edgeMask uint8 shade Shade shadow Shadow + coverage *StrokeCoverage generation uint32 kind Kind alive bool @@ -165,7 +180,7 @@ func (scene *Scene) Root() ID { // AddGroup creates a retained group below parent. func (scene *Scene) AddGroup(parent ID) (ID, bool) { - return scene.add(parent, KindGroup, Rect{}, Color{}, 0, [3]Point{}, 0, Shade{}, Shadow{}) + return scene.add(parent, KindGroup, Rect{}, Color{}, 0, [3]Point{}, 0, Shade{}, Shadow{}, nil) } // AddRectangle creates a retained rectangle below parent. @@ -175,44 +190,44 @@ func (scene *Scene) AddRectangle(parent ID, bounds Rect, color Color) (ID, bool) // AddRoundedRectangle creates a retained rounded rectangle below parent. func (scene *Scene) AddRoundedRectangle(parent ID, bounds Rect, color Color, radius float32) (ID, bool) { - return scene.add(parent, KindRectangle, bounds, color, radius, [3]Point{}, 0, Shade{}, Shadow{}) + return scene.add(parent, KindRectangle, bounds, color, radius, [3]Point{}, 0, Shade{}, Shadow{}, nil) } // AddTriangle creates one retained vector-mesh triangle below parent. -func (scene *Scene) AddTriangle(parent ID, points [3]Point, color Color, edgeMask uint8, shade Shade) (ID, bool) { - return scene.add(parent, KindTriangle, Rect{}, color, 0, points, edgeMask, shade, Shadow{}) +func (scene *Scene) AddTriangle(parent ID, points [3]Point, color Color, edgeMask uint8, shade Shade, coverage *StrokeCoverage) (ID, bool) { + return scene.add(parent, KindTriangle, Rect{}, color, 0, points, edgeMask, shade, Shadow{}, coverage) } -func (scene *Scene) add(parent ID, kind Kind, bounds Rect, color Color, radius float32, points [3]Point, edgeMask uint8, shade Shade, shadow Shadow) (ID, bool) { +func (scene *Scene) add(parent ID, kind Kind, bounds Rect, color Color, radius float32, points [3]Point, edgeMask uint8, shade Shade, shadow Shadow, coverage *StrokeCoverage) (ID, bool) { parentNode, ok := scene.liveNode(parent) if !ok { return 0, false } - return scene.insert(parent, parentNode.lastChild, kind, bounds, color, radius, points, edgeMask, shade, shadow) + return scene.insert(parent, parentNode.lastChild, kind, bounds, color, radius, points, edgeMask, shade, shadow, coverage) } // InsertRoundedRectangle creates a rounded rectangle below parent, right after // the child previous (the first child when previous is zero), so a shape can // appear in the middle of the paint order without disturbing its neighbours. func (scene *Scene) InsertRoundedRectangle(parent, previous ID, bounds Rect, color Color, radius float32) (ID, bool) { - return scene.insert(parent, previous, KindRectangle, bounds, color, radius, [3]Point{}, 0, Shade{}, Shadow{}) + return scene.insert(parent, previous, KindRectangle, bounds, color, radius, [3]Point{}, 0, Shade{}, Shadow{}, nil) } // InsertShadow creates the soft shadow of a rounded rectangle below parent, right // after the child previous (the first child when previous is zero). func (scene *Scene) InsertShadow(parent, previous ID, bounds Rect, color Color, radius float32, shadow Shadow) (ID, bool) { - return scene.insert(parent, previous, KindShadow, bounds, color, radius, [3]Point{}, 0, Shade{}, shadow) + return scene.insert(parent, previous, KindShadow, bounds, color, radius, [3]Point{}, 0, Shade{}, shadow, nil) } // InsertTriangle creates a triangle below parent, right after the child // previous (the first child when previous is zero). -func (scene *Scene) InsertTriangle(parent, previous ID, points [3]Point, color Color, edgeMask uint8, shade Shade) (ID, bool) { - return scene.insert(parent, previous, KindTriangle, Rect{}, color, 0, points, edgeMask, shade, Shadow{}) +func (scene *Scene) InsertTriangle(parent, previous ID, points [3]Point, color Color, edgeMask uint8, shade Shade, coverage *StrokeCoverage) (ID, bool) { + return scene.insert(parent, previous, KindTriangle, Rect{}, color, 0, points, edgeMask, shade, Shadow{}, coverage) } // insert links a new child of parent after previous. A previous that is not a // child of parent is rejected. -func (scene *Scene) insert(parent, previous ID, kind Kind, bounds Rect, color Color, radius float32, points [3]Point, edgeMask uint8, shade Shade, shadow Shadow) (ID, bool) { +func (scene *Scene) insert(parent, previous ID, kind Kind, bounds Rect, color Color, radius float32, points [3]Point, edgeMask uint8, shade Shade, shadow Shadow, coverage *StrokeCoverage) (ID, bool) { parentNode, ok := scene.liveNode(parent) if !ok || parentNode.kind != KindGroup { return 0, false @@ -237,6 +252,7 @@ func (scene *Scene) insert(parent, previous ID, kind Kind, bounds Rect, color Co child.edgeMask = edgeMask child.shade = shade child.shadow = shadow + child.coverage = coverage id := makeID(index, child.generation) child.previous = previous @@ -282,6 +298,7 @@ func (scene *Scene) SetRoundedRectangle(id ID, bounds Rect, color Color, radius current.edgeMask = 0 current.shade = Shade{} current.shadow = Shadow{} + current.coverage = nil scene.markDirty(id, current) return true } @@ -304,18 +321,20 @@ func (scene *Scene) SetShadow(id ID, bounds Rect, color Color, radius float32, s current.edgeMask = 0 current.shade = Shade{} current.shadow = shadow + current.coverage = nil scene.markDirty(id, current) return true } // SetTriangle updates one retained vector-mesh triangle. A rectangle becomes a // triangle in place and keeps its position in paint order. -func (scene *Scene) SetTriangle(id ID, points [3]Point, color Color, edgeMask uint8, shade Shade) bool { +func (scene *Scene) SetTriangle(id ID, points [3]Point, color Color, edgeMask uint8, shade Shade, coverage *StrokeCoverage) bool { current, ok := scene.liveNode(id) if !ok || current.kind == KindGroup { return false } - if current.kind == KindTriangle && current.points == points && current.color == color && current.edgeMask == edgeMask && current.shade == shade { + if current.kind == KindTriangle && current.points == points && current.color == color && current.edgeMask == edgeMask && + current.shade == shade && (current.coverage == coverage || current.coverage != nil && coverage != nil && *current.coverage == *coverage) { return false } current.kind = KindTriangle @@ -323,6 +342,7 @@ func (scene *Scene) SetTriangle(id ID, points [3]Point, color Color, edgeMask ui current.color = color current.edgeMask = edgeMask current.shade = shade + current.coverage = coverage current.bounds = Rect{} current.radius = 0 current.shadow = Shadow{} @@ -420,7 +440,7 @@ func (scene *Scene) DrainChanges(destination []Change) []Change { var shape *Shape if current.kind == KindTriangle || current.kind == KindShadow { scene.shapeScratch = append(scene.shapeScratch, Shape{ - Points: current.points, Shade: current.shade, Shadow: current.shadow, + Points: current.points, Shade: current.shade, Shadow: current.shadow, Coverage: current.coverage, }) shape = &scene.shapeScratch[len(scene.shapeScratch)-1] } diff --git a/internal/scene/scene_test.go b/internal/scene/scene_test.go index 3b171d8e7..9706ac29d 100644 --- a/internal/scene/scene_test.go +++ b/internal/scene/scene_test.go @@ -186,7 +186,7 @@ func TestSceneInsertsAShapeInTheMiddleOfPaintOrder(t *testing.T) { if !ok { t.Fatal("insert after a child failed") } - head, ok := graph.InsertTriangle(graph.Root(), 0, [3]Point{{X: 1}}, Color{}, 5, Shade{}) + head, ok := graph.InsertTriangle(graph.Root(), 0, [3]Point{{X: 1}}, Color{}, 5, Shade{}, nil) if !ok { t.Fatal("insert as the first child failed") } @@ -225,14 +225,14 @@ func TestSceneLeafChangesKindInPlace(t *testing.T) { id, _ := graph.AddRectangle(graph.Root(), Rect{X: 1, Width: 5}, Color{Alpha: 1}) graph.DrainChanges(nil) - if !graph.SetTriangle(id, [3]Point{{X: 1}, {X: 2}, {X: 3}}, Color{Alpha: 1}, 5, Shade{}) { + if !graph.SetTriangle(id, [3]Point{{X: 1}, {X: 2}, {X: 3}}, Color{Alpha: 1}, 5, Shade{}, nil) { t.Fatal("a rectangle did not become a triangle") } changes := graph.DrainChanges(nil) if len(changes) != 1 || changes[0].Kind != KindTriangle || changes[0].Bounds != (Rect{}) || changes[0].Shape == nil || changes[0].Shape.Points[2].X != 3 || changes[0].EdgeMask != 5 { t.Fatalf("rectangle to triangle = %+v", changes) } - if graph.SetTriangle(id, [3]Point{{X: 1}, {X: 2}, {X: 3}}, Color{Alpha: 1}, 5, Shade{}) { + if graph.SetTriangle(id, [3]Point{{X: 1}, {X: 2}, {X: 3}}, Color{Alpha: 1}, 5, Shade{}, nil) { t.Fatal("setting the same triangle again reported a change") } if !graph.SetRoundedRectangle(id, Rect{X: 9}, Color{Alpha: 1}, 2) { @@ -242,7 +242,7 @@ func TestSceneLeafChangesKindInPlace(t *testing.T) { if len(changes) != 1 || changes[0].Kind != KindRectangle || changes[0].Shape != nil || changes[0].Radius != 2 { t.Fatalf("triangle to rectangle = %+v", changes) } - if graph.SetTriangle(graph.Root(), [3]Point{}, Color{}, 0, Shade{}) || graph.SetRectangle(graph.Root(), Rect{}, Color{}) { + if graph.SetTriangle(graph.Root(), [3]Point{}, Color{}, 0, Shade{}, nil) || graph.SetRectangle(graph.Root(), Rect{}, Color{}) { t.Fatal("a group became a shape") } } @@ -251,18 +251,18 @@ func TestTriangleShadeIsPublishedChangeCheckedAndClearedByARectangle(t *testing. graph := New() points := [3]Point{{X: 1}, {X: 2}, {X: 3}} shade := Shade{On: true, Colors: [2]Color{{Red: 1, Alpha: 1}, {Blue: 1, Alpha: 1}}} - id, _ := graph.AddTriangle(graph.Root(), points, Color{Green: 1, Alpha: 1}, 0, shade) + id, _ := graph.AddTriangle(graph.Root(), points, Color{Green: 1, Alpha: 1}, 0, shade, nil) changes := graph.DrainChanges(nil) if changes[len(changes)-1].Shape == nil || changes[len(changes)-1].Shape.Shade != shade { t.Fatalf("published shape = %+v", changes[len(changes)-1].Shape) } - if graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, shade) { + if graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, shade, nil) { t.Fatal("setting the same shaded triangle reported a change") } - if !graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, Shade{}) { + if !graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, Shade{}, nil) { t.Fatal("dropping the shade reported no change") } - graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, shade) + graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, shade, nil) graph.SetRectangle(id, Rect{Width: 4}, Color{Alpha: 1}) changes = graph.DrainChanges(changes[:0]) if len(changes) != 1 || changes[0].Shape != nil { From f54ffb3ce5144330785ecde8d8546bccc90f0748 Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Fri, 27 Nov 2026 23:12:39 +0800 Subject: [PATCH 05/29] fix(filewatch): report replacement of a watched directory on Windows --- .github/workflows/ci.yml | 2 + app/directory_watch.go | 7 +- internal/filewatch/watch.go | 12 +-- internal/filewatch/watch_windows.go | 109 ++++++++++++++++++++--- internal/filewatch/watch_windows_test.go | 64 +++++++++++++ 5 files changed, 173 insertions(+), 21 deletions(-) create mode 100644 internal/filewatch/watch_windows_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 25e7aa565..f84b3e5af 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -377,6 +377,8 @@ jobs: # on Windows. - name: directory picker initial location run: go test ./internal/platform/windows ./app -run '^Test(FileDialogInitialDirectory|DriverInterceptsOpenDirectory)$' -count=1 -v + - name: Native directory watches + run: go test ./internal/filewatch -count=1 -timeout=1m - name: Material contracts and controls (WARP) run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview|QueuedMenuKeysLeaveTerminalCompositionWithItsOwner|MenuKeysPreserveSystemChordsAndShift|TerminalMenuStopsCapturingWhenWindowLosesFocus|DisabledIMEOffersMenuShortcutDuringComposition)' -count=1 -v - name: Offscreen incremental frame pixels diff --git a/app/directory_watch.go b/app/directory_watch.go index 291ea70ed..0142033a4 100644 --- a/app/directory_watch.go +++ b/app/directory_watch.go @@ -25,9 +25,10 @@ type DirectoryChanges struct { // DirectoryWatch reports changes to the entries of one directory from the // operating system's own notification (inotify, FSEvents, ReadDirectoryChangesW). // -// It does not poll and keeps no timer. An open watch holds one system -// registration and one goroutine blocked on it; closing it releases both, and an -// application that opens none pays nothing. A change wakes the window thread +// It does not poll and keeps no timer. An open watch holds system registrations +// and one goroutine blocked on them. On Windows the watch also follows changes +// to the directory's name when the system lets it watch the parent directory. +// Closing the watch releases these resources. A change wakes the window thread // through the function given at the start, which only hands the news on (for // example Invalidator.Invalidate, whose Config.OnWake then reads it with // Changes). diff --git a/internal/filewatch/watch.go b/internal/filewatch/watch.go index 9a11be6c4..64c2d10b3 100644 --- a/internal/filewatch/watch.go +++ b/internal/filewatch/watch.go @@ -2,12 +2,12 @@ // directory tree, changed, using the // platform's own change notification (inotify, FSEvents, ReadDirectoryChangesW). // -// It does not poll. A Watch owns one operating-system registration and, while it -// is open, one goroutine blocked on the system's wait; closing it releases both, -// and an application that opens no Watch pays nothing. Events carry only the name -// of the entry that changed: editors replace files by writing a temporary one and -// renaming it, so the kinds the platforms report differ and none of them can be -// trusted over looking at the entry afterwards. +// It does not poll. A Watch owns its operating-system registrations and, while +// it is open, one goroutine blocked on the system's wait. Closing it releases +// them, and an application that opens no Watch pays nothing. Events carry only +// the name of the entry that changed: editors replace files by writing a +// temporary one and renaming it, so the kinds the platforms report differ and +// none of them can be trusted over looking at the entry afterwards. package filewatch import ( diff --git a/internal/filewatch/watch_windows.go b/internal/filewatch/watch_windows.go index 255c1c04e..ce0281122 100644 --- a/internal/filewatch/watch_windows.go +++ b/internal/filewatch/watch_windows.go @@ -21,12 +21,16 @@ var ( procCreateEvent = kernel32.NewProc("CreateEventW") procSetEvent = kernel32.NewProc("SetEvent") procWaitMultiple = kernel32.NewProc("WaitForMultipleObjects") + procFindFirstChange = kernel32.NewProc("FindFirstChangeNotificationW") + procFindNextChange = kernel32.NewProc("FindNextChangeNotification") + procFindCloseChange = kernel32.NewProc("FindCloseChangeNotification") ) const ( fileListDirectory = 0x0001 fileFlagOverlapped = 0x40000000 - filterChange = 0x1 | 0x2 | 0x8 | 0x10 | 0x40 // file/dir name, attributes, size, last write, creation + filterChange = 0x1 | syscall.FILE_NOTIFY_CHANGE_DIR_NAME | 0x8 | 0x10 | 0x40 // file/dir name, attributes, size, last write, creation + shareDirectory = syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE | syscall.FILE_SHARE_DELETE actionAdded = 1 actionRemoved = 2 actionModified = 3 @@ -48,6 +52,7 @@ type directoryBackend struct { handle syscall.Handle ioDone syscall.Handle stop syscall.Handle + root rootGuard done chan struct{} once sync.Once // overlapped and the read buffer are written by the system after the call @@ -57,12 +62,15 @@ type directoryBackend struct { } func openBackend(dir string, w *Watch) (backend, error) { - path, err := syscall.UTF16PtrFromString(filepath.Clean(dir)) + absolute, err := filepath.Abs(dir) if err != nil { return nil, err } - handle, err := syscall.CreateFile(path, fileListDirectory, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, nil, + path, err := syscall.UTF16PtrFromString(absolute) + if err != nil { + return nil, err + } + handle, err := syscall.CreateFile(path, fileListDirectory, shareDirectory, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS|fileFlagOverlapped, 0) if err != nil { return nil, &os.PathError{Op: "CreateFile", Path: dir, Err: err} @@ -85,6 +93,7 @@ func openBackend(dir string, w *Watch) (backend, error) { syscall.CloseHandle(handle) return nil, &os.PathError{Op: "ReadDirectoryChangesW", Path: dir, Err: err} } + b.root = watchRootName(absolute, path, handle) go b.run(w) return b, nil } @@ -107,6 +116,51 @@ func (b *directoryBackend) close() { }) } +// ReadDirectoryChangesW follows the opened directory and never reports changes +// to that directory's own name. Watch direct directory names in its parent +// as well. This notification is only a signal: compare file IDs to distinguish +// a sibling change from a move or a different directory at the same path. +type rootGuard struct { + event syscall.Handle + path *uint16 + info syscall.ByHandleFileInformation +} + +func watchRootName(dir string, path *uint16, handle syscall.Handle) rootGuard { + parent := filepath.Dir(dir) + if parent == dir { + return rootGuard{} // volume root + } + var info syscall.ByHandleFileInformation + if syscall.GetFileInformationByHandle(handle, &info) != nil { + return rootGuard{} + } + parentPath, err := syscall.UTF16PtrFromString(parent) + if err != nil { + return rootGuard{} + } + event, _, _ := procFindFirstChange.Call(uintptr(unsafe.Pointer(parentPath)), 0, syscall.FILE_NOTIFY_CHANGE_DIR_NAME) + if syscall.Handle(event) == syscall.InvalidHandle { + // A caller can have access to the directory without being able to + // list its parent. Keep delivering the directory's own changes. + return rootGuard{} + } + return rootGuard{event: syscall.Handle(event), path: path, info: info} +} + +func (g *rootGuard) sameDirectory() bool { + h, err := syscall.CreateFile(g.path, 0, shareDirectory, nil, + syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) + if err != nil { + return false + } + defer syscall.CloseHandle(h) + var current syscall.ByHandleFileInformation + return syscall.GetFileInformationByHandle(h, ¤t) == nil && + current.VolumeSerialNumber == g.info.VolumeSerialNumber && + current.FileIndexHigh == g.info.FileIndexHigh && current.FileIndexLow == g.info.FileIndexLow +} + // issue starts the next overlapped read. The first one is made before Open // returns, because changes are only buffered by the system once a read has been // issued; later ones follow a completion, and the system keeps what happened in @@ -127,20 +181,50 @@ func (b *directoryBackend) issue() error { func (b *directoryBackend) run(w *Watch) { defer close(b.done) - for { - handles := [2]syscall.Handle{b.ioDone, b.stop} - which, _, _ := procWaitMultiple.Call(2, uintptr(unsafe.Pointer(&handles[0])), 0, infinite) - var n uint32 - if which != waitObject0 { - // Stopped (or the wait failed): abandon the read and wait for the system - // to stop writing into the buffer before it is released. + pending := true + defer func() { + if pending { + // Wait for the system to stop writing into the buffer before it + // is released. procCancelIoEx.Call(uintptr(b.handle), uintptr(unsafe.Pointer(&b.overlapped))) + var n uint32 procGetOverlappedResult.Call(uintptr(b.handle), uintptr(unsafe.Pointer(&b.overlapped)), uintptr(unsafe.Pointer(&n)), 1) - if which != waitObject0+1 { + } + }() + // Stop takes priority over further changes, and root changes take + // priority over events that may have come from the old directory. + handles := []syscall.Handle{b.stop, b.ioDone} + if b.root.event != 0 { + defer procFindCloseChange.Call(uintptr(b.root.event)) + handles = []syscall.Handle{b.stop, b.root.event, b.ioDone} + // The path may have changed before the parent notification was armed. + if !b.root.sameDirectory() { + w.postResync() + return + } + } + readReady := waitObject0 + uintptr(len(handles)-1) + for { + which, _, _ := procWaitMultiple.Call(uintptr(len(handles)), uintptr(unsafe.Pointer(&handles[0])), 0, infinite) + switch { + case which == waitObject0: + return + case which == readReady: + pending = false + case b.root.event != 0 && which == waitObject0+1: + // Rearm before looking up the path, so a change during the lookup + // either shows up in the lookup or signals the next wait. + ok, _, _ := procFindNextChange.Call(uintptr(b.root.event)) + if ok == 0 || !b.root.sameDirectory() { w.postResync() + return } + continue + default: + w.postResync() return } + var n uint32 r, _, err := procGetOverlappedResult.Call(uintptr(b.handle), uintptr(unsafe.Pointer(&b.overlapped)), uintptr(unsafe.Pointer(&n)), 0) if r == 0 { if errno, ok := err.(syscall.Errno); !ok || errno != errorOperationAbort { @@ -157,6 +241,7 @@ func (b *directoryBackend) run(w *Watch) { w.postResync() return } + pending = true } } diff --git a/internal/filewatch/watch_windows_test.go b/internal/filewatch/watch_windows_test.go new file mode 100644 index 000000000..f380d167d --- /dev/null +++ b/internal/filewatch/watch_windows_test.go @@ -0,0 +1,64 @@ +package filewatch + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func TestWindowsReplacingWatchedDirectoryAsksForResync(t *testing.T) { + for _, tree := range []bool{false, true} { + name := "directory" + if tree { + name = "tree" + } + t.Run(name, func(t *testing.T) { + parent := t.TempDir() + root := filepath.Join(parent, "workspace") + moved := filepath.Join(t.TempDir(), "moved") + if err := os.Mkdir(root, 0o700); err != nil { + t.Fatal(err) + } + woken := make(chan struct{}, 1) + watch, err := openWatch(root, tree, nil, func() { + select { + case woken <- struct{}{}: + default: + } + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(watch.Close) + + if err := os.Rename(root, moved); err != nil { + t.Fatalf("move watched root: %v", err) + } + if err := os.Mkdir(root, 0o700); err != nil { + t.Fatalf("recreate watched root: %v", err) + } + select { + case <-woken: + if p := watch.Drain(nil); !p.Resync || len(p.Names) != 0 { + t.Fatalf("root replacement reported %+v, want only Resync", p) + } + case <-time.After(4 * time.Second): + t.Fatal("root replacement did not wake the watch") + } + watch.Close() + if err := os.Remove(moved); err != nil { + t.Fatalf("remove the old root after Close: %v", err) + } + if err := os.Mkdir(moved, 0o700); err != nil { + t.Fatalf("reuse the old root path after Close: %v", err) + } + if err := os.RemoveAll(parent); err != nil { + t.Fatalf("remove the watched parent after Close: %v", err) + } + if err := os.Mkdir(parent, 0o700); err != nil { + t.Fatalf("reuse the watched parent path after Close: %v", err) + } + }) + } +} From a2d34fd47d7e15d826291d17ae6e7a0513b50357 Mon Sep 17 00:00:00 2001 From: darrenjindai <279011405@qq.com> Date: Fri, 27 Nov 2026 23:12:53 +0800 Subject: [PATCH 06/29] feat(app): own notification activation on the application event loop --- app/application.go | 9 +- app/application_native.go | 18 ++ app/capabilities.go | 3 + app/capabilities_native.go | 2 +- app/capability_notification_native.go | 5 + app/capability_notification_other.go | 5 + app/notification.go | 213 +++++++++++++++ app/notification_darwin.go | 21 ++ app/notification_test.go | 249 ++++++++++++++++++ app/notification_unsupported.go | 7 + app/notification_windows.go | 16 ++ docs/notification-activation.md | 101 +++++++ examples/guides/notifications/main.go | 43 +++ .../platform/darwin/notification_darwin.go | 91 +++++++ .../darwin/notification_darwin_test.go | 47 ++++ internal/platform/darwin/system_darwin.h | 3 + internal/platform/darwin/system_darwin.m | 93 +++++++ internal/platform/notification_callbacks.go | 43 +++ .../platform/notification_callbacks_test.go | 32 +++ .../platform/windows/notification_windows.go | 170 ++++++++++++ .../windows/notification_windows_test.go | 156 +++++++++++ internal/platform/windows/post_windows.go | 5 + internal/platform/windows/system_windows.go | 13 +- 23 files changed, 1338 insertions(+), 7 deletions(-) create mode 100644 app/capability_notification_native.go create mode 100644 app/capability_notification_other.go create mode 100644 app/notification.go create mode 100644 app/notification_darwin.go create mode 100644 app/notification_test.go create mode 100644 app/notification_unsupported.go create mode 100644 app/notification_windows.go create mode 100644 docs/notification-activation.md create mode 100644 examples/guides/notifications/main.go create mode 100644 internal/platform/darwin/notification_darwin.go create mode 100644 internal/platform/darwin/notification_darwin_test.go create mode 100644 internal/platform/notification_callbacks.go create mode 100644 internal/platform/notification_callbacks_test.go create mode 100644 internal/platform/windows/notification_windows.go create mode 100644 internal/platform/windows/notification_windows_test.go diff --git a/app/application.go b/app/application.go index e06cf227b..cb2dfeaac 100644 --- a/app/application.go +++ b/app/application.go @@ -36,6 +36,8 @@ type WindowControl interface { // Host is the event loop an Application runs on. The native backends provide // one over their platform adapters; a development runner such as package // headless provides one to drive an application without a window. +// A host may additionally implement ShowNotification(Notification, +// NotificationEvents) (NotificationControl, error) for interactive notifications. type Host interface { // OpenWindow creates and presents a window. closed must be called exactly // once, after the window has released its resources. @@ -248,8 +250,10 @@ type Application struct { // active is the window that last became the one the user works in, which is // where the application menu bar's commands take effect, as a native menu's // key equivalents do. - active *Window - openedAny bool + active *Window + openedAny bool + notifications map[*NotificationHandle]struct{} + notificationsClosed bool } // OpenWindow creates and presents one independent retained window. @@ -434,6 +438,7 @@ func (application *Application) SetProgress(fraction float32) { // goroutine. func (application *Application) Quit() { if application != nil && application.host != nil { + application.closeNotifications() application.host.Quit() } } diff --git a/app/application_native.go b/app/application_native.go index 0ec3ae514..2417b33ec 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -18,9 +18,16 @@ import ( // start the native application from main to satisfy AppKit's main-thread requirement. func RunApplication(start func(*Application) error) error { attendFaults() + var owned *Application + defer func() { + if owned != nil { + owned.closeNotifications() + } + }() if applicationRunner != nil { return applicationRunner(func(host Host) error { application := &Application{host: host} + owned = application if err := start(application); err != nil { return err } @@ -35,6 +42,7 @@ func RunApplication(start func(*Application) error) error { defer runtime.UnlockOSThread() return runNativeApplication(func(native platform.Application) error { application := &Application{host: nativeHost{native}} + owned = application if err := start(application); err != nil { return err } @@ -48,6 +56,8 @@ func RunApplication(start func(*Application) error) error { // nativeHost is the Host over a platform adapter. type nativeHost struct{ native platform.Application } +var _ notificationHost = nativeHost{} + func (host nativeHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func()) (WindowControl, error) { windowConfig, painter, cleanup, err := prepareNativeWindow(config, canvas) if err != nil { @@ -282,3 +292,11 @@ func (item nativeStatusItem) SetStatusHover(handler func(StatusAnchor, bool)) bo }) } func (item nativeStatusItem) RefreshMenu() { item.item.RefreshMenu() } + +func (host nativeHost) ShowNotification(value Notification, events NotificationEvents) (NotificationControl, error) { + cancel, err := nativeShowNotification(value, events) + if err != nil { + return nil, err + } + return &nativeNotificationControl{cancel: cancel}, nil +} diff --git a/app/capabilities.go b/app/capabilities.go index 4b072b23e..87a4d5245 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -63,6 +63,9 @@ const ( // them. Only Windows takes them; macOS and Linux file managers read files // by path and cannot ask for a paste's content later. CapabilityClipboardFilePromise + // CapabilityNotificationActivation means an application can own cancellable + // system notifications and receive activation while its loop is running. + CapabilityNotificationActivation ) // Capabilities is a set of platform integrations. diff --git a/app/capabilities_native.go b/app/capabilities_native.go index 988d13dd1..5dbd9c013 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -42,6 +42,6 @@ func nativeCapabilities() Capabilities { } else { capabilities |= CapabilityWindowMaximize } - capabilities |= capabilityTransparentWindow + capabilities |= capabilityTransparentWindow | capabilityNotificationActivation return Capabilities(capabilities) } diff --git a/app/capability_notification_native.go b/app/capability_notification_native.go new file mode 100644 index 000000000..2c91627ad --- /dev/null +++ b/app/capability_notification_native.go @@ -0,0 +1,5 @@ +//go:build (darwin && !ios) || windows + +package app + +const capabilityNotificationActivation = CapabilityNotificationActivation diff --git a/app/capability_notification_other.go b/app/capability_notification_other.go new file mode 100644 index 000000000..2bf6cb7a3 --- /dev/null +++ b/app/capability_notification_other.go @@ -0,0 +1,5 @@ +//go:build (!darwin && !windows) || ios + +package app + +const capabilityNotificationActivation Capability = 0 diff --git a/app/notification.go b/app/notification.go new file mode 100644 index 000000000..58cb51f92 --- /dev/null +++ b/app/notification.go @@ -0,0 +1,213 @@ +package app + +import ( + "fmt" + "strings" + "sync" + "unicode/utf8" + + "github.com/vivaui/viva/internal/diag" +) + +// NotificationControl is the cancellable notification an optional Host supplies. +// Close requests native withdrawal and invalidates callbacks. It is idempotent +// and safe from any goroutine. A host returns a non-nil control on success. +type NotificationControl interface{ Close() } + +// Application delivers NotificationEvents on its event-loop thread. Hosts may +// signal their supplied callbacks from any thread; Application queues them. +// Both callbacks are optional. OnError reports asynchronous authorization or +// delivery failure; errors without a handler go to the diagnostic sink. +// Activation or failure consumes the handle, so only one terminal event runs. +type NotificationEvents struct { + OnActivate func() + OnError func(error) +} + +type notificationHost interface { + ShowNotification(Notification, NotificationEvents) (NotificationControl, error) +} + +// NotificationHandle owns one notification. Close requests withdrawal and discards +// queued callbacks. A callback already running may finish. It is nil-safe, +// idempotent and safe from any goroutine. Applications close handles whose +// targets become stale; Quit and the end of RunApplication close all remaining +// handles automatically. A native dismissal does not promise a terminal event. +type NotificationHandle struct { + mu sync.Mutex + closed bool + queued bool + control NotificationControl + application *Application + callback func() +} + +func (handle *NotificationHandle) Close() { handle.finish(false) } + +// finish claims a terminal event before releasing native ownership. No user or +// host code runs under either mutex, so Close and callbacks may be reentrant. +func (handle *NotificationHandle) finish(deliver bool) func() { + if handle == nil { + return nil + } + handle.mu.Lock() + if handle.closed { + handle.mu.Unlock() + return nil + } + handle.closed = true + control := handle.control + owner := handle.application + callback := handle.callback + handle.callback = nil + if !deliver { + callback = nil + } + handle.control = nil + handle.application = nil + handle.mu.Unlock() + if owner != nil { + owner.mu.Lock() + delete(owner.notifications, handle) + owner.mu.Unlock() + } + if control != nil { + control.Close() + } + return callback +} + +func (handle *NotificationHandle) attach(control NotificationControl) { + handle.mu.Lock() + closed := handle.closed + if !closed { + handle.control = control + } + handle.mu.Unlock() + if closed { + control.Close() + } +} + +// post bounds each handle to one queued terminal callback, even for a custom +// host that races activation against failure. Close can still cancel that post. +func (handle *NotificationHandle) post(callback func()) { + handle.mu.Lock() + if handle.closed || handle.queued { + handle.mu.Unlock() + return + } + handle.queued = true + handle.callback = callback + owner := handle.application + handle.mu.Unlock() + // The queue retains only this handle. Close clears callback and owner even + // if a custom host stops its loop before processing the queued method. + owner.Post(handle.deliver) +} + +func (handle *NotificationHandle) deliver() { + if callback := handle.finish(true); callback != nil { + callback() + } +} + +// ShowNotification requests an interactive system notification. Call it from +// startup or a window callback, like AddStatusItem. The request does not wait +// for authorization UI or user interaction. Success accepts a request, rather than +// promising the OS will display it; system policy may suppress it. +// +// Content must be nonblank valid UTF-8 without NUL. Native limits may truncate +// title/body. The returned handle is application-owned until activation, error +// or Close. Callbacks run on the event loop and may open or restore windows. +// CapabilityNotificationActivation reports native support. Custom/headless +// hosts opt in with ShowNotification(Notification, NotificationEvents) +// (NotificationControl,error); unsupported hosts return ErrUnsupported. +// +// macOS requires an application bundle identifier and system permission. Windows +// uses notification-area balloons, not a persistent toast-activation service. +// Activation works only while this process and its application loop are alive. +// SendNotification remains the compatible title/body-only API. +func (application *Application) ShowNotification(value Notification, events NotificationEvents) (*NotificationHandle, error) { + if application == nil || application.host == nil { + return nil, fmt.Errorf("app: application is not running") + } + if !utf8.ValidString(value.Title) || !utf8.ValidString(value.Body) || strings.ContainsRune(value.Title, 0) || strings.ContainsRune(value.Body, 0) { + return nil, fmt.Errorf("app: notification text must be valid UTF-8 without NUL") + } + if strings.TrimSpace(value.Title) == "" && strings.TrimSpace(value.Body) == "" { + return nil, fmt.Errorf("app: notification requires title or body") + } + host, ok := application.host.(notificationHost) + if !ok { + return nil, fmt.Errorf("%w: notification activation", ErrUnsupported) + } + handle := &NotificationHandle{application: application} + application.mu.Lock() + if application.notificationsClosed { + application.mu.Unlock() + return nil, fmt.Errorf("app: application notifications are closed") + } + if application.notifications == nil { + application.notifications = make(map[*NotificationHandle]struct{}) + } + application.notifications[handle] = struct{}{} + application.mu.Unlock() + control, err := host.ShowNotification(value, NotificationEvents{ + OnActivate: func() { handle.post(events.OnActivate) }, + OnError: func(err error) { + if err == nil { + err = fmt.Errorf("app: notification host reported an unspecified failure") + } + handle.post(func() { + if events.OnError != nil { + events.OnError(err) + } else { + reportNotificationError(err) + } + }) + }, + }) + if err != nil { + handle.Close() + return nil, err + } + if control == nil { + handle.Close() + return nil, fmt.Errorf("app: notification host returned no control") + } + handle.attach(control) + return handle, nil +} + +func (application *Application) closeNotifications() { + application.mu.Lock() + application.notificationsClosed = true + handles := application.notifications + application.notifications = nil + application.mu.Unlock() + for handle := range handles { + handle.Close() + } +} + +// nativeNotificationControl adapts a platform cancellation without leaking an +// internal type through the optional public Host contract. +type nativeNotificationControl struct { + once sync.Once + cancel func() +} + +func (control *nativeNotificationControl) Close() { + control.once.Do(func() { + if control.cancel != nil { + control.cancel() + } + }) +} + +func reportNotificationError(err error) { + if err != nil { + diag.Report(diag.Error, "notification", "delivery-failed", err.Error()) + } +} diff --git a/app/notification_darwin.go b/app/notification_darwin.go new file mode 100644 index 000000000..f9d3ec173 --- /dev/null +++ b/app/notification_darwin.go @@ -0,0 +1,21 @@ +//go:build darwin && !ios + +package app + +import ( + "github.com/vivaui/viva/internal/platform" + darwinplatform "github.com/vivaui/viva/internal/platform/darwin" +) + +func nativeShowNotification(notification Notification, events NotificationEvents) (func(), error) { + failed := func(err error) { + err = darwinNotificationError(err) + if events.OnError != nil { + events.OnError(err) + } else { + reportNotificationError(err) + } + } + cancel, err := darwinplatform.ShowNotification(notification.Title, notification.Body, platform.NotificationEvents{Activated: events.OnActivate, Failed: failed}) + return cancel, darwinNotificationError(err) +} diff --git a/app/notification_test.go b/app/notification_test.go new file mode 100644 index 000000000..4d2af2fc7 --- /dev/null +++ b/app/notification_test.go @@ -0,0 +1,249 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + + "github.com/vivaui/viva/gfx" +) + +type notificationTestControl struct{ closed atomic.Int32 } + +func (control *notificationTestControl) Close() { control.closed.Add(1) } + +type notificationTestHost struct { + fakeHost + mu sync.Mutex + posts []func() + events []NotificationEvents + controls []*notificationTestControl + show func(NotificationEvents) + err error +} + +func (host *notificationTestHost) Post(fn func()) { + host.mu.Lock() + host.posts = append(host.posts, fn) + host.mu.Unlock() +} +func (host *notificationTestHost) drain() { + for { + host.mu.Lock() + if len(host.posts) == 0 { + host.mu.Unlock() + return + } + fn := host.posts[0] + host.posts = host.posts[1:] + host.mu.Unlock() + fn() + } +} +func (host *notificationTestHost) ShowNotification(_ Notification, events NotificationEvents) (NotificationControl, error) { + host.events = append(host.events, events) + if host.err != nil { + return nil, host.err + } + control := ¬ificationTestControl{} + host.controls = append(host.controls, control) + if host.show != nil { + host.show(events) + } + return control, nil +} + +func TestNotificationDispatchesOnLoopAndConsumesOnlyOneEvent(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + calls := 0 + handle, err := application.ShowNotification(Notification{Title: "测试通知"}, NotificationEvents{OnActivate: func() { calls++; application.Post(func() { calls++ }) }}) + if err != nil { + t.Fatal(err) + } + host.events[0].OnActivate() + host.events[0].OnActivate() + host.events[0].OnError(errors.New("late failure")) + if calls != 0 { + t.Fatal("native callback changed UI state before the event loop") + } + host.drain() + if calls != 2 || host.controls[0].closed.Load() != 1 || len(application.notifications) != 0 { + t.Fatal("terminal event did not consume ownership exactly once", calls) + } + handle.Close() + if host.controls[0].closed.Load() != 1 || handle.application != nil || handle.callback != nil { + t.Fatal("consumed control retained its owner or closed twice") + } +} + +func TestNotificationCloseCancelsQueuedActivationConcurrently(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + calls := 0 + handle, err := application.ShowNotification(Notification{Body: "body"}, NotificationEvents{OnActivate: func() { calls++ }}) + if err != nil { + t.Fatal(err) + } + host.events[0].OnActivate() + var jobs sync.WaitGroup + for range 32 { + jobs.Add(1) + go func() { defer jobs.Done(); handle.Close() }() + } + jobs.Wait() + host.drain() + if calls != 0 || host.controls[0].closed.Load() != 1 { + t.Fatal("Close did not discard queued callbacks") + } + var empty *NotificationHandle + empty.Close() + (&NotificationHandle{}).Close() +} + +func TestNotificationErrorsValidationAndOptionalCallbacks(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + for _, value := range []Notification{{}, {Title: "\x00"}, {Body: string([]byte{0xff})}} { + if _, err := application.ShowNotification(value, NotificationEvents{}); err == nil { + t.Fatal("invalid content reached host") + } + } + if len(host.events) != 0 { + t.Fatal("invalid request reached host") + } + failure := errors.New("authorization denied") + got := error(nil) + handle, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{OnError: func(err error) { got = err }}) + if err != nil { + t.Fatal(err) + } + host.events[0].OnError(failure) + host.drain() + handle.Close() + if got != failure || len(application.notifications) != 0 { + t.Fatal("asynchronous error lost ownership or identity", got) + } + host.err = failure + if _, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{}); err != failure || len(application.notifications) != 0 { + t.Fatal("immediate failure retained a handle", err) + } + host.err = nil + handle, err = application.ShowNotification(Notification{Body: "callbacks optional"}, NotificationEvents{}) + if err != nil { + t.Fatal(err) + } + handle.Close() + unsupported := &Application{host: &fakeHost{}} + if _, err := unsupported.ShowNotification(Notification{Title: "test"}, NotificationEvents{}); !errors.Is(err, ErrUnsupported) { + t.Fatal("host support was inferred from the OS", err) + } +} + +func TestNotificationSynchronousHostEventAndCloseBeforeAttach(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + calls := 0 + host.show = func(events NotificationEvents) { events.OnActivate(); application.Quit() } + _, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{OnActivate: func() { calls++ }}) + if err != nil { + t.Fatal(err) + } + host.drain() + if calls != 0 || host.controls[0].closed.Load() != 1 || len(application.notifications) != 0 { + t.Fatal("late control escaped application shutdown") + } + if _, err := application.ShowNotification(Notification{Title: "after quit"}, NotificationEvents{}); err == nil { + t.Fatal("quit application accepted notification") + } +} + +func TestNotificationRunApplicationCleanup(t *testing.T) { + host := ¬ificationTestHost{} + previous := applicationRunner + defer func() { applicationRunner = previous }() + applicationRunner = func(start func(Host) error) error { return start(host) } + calls := 0 + err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{Title: "test"}, &gfx.Canvas{}); err != nil { + return err + } + _, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{OnActivate: func() { calls++ }}) + return err + }) + defer func() { + for _, window := range host.windows { + window.Close() + } + }() + if err != nil { + t.Fatal(err) + } + host.events[0].OnActivate() + host.drain() + if calls != 0 || host.controls[0].closed.Load() != 1 { + t.Fatal("notification survived the application runner") + } +} + +func TestNotificationConcurrentCallbacksAndCancellation(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + calls := atomic.Int32{} + handle, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{OnActivate: func() { calls.Add(1) }, OnError: func(error) { calls.Add(1) }}) + if err != nil { + t.Fatal(err) + } + events := host.events[0] + var jobs sync.WaitGroup + for index := range 48 { + jobs.Add(1) + go func() { + defer jobs.Done() + switch index % 3 { + case 0: + handle.Close() + case 1: + events.OnActivate() + case 2: + events.OnError(errors.New("failed")) + } + }() + } + jobs.Wait() + host.drain() + if calls.Load() != 0 || host.controls[0].closed.Load() != 1 { + t.Fatal("cancellation lost the callback race") + } +} + +func TestNotificationStartupFailureCleansUp(t *testing.T) { + for _, failStartup := range []bool{true, false} { + t.Run(map[bool]string{true: "start error", false: "no window"}[failStartup], func(t *testing.T) { + host := ¬ificationTestHost{} + previous := applicationRunner + defer func() { applicationRunner = previous }() + applicationRunner = func(start func(Host) error) error { return start(host) } + sentinel := errors.New("startup failed") + err := RunApplication(func(application *Application) error { + if _, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{}); err != nil { + return err + } + if failStartup { + return sentinel + } + return nil + }) + want := sentinel + if !failStartup { + want = ErrNoWindows + } + if err != want || host.controls[0].closed.Load() != 1 { + t.Fatal("startup failure leaked notification", err) + } + }) + } +} diff --git a/app/notification_unsupported.go b/app/notification_unsupported.go new file mode 100644 index 000000000..2a05f8ad5 --- /dev/null +++ b/app/notification_unsupported.go @@ -0,0 +1,7 @@ +//go:build (!darwin && !windows) || ios + +package app + +func nativeShowNotification(Notification, NotificationEvents) (func(), error) { + return nil, ErrUnsupported +} diff --git a/app/notification_windows.go b/app/notification_windows.go new file mode 100644 index 000000000..f2e36d390 --- /dev/null +++ b/app/notification_windows.go @@ -0,0 +1,16 @@ +package app + +import ( + "github.com/vivaui/viva/internal/platform" + windowsplatform "github.com/vivaui/viva/internal/platform/windows" +) + +func nativeShowNotification(notification Notification, events NotificationEvents) (func(), error) { + return windowsplatform.ShowNotification(notification.Title, notification.Body, platform.NotificationEvents{Activated: events.OnActivate, Failed: func(err error) { + if events.OnError != nil { + events.OnError(err) + } else { + reportNotificationError(err) + } + }}) +} diff --git a/docs/notification-activation.md b/docs/notification-activation.md new file mode 100644 index 000000000..d06196094 --- /dev/null +++ b/docs/notification-activation.md @@ -0,0 +1,101 @@ +# Interactive system notifications + +Use `Application.ShowNotification` when a notification needs activation or +withdrawal. The existing comparable `app.Notification{Title, Body}` value and +`app.SendNotification` title/body-only function remain compatible. + +```go +handle, err := application.ShowNotification( + app.Notification{Title: "Download complete", Body: "Click to open the window."}, + app.NotificationEvents{ + OnActivate: func() { window.Show() }, + OnError: func(err error) { log.Printf("notification: %v", err) }, + }, +) +if err != nil { + // The request was rejected before native delivery could be accepted. + log.Printf("request notification: %v", err) +} +// Later, when this notification is no longer relevant: +handle.Close() +``` + +Call from startup or an event callback, like `AddStatusItem`. Both event handlers +are optional, and `Close` is nil-safe and safe from any goroutine. The application +marshals native signals onto its existing event loop: callbacks can restore or +open windows without a separate dispatch queue. At most one terminal event is +queued for a handle, and activation or error consumes its ownership. `Close` +invalidates queued events; a callback already running may finish. + +The application owns active handles and closes them on `Quit`, startup failure +or the end of `RunApplication`. Applications should also close stale handles +while running. A system dismissal does not promise a terminal event, so retaining +an arbitrary number of handles until process exit is not a resource policy. No +application-specific timeout, deduplication or navigation payload lives in Viva. + +## Support and host boundary + +`app.Supports(app.CapabilityNotificationActivation)` reports native build-target +support on desktop macOS and Windows. Other native platforms return +`app.ErrUnsupported`. Capabilities describe the build target, not what a custom +runtime host implements. + +A custom `app.Host` opts in with the public method: + +```go +ShowNotification(app.Notification, app.NotificationEvents) (app.NotificationControl, error) +``` + +The host returns a non-nil control promptly, reports asynchronous failures through +`OnError`, and may signal callbacks from native threads. Its control requests +withdrawal and invalidates native callbacks with an idempotent, any-goroutine +`Close`. No `internal/platform` import is required. A host without this optional +method returns `ErrUnsupported` instead of accidentally accessing the real OS; +headless applications can supply a synthetic host for notification tests. + +## Platform semantics + +- macOS uses `UNUserNotificationCenter`, requiring an application bundle + identifier and permission. The first request can ask for authorization + asynchronously. Denial is `app.ErrPermissionDenied`, delivered immediately or + through `OnError` according to when it is discovered. Closing while permission + is pending prevents late authorization from reinstating the request. A loose + command-line binary cannot stand in for packaged-app permission testing. +- Windows uses Shell notification-area balloons through the application's + message-only event-loop window, so closing an ordinary window does not retire + a notification. Each carrier has an independent full-width identifier; + callbacks are not routed through the last message sent. The legacy callback + layout preserves all 32 identifier bits instead of version 4's 16-bit field. + A title-only request is represented as body text because an empty Shell body + is a withdrawal request. Closing the loop removes remaining carriers. This is not a persistent toast + activation service and does not add activation after process exit. + +A successful request does not prove that the OS displayed it: notification policy, +quiet modes and Shell state can suppress delivery. Native field limits may +truncate text; UTF-16 truncation preserves surrogate pairs. The title and body +must contain valid UTF-8 without NUL and cannot both be blank. Closing requests +native withdrawal; the OS controls already-presented UI. Unhandled asynchronous +failures enter the structured `notification/delivery-failed` diagnostic stream, +not the recovered-panic fault stream. + +## Lifecycle and verification + +The framework starts no timer, polling loop or Go worker for interactive +notifications. Application tracking and native callback maps allocate lazily; +active requests retain text, callbacks and native resources until activation, +failure or explicit close. Programs that do not request notifications still carry +some linked code and additional application metadata; binary-size comparisons +should quantify that cost rather than claim it is zero. + +`examples/guides/notifications` provides show, withdraw and window-restore actions. +On macOS, package it with the normal Viva application-bundle tooling before +checking permission, notification-center delivery and activation. On Windows, +verify multiple notifications, ordinary-window closure, cancellation and loop +shutdown. Real OS delivery/permission verification is separate from unit tests. + +The automated contracts use a synthetic public host to test loop dispatch, +concurrent cancellation, one terminal event, errors, callbacks before host return, +late controls, startup failures and runner cleanup. Native Darwin tests exercise +actual bridge registry consumption and permission-error mapping without requesting +permission or presenting UI. Windows tests exercise callback identities, +wrong-host rejection, duplicate events, carrier cleanup and UTF-16 truncation. diff --git a/examples/guides/notifications/main.go b/examples/guides/notifications/main.go new file mode 100644 index 000000000..f9f84b86c --- /dev/null +++ b/examples/guides/notifications/main.go @@ -0,0 +1,43 @@ +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +func main() { + err := app.RunApplication(func(application *app.Application) error { + var window *app.Window + var latest *app.NotificationHandle + var err error + window, err = ui.OpenWindow(application, app.Config{Title: "System notifications", Width: 600, Height: 300}, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + if !app.Supports(app.CapabilityNotificationActivation) { + ui.Text(c, "Interactive notifications are not supported on this target.") + return + } + ui.Text(c, "On macOS, run the packaged application and allow system notifications.") + if ui.Button(c, "Show notification").Clicked() { + latest.Close() + latest, err = application.ShowNotification(app.Notification{Title: "Viva", Body: "Click to restore the application window."}, app.NotificationEvents{ + OnActivate: func() { window.Show() }, + OnError: func(err error) { log.Printf("notification delivery: %v", err) }, + }) + if err != nil { + log.Printf("request notification: %v", err) + } + } + if ui.Button(c, "Withdraw notification").Clicked() { + latest.Close() + latest = nil + } + }) + }}) + return err + }) + if err != nil { + log.Fatal(err) + } +} diff --git a/internal/platform/darwin/notification_darwin.go b/internal/platform/darwin/notification_darwin.go new file mode 100644 index 000000000..18437ba17 --- /dev/null +++ b/internal/platform/darwin/notification_darwin.go @@ -0,0 +1,91 @@ +//go:build darwin && !ios + +package darwin + +/* +#include +#include "system_darwin.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +var notificationCallbacks platform.NotificationRegistry + +func ShowNotification(title, body string, events platform.NotificationEvents) (func(), error) { + id := notificationCallbacks.Add(events) + titleText, err := systemCString("notification title", title) + if err != nil { + notificationCallbacks.Remove(id) + return nil, err + } + bodyText, err := systemCString("notification body", body) + if err != nil { + notificationCallbacks.Remove(id) + C.free(unsafe.Pointer(titleText)) + return nil, err + } + identifier := C.CString(id) + defer C.free(unsafe.Pointer(identifier)) + defer C.free(unsafe.Pointer(titleText)) + defer C.free(unsafe.Pointer(bodyText)) + var message *C.char + status := C.viva_system_show_interactive_notification(identifier, titleText, bodyText, &message) + if status != 0 { + notificationCallbacks.Remove(id) + if status == -2 { + if message != nil { + C.viva_system_free(unsafe.Pointer(message)) + } + return nil, ErrPermissionDenied + } + return nil, systemError("send interactive notification", message) + } + return func() { + notificationCallbacks.Remove(id) + identifier := C.CString(id) + defer C.free(unsafe.Pointer(identifier)) + C.viva_system_remove_notification(identifier) + }, nil +} + +//export vivaSystemNotificationActivated +func vivaSystemNotificationActivated(identifier *C.char) { + activateNotification(C.GoString(identifier)) +} + +//export vivaSystemNotificationIsActive +func vivaSystemNotificationIsActive(identifier *C.char) C.int { + if notificationCallbacks.Has(C.GoString(identifier)) { + return 1 + } + return 0 +} + +//export vivaSystemNotificationFailed +func vivaSystemNotificationFailed(identifier, message *C.char, denied C.int) { + failNotification(C.GoString(identifier), C.GoString(message), denied != 0) +} + +func failNotification(identifier, message string, denied bool) { + events := notificationCallbacks.Take(identifier) + if events.Failed == nil { + return + } + var err error = fmt.Errorf("darwin: notification delivery failed: %s", message) + if denied { + err = ErrPermissionDenied + } + events.Failed(err) +} + +func activateNotification(identifier string) { + if activate := notificationCallbacks.Take(identifier).Activated; activate != nil { + activate() + } +} diff --git a/internal/platform/darwin/notification_darwin_test.go b/internal/platform/darwin/notification_darwin_test.go new file mode 100644 index 000000000..7dd37da0b --- /dev/null +++ b/internal/platform/darwin/notification_darwin_test.go @@ -0,0 +1,47 @@ +//go:build darwin && !ios + +package darwin + +import ( + "errors" + "github.com/vivaui/viva/internal/platform" + "testing" +) + +func TestNotificationNativeActivationConsumesCallback(t *testing.T) { + calls := 0 + id := notificationCallbacks.Add(platform.NotificationEvents{Activated: func() { calls++ }}) + activateNotification(id) + activateNotification(id) + if calls != 1 || notificationCallbacks.Has(id) { + t.Fatal("native activation was not consumed exactly once") + } + id = notificationCallbacks.Add(platform.NotificationEvents{Activated: func() { calls++ }}) + notificationCallbacks.Remove(id) + activateNotification(id) + if calls != 1 { + t.Fatal("cancelled native identity was reactivated") + } +} +func TestNotificationNativeRejectsNULBeforeDelivery(t *testing.T) { + if close, err := ShowNotification("bad\x00title", "body", platform.NotificationEvents{}); err == nil || close != nil { + t.Fatal("invalid native string reached notification center") + } + if close, err := ShowNotification("title", "bad\x00body", platform.NotificationEvents{}); err == nil || close != nil { + t.Fatal("invalid native body reached notification center") + } +} + +func TestNotificationNativeFailureAndLateCancellation(t *testing.T) { + calls := 0 + var got error + id := notificationCallbacks.Add(platform.NotificationEvents{Failed: func(err error) { calls++; got = err }}) + failNotification(id, "denied", true) + failNotification(id, "duplicate", false) + if calls != 1 || !errors.Is(got, ErrPermissionDenied) || notificationCallbacks.Has(id) { + t.Fatal("permission failure did not consume native callback", calls, got) + } + id = notificationCallbacks.Add(platform.NotificationEvents{Failed: func(error) { t.Error("cancelled failure delivered") }}) + notificationCallbacks.Remove(id) + failNotification(id, "late failure", false) +} diff --git a/internal/platform/darwin/system_darwin.h b/internal/platform/darwin/system_darwin.h index e6f0ce324..ad52cb83c 100644 --- a/internal/platform/darwin/system_darwin.h +++ b/internal/platform/darwin/system_darwin.h @@ -99,6 +99,9 @@ int viva_system_send_notification( char **error_message ); +int viva_system_show_interactive_notification(const char *identifier, const char *title, const char *body, char **error_message); +void viva_system_remove_notification(const char *identifier); + void viva_system_free(void *memory); void viva_system_free_string_array(viva_system_string_array values); diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m index 21a3a800f..e585927c2 100644 --- a/internal/platform/darwin/system_darwin.m +++ b/internal/platform/darwin/system_darwin.m @@ -1252,6 +1252,11 @@ int viva_system_play_sound(uint8_t sound, char **error_message) { return status; } +// Standalone native fixtures do not link the Go callback bridge. +extern void vivaSystemNotificationActivated(char *) __attribute__((weak_import)); +extern int vivaSystemNotificationIsActive(char *) __attribute__((weak_import)); +extern void vivaSystemNotificationFailed(char *, char *, int) __attribute__((weak_import)); + @interface VivaNotificationDelegate : NSObject @end @@ -1271,6 +1276,16 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center #pragma clang diagnostic pop } } +- (void)userNotificationCenter:(UNUserNotificationCenter *)center + didReceiveNotificationResponse:(UNNotificationResponse *)response + withCompletionHandler:(void (^)(void))completionHandler { + if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier] && + vivaSystemNotificationActivated != NULL) { + vivaSystemNotificationActivated((char *)response.notification.request.identifier.UTF8String); + } + completionHandler(); +} + @end static VivaNotificationDelegate *viva_notification_delegate(void) { @@ -1408,6 +1423,84 @@ int viva_system_send_notification( } } +static BOOL viva_interactive_notification_active(NSString *identifier) { + return vivaSystemNotificationIsActive != NULL && vivaSystemNotificationIsActive((char *)identifier.UTF8String) != 0; +} + +void viva_system_remove_notification(const char *identifier) { + @autoreleasepool { + if (NSBundle.mainBundle.bundleIdentifier.length == 0 || identifier == NULL) return; + NSString *value = viva_string(identifier); + if (value == nil) return; + UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter; + [center removePendingNotificationRequestsWithIdentifiers:@[value]]; + [center removeDeliveredNotificationsWithIdentifiers:@[value]]; + } +} + +static void viva_interactive_notification_failed(NSString *identifier, NSString *message, BOOL denied) { + if (vivaSystemNotificationFailed != NULL) { + vivaSystemNotificationFailed((char *)identifier.UTF8String, (char *)message.UTF8String, denied ? 1 : 0); + } +} + +static void viva_interactive_notification_schedule(UNUserNotificationCenter *center, NSString *identifier, NSString *title, NSString *body) { + if (!viva_interactive_notification_active(identifier)) return; + UNMutableNotificationContent *content = [[[UNMutableNotificationContent alloc] init] autorelease]; + content.title = title; + content.body = body; + content.sound = UNNotificationSound.defaultSound; + UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:nil]; + [center addNotificationRequest:request withCompletionHandler:^(NSError *error) { + if (error != nil) { + viva_interactive_notification_failed(identifier, error.localizedDescription, NO); + } + // Cancellation can race scheduling. Remove the request again after the + // native completion so late authorization never reinstates a retired request. + if (!viva_interactive_notification_active(identifier)) { + viva_system_remove_notification(identifier.UTF8String); + } + }]; +} + +int viva_system_show_interactive_notification(const char *identifier, const char *title, const char *body, char **error_message) { + @autoreleasepool { + if (NSBundle.mainBundle.bundleIdentifier.length == 0) { + viva_set_error(error_message, @"notifications require an application bundle identifier"); + return -1; + } + NSString *key = viva_string(identifier), *notificationTitle = viva_string(title), *notificationBody = viva_string(body); + if (key == nil || notificationTitle == nil || notificationBody == nil) { + viva_set_error(error_message, @"notification text is not valid UTF-8"); + return -1; + } + UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter; + center.delegate = viva_notification_delegate(); + [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) { + if (!viva_interactive_notification_active(key)) return; + if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) { + [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound) + completionHandler:^(BOOL allowed, NSError *error) { + if (!viva_interactive_notification_active(key)) return; + if (!allowed || error != nil) { + viva_interactive_notification_failed(key, error.localizedDescription ?: @"notification permission was denied", !allowed); + return; + } + viva_interactive_notification_schedule(center, key, notificationTitle, notificationBody); + }]; + } else if (settings.authorizationStatus == UNAuthorizationStatusDenied) { + viva_interactive_notification_failed(key, @"notification permission is denied in System Settings", YES); + } else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized || + settings.authorizationStatus == UNAuthorizationStatusProvisional) { + viva_interactive_notification_schedule(center, key, notificationTitle, notificationBody); + } else { + viva_interactive_notification_failed(key, @"notification authorization status is unsupported", NO); + } + }]; + return 0; + } +} + void viva_system_free(void *memory) { free(memory); } diff --git a/internal/platform/notification_callbacks.go b/internal/platform/notification_callbacks.go new file mode 100644 index 000000000..8669affa7 --- /dev/null +++ b/internal/platform/notification_callbacks.go @@ -0,0 +1,43 @@ +package platform + +import ( + "crypto/rand" + "sync" +) + +type NotificationEvents struct { + Activated func() + Failed func(error) +} + +// NotificationRegistry owns active-process callbacks keyed by opaque identities. +// Cancellation removes the callback before a late native response can use it. +type NotificationRegistry struct { + mu sync.Mutex + values map[string]NotificationEvents +} + +func (callbacks *NotificationRegistry) Add(events NotificationEvents) string { + id := rand.Text() + callbacks.mu.Lock() + defer callbacks.mu.Unlock() + if callbacks.values == nil { + callbacks.values = make(map[string]NotificationEvents) + } + callbacks.values[id] = events + return id +} +func (callbacks *NotificationRegistry) Has(id string) bool { + callbacks.mu.Lock() + defer callbacks.mu.Unlock() + _, exists := callbacks.values[id] + return exists +} +func (callbacks *NotificationRegistry) Take(id string) NotificationEvents { + callbacks.mu.Lock() + defer callbacks.mu.Unlock() + events := callbacks.values[id] + delete(callbacks.values, id) + return events +} +func (callbacks *NotificationRegistry) Remove(id string) { callbacks.Take(id) } diff --git a/internal/platform/notification_callbacks_test.go b/internal/platform/notification_callbacks_test.go new file mode 100644 index 000000000..61726652f --- /dev/null +++ b/internal/platform/notification_callbacks_test.go @@ -0,0 +1,32 @@ +package platform + +import ( + "sync" + "sync/atomic" + "testing" +) + +func TestNotificationRegistryActivationOnceAndCancellation(t *testing.T) { + var callbacks NotificationRegistry + var calls atomic.Int32 + id := callbacks.Add(NotificationEvents{Activated: func() { calls.Add(1); callbacks.Remove("other") }}) + var jobs sync.WaitGroup + for range 32 { + jobs.Add(1) + go func() { + defer jobs.Done() + if activate := callbacks.Take(id).Activated; activate != nil { + activate() + } + }() + } + jobs.Wait() + if calls.Load() != 1 || callbacks.Has(id) { + t.Fatal("activation was not consumed exactly once") + } + id = callbacks.Add(NotificationEvents{Activated: func() { t.Error("cancelled activation") }}) + callbacks.Remove(id) + if callbacks.Has(id) || callbacks.Take(id).Activated != nil { + t.Fatal("cancelled callback retained") + } +} diff --git a/internal/platform/windows/notification_windows.go b/internal/platform/windows/notification_windows.go new file mode 100644 index 000000000..94aed6d3c --- /dev/null +++ b/internal/platform/windows/notification_windows.go @@ -0,0 +1,170 @@ +package windows + +import ( + "fmt" + "sync" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +const ( + wmNotificationActivation = 0x8014 + notificationBalloonClick = 0x0405 // NIN_BALLOONUSERCLICK + notificationIDNamespace uint32 = 1 << 31 +) + +type interactiveNotification struct { + host uintptr + activate func() +} + +var interactiveNotifications = struct { + sync.Mutex + next uint32 + entries map[uint32]interactiveNotification +}{} + +// ShowNotification serializes Shell and window access on the owning event loop. +// Closing invalidates callbacks immediately, even before queued native work runs. +func ShowNotification(title, body string, events platform.NotificationEvents) (func(), error) { + application := wakeOwner.Load() + if application == nil { + return nil, fmt.Errorf("windows: notification requires a running application") + } + var mu sync.Mutex + closed := false + var nativeCancel func() + activate := func() { + mu.Lock() + active := !closed + closed = true + mu.Unlock() + if active && events.Activated != nil { + events.Activated() + } + } + application.Post(func() { + mu.Lock() + stopped := closed + mu.Unlock() + if stopped { + return + } + cancel, err := showNotification(application, title, body, activate) + mu.Lock() + stopped = closed + if !stopped { + nativeCancel = cancel + } + mu.Unlock() + if stopped && cancel != nil { + cancel() + } + if err != nil { + mu.Lock() + active := !closed + closed = true + mu.Unlock() + if active && events.Failed != nil { + events.Failed(err) + } + } + }) + return func() { + mu.Lock() + closed = true + cancel := nativeCancel + nativeCancel = nil + mu.Unlock() + if cancel != nil { + application.Post(cancel) + } + }, nil +} + +func showNotification(application *windowsApplication, title, body string, activate func()) (func(), error) { + // The event-loop carrier outlives ordinary windows. Closing the window that + // happened to be active must not retire an application-owned notification. + host := application.wakeWindow.Load() + if host == 0 { + return nil, fmt.Errorf("windows: notification requires a running application") + } + icon := notificationIcon(notificationHost()) + if icon == 0 { + var err error + icon, _, err = loadIcon.Call(0, 32512) + if icon == 0 { + return nil, windowsCallError("load notification icon", err) + } + } + interactiveNotifications.Lock() + if interactiveNotifications.next >= notificationIDNamespace-1 { + interactiveNotifications.Unlock() + return nil, fmt.Errorf("windows: notification identifiers exhausted") + } + interactiveNotifications.next++ + id := notificationIDNamespace | interactiveNotifications.next + if interactiveNotifications.entries == nil { + interactiveNotifications.entries = make(map[uint32]interactiveNotification) + } + interactiveNotifications.entries[id] = interactiveNotification{host: host, activate: activate} + interactiveNotifications.Unlock() + // NIF_INFO with an empty body withdraws a balloon. Preserve title-only + // requests as body text rather than accidentally asking the Shell to remove it. + if body == "" { + body = title + title = "" + } + data := notificationIconData(host, icon, title, body) + data.ID = id + data.Flags |= notifyMessage + data.CallbackMessage = wmNotificationActivation + // Retain the legacy callback layout deliberately: wParam contains the full + // 32-bit uID. Version 4 truncates it to 16 bits and can alias stale callbacks. + if ok, _, err := callNotifyIcon(notifyAdd, &data); ok == 0 { + forgetInteractiveNotification(host, id) + return nil, windowsCallError("send interactive notification", err) + } + return func() { forgetInteractiveNotification(host, id) }, nil +} + +func forgetInteractiveNotification(host uintptr, id uint32) func() { + interactiveNotifications.Lock() + entry, ok := interactiveNotifications.entries[id] + if ok && entry.host == host { + delete(interactiveNotifications.entries, id) + } else { + ok = false + } + interactiveNotifications.Unlock() + if !ok { + return nil + } + data := notifyIconData{Size: uint32(unsafe.Sizeof(notifyIconData{})), Window: host, ID: id} + callNotifyIcon(notifyDelete, &data) + return entry.activate +} + +func activateSystemNotification(host uintptr, id, event uint32) { + if event != notificationBalloonClick { + return + } + if activate := forgetInteractiveNotification(host, id); activate != nil { + activate() + } +} + +func removeInteractiveNotifications(host uintptr) { + interactiveNotifications.Lock() + var ids []uint32 + for id, entry := range interactiveNotifications.entries { + if entry.host == host { + ids = append(ids, id) + } + } + interactiveNotifications.Unlock() + for _, id := range ids { + forgetInteractiveNotification(host, id) + } +} diff --git a/internal/platform/windows/notification_windows_test.go b/internal/platform/windows/notification_windows_test.go new file mode 100644 index 000000000..44086a728 --- /dev/null +++ b/internal/platform/windows/notification_windows_test.go @@ -0,0 +1,156 @@ +package windows + +import ( + "github.com/vivaui/viva/internal/platform" + "runtime" + "syscall" + "testing" +) + +func TestNotificationActivationIdentityAndCancellation(t *testing.T) { + previous := callNotifyIcon + callNotifyIcon = func(uintptr, *notifyIconData) (uintptr, uintptr, error) { return 1, 0, nil } + defer func() { callNotifyIcon = previous }() + const host = uintptr(0x1234) + id := notificationIDNamespace | 123 + calls := 0 + interactiveNotifications.Lock() + if interactiveNotifications.entries == nil { + interactiveNotifications.entries = make(map[uint32]interactiveNotification) + } + interactiveNotifications.entries[id] = interactiveNotification{host: host, activate: func() { calls++ }} + interactiveNotifications.Unlock() + activateSystemNotification(host+1, id, notificationBalloonClick) + activateSystemNotification(host, id, 0) + if calls != 0 { + t.Fatal("wrong host or event activated a notification") + } + wakeProc(host, wmNotificationActivation, uintptr(id), notificationBalloonClick) + wakeProc(host, wmNotificationActivation, uintptr(id), notificationBalloonClick) + if calls != 1 { + t.Fatalf("activation calls = %d", calls) + } + interactiveNotifications.Lock() + interactiveNotifications.entries[id+1] = interactiveNotification{host: host, activate: func() { calls++ }} + interactiveNotifications.Unlock() + removeInteractiveNotifications(host) + activateSystemNotification(host, id+1, notificationBalloonClick) + if calls != 1 { + t.Fatal("closed host retained activation") + } +} + +func TestNotificationTruncationPreservesUTF16(t *testing.T) { + var short [3]uint16 + copyUTF16(short[:], "a😀b") + if short[0] != 'a' || short[1] != 0 { + t.Fatal("truncated title retained half a surrogate pair", short) + } + var fitting [4]uint16 + copyUTF16(fitting[:], "a😀b") + if fitting[0] != 'a' || fitting[1] != 0xd83d || fitting[2] != 0xde00 || fitting[3] != 0 { + t.Fatal("title lost a complete surrogate pair", fitting) + } + copyUTF16(nil, "ignored") +} + +// The Shell call is mocked, so this exercises the real message-only carrier and +// queued lifecycle without displaying a notification or opening a visual window. +func TestNotificationCarrierAndQueuedCancellation(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + application := &windowsApplication{} + if err := application.openWakeWindow(); err != nil { + t.Fatal(err) + } + previous := callNotifyIcon + defer func() { application.closeWakeWindow(); callNotifyIcon = previous }() + var data notifyIconData + adds, calls := 0, 0 + callNotifyIcon = func(operation uintptr, value *notifyIconData) (uintptr, uintptr, error) { + if operation == notifyAdd { + data = *value + adds++ + } + return 1, 0, nil + } + events := platform.NotificationEvents{Activated: func() { calls++ }, Failed: func(err error) { t.Error(err) }} + cancel, err := ShowNotification("Title only", "", events) + if err != nil { + t.Fatal(err) + } + application.drainPosts() + if adds != 1 || data.Window != application.wakeWindow.Load() || syscall.UTF16ToString(data.Info[:]) != "Title only" || data.State¬ifyHidden == 0 || data.StateMask¬ifyHidden == 0 || data.Flags¬ifyState == 0 { + t.Fatal("request lost its application carrier, title-only content or hidden state") + } + oldID := data.ID + cancel() + wakeProc(data.Window, wmNotificationActivation, uintptr(oldID), notificationBalloonClick) + application.drainPosts() + if calls != 0 { + t.Fatal("late click escaped queued cancellation") + } + cancel, err = ShowNotification("Second", "body", events) + if err != nil { + t.Fatal(err) + } + application.drainPosts() + if data.ID == oldID { + t.Fatal("notification identity was reused") + } + wakeProc(data.Window, wmNotificationActivation, uintptr(oldID), notificationBalloonClick) + wakeProc(data.Window, wmNotificationActivation, uintptr(data.ID), notificationBalloonClick) + wakeProc(data.Window, wmNotificationActivation, uintptr(data.ID), notificationBalloonClick) + if calls != 1 { + t.Fatal("click identity did not select one live notification", calls) + } + cancel() + application.drainPosts() + cancel, err = ShowNotification("Cancelled before posting", "body", events) + if err != nil { + t.Fatal(err) + } + cancel() + application.drainPosts() + if adds != 2 { + t.Fatal("cancelled queued request reached the Shell") + } +} + +func TestNotificationShellFailureReleasesIdentity(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + application := &windowsApplication{} + if err := application.openWakeWindow(); err != nil { + t.Fatal(err) + } + previous := callNotifyIcon + defer func() { application.closeWakeWindow(); callNotifyIcon = previous }() + var id uint32 + callNotifyIcon = func(operation uintptr, data *notifyIconData) (uintptr, uintptr, error) { + id = data.ID + if operation == notifyAdd { + return 0, 0, syscall.EINVAL + } + return 1, 0, nil + } + errors := 0 + cancel, err := ShowNotification("title", "body", platform.NotificationEvents{Failed: func(err error) { + if err == nil { + t.Error("nil native failure") + } + errors++ + }}) + if err != nil { + t.Fatal(err) + } + application.drainPosts() + cancel() + application.drainPosts() + interactiveNotifications.Lock() + _, retained := interactiveNotifications.entries[id] + interactiveNotifications.Unlock() + if errors != 1 || retained { + t.Fatal("Shell failure retained a callback", errors, retained) + } +} diff --git a/internal/platform/windows/post_windows.go b/internal/platform/windows/post_windows.go index f677ae0b4..22313122f 100644 --- a/internal/platform/windows/post_windows.go +++ b/internal/platform/windows/post_windows.go @@ -41,6 +41,10 @@ var ( // wakeProc runs posted work for the wake window. A modal loop dispatches the // wake here just as the application's own loop does. func wakeProc(window, kind, first, second uintptr) (result uintptr) { + if kind == wmNotificationActivation { + activateSystemNotification(window, uint32(first), uint32(second)) + return 0 + } if kind == wmPost { if application := wakeOwner.Load(); application != nil { application.drainPosts() @@ -89,6 +93,7 @@ func (application *windowsApplication) openWakeWindow() error { // closeWakeWindow drops the wake window; no posted work runs after it. func (application *windowsApplication) closeWakeWindow() { if window := application.wakeWindow.Swap(0); window != 0 { + removeInteractiveNotifications(window) destroyWindow.Call(window) } wakeOwner.CompareAndSwap(application, nil) diff --git a/internal/platform/windows/system_windows.go b/internal/platform/windows/system_windows.go index 7458f5eba..707fec3f5 100644 --- a/internal/platform/windows/system_windows.go +++ b/internal/platform/windows/system_windows.go @@ -1010,12 +1010,17 @@ func dialogOwner() uintptr { } func copyUTF16(destination []uint16, value string) { + if len(destination) == 0 { + return + } encoded := syscall.StringToUTF16(value) - if len(encoded) > len(destination) { - encoded = encoded[:len(destination)] - encoded[len(encoded)-1] = 0 + count := min(len(encoded)-1, len(destination)-1) + // Reserve NUL and never truncate between the two halves of a surrogate pair. + if count > 0 && count < len(encoded)-1 && encoded[count-1] >= 0xd800 && encoded[count-1] <= 0xdbff { + count-- } - copy(destination, encoded) + copy(destination, encoded[:count]) + destination[count] = 0 } func windowsCallError(action string, callErr error) error { From 3d0ea01ac867866928f8a64f0c0d88b969c8f1f8 Mon Sep 17 00:00:00 2001 From: Dean Cen Date: Fri, 27 Nov 2026 23:13:11 +0800 Subject: [PATCH 07/29] feat(audio): add cross-platform microphone input capture --- audio/audio.go | 3 + audio/device_test.go | 27 +++ audio/input.go | 203 ++++++++++++++++++++ audio/input_darwin.c | 383 +++++++++++++++++++++++++++++++++++++ audio/input_darwin.go | 69 +++++++ audio/input_linux.go | 119 ++++++++++++ audio/input_linux_other.go | 5 + audio/input_other.go | 5 + audio/input_test.go | 164 ++++++++++++++++ audio/input_windows.go | 206 ++++++++++++++++++++ audio/output_linux.go | 5 + 11 files changed, 1189 insertions(+) create mode 100644 audio/input.go create mode 100644 audio/input_darwin.c create mode 100644 audio/input_darwin.go create mode 100644 audio/input_linux.go create mode 100644 audio/input_linux_other.go create mode 100644 audio/input_other.go create mode 100644 audio/input_test.go create mode 100644 audio/input_windows.go diff --git a/audio/audio.go b/audio/audio.go index 7d4b12280..438a73d89 100644 --- a/audio/audio.go +++ b/audio/audio.go @@ -24,6 +24,9 @@ var ( // output that can play the stream: the package is not implemented for the // platform, the system library is missing, or no default device exists. ErrUnsupported = errors.New("audio: no output device is available") + // ErrInputUnsupported reports that this build target, or the system, has no + // input device that can capture audio. + ErrInputUnsupported = errors.New("audio: no input device is available") // ErrClosed reports a Write after Close. ErrClosed = errors.New("audio: output is closed") // ErrFrame reports data that does not hold whole frames. diff --git a/audio/device_test.go b/audio/device_test.go index 74e092957..e45b5f5a2 100644 --- a/audio/device_test.go +++ b/audio/device_test.go @@ -1,6 +1,7 @@ package audio import ( + "io" "os" "testing" "time" @@ -32,3 +33,29 @@ func TestOutputDevice(t *testing.T) { } } } + +// TestInputDevice captures a short sample from the machine's default input. +// Like TestOutputDevice, it is opt-in under VIVA_AUDIO_TEST=1. +func TestInputDevice(t *testing.T) { + if os.Getenv("VIVA_AUDIO_TEST") == "" { + t.Skip("set VIVA_AUDIO_TEST=1 to open the default input device") + } + for _, format := range []Format{ + {SampleRate: 48000, Channels: 1}, + {SampleRate: 44100, Channels: 2}, + {SampleRate: 16000, Channels: 1}, + } { + in, err := OpenInput(format) + if err != nil { + t.Fatalf("OpenInput(%+v): %v", format, err) + } + buf := make([]byte, format.SampleRate/20*format.Channels*2) + if _, err := io.ReadFull(in, buf); err != nil { + _ = in.Close() + t.Fatalf("ReadFull(%+v): %v", format, err) + } + if err := in.Close(); err != nil { + t.Fatalf("Close(%+v): %v", format, err) + } + } +} diff --git a/audio/input.go b/audio/input.go new file mode 100644 index 000000000..7d5534f97 --- /dev/null +++ b/audio/input.go @@ -0,0 +1,203 @@ +package audio + +import ( + "fmt" + "io" + "runtime" + "sync" +) + +// Input is a stream capturing PCM from the system's default input device. It +// implements io.ReadCloser; each Read returns interleaved 16-bit signed +// little-endian frames in the format given to OpenInput. +// +// While an Input is open it holds one goroutine, a fixed ring buffer, and the +// capture device. If the caller stops reading temporarily, oldest frames are +// discarded so the capture thread never stalls. +type Input struct { + format Format + align int + + mu sync.Mutex + cond *sync.Cond + ring []byte + head int // read offset in ring + used int // unread bytes in ring + closed bool + failed error + dev inputDevice + openErr error + done chan struct{} + ready chan struct{} +} + +// OpenInput opens the default input device for format. It returns +// ErrInputUnsupported when the platform, the system library, or the system's +// default input device cannot capture. +func OpenInput(format Format) (*Input, error) { + if err := format.valid(); err != nil { + return nil, err + } + align := format.Channels * 2 + // Keep up to a quarter second of captured audio in the ring. + ringBytes := max(format.SampleRate/4*align, 4096) + ringBytes -= ringBytes % align + if ringBytes < align { + ringBytes = align + } + in := &Input{ + format: format, + align: align, + ring: make([]byte, ringBytes), + done: make(chan struct{}), + ready: make(chan struct{}), + } + in.cond = sync.NewCond(&in.mu) + go in.run() + <-in.ready + if in.openErr != nil { + <-in.done + return nil, in.openErr + } + return in, nil +} + +// Format returns the format given to OpenInput. +func (in *Input) Format() Format { return in.format } + +func (in *Input) run() { + runtime.LockOSThread() + defer close(in.done) + + dev, err := loadInputDevice(in.format) + in.mu.Lock() + in.openErr = err + if err != nil { + in.failed = err + } else { + in.dev = dev + } + in.mu.Unlock() + close(in.ready) + if err != nil { + return + } + + scratch := make([]byte, max(in.format.SampleRate/4, 4096)*in.align) + for { + n, err := dev.read(scratch) + if n > 0 { + in.push(scratch[:n]) + } + if err != nil { + in.mu.Lock() + if !in.closed { + in.failed = err + } + in.cond.Broadcast() + in.mu.Unlock() + break + } + in.mu.Lock() + closed := in.closed + in.mu.Unlock() + if closed { + break + } + } + dev.close() +} + +func (in *Input) push(pcm []byte) { + in.mu.Lock() + defer in.mu.Unlock() + if in.closed { + return + } + capRing := len(in.ring) + if len(pcm) >= capRing { + pcm = pcm[len(pcm)-capRing:] + in.head = 0 + in.used = 0 + } else if overflow := in.used + len(pcm) - capRing; overflow > 0 { + in.head = (in.head + overflow) % capRing + in.used -= overflow + } + write := (in.head + in.used) % capRing + first := min(len(pcm), capRing-write) + copy(in.ring[write:], pcm[:first]) + if first < len(pcm) { + copy(in.ring, pcm[first:]) + } + in.used += len(pcm) + in.cond.Broadcast() +} + +// Read copies captured PCM frames into pcm, blocking until at least one byte +// is available or the stream ends. Returns io.EOF after Close. +func (in *Input) Read(pcm []byte) (int, error) { + if len(pcm) == 0 { + return 0, nil + } + in.mu.Lock() + defer in.mu.Unlock() + for in.used == 0 && !in.closed && in.failed == nil { + in.cond.Wait() + } + if in.closed { + return 0, io.EOF + } + if in.used == 0 && in.failed != nil { + return 0, in.failed + } + take := min(len(pcm), in.used) + if len(pcm) >= in.align && take >= in.align { + take -= take % in.align + } + capRing := len(in.ring) + first := min(take, capRing-in.head) + copy(pcm[:first], in.ring[in.head:in.head+first]) + if first < take { + copy(pcm[first:take], in.ring[:take-first]) + } + in.head = (in.head + take) % capRing + in.used -= take + return take, nil +} + +// Close stops capturing and releases the input device. It is safe to call more +// than once, and unblocks any waiting Read with io.EOF. +func (in *Input) Close() error { + in.mu.Lock() + already := in.closed + in.closed = true + dev := in.dev + in.cond.Broadcast() + in.mu.Unlock() + if !already && dev != nil { + dev.stop() + } + <-in.done + return nil +} + +func loadInputDevice(format Format) (dev inputDevice, err error) { + defer func() { + if recovered := recover(); recovered != nil { + dev, err = nil, fmt.Errorf("audio: %v", recovered) + } + }() + return openInputDevice(format) +} + +// inputDevice is one platform's capture stream. read and close run on the +// capture goroutine locked to an OS thread; stop may be called from any +// goroutine to unblock read. +type inputDevice interface { + read(pcm []byte) (int, error) + stop() + close() +} + +// openInputDevice is the platform's implementation. Tests replace it. +var openInputDevice = platformInputDevice diff --git a/audio/input_darwin.c b/audio/input_darwin.c new file mode 100644 index 000000000..25a1f4d3b --- /dev/null +++ b/audio/input_darwin.c @@ -0,0 +1,383 @@ +//go:build darwin && !ios + +#include +#include +#include +#include +#include +#include + +typedef struct viva_audio_input viva_audio_input; + +// viva_audio_input captures from the default input HAL AudioUnit into a ring +// buffer. CoreAudio's input callback runs on its own real-time thread and only +// copies bytes under the mutex; Go reads from the ring without touching CoreAudio. +struct viva_audio_input { + pthread_mutex_t mutex; + pthread_cond_t cond; + uint8_t *data; + size_t capacity; + size_t frame; + size_t read; + size_t used; + AudioUnit unit; + AudioConverterRef converter; + AudioStreamBasicDescription client_fmt; + AudioStreamBasicDescription target_fmt; + uint8_t *capture_buf; + size_t capture_cap; + uint8_t *convert_buf; + size_t convert_cap; + const uint8_t *conv_ptr; + UInt32 conv_bytes; + int started; + int closed; +}; + +static size_t viva_in_min(size_t a, size_t b) { return a < b ? a : b; } + +static void viva_in_ring_push(struct viva_audio_input *a, const uint8_t *src, size_t len) { + if (len == 0) { + return; + } + pthread_mutex_lock(&a->mutex); + if (a->closed) { + pthread_mutex_unlock(&a->mutex); + return; + } + if (len >= a->capacity) { + src += len - a->capacity; + len = a->capacity; + a->read = 0; + a->used = 0; + } else if (a->used + len > a->capacity) { + size_t drop = a->used + len - a->capacity; + a->read = (a->read + drop) % a->capacity; + a->used -= drop; + } + size_t write = (a->read + a->used) % a->capacity; + size_t first = viva_in_min(len, a->capacity - write); + memcpy(a->data + write, src, first); + if (len > first) { + memcpy(a->data, src + first, len - first); + } + a->used += len; + pthread_cond_signal(&a->cond); + pthread_mutex_unlock(&a->mutex); +} + +static OSStatus viva_in_conv_supply(AudioConverterRef converter, UInt32 *packets, + AudioBufferList *data, + AudioStreamPacketDescription **desc, + void *ref) { + (void)converter; + (void)desc; + struct viva_audio_input *a = ref; + if (a->conv_bytes == 0) { + *packets = 0; + data->mBuffers[0].mDataByteSize = 0; + data->mBuffers[0].mData = NULL; + return noErr; + } + UInt32 avail = a->conv_bytes / a->client_fmt.mBytesPerPacket; + UInt32 take = *packets < avail ? *packets : avail; + UInt32 take_bytes = take * a->client_fmt.mBytesPerPacket; + data->mNumberBuffers = 1; + data->mBuffers[0].mNumberChannels = a->client_fmt.mChannelsPerFrame; + data->mBuffers[0].mData = (void *)a->conv_ptr; + data->mBuffers[0].mDataByteSize = take_bytes; + a->conv_ptr += take_bytes; + a->conv_bytes -= take_bytes; + *packets = take; + return noErr; +} + +static OSStatus viva_in_callback(void *ref, AudioUnitRenderActionFlags *flags, + const AudioTimeStamp *timestamp, UInt32 bus, + UInt32 frames, AudioBufferList *io_data) { + (void)io_data; + struct viva_audio_input *a = ref; + size_t need = (size_t)frames * a->client_fmt.mBytesPerFrame; + if (need == 0 || need > a->capture_cap) { + return noErr; + } + + AudioBufferList abl; + abl.mNumberBuffers = 1; + abl.mBuffers[0].mNumberChannels = a->client_fmt.mChannelsPerFrame; + abl.mBuffers[0].mDataByteSize = (UInt32)need; + abl.mBuffers[0].mData = a->capture_buf; + + OSStatus err = AudioUnitRender(a->unit, flags, timestamp, bus, frames, &abl); + if (err != noErr) { + return err; + } + + if (a->converter == NULL) { + viva_in_ring_push(a, a->capture_buf, abl.mBuffers[0].mDataByteSize); + return noErr; + } + + a->conv_ptr = a->capture_buf; + a->conv_bytes = abl.mBuffers[0].mDataByteSize; + while (a->conv_bytes > 0) { + UInt32 out_packets = (UInt32)(a->convert_cap / a->target_fmt.mBytesPerPacket); + AudioBufferList out_abl; + out_abl.mNumberBuffers = 1; + out_abl.mBuffers[0].mNumberChannels = a->target_fmt.mChannelsPerFrame; + out_abl.mBuffers[0].mDataByteSize = out_packets * a->target_fmt.mBytesPerPacket; + out_abl.mBuffers[0].mData = a->convert_buf; + + err = AudioConverterFillComplexBuffer(a->converter, viva_in_conv_supply, a, + &out_packets, &out_abl, NULL); + if (out_packets > 0 && out_abl.mBuffers[0].mDataByteSize > 0) { + viva_in_ring_push(a, a->convert_buf, out_abl.mBuffers[0].mDataByteSize); + } + if (err != noErr || out_packets == 0) { + break; + } + } + return noErr; +} + +viva_audio_input *viva_audio_input_open(double rate, uint32_t channels, int32_t *status) { + *status = 0; + if (rate < 8000 || rate > 192000 || channels < 1 || channels > 2) { + *status = kAudioUnitErr_InvalidParameter; + return NULL; + } + + AudioObjectPropertyAddress dev_addr = { + .mSelector = kAudioHardwarePropertyDefaultInputDevice, + .mScope = kAudioObjectPropertyScopeGlobal, + .mElement = kAudioObjectPropertyElementMain, + }; + AudioDeviceID dev_id = kAudioObjectUnknown; + UInt32 dev_size = sizeof(dev_id); + OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &dev_addr, 0, NULL, &dev_size, &dev_id); + if (err != noErr || dev_id == kAudioObjectUnknown) { + *status = -1; + return NULL; + } + + AudioComponentDescription description = { + .componentType = kAudioUnitType_Output, + .componentSubType = kAudioUnitSubType_HALOutput, + .componentManufacturer = kAudioUnitManufacturer_Apple, + }; + AudioComponent component = AudioComponentFindNext(NULL, &description); + if (component == NULL) { + *status = -1; + return NULL; + } + + struct viva_audio_input *a = calloc(1, sizeof(*a)); + if (a == NULL) { + *status = kAudioUnitErr_NoConnection; + return NULL; + } + a->frame = (size_t)channels * 2; + a->capacity = (size_t)(rate / 4.0) * a->frame; + if (a->capacity < 4096) { + a->capacity = 4096; + } + a->capacity -= a->capacity % a->frame; + a->data = malloc(a->capacity); + a->capture_cap = 65536; + a->capture_buf = malloc(a->capture_cap); + a->convert_cap = 65536; + a->convert_buf = malloc(a->convert_cap); + if (a->data == NULL || a->capture_buf == NULL || a->convert_buf == NULL) { + free(a->data); + free(a->capture_buf); + free(a->convert_buf); + free(a); + *status = kAudioUnitErr_NoConnection; + return NULL; + } + if (pthread_mutex_init(&a->mutex, NULL) != 0 || + pthread_cond_init(&a->cond, NULL) != 0) { + free(a->data); + free(a->capture_buf); + free(a->convert_buf); + free(a); + *status = kAudioUnitErr_NoConnection; + return NULL; + } + + err = AudioComponentInstanceNew(component, &a->unit); + if (err != noErr) { + goto fail; + } + + UInt32 enable_in = 1; + err = AudioUnitSetProperty(a->unit, kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Input, 1, &enable_in, sizeof(enable_in)); + if (err != noErr) { + goto fail; + } + + UInt32 disable_out = 0; + err = AudioUnitSetProperty(a->unit, kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Output, 0, &disable_out, sizeof(disable_out)); + if (err != noErr) { + goto fail; + } + + err = AudioUnitSetProperty(a->unit, kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, 0, &dev_id, sizeof(dev_id)); + if (err != noErr) { + goto fail; + } + + AudioStreamBasicDescription hw_fmt; + UInt32 hw_size = sizeof(hw_fmt); + err = AudioUnitGetProperty(a->unit, kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, 1, &hw_fmt, &hw_size); + if (err != noErr) { + goto fail; + } + + UInt32 hw_channels = hw_fmt.mChannelsPerFrame; + if (hw_channels == 0) { + hw_channels = channels; + } + if (hw_channels > 2) { + hw_channels = 2; + } + double hw_rate = hw_fmt.mSampleRate > 0 ? hw_fmt.mSampleRate : rate; + + a->client_fmt = (AudioStreamBasicDescription){ + .mSampleRate = hw_rate, + .mFormatID = kAudioFormatLinearPCM, + .mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked, + .mBytesPerPacket = hw_channels * 2, + .mFramesPerPacket = 1, + .mBytesPerFrame = hw_channels * 2, + .mChannelsPerFrame = hw_channels, + .mBitsPerChannel = 16, + }; + a->target_fmt = (AudioStreamBasicDescription){ + .mSampleRate = rate, + .mFormatID = kAudioFormatLinearPCM, + .mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked, + .mBytesPerPacket = (UInt32)a->frame, + .mFramesPerPacket = 1, + .mBytesPerFrame = (UInt32)a->frame, + .mChannelsPerFrame = channels, + .mBitsPerChannel = 16, + }; + + err = AudioUnitSetProperty(a->unit, kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Output, 1, &a->client_fmt, sizeof(a->client_fmt)); + if (err != noErr) { + goto fail; + } + + if (a->client_fmt.mSampleRate != a->target_fmt.mSampleRate || + a->client_fmt.mChannelsPerFrame != a->target_fmt.mChannelsPerFrame) { + err = AudioConverterNew(&a->client_fmt, &a->target_fmt, &a->converter); + if (err != noErr) { + goto fail; + } + } + + AURenderCallbackStruct callback = { + .inputProc = viva_in_callback, + .inputProcRefCon = a, + }; + err = AudioUnitSetProperty(a->unit, kAudioOutputUnitProperty_SetInputCallback, + kAudioUnitScope_Global, 0, &callback, sizeof(callback)); + if (err != noErr) { + goto fail; + } + + err = AudioUnitInitialize(a->unit); + if (err != noErr) { + goto fail; + } + err = AudioOutputUnitStart(a->unit); + if (err != noErr) { + AudioUnitUninitialize(a->unit); + goto fail; + } + a->started = 1; + return a; + +fail: + *status = err; + if (a->converter != NULL) { + AudioConverterDispose(a->converter); + } + if (a->unit != NULL) { + AudioComponentInstanceDispose(a->unit); + } + pthread_mutex_destroy(&a->mutex); + pthread_cond_destroy(&a->cond); + free(a->data); + free(a->capture_buf); + free(a->convert_buf); + free(a); + return NULL; +} + +int64_t viva_audio_input_read(viva_audio_input *a, void *pcm, uintptr_t len) { + if (a == NULL || len == 0) { + return 0; + } + pthread_mutex_lock(&a->mutex); + while (a->used == 0 && !a->closed) { + pthread_cond_wait(&a->cond, &a->mutex); + } + if (a->closed) { + pthread_mutex_unlock(&a->mutex); + return 0; + } + size_t take = viva_in_min((size_t)len, a->used); + take -= take % a->frame; + if (take == 0 && a->used > 0) { + take = viva_in_min((size_t)len, a->used); + } + uint8_t *dst = pcm; + size_t first = viva_in_min(take, a->capacity - a->read); + memcpy(dst, a->data + a->read, first); + if (take > first) { + memcpy(dst + first, a->data, take - first); + } + a->read = (a->read + take) % a->capacity; + a->used -= take; + pthread_mutex_unlock(&a->mutex); + return (int64_t)take; +} + +void viva_audio_input_stop(viva_audio_input *a) { + if (a == NULL) { + return; + } + pthread_mutex_lock(&a->mutex); + a->closed = 1; + pthread_cond_broadcast(&a->cond); + pthread_mutex_unlock(&a->mutex); +} + +void viva_audio_input_close(viva_audio_input *a) { + if (a == NULL) { + return; + } + viva_audio_input_stop(a); + if (a->started) { + AudioOutputUnitStop(a->unit); + a->started = 0; + } + AudioUnitUninitialize(a->unit); + AudioComponentInstanceDispose(a->unit); + if (a->converter != NULL) { + AudioConverterDispose(a->converter); + } + pthread_mutex_destroy(&a->mutex); + pthread_cond_destroy(&a->cond); + free(a->data); + free(a->capture_buf); + free(a->convert_buf); + free(a); +} diff --git a/audio/input_darwin.go b/audio/input_darwin.go new file mode 100644 index 000000000..87a3e3e8c --- /dev/null +++ b/audio/input_darwin.go @@ -0,0 +1,69 @@ +//go:build darwin && !ios + +package audio + +/* +#cgo darwin LDFLAGS: -framework AudioToolbox -framework CoreAudio +#include + +typedef struct viva_audio_input viva_audio_input; + +viva_audio_input *viva_audio_input_open(double rate, uint32_t channels, int32_t *status); +int64_t viva_audio_input_read(viva_audio_input *a, void *pcm, uintptr_t len); +void viva_audio_input_stop(viva_audio_input *a); +void viva_audio_input_close(viva_audio_input *a); +*/ +import "C" + +import ( + "errors" + "fmt" + "runtime" + "unsafe" +) + +var errInputStopped = errors.New("audio: input stopped") + +type darwinInputDevice struct { + handle *C.viva_audio_input +} + +func platformInputDevice(format Format) (inputDevice, error) { + var status C.int32_t + handle := C.viva_audio_input_open(C.double(format.SampleRate), C.uint32_t(format.Channels), &status) + if handle == nil { + if status == -1 { + return nil, fmt.Errorf("audio: the default input device is missing: %w", ErrInputUnsupported) + } + return nil, fmt.Errorf("audio: open the default input unit: OSStatus %d", int32(status)) + } + return &darwinInputDevice{handle: handle}, nil +} + +func (d *darwinInputDevice) read(pcm []byte) (int, error) { + if len(pcm) == 0 { + return 0, nil + } + n := C.viva_audio_input_read(d.handle, unsafe.Pointer(&pcm[0]), C.uintptr_t(len(pcm))) + runtime.KeepAlive(pcm) + if n == 0 { + return 0, errInputStopped + } + if n < 0 { + return 0, fmt.Errorf("audio: capture on the input unit: OSStatus %d", int64(n)) + } + return int(n), nil +} + +func (d *darwinInputDevice) stop() { + if d.handle != nil { + C.viva_audio_input_stop(d.handle) + } +} + +func (d *darwinInputDevice) close() { + if d.handle != nil { + C.viva_audio_input_close(d.handle) + d.handle = nil + } +} diff --git a/audio/input_linux.go b/audio/input_linux.go new file mode 100644 index 000000000..1e8e02867 --- /dev/null +++ b/audio/input_linux.go @@ -0,0 +1,119 @@ +//go:build linux && (amd64 || arm64) + +package audio + +import ( + "errors" + "fmt" + "sync/atomic" + "time" + "unsafe" + + "github.com/ebitengine/purego" +) + +var errInputStopped = errors.New("audio: input stopped") + +type alsaInputDevice struct { + library uintptr + pcm uintptr + frame int + chunkFrames int + api *alsaAPI + stopped atomic.Bool +} + +func platformInputDevice(format Format) (inputDevice, error) { + api, library, err := openALSA() + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrInputUnsupported, err) + } + name := []byte("default\x00") + var pcm uintptr + if status := api.open(&pcm, &name[0], alsaCapture, 0); status < 0 { + message := alsaError(api, status) + purego.Dlclose(library) + return nil, fmt.Errorf("audio: open the ALSA default capture device: %s: %w", message, ErrInputUnsupported) + } + if err := configureALSA(api, pcm, format); err != nil { + api.close(pcm) + purego.Dlclose(library) + return nil, err + } + return &alsaInputDevice{ + library: library, + pcm: pcm, + frame: format.Channels * 2, + chunkFrames: max(format.SampleRate/100, 1), + api: api, + }, nil +} + +func (d *alsaInputDevice) read(pcm []byte) (int, error) { + wantFrames := min(len(pcm)/d.frame, d.chunkFrames) + if wantFrames < 1 { + wantFrames = 1 + } + for { + if d.stopped.Load() { + return 0, errInputStopped + } + ready := d.api.wait(d.pcm, 50) + if d.stopped.Load() { + return 0, errInputStopped + } + if ready == 0 { + continue + } + if ready < 0 { + if status := d.api.recover(d.pcm, ready, 1); status < 0 { + return 0, fmt.Errorf("audio: wait on the ALSA capture device: %s", alsaError(d.api, status)) + } + continue + } + got := d.api.readi(d.pcm, unsafe.Pointer(&pcm[0]), uintptr(wantFrames)) + if got > 0 { + return int(got) * d.frame, nil + } + if got == 0 { + time.Sleep(time.Millisecond) + continue + } + recovered := false + for range alsaRecoverRetries { + if d.stopped.Load() { + return 0, errInputStopped + } + if status := d.api.recover(d.pcm, int32(got), 1); status < 0 { + return 0, fmt.Errorf("audio: capture on the ALSA device: %s", alsaError(d.api, status)) + } + got = d.api.readi(d.pcm, unsafe.Pointer(&pcm[0]), uintptr(wantFrames)) + if got > 0 { + return int(got) * d.frame, nil + } + if got == 0 { + recovered = true + break + } + } + if !recovered { + return 0, fmt.Errorf("audio: the ALSA capture device stopped: %s", alsaError(d.api, int32(got))) + } + } +} + +func (d *alsaInputDevice) stop() { + d.stopped.Store(true) +} + +func (d *alsaInputDevice) close() { + if d.pcm != 0 { + d.api.drop(d.pcm) + d.api.close(d.pcm) + d.pcm = 0 + } + if d.library != 0 { + purego.Dlclose(d.library) + d.library = 0 + } +} diff --git a/audio/input_linux_other.go b/audio/input_linux_other.go new file mode 100644 index 000000000..29837afa7 --- /dev/null +++ b/audio/input_linux_other.go @@ -0,0 +1,5 @@ +//go:build linux && !amd64 && !arm64 && !android + +package audio + +func platformInputDevice(Format) (inputDevice, error) { return nil, ErrInputUnsupported } diff --git a/audio/input_other.go b/audio/input_other.go new file mode 100644 index 000000000..b029b55e5 --- /dev/null +++ b/audio/input_other.go @@ -0,0 +1,5 @@ +//go:build (!darwin || ios) && !windows && !linux + +package audio + +func platformInputDevice(Format) (inputDevice, error) { return nil, ErrInputUnsupported } diff --git a/audio/input_test.go b/audio/input_test.go new file mode 100644 index 000000000..518700a96 --- /dev/null +++ b/audio/input_test.go @@ -0,0 +1,164 @@ +package audio + +import ( + "bytes" + "errors" + "io" + "sync" + "testing" + "time" +) + +type fakeInputDevice struct { + mu sync.Mutex + chunks chan []byte + closed bool + fail error +} + +func newFakeInputDevice() *fakeInputDevice { + return &fakeInputDevice{chunks: make(chan []byte, 16)} +} + +func (d *fakeInputDevice) push(pcm []byte) { + d.chunks <- append([]byte(nil), pcm...) +} + +func (d *fakeInputDevice) read(dst []byte) (int, error) { + chunk, ok := <-d.chunks + if !ok { + if d.fail != nil { + return 0, d.fail + } + return 0, io.EOF + } + return copy(dst, chunk), nil +} + +func (d *fakeInputDevice) stop() { + d.mu.Lock() + if !d.closed { + d.closed = true + close(d.chunks) + } + d.mu.Unlock() +} + +func (d *fakeInputDevice) close() { + d.stop() +} + +func withInputDevice(t testing.TB, dev inputDevice, err error) { + t.Helper() + previous := openInputDevice + openInputDevice = func(Format) (inputDevice, error) { return dev, err } + t.Cleanup(func() { openInputDevice = previous }) +} + +func TestOpenInputRejectsBadFormats(t *testing.T) { + for _, format := range []Format{ + {SampleRate: 0, Channels: 2}, + {SampleRate: 7999, Channels: 2}, + {SampleRate: 192001, Channels: 1}, + {SampleRate: 8000, Channels: 0}, + {SampleRate: 8000, Channels: 3}, + } { + if _, err := OpenInput(format); !errors.Is(err, ErrFormat) { + t.Errorf("OpenInput(%+v) error = %v, want ErrFormat", format, err) + } + } +} + +func TestOpenInputReportsPlatformError(t *testing.T) { + withInputDevice(t, nil, ErrInputUnsupported) + if _, err := OpenInput(testFormat()); !errors.Is(err, ErrInputUnsupported) { + t.Fatalf("OpenInput error = %v, want ErrInputUnsupported", err) + } +} + +func TestInputStreamsInOrderAndCloseUnblocksRead(t *testing.T) { + dev := newFakeInputDevice() + withInputDevice(t, dev, nil) + + in, err := OpenInput(Format{SampleRate: 16000, Channels: 1}) + if err != nil { + t.Fatal(err) + } + if in.Format() != (Format{SampleRate: 16000, Channels: 1}) { + t.Fatalf("Format() = %+v", in.Format()) + } + + want := []byte{1, 2, 3, 4, 5, 6, 7, 8} + dev.push(want[:4]) + dev.push(want[4:]) + + got := make([]byte, len(want)) + if _, err := io.ReadFull(in, got); err != nil { + t.Fatalf("ReadFull: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("read %v, want %v", got, want) + } + + readErr := make(chan error, 1) + go func() { + var buf [16]byte + _, err := in.Read(buf[:]) + readErr <- err + }() + time.Sleep(20 * time.Millisecond) + if err := in.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + select { + case err := <-readErr: + if !errors.Is(err, io.EOF) { + t.Fatalf("Read after Close = %v, want io.EOF", err) + } + case <-time.After(time.Second): + t.Fatal("Read did not unblock after Close") + } + if err := in.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } +} + +func TestInputRingDropsOldestFramesWhenOverflowed(t *testing.T) { + dev := newFakeInputDevice() + withInputDevice(t, dev, nil) + + in, err := OpenInput(Format{SampleRate: 8000, Channels: 2}) + if err != nil { + t.Fatal(err) + } + defer in.Close() + + // Ring size for 8000 Hz stereo is 8000 bytes; push 10000 bytes so the first + // 2000 bytes are dropped in favor of newer frames. + chunk := make([]byte, 4000) + for i := range chunk { + chunk[i] = 1 + } + dev.push(chunk) + chunk2 := make([]byte, 4000) + for i := range chunk2 { + chunk2[i] = 2 + } + dev.push(chunk2) + chunk3 := make([]byte, 2000) + for i := range chunk3 { + chunk3[i] = 3 + } + dev.push(chunk3) + + // Wait briefly for the capture goroutine to drain all 3 chunks into the ring. + time.Sleep(30 * time.Millisecond) + + buf := make([]byte, 8000) + if _, err := io.ReadFull(in, buf); err != nil { + t.Fatalf("ReadFull: %v", err) + } + if buf[0] != 1 || buf[2000] != 2 || buf[6000] != 3 { + t.Fatalf("ring overwrite unexpected: first=%d mid=%d tail=%d", buf[0], buf[2000], buf[6000]) + } +} diff --git a/audio/input_windows.go b/audio/input_windows.go new file mode 100644 index 000000000..a8863067b --- /dev/null +++ b/audio/input_windows.go @@ -0,0 +1,206 @@ +//go:build windows + +package audio + +import ( + "errors" + "fmt" + "runtime" + "sync" + "unsafe" + + "golang.org/x/sys/windows" +) + +const ( + wasapiCapture = 1 // eCapture + wasapiBufferFlagSilent = 0x2 +) + +var ( + iidAudioCaptureClient = guid{0xC8ADBD64, 0xE71E, 0x48A0, [8]byte{0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}} + errInputStopped = errors.New("audio: input stopped") +) + +type wasapiInputDevice struct { + enumerator uintptr + endpoint uintptr + client uintptr + capture uintptr + audioEvent windows.Handle + stopMu sync.Mutex + stopEvent windows.Handle + started bool + frameBytes int +} + +func platformInputDevice(format Format) (inputDevice, error) { + result, _, _ := coInitializeEx.Call(0, coinitMultithreaded) + switch uint32(result) { + case 0, coinitSFalse: + case hresultChangedMode: + return nil, fmt.Errorf("audio: the audio thread is already in a COM apartment of another mode: %w", ErrInputUnsupported) + default: + return nil, hresult("initialize COM", result) + } + d := &wasapiInputDevice{frameBytes: format.Channels * 2} + if err := d.open(format); err != nil { + d.close() + return nil, err + } + return d, nil +} + +func (d *wasapiInputDevice) open(format Format) error { + r, _, _ := coCreateInstance.Call( + uintptr(unsafe.Pointer(&clsidMMDeviceEnumerator)), + 0, + clsctxAll, + uintptr(unsafe.Pointer(&iidMMDeviceEnumerator)), + uintptr(unsafe.Pointer(&d.enumerator)), + ) + runtime.KeepAlive(&clsidMMDeviceEnumerator) + runtime.KeepAlive(&iidMMDeviceEnumerator) + if err := hresult("create the audio endpoint enumerator", r); err != nil { + return fmt.Errorf("%w: %v", ErrInputUnsupported, err) + } + // IMMDeviceEnumerator::GetDefaultAudioEndpoint(eCapture, eConsole, ...). + if r := comCall(d.enumerator, 4, wasapiCapture, wasapiConsole, uintptr(unsafe.Pointer(&d.endpoint))); int32(uint32(r)) < 0 { + return fmt.Errorf("audio: no default input device: %w", ErrInputUnsupported) + } + // IMMDevice::Activate(IID_IAudioClient, ...). + if r := comCall(d.endpoint, 3, uintptr(unsafe.Pointer(&iidAudioClient)), clsctxAll, 0, uintptr(unsafe.Pointer(&d.client))); int32(uint32(r)) < 0 { + return hresult("activate the audio capture client", r) + } + + wfx := waveFormatEx{ + FormatTag: waveFormatPCM, + Channels: uint16(format.Channels), + SamplesPerSec: uint32(format.SampleRate), + BlockAlign: uint16(format.Channels * 2), + BitsPerSample: 16, + } + wfx.AvgBytesPerSec = wfx.SamplesPerSec * uint32(wfx.BlockAlign) + const flags = wasapiEventCallback | wasapiAutoConvertPCM | wasapiSRCDefaultQuality + if r := comCall(d.client, 3, + wasapiShareModeShared, + flags, + wasapiBufferDuration100ns, + 0, + uintptr(unsafe.Pointer(&wfx)), + 0, + ); int32(uint32(r)) < 0 { + return hresult("initialize the audio capture client", r) + } + runtime.KeepAlive(&wfx) + + var frames uint32 + if r := comCall(d.client, 4, uintptr(unsafe.Pointer(&frames))); int32(uint32(r)) < 0 { + return hresult("read the capture buffer size", r) + } + if frames == 0 { + return fmt.Errorf("audio: the audio capture client reported an empty buffer") + } + // IAudioClient::GetService(IID_IAudioCaptureClient). + if r := comCall(d.client, 14, uintptr(unsafe.Pointer(&iidAudioCaptureClient)), uintptr(unsafe.Pointer(&d.capture))); int32(uint32(r)) < 0 { + return hresult("get the audio capture client", r) + } + audioEvent, err := windows.CreateEvent(nil, 0, 0, nil) + if err != nil { + return fmt.Errorf("audio: create the capture event: %w", err) + } + d.audioEvent = audioEvent + stopEvent, err := windows.CreateEvent(nil, 1, 0, nil) + if err != nil { + return fmt.Errorf("audio: create the capture stop event: %w", err) + } + d.stopEvent = stopEvent + // IAudioClient::SetEventHandle. + if r := comCall(d.client, 13, uintptr(d.audioEvent)); int32(uint32(r)) < 0 { + return hresult("set the capture event", r) + } + // IAudioClient::Start. + if r := comCall(d.client, 10); int32(uint32(r)) < 0 { + return hresult("start the audio capture client", r) + } + d.started = true + return nil +} + +func (d *wasapiInputDevice) read(pcm []byte) (int, error) { + written := 0 + for written == 0 { + var packetFrames uint32 + if r := comCall(d.capture, 5, uintptr(unsafe.Pointer(&packetFrames))); int32(uint32(r)) < 0 { + return 0, hresult("read the next capture packet size", r) + } + if packetFrames == 0 { + handles := [2]windows.Handle{d.audioEvent, d.stopEvent} + ev, err := windows.WaitForMultipleObjects(handles[:], false, 200) + if err != nil { + return 0, fmt.Errorf("audio: wait for capture event: %w", err) + } + if ev == windows.WAIT_OBJECT_0+1 { + return 0, errInputStopped + } + continue + } + for packetFrames > 0 { + var data unsafe.Pointer + var numFrames uint32 + var flags uint32 + if r := comCall(d.capture, 3, uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&numFrames)), uintptr(unsafe.Pointer(&flags)), 0, 0); int32(uint32(r)) < 0 { + return written, hresult("get a capture buffer", r) + } + nBytes := int(numFrames) * d.frameBytes + if nBytes > 0 && written+nBytes <= len(pcm) { + if flags&wasapiBufferFlagSilent != 0 || data == nil { + clear(pcm[written : written+nBytes]) + } else { + copy(pcm[written:written+nBytes], unsafe.Slice((*byte)(data), nBytes)) + } + written += nBytes + } + if r := comCall(d.capture, 4, uintptr(numFrames)); int32(uint32(r)) < 0 { + return written, hresult("release a capture buffer", r) + } + if written >= len(pcm) { + break + } + if r := comCall(d.capture, 5, uintptr(unsafe.Pointer(&packetFrames))); int32(uint32(r)) < 0 { + return written, hresult("read the next capture packet size", r) + } + } + } + return written, nil +} + +func (d *wasapiInputDevice) stop() { + d.stopMu.Lock() + if d.stopEvent != 0 { + _ = windows.SetEvent(d.stopEvent) + } + d.stopMu.Unlock() +} + +func (d *wasapiInputDevice) close() { + if d.client != 0 && d.started { + comCall(d.client, 11) // Stop + d.started = false + } + release(&d.capture) + release(&d.client) + release(&d.endpoint) + release(&d.enumerator) + if d.audioEvent != 0 { + _ = windows.CloseHandle(d.audioEvent) + d.audioEvent = 0 + } + d.stopMu.Lock() + if d.stopEvent != 0 { + _ = windows.CloseHandle(d.stopEvent) + d.stopEvent = 0 + } + d.stopMu.Unlock() + coUninitialize.Call() +} diff --git a/audio/output_linux.go b/audio/output_linux.go index fee369b1c..95df636ab 100644 --- a/audio/output_linux.go +++ b/audio/output_linux.go @@ -13,6 +13,7 @@ import ( // ALSA constants (alsa/pcm.h). const ( alsaPlayback = 0 + alsaCapture = 1 alsaNoWait = 1 // SND_PCM_NONBLOCK, deliberately not used alsaAccessRWInter = 3 // SND_PCM_ACCESS_RW_INTERLEAVED alsaFormatS16LE = 2 // SND_PCM_FORMAT_S16_LE @@ -35,7 +36,9 @@ type alsaAPI struct { drop func(pcm uintptr) int32 prepare func(pcm uintptr) int32 recover func(pcm uintptr, err int32, silent int32) int32 + wait func(pcm uintptr, timeout int32) int32 writei func(pcm uintptr, buf unsafe.Pointer, frames uintptr) int64 + readi func(pcm uintptr, buf unsafe.Pointer, frames uintptr) int64 strerror func(err int32) *byte paramsMalloc func(params *uintptr) int32 paramsFree func(params uintptr) @@ -67,7 +70,9 @@ func openALSA() (*alsaAPI, uintptr, error) { purego.RegisterLibFunc(&api.drop, library, "snd_pcm_drop") purego.RegisterLibFunc(&api.prepare, library, "snd_pcm_prepare") purego.RegisterLibFunc(&api.recover, library, "snd_pcm_recover") + purego.RegisterLibFunc(&api.wait, library, "snd_pcm_wait") purego.RegisterLibFunc(&api.writei, library, "snd_pcm_writei") + purego.RegisterLibFunc(&api.readi, library, "snd_pcm_readi") purego.RegisterLibFunc(&api.strerror, library, "snd_strerror") purego.RegisterLibFunc(&api.paramsMalloc, library, "snd_pcm_hw_params_malloc") purego.RegisterLibFunc(&api.paramsFree, library, "snd_pcm_hw_params_free") From f9c0fcee8b2922e1ad4d4ba42379a65308070d93 Mon Sep 17 00:00:00 2001 From: darrenjindai <279011405@qq.com> Date: Fri, 27 Nov 2026 23:17:10 +0800 Subject: [PATCH 08/29] feat(app): add native window watermarks --- app/app.go | 8 + app/application.go | 1 + app/application_native.go | 14 + app/capabilities.go | 3 + app/capabilities_native.go | 2 +- app/capability_watermark_native.go | 5 + app/capability_watermark_other.go | 5 + app/content_window.go | 8 + app/run.go | 4 + app/run_canvas.go | 4 + app/watermark.go | 78 ++++ app/watermark_test.go | 93 +++++ docs/window-watermark.md | 92 +++++ examples/guides/watermark/main.go | 21 ++ gfx/theme.go | 1 + headless/application.go | 29 +- headless/application_test.go | 35 ++ internal/platform/contract.go | 3 +- internal/platform/darwin/native.h | 2 + internal/platform/darwin/native.m | 33 ++ internal/platform/darwin/platform.go | 10 + .../platform/darwin/testdata/dock_reopen.m | 1 + internal/platform/darwin/testdata/file_drop.m | 1 + .../platform/darwin/testdata/live_resize.m | 1 + .../platform/darwin/testdata/modifier_taps.m | 1 + .../platform/darwin/testdata/text_selection.m | 1 + .../platform/darwin/testdata/traffic_lights.m | 1 + internal/platform/darwin/testdata/watermark.m | 79 ++++ .../platform/darwin/testdata/window_close.m | 1 + .../darwin/testdata/window_decoration.m | 1 + .../darwin/testdata/window_notification.m | 1 + .../platform/darwin/testdata/window_size.m | 1 + .../darwin/watermark_config_darwin.go | 13 + internal/platform/darwin/watermark_darwin.go | 33 ++ internal/platform/darwin/watermark_darwin.h | 13 + internal/platform/darwin/watermark_darwin.m | 254 +++++++++++++ .../platform/darwin/watermark_darwin_test.go | 20 + internal/platform/darwin/web_darwin.m | 2 + internal/platform/watermark.go | 93 +++++ internal/platform/watermark_test.go | 71 ++++ .../platform/windows/always_on_top_windows.go | 3 + internal/platform/windows/text_windows.go | 4 +- .../platform/windows/text_windows_test.go | 7 + .../platform/windows/watermark_windows.go | 342 ++++++++++++++++++ .../windows/watermark_windows_test.go | 124 +++++++ internal/platform/windows/web_windows.go | 2 + internal/platform/windows/window_windows.go | 38 ++ 47 files changed, 1555 insertions(+), 4 deletions(-) create mode 100644 app/capability_watermark_native.go create mode 100644 app/capability_watermark_other.go create mode 100644 app/watermark.go create mode 100644 app/watermark_test.go create mode 100644 docs/window-watermark.md create mode 100644 examples/guides/watermark/main.go create mode 100644 internal/platform/darwin/testdata/watermark.m create mode 100644 internal/platform/darwin/watermark_config_darwin.go create mode 100644 internal/platform/darwin/watermark_darwin.go create mode 100644 internal/platform/darwin/watermark_darwin.h create mode 100644 internal/platform/darwin/watermark_darwin.m create mode 100644 internal/platform/darwin/watermark_darwin_test.go create mode 100644 internal/platform/watermark.go create mode 100644 internal/platform/watermark_test.go create mode 100644 internal/platform/windows/watermark_windows.go create mode 100644 internal/platform/windows/watermark_windows_test.go diff --git a/app/app.go b/app/app.go index ccced95e7..7022a8f5d 100644 --- a/app/app.go +++ b/app/app.go @@ -149,6 +149,9 @@ type Config struct { // at window creation, even if it initially returns BackdropNone, allowing // later material changes without rebuilding the application. WindowBackdrop func() BackdropStyle + // Watermark is an input-transparent native overlay above all content, including + // web views. Unsupported native platforms ignore it; see CapabilityWindowWatermark. + Watermark Watermark // OnBackdropChange reports API activation initially and when it changes. // Windows may still substitute a solid color. Other platforms do not call // it. Update paint state without blocking; a change schedules a repaint. @@ -333,6 +336,11 @@ type StateSlot struct { } func (config Config) normalize() (Config, error) { + watermark, err := config.Watermark.normalized() + if err != nil { + return Config{}, err + } + config.Watermark = watermark if config.Title == "" { config.Title = defaultTitle } diff --git a/app/application.go b/app/application.go index cb2dfeaac..0c4af0d9f 100644 --- a/app/application.go +++ b/app/application.go @@ -23,6 +23,7 @@ var ErrNoWindows = errors.New("app: application opened no windows") // 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. +// A watermark-capable host additionally implements SetWatermark(Watermark) error. // A decoration-capable host additionally implements SetDecorated(bool, func(error)) error. type WindowControl interface { Close() diff --git a/app/application_native.go b/app/application_native.go index 2417b33ec..134d48198 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -76,6 +76,11 @@ func (host nativeHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func cleanup() return nil, err } + if config.Watermark.Text != "" { + if _, ok := window.(nativeWatermarkControl); !ok { + reportUnsupportedWatermark() + } + } // A command the runtime did not receive through an event handler, such as a // menu action, hands its result here: the painter carries it out and the // window's waker asks for the frame that shows it. @@ -99,6 +104,7 @@ var _ fullscreenControl = resultWindow{} var _ alwaysOnTopControl = resultWindow{} var _ shortcutCapturer = resultWindow{} var _ titleControl = resultWindow{} +var _ watermarkControl = resultWindow{} var _ windowIconControl = resultWindow{} var _ platform.WindowMover = resultWindow{} @@ -276,6 +282,14 @@ func (host nativeHost) Quit() { host.native.Quit() } func (host nativeHost) Post(fn func()) { host.native.Post(fn) } +func (window resultWindow) SetWatermark(value Watermark) error { + control, ok := window.WindowControl.(nativeWatermarkControl) + if !ok { + return fmt.Errorf("%w: window watermarks", ErrUnsupported) + } + return control.SetWatermark(value.platform()) +} + type nativeStatusItem struct{ item platform.StatusItem } func (item nativeStatusItem) SetIcon(icon StatusIcon) error { diff --git a/app/capabilities.go b/app/capabilities.go index 87a4d5245..cae63c14e 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -66,6 +66,9 @@ const ( // CapabilityNotificationActivation means an application can own cancellable // system notifications and receive activation while its loop is running. CapabilityNotificationActivation + // CapabilityWindowWatermark means native text patterns can cover canvas and + // embedded native views without receiving input. + CapabilityWindowWatermark ) // Capabilities is a set of platform integrations. diff --git a/app/capabilities_native.go b/app/capabilities_native.go index 5dbd9c013..9e88abdd5 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -42,6 +42,6 @@ func nativeCapabilities() Capabilities { } else { capabilities |= CapabilityWindowMaximize } - capabilities |= capabilityTransparentWindow | capabilityNotificationActivation + capabilities |= capabilityTransparentWindow | capabilityNotificationActivation | capabilityWindowWatermark return Capabilities(capabilities) } diff --git a/app/capability_watermark_native.go b/app/capability_watermark_native.go new file mode 100644 index 000000000..6afcaa64a --- /dev/null +++ b/app/capability_watermark_native.go @@ -0,0 +1,5 @@ +//go:build (darwin && !ios) || windows + +package app + +const capabilityWindowWatermark = CapabilityWindowWatermark diff --git a/app/capability_watermark_other.go b/app/capability_watermark_other.go new file mode 100644 index 000000000..9c463da78 --- /dev/null +++ b/app/capability_watermark_other.go @@ -0,0 +1,5 @@ +//go:build (!darwin && !windows) || ios + +package app + +const capabilityWindowWatermark Capability = 0 diff --git a/app/content_window.go b/app/content_window.go index 740a43678..2993b6a40 100644 --- a/app/content_window.go +++ b/app/content_window.go @@ -126,3 +126,11 @@ func (content *ContentWindow) RequestClose() { content.Close() } } + +// SetWatermark updates the content window's native overlay, as Window.SetWatermark. +func (content *ContentWindow) SetWatermark(value Watermark) error { + if content == nil || content.window == nil { + return fmt.Errorf("app: content window is closed") + } + return content.window.SetWatermark(value) +} diff --git a/app/run.go b/app/run.go index 783f4cd8a..9c74ba81b 100644 --- a/app/run.go +++ b/app/run.go @@ -19,10 +19,14 @@ func Run(config Config) error { return err } + if normalized.Watermark.Text != "" && !Supports(CapabilityWindowWatermark) { + reportUnsupportedWatermark() + } runtime.LockOSThread() defer runtime.UnlockOSThread() return runNative(platform.Config{ + Watermark: normalized.Watermark.platform(), Title: normalized.Title, Class: normalized.Class, Icon: normalized.Icon.platform(), diff --git a/app/run_canvas.go b/app/run_canvas.go index 6beb89fac..db3443e18 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -27,6 +27,9 @@ func RunCanvas(config Config, canvas *gfx.Canvas) error { if err != nil { return err } + if normalized.Watermark.Text != "" && !Supports(CapabilityWindowWatermark) { + reportUnsupportedWatermark() + } if normalized.TextInput != nil && !nativeTextInputSupported { return fmt.Errorf("%w: native text input", ErrUnsupported) } @@ -173,6 +176,7 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, closeHandler = platform.CloseRequestHandler(normalized.OnCloseRequest) } config := platform.Config{ + Watermark: normalized.Watermark.platform(), Actions: painter.windowActions(), TextInput: painter.initialTextInput(), TakeTextMenu: painter.textMenuTaker(), diff --git a/app/watermark.go b/app/watermark.go new file mode 100644 index 000000000..67c95cd92 --- /dev/null +++ b/app/watermark.go @@ -0,0 +1,78 @@ +package app + +import ( + "fmt" + "sync" + + "github.com/vivaui/viva/gfx" + + "github.com/vivaui/viva/internal/diag" + "github.com/vivaui/viva/internal/platform" +) + +// Watermark is a retained, input-transparent single-line text pattern above canvas and native +// views. Text is centered in each tile using font metrics, then the pattern is +// rotated by Angle degrees in the content's top-left, Y-down coordinate system. +// Zero sizes use 12pt text and a 240 by 180 logical-pixel tile. A zero Color uses +// neutral gray at 12% opacity; other colors are linear RGBA, as Config.ClearColor. +// FontWeight uses gfx.WeightLight through gfx.WeightBold. FontFamily optionally +// names an installed family, with native fallback; empty uses the system font. +// Typography is explicit and independent of the canvas's interface font setting. +// Text is limited to 16 KiB, font size to 4096 logical pixels and tile sides to +// 8192 logical pixels; native backing tiles are additionally limited to 16 Mpixels. +// Empty Text disables the overlay. Use Supports(CapabilityWindowWatermark) to +// check native support; headless hosts may record the configuration for tests. +type Watermark struct { + Text, FontFamily string + Color Color + FontSize, FontWeight, Angle float32 + TileWidth, TileHeight float32 + Insets gfx.Insets +} + +func (w Watermark) platform() platform.Watermark { + return platform.Watermark{Text: w.Text, FontFamily: w.FontFamily, Color: platform.Color(w.Color), FontSize: w.FontSize, FontWeight: w.FontWeight, Angle: w.Angle, TileWidth: w.TileWidth, TileHeight: w.TileHeight, Insets: w.Insets} +} + +func (w Watermark) normalized() (Watermark, error) { + value, err := platform.NormalizeWatermark(w.platform()) + if err != nil { + return Watermark{}, err + } + return Watermark{Text: value.Text, FontFamily: value.FontFamily, Color: Color(value.Color), FontSize: value.FontSize, FontWeight: value.FontWeight, Angle: value.Angle, TileWidth: value.TileWidth, TileHeight: value.TileHeight, Insets: value.Insets}, nil +} + +// Hosts implement this optional capability using the public value; application +// hosts outside Viva cannot import internal/platform. +type watermarkControl interface{ SetWatermark(Watermark) error } +type nativeWatermarkControl interface { + SetWatermark(platform.Watermark) error +} + +// SetWatermark replaces the retained overlay. Calls are safe from any goroutine; +// native changes run on the window thread, and Windows queues the latest request. +// A successful return accepts the request, not completion of native rendering. +// Invalid requests change nothing; asynchronous native failures use the diagnostic +// sink. Unsupported hosts return an error wrapping ErrUnsupported. +func (window *Window) SetWatermark(value Watermark) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("app: window is closed") + } + value, err := value.normalized() + if err != nil { + return err + } + control, ok := window.control.(watermarkControl) + if !ok { + return fmt.Errorf("%w: window watermarks", ErrUnsupported) + } + return control.SetWatermark(value) +} + +var unsupportedWatermarkNotice sync.Once + +func reportUnsupportedWatermark() { + unsupportedWatermarkNotice.Do(func() { + diag.Report(diag.Debug, "window", "watermark-unsupported", "native window watermarks are unsupported by this host") + }) +} diff --git a/app/watermark_test.go b/app/watermark_test.go new file mode 100644 index 000000000..36fbc78df --- /dev/null +++ b/app/watermark_test.go @@ -0,0 +1,93 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +type watermarkTestControl struct { + fakeWindow + values []platform.Watermark +} + +func (control *watermarkTestControl) SetWatermark(value platform.Watermark) error { + control.values = append(control.values, value) + return nil +} + +func TestWatermarkDelegatesThroughResultWindowAndRejectsInvalidChanges(t *testing.T) { + control := &watermarkTestControl{} + window := &Window{control: resultWindow{WindowControl: control}} + value := Watermark{Text: "测试用户 10086", Color: Color{Alpha: 0.1}, FontWeight: -0.4} + if err := window.SetWatermark(value); err != nil { + t.Fatal(err) + } + if len(control.values) != 1 || control.values[0].Text != value.Text || control.values[0].FontSize != 12 { + t.Fatal("optional capability lost in native wrapper", control.values) + } + value.Insets.Left = -1 + if err := window.SetWatermark(value); err == nil || len(control.values) != 1 { + t.Fatal("invalid change reached host") + } + window.closed.Store(true) + if err := window.SetWatermark(Watermark{}); err == nil { + t.Fatal("closed window accepted change") + } + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetWatermark(Watermark{}); !errors.Is(err, ErrUnsupported) { + t.Fatal("unsupported host lost sentinel", err) + } +} + +func TestWatermarkInitialConfigNormalization(t *testing.T) { + value, err := (Config{Watermark: Watermark{Text: "测试用户 10086", Color: Color{Alpha: 0.1}}}).normalize() + if err != nil || value.Watermark.FontSize != 12 { + t.Fatal("initial watermark not normalized", err, value.Watermark) + } + _, err = (Config{Watermark: Watermark{Text: "bad\x00value"}}).normalize() + if err == nil { + t.Fatal("invalid initial text accepted") + } +} + +func TestWatermarkReachesNativeWindowConfig(t *testing.T) { + value := Watermark{Text: "测试用户 10086", Color: Color{Alpha: 0.1}, Insets: gfx.Insets{Top: 42, Left: 120}} + normalized, err := (Config{Watermark: value}).normalize() + if err != nil { + t.Fatal(err) + } + painter, err := newPainter(&gfx.Canvas{}, &normalized) + if err != nil { + t.Fatal(err) + } + config, frames := nativeWindowConfig(&normalized, painter) + if frames != nil { + defer frames.stop() + } + if config.Watermark.Text != value.Text || config.Watermark.Insets != value.Insets || config.Watermark.TileWidth != 240 { + t.Fatal("native initial configuration lost watermark", config.Watermark) + } +} + +func TestWatermarkTextOnlyDefaultsAndContentWindowForwarding(t *testing.T) { + control := &watermarkTestControl{} + content := &ContentWindow{window: &Window{control: resultWindow{WindowControl: control}}} + if err := content.SetWatermark(Watermark{Text: "DRAFT"}); err != nil { + t.Fatal(err) + } + if len(control.values) != 1 || control.values[0].Color.Alpha <= 0 { + t.Fatal("text-only watermark is invisible", control.values) + } + if err := content.SetWatermark(Watermark{}); err != nil || control.values[1] != (platform.Watermark{}) { + t.Fatal("empty text did not disable watermark", err) + } + var closed *ContentWindow + if err := closed.SetWatermark(Watermark{}); err == nil { + t.Fatal("nil content window accepted watermark") + } +} diff --git a/docs/window-watermark.md b/docs/window-watermark.md new file mode 100644 index 000000000..3d61c46f5 --- /dev/null +++ b/docs/window-watermark.md @@ -0,0 +1,92 @@ +# Native window watermarks + +A native watermark is an input-transparent tiled text overlay above both canvas +content and embedded native views. It belongs to a window, including an +`OpenContentWindow` document or tool window. Text, identity and coverage policy +belong to the application. + +```go +config := app.Config{ + Title: "Document", + Width: 800, Height: 500, + Watermark: app.Watermark{Text: "DRAFT"}, +} +``` + +Text alone is visible: the zero color selects neutral linear gray at 12% opacity, +zero font size selects 12 logical pixels, and the tile defaults to 240 by 180 +logical pixels. Text is centered horizontally and vertically using font metrics. +There is no SVG baseline parameter. Empty text, including `app.Watermark{}`, +removes the overlay. A nonzero color is used exactly, including its alpha. + +For explicit styling, use existing framework types: + +```go +config.Watermark = app.Watermark{ + Text: "CONFIDENTIAL", + FontWeight: gfx.WeightLight, + FontFamily: "Arial", // optional; empty uses the native system font + Angle: -25, + Insets: gfx.All(24), +} +``` + +The watermark's typography is explicit and independent of interface-font state. +Applications that want the same family pass their selected family when updating +the watermark. This avoids making window composition depend on the canvas text +engine or on process-global font changes. Native fallback handles missing faces +and glyphs. Weight uses the same scale and constants as `gfx.TextStyle.Weight`. + +`app.Supports(app.CapabilityWindowWatermark)` reports native support on macOS and +Windows. Capabilities are static for a build target, rather than a runtime-host +promise. Other native platforms ignore initial configuration and return +`app.ErrUnsupported` for updates. The headless application host records normalized +state and accepts updates for lifecycle tests; it does not draw a native overlay. + +`window.SetWatermark(value)` and `contentWindow.SetWatermark(value)` are safe from +any goroutine. Validation completes before a request reaches the host. Windows +coalesces pending requests and applies the latest one on its window thread; +macOS applies on the main thread. Success means the request was accepted, not that +a frame is already presented. Later native failures use the diagnostic sink. +Custom `app.Host` controls implement the optional public method +`SetWatermark(app.Watermark) error`; no internal package import is required. + +Text must be valid UTF-8 without NUL or line breaks, at most 16 KiB. Color channels +must be finite and in [0,1], dimensions and insets finite and nonnegative, and +weight between `gfx.WeightLight` and `gfx.WeightBold`. Font size is at most 4096, +tile sides at most 8192 logical pixels; a native tile is additionally limited to +8192 pixels per side and 16 Mpixels at the actual backing scale. Invalid public +requests leave existing state intact. Windows restores prior configuration if +native application of an accepted request fails. + +## Lifecycle and cost + +No watermark view or popup is created for an empty watermark. Enabled macOS +windows retain a small backing-scale text tile and clipping/composition layers. +The inverse-rotated clip rectangle bounds the pattern plane and keeps its origin +stable during resize. An unattached view waits for the real window's backing +scale before generating a tile. + +Enabled Windows windows retain a 4-byte-per-pixel client DIB, a small tile and +Direct2D resources. The client DIB is released while hidden or minimized. +Translation reuses retained pixels; rotation and insets do not rasterize text +again. Resize follows the window's existing resize scheduler. The owned overlay +tracks its owner's topmost promotion and demotion. + +## Reproduce and verify + +Run `go run ./examples/guides/watermark` on macOS or Windows. Verify button input, +resize, mixed-DPI moves, hide/show, and removal through `SetWatermark` with empty +text. To exercise native-view stacking, configure a web view in the same window +and verify that the watermark covers it while text selection and scrolling still +reach the page. + +Automated contracts cover normalization, visible zero-value styling, bounds, +public-host forwarding, content-window forwarding and headless retention/close. +The native macOS fixture creates real CoreText lines and CGPatterns, tests +centering, backing-scale orientation, inverse-rotation coverage, view stacking, +clipping and input transparency, without drawing text or taking screenshots. +Windows native tests additionally exercise topmost transitions and retained +translation/resize behavior; cross-compilation alone does not verify those tests +on a Windows desktop. Real-device visual acceptance is separate from these +contracts. diff --git a/examples/guides/watermark/main.go b/examples/guides/watermark/main.go new file mode 100644 index 000000000..1d633af98 --- /dev/null +++ b/examples/guides/watermark/main.go @@ -0,0 +1,21 @@ +// A native watermark stays above embedded views without receiving input. +package main + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "log" +) + +func main() { + config := app.Config{Title: "Native watermark", Width: 800, Height: 500} + if app.Supports(app.CapabilityWindowWatermark) { + config.Watermark = app.Watermark{Text: "DRAFT", Angle: -25, FontWeight: gfx.WeightLight, Insets: gfx.All(24)} + } + if err := ui.Run(config, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Children(func() { ui.Button(c, "The watermark does not intercept input") }) + }}); err != nil { + log.Fatal(err) + } +} diff --git a/gfx/theme.go b/gfx/theme.go index 09079f605..f6d1af0b3 100644 --- a/gfx/theme.go +++ b/gfx/theme.go @@ -6,6 +6,7 @@ import ( ) const ( + WeightLight float32 = -0.4 WeightRegular float32 = 0 WeightMedium float32 = 0.15 WeightSemibold float32 = 0.23 diff --git a/headless/application.go b/headless/application.go index aa9e89f9d..fc6744eaf 100644 --- a/headless/application.go +++ b/headless/application.go @@ -15,6 +15,7 @@ import ( "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" ) type applicationWindow struct { @@ -26,6 +27,7 @@ type applicationWindow struct { id uint64 title string icon app.WindowIcon + watermark platform.Watermark panel bool notification bool hidden bool @@ -87,7 +89,11 @@ func (application *applicationSession) Post(fn func()) { // OpenWindow implements app.Host. func (application *applicationSession) OpenWindow(config app.Config, canvas *gfx.Canvas, closed func()) (app.WindowControl, error) { - entry := &applicationWindow{icon: config.Icon} + watermark, err := headlessWatermark(config.Watermark) + if err != nil { + return nil, err + } + entry := &applicationWindow{icon: config.Icon, watermark: watermark} if config.Invalidator == nil { config.Invalidator = &app.Invalidator{} } @@ -745,3 +751,24 @@ func (application *applicationSession) afterCommand(reply string) (string, bool) } return strings.TrimSuffix(reply, "\n") + " windows=0\n", true } + +// SetWatermark records normalized state without claiming native composition support. +// The application lock provides the same any-goroutine contract as native controls. +func (window *headlessWindow) SetWatermark(request app.Watermark) error { + value, err := headlessWatermark(request) + if err != nil { + return err + } + window.application.mu.Lock() + defer window.application.mu.Unlock() + entry := window.application.windows[window.id] + if entry == nil { + return fmt.Errorf("headless: window is closed") + } + entry.watermark = value + return nil +} + +func headlessWatermark(value app.Watermark) (platform.Watermark, error) { + return platform.NormalizeWatermark(platform.Watermark{Text: value.Text, FontFamily: value.FontFamily, Color: platform.Color(value.Color), FontSize: value.FontSize, FontWeight: value.FontWeight, Angle: value.Angle, TileWidth: value.TileWidth, TileHeight: value.TileHeight, Insets: value.Insets}) +} diff --git a/headless/application_test.go b/headless/application_test.go index 1c7b83f30..2eddb9924 100644 --- a/headless/application_test.go +++ b/headless/application_test.go @@ -186,3 +186,38 @@ func TestProgressCommandReportsWhatTheIconWasAskedToShow(t *testing.T) { t.Fatalf("cleared: %q", text) } } + +func TestHeadlessWatermarkRecordsStateAndRejectsClosedUpdates(t *testing.T) { + application := newApplicationSession(Options{Scale: 1}) + defer application.closeAll() + control, err := application.OpenWindow(app.Config{Title: "watermark", Width: 200, Height: 100, Watermark: app.Watermark{Text: "DRAFT"}}, nil, func() {}) + if err != nil { + t.Fatal(err) + } + window := control.(*headlessWindow) + application.mu.Lock() + initial := application.windows[window.id].watermark + application.mu.Unlock() + if initial.Text != "DRAFT" || initial.Color.Alpha <= 0 { + t.Fatal("initial state was lost", initial) + } + value := app.Watermark{Text: "CONFIDENTIAL"} + if err := window.SetWatermark(value); err != nil { + t.Fatal(err) + } + invalid := value + invalid.Insets.Left = -1 + if err := window.SetWatermark(invalid); err == nil { + t.Fatal("invalid update accepted") + } + application.mu.Lock() + current := application.windows[window.id].watermark + application.mu.Unlock() + if current.Text != value.Text { + t.Fatal("invalid update changed retained state") + } + window.Close() + if err := window.SetWatermark(value); err == nil { + t.Fatal("closed host accepted update") + } +} diff --git a/internal/platform/contract.go b/internal/platform/contract.go index bc6541ad4..07806937f 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -23,7 +23,8 @@ type Color struct { // Config contains the data needed to create a native window. type Config struct { - Title string + Watermark Watermark + Title string // Class names the application to the desktop environment where it keeps // windows of one application together under a launcher entry (the X11 // WM_CLASS). Empty means the executable's file name. diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 9e3e6fdaa..36863dc09 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -1,3 +1,4 @@ +#include "watermark_darwin.h" #ifndef VIVA_INTERNAL_PLATFORM_DARWIN_NATIVE_H #define VIVA_INTERNAL_PLATFORM_DARWIN_NATIVE_H @@ -304,6 +305,7 @@ enum { typedef struct { const char *title; + viva_watermark watermark; int width; int height; int min_width; diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 50af4326f..e9d9988bd 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -3582,6 +3582,9 @@ - (BOOL)canBecomeMainWindow { @end @interface VivaAppDelegate : NSObject { + viva_watermark _initialWatermark; + NSString *_initialWatermarkText; + NSString *_initialWatermarkFamily; NSRect _anchor; BOOL _hasAnchor; BOOL _hasOrigin; @@ -3703,6 +3706,11 @@ - (instancetype)initWithConfig:(viva_window_config)config self = [super init]; if (self != nil) { _title = [[NSString alloc] initWithUTF8String:config.title]; + _initialWatermark = config.watermark; + _initialWatermarkText = [[NSString alloc] initWithUTF8String:config.watermark.text ?: ""]; + _initialWatermark.text = NULL; + _initialWatermarkFamily = [[NSString alloc] initWithUTF8String:config.watermark.font_family ?: ""]; + _initialWatermark.font_family = NULL; _width = config.width; _height = config.height; _minWidth = config.min_width; @@ -3766,6 +3774,8 @@ - (void)dealloc { } [_titlebarWatched release]; [_window release]; + [_initialWatermarkText release]; + [_initialWatermarkFamily release]; [_title release]; [_rectangleBuffer release]; [_rectanglePipeline release]; @@ -3882,6 +3892,12 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification { return; } _window.contentView = view; + // UTF-8 pointers are borrowed only for this synchronous consumption. + _initialWatermark.text = _initialWatermarkText.UTF8String; + _initialWatermark.font_family = _initialWatermarkFamily.UTF8String; + viva_watermark_apply(view, _initialWatermark); + _initialWatermark.text = NULL; + _initialWatermark.font_family = NULL; if (_fileDropEnabled) { [view enableFileDrops]; } @@ -5880,3 +5896,20 @@ void viva_override_default_integer(const char *key, int value, int remove) { } #endif /* VIVA_OFFSCREEN */ + +int viva_application_set_watermark(void *window, viva_watermark config) { + __block int found = 0; + void (^work)(void) = ^{ + NSView *host = viva_application_window_view(window); + if (host != nil) { + viva_watermark_apply(host, config); + found = 1; + } + }; + if ([NSThread isMainThread]) { + work(); + } else { + dispatch_sync(dispatch_get_main_queue(), work); + } + return found; +} diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 964d7397a..6f86c0107 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -344,6 +344,15 @@ func onlyMoved(previous, next TextInput) bool { func (application *nativeApplication) SupportsDragPreview() {} func (application *nativeApplication) OpenWindow(config Config) (platform.Window, error) { + watermark, err := platform.NormalizeWatermark(config.Watermark) + if err != nil { + return nil, err + } + config.Watermark = watermark + watermarkText := C.CString(config.Watermark.Text) + defer C.free(unsafe.Pointer(watermarkText)) + watermarkFamily := C.CString(config.Watermark.FontFamily) + defer C.free(unsafe.Pointer(watermarkFamily)) title := C.CString(config.Title) defer C.free(unsafe.Pointer(title)) @@ -441,6 +450,7 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window } token := C.viva_application_open_window(C.viva_window_config{ title: title, + watermark: nativeWatermark(config.Watermark, watermarkText, watermarkFamily), width: C.int(config.Width), height: C.int(config.Height), min_width: C.int(config.MinWidth), diff --git a/internal/platform/darwin/testdata/dock_reopen.m b/internal/platform/darwin/testdata/dock_reopen.m index 09dab38ce..5c74148b4 100644 --- a/internal/platform/darwin/testdata/dock_reopen.m +++ b/internal/platform/darwin/testdata/dock_reopen.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/file_drop.m b/internal/platform/darwin/testdata/file_drop.m index e71475272..9b224b1a3 100644 --- a/internal/platform/darwin/testdata/file_drop.m +++ b/internal/platform/darwin/testdata/file_drop.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/live_resize.m b/internal/platform/darwin/testdata/live_resize.m index ed90feede..de5abc9db 100644 --- a/internal/platform/darwin/testdata/live_resize.m +++ b/internal/platform/darwin/testdata/live_resize.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/modifier_taps.m b/internal/platform/darwin/testdata/modifier_taps.m index 5ab013d00..7ad2a8380 100644 --- a/internal/platform/darwin/testdata/modifier_taps.m +++ b/internal/platform/darwin/testdata/modifier_taps.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m index 93b0a77d6..72b34cfa8 100644 --- a/internal/platform/darwin/testdata/text_selection.m +++ b/internal/platform/darwin/testdata/text_selection.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index 3f333e0c9..5789e46f0 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/watermark.m b/internal/platform/darwin/testdata/watermark.m new file mode 100644 index 000000000..ceb04fafd --- /dev/null +++ b/internal/platform/darwin/testdata/watermark.m @@ -0,0 +1,79 @@ +#import +#include "../watermark_darwin.m" +#include "../cursor_owner_darwin.h" + +// Exercise only the native view tree: no window, GPU, tile rasterization, or screenshot. +@interface WatermarkProbe : VivaWatermarkView +@end +@implementation WatermarkProbe +- (void)updatePattern {} +@end +@interface WatermarkTestHost : NSView +@end +@implementation WatermarkTestHost +- (BOOL)isFlipped {return YES;} +@end +int main(void) { + @autoreleasepool { + // Allocate only: no text rasterization, window, GPU, or screenshot. + // The previous extended-linear/8-bit combination returned NULL on macOS. + for (size_t scale=1; scale<=2; scale++) { + CGContextRef context=watermarkCreateTileContext(240*scale,180*scale); + if(context==NULL) return 8; + if(CGBitmapContextGetBitsPerComponent(context)!=8 || CGBitmapContextGetWidth(context)!=240*scale || CGBitmapContextGetHeight(context)!=180*scale) return 9; + CGContextRelease(context); + } + // Exercise real CoreText metrics and real CGPattern ownership without drawing + // text, allocating a window, or reading pixels/screenshots. + CGColorSpaceRef space=CGColorSpaceCreateWithName(kCGColorSpaceLinearSRGB); + CGFloat channels[]={0.5,0.5,0.5,0.12}; + CGColorRef color=CGColorCreate(space,channels); + for (NSString *text in @[@"DRAFT",@"测试用户 10086"]) { + CTLineRef line=watermarkCreateLine(text,@"",12,-0.4,color); + CGFloat ascent=0,descent=0; + double advance=CTLineGetTypographicBounds(line,&ascent,&descent,NULL); + CGPoint origin=watermarkTextOrigin(line,240,180); + if(advance<=0 || fabs(origin.x+advance/2-120)>0.001 || fabs(origin.y+(ascent-descent)/2-90)>0.001) return 7; + CFRelease(line); + } + CGColorRelease(color);CGColorSpaceRelease(space); + for (size_t scale=1;scale<=2;scale++) { + CGAffineTransform matrix=watermarkPatternMatrix(scale); + CGSize right=CGSizeApplyAffineTransform(CGSizeMake(scale,0),matrix); + CGSize up=CGSizeApplyAffineTransform(CGSizeMake(0,scale),matrix); + if(right.width!=1 || right.height!=0 || up.width!=0 || up.height!=1) return 10; + CGContextRef context=watermarkCreateTileContext(240*scale,180*scale); + CGImageRef image=CGBitmapContextCreateImage(context);CGContextRelease(context); + CGPatternRef pattern=watermarkCreatePattern(image,scale); + if(pattern==NULL) {CGImageRelease(image);return 11;} + CGPatternRelease(pattern); + } + for (int angle=-90;angle<=90;angle+=15) { + CGAffineTransform rotation=CGAffineTransformMakeRotation(angle*M_PI/180); + CGRect bounds=watermarkPatternBounds(3840,2160,rotation); + CGRect required=CGRectApplyAffineTransform(CGRectMake(0,0,3840,2160),CGAffineTransformInvert(rotation)); + if(!CGRectContainsRect(bounds,required)) return 12; + // Coverage uses the inverse-rotated rectangle, not a huge square plane. + if(bounds.size.width>hypot(3840,2160)+2 || bounds.size.height>hypot(3840,2160)+2) return 13; + } + NSView *host=[[WatermarkTestHost alloc] initWithFrame:NSMakeRect(0,0,800,600)]; + NSView *page=[[NSView alloc] initWithFrame:host.bounds]; + WatermarkProbe *overlay=[[WatermarkProbe alloc] initWithFrame:host.bounds]; + [overlay configure:(viva_watermark){.text="测试用户 10086",.alpha=.1,.font_size=12,.tile_width=240,.tile_height=180,.angle=-25,.top=42,.left=120}]; + [host addSubview:overlay]; + [host addSubview:page positioned:NSWindowAbove relativeTo:nil]; + viva_raise_watermark(host); + if(host.subviews.lastObject!=overlay) return 1; + if([overlay hitTest:NSMakePoint(200,200)]!=nil || overlay.acceptsFirstResponder) return 2; + if([host hitTest:NSMakePoint(200,200)]!=page) return 3; + [overlay layout]; + CALayer *clip=overlay.layer.sublayers.firstObject; + if(!clip.masksToBounds || clip.frame.origin.x!=120 || clip.frame.origin.y!=42 || clip.frame.size.width!=680 || clip.frame.size.height!=558) return 4; + [overlay setFrameSize:NSMakeSize(1000,700)];[overlay layout]; + if(clip.frame.size.width!=880 || clip.frame.size.height!=658) return 5; + viva_watermark_apply(host,(viva_watermark){0}); + if([host.subviews containsObject:overlay]) return 6; + [overlay release];[page release];[host release]; + } + return 0; +} diff --git a/internal/platform/darwin/testdata/window_close.m b/internal/platform/darwin/testdata/window_close.m index 3cb10a1fb..5ea1e3503 100644 --- a/internal/platform/darwin/testdata/window_close.m +++ b/internal/platform/darwin/testdata/window_close.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/window_decoration.m b/internal/platform/darwin/testdata/window_decoration.m index d942aff61..a5806202e 100644 --- a/internal/platform/darwin/testdata/window_decoration.m +++ b/internal/platform/darwin/testdata/window_decoration.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/window_notification.m b/internal/platform/darwin/testdata/window_notification.m index ee49a879d..02f6ff06e 100644 --- a/internal/platform/darwin/testdata/window_notification.m +++ b/internal/platform/darwin/testdata/window_notification.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include "window_test_callbacks.h" diff --git a/internal/platform/darwin/testdata/window_size.m b/internal/platform/darwin/testdata/window_size.m index 7fab1de82..bbb866887 100644 --- a/internal/platform/darwin/testdata/window_size.m +++ b/internal/platform/darwin/testdata/window_size.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/watermark_config_darwin.go b/internal/platform/darwin/watermark_config_darwin.go new file mode 100644 index 000000000..7f2acde4a --- /dev/null +++ b/internal/platform/darwin/watermark_config_darwin.go @@ -0,0 +1,13 @@ +//go:build darwin + +package darwin + +/* +#include "watermark_darwin.h" +*/ +import "C" +import "github.com/vivaui/viva/internal/platform" + +func nativeWatermark(value platform.Watermark, text, family *C.char) C.viva_watermark { + return C.viva_watermark{text: text, font_family: family, red: C.double(value.Color.Red), green: C.double(value.Color.Green), blue: C.double(value.Color.Blue), alpha: C.double(value.Color.Alpha), font_size: C.float(value.FontSize), font_weight: C.float(value.FontWeight), angle: C.float(value.Angle), tile_width: C.float(value.TileWidth), tile_height: C.float(value.TileHeight), top: C.float(value.Insets.Top), right: C.float(value.Insets.Right), bottom: C.float(value.Insets.Bottom), left: C.float(value.Insets.Left)} +} diff --git a/internal/platform/darwin/watermark_darwin.go b/internal/platform/darwin/watermark_darwin.go new file mode 100644 index 000000000..28157b84e --- /dev/null +++ b/internal/platform/darwin/watermark_darwin.go @@ -0,0 +1,33 @@ +//go:build darwin && !ios + +package darwin + +/* +#include +#include "watermark_darwin.h" +*/ +import "C" +import ( + "fmt" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +func (window *nativeWindow) SetWatermark(value platform.Watermark) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("darwin: window is closed") + } + value, err := platform.NormalizeWatermark(value) + if err != nil { + return err + } + text := C.CString(value.Text) + defer C.free(unsafe.Pointer(text)) + family := C.CString(value.FontFamily) + defer C.free(unsafe.Pointer(family)) + if C.viva_application_set_watermark(window.token, nativeWatermark(value, text, family)) == 0 { + return fmt.Errorf("darwin: window is unavailable") + } + return nil +} diff --git a/internal/platform/darwin/watermark_darwin.h b/internal/platform/darwin/watermark_darwin.h new file mode 100644 index 000000000..aaac3fcd7 --- /dev/null +++ b/internal/platform/darwin/watermark_darwin.h @@ -0,0 +1,13 @@ +#ifndef VIVA_WATERMARK_H +#define VIVA_WATERMARK_H + +typedef struct { + const char *text, *font_family; + double red, green, blue, alpha; + float font_size, font_weight, angle, tile_width, tile_height; + float top, right, bottom, left; +} viva_watermark; +void viva_watermark_apply(void *host, viva_watermark config); +void viva_raise_watermark(void *host); +int viva_application_set_watermark(void *window, viva_watermark config); +#endif diff --git a/internal/platform/darwin/watermark_darwin.m b/internal/platform/darwin/watermark_darwin.m new file mode 100644 index 000000000..65bc6c26b --- /dev/null +++ b/internal/platform/darwin/watermark_darwin.m @@ -0,0 +1,254 @@ +//go:build !ios + +#import +#import +#import +#include "watermark_darwin.h" + +static const size_t watermarkMaxTileSize = 8192; +static const size_t watermarkMaxTilePixels = 16u << 20; + +@interface VivaWatermarkView : NSView { + viva_watermark _config; + NSString *_text, *_family; + CALayer *_clipLayer; + CALayer *_patternLayer; + CGFloat _tileScale; +} +- (void)configure:(viva_watermark)config; +@end + +static void watermarkDrawTile(void *info, CGContextRef context) { + CGImageRef image = info; + // Pattern coordinates are device pixels; the pattern matrix restores logical units. + CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image); +} + +// Core Animation presents the bitmap contents upright in the flipped host. +// Only convert device pixels to logical units here; reflecting Y again would +// mirror the glyphs as well as the baseline. +static CGAffineTransform watermarkPatternMatrix(CGFloat scale) { + return CGAffineTransformMakeScale(1 / scale, 1 / scale); +} + +static void watermarkReleaseTile(void *info) { + CGImageRelease(info); +} + +// Extended linear RGB requires floating-point components. The retained tile uses +// 8-bit components, so use bounded linear sRGB to match the canvas color values. +static CGContextRef watermarkCreateTileContext(size_t width, size_t height) { + CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceLinearSRGB); + CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGImageAlphaPremultipliedLast); + CGColorSpaceRelease(space); + return context; +} + +// These helpers share production font metrics, pattern ownership and coverage +// geometry with the native contract test, which does not rasterize text. +static CTLineRef watermarkCreateLine(NSString *text, NSString *family, CGFloat size, CGFloat weight, CGColorRef color) { + NSFont *font = [NSFont systemFontOfSize:size weight:weight]; + if (family.length > 0) { + NSFontDescriptor *descriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:@{ + NSFontFamilyAttribute: family, + NSFontTraitsAttribute: @{NSFontWeightTrait: @(weight)}, + }]; + font = [NSFont fontWithDescriptor:descriptor size:size] ?: font; + } + NSAttributedString *string = [[NSAttributedString alloc] initWithString:text attributes:@{ + (id)kCTFontAttributeName: font, + (id)kCTForegroundColorAttributeName: (id)color, + }]; + CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)string); + [string release]; + return line; +} + +static CGPoint watermarkTextOrigin(CTLineRef line, CGFloat width, CGFloat height) { + CGFloat ascent = 0, descent = 0; + double advance = CTLineGetTypographicBounds(line, &ascent, &descent, NULL); + return CGPointMake((width - advance) / 2, (height - ascent - descent) / 2 + descent); +} + +static CGPatternRef watermarkCreatePattern(CGImageRef image, CGFloat scale) { + CGPatternCallbacks callbacks = {0, watermarkDrawTile, watermarkReleaseTile}; + size_t width = CGImageGetWidth(image), height = CGImageGetHeight(image); + return CGPatternCreate(image, CGRectMake(0, 0, width, height), watermarkPatternMatrix(scale), width, height, + kCGPatternTilingConstantSpacing, true, &callbacks); +} + +static CGRect watermarkPatternBounds(CGFloat width, CGFloat height, CGAffineTransform rotation) { + if (width <= 0 || height <= 0) { + return CGRectZero; + } + return CGRectIntegral(CGRectApplyAffineTransform(CGRectMake(0, 0, width, height), CGAffineTransformInvert(rotation))); +} + +@implementation VivaWatermarkView +- (instancetype)initWithFrame:(NSRect)frame { + self = [super initWithFrame:frame]; + if (self != nil) { + self.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + self.wantsLayer = YES; + self.layer.geometryFlipped = YES; + _clipLayer = [CALayer layer]; + _clipLayer.masksToBounds = YES; + _patternLayer = [CALayer layer]; + [_clipLayer addSublayer:_patternLayer]; + [self.layer addSublayer:_clipLayer]; + } + return self; +} + +- (BOOL)isFlipped { return YES; } +- (NSView *)hitTest:(NSPoint)point { return nil; } +- (BOOL)acceptsFirstResponder { return NO; } + +- (void)dealloc { + [_text release]; + [_family release]; + [super dealloc]; +} + +- (void)configure:(viva_watermark)config { + NSString *text = [NSString stringWithUTF8String:config.text != NULL ? config.text : ""]; + NSString *family = [NSString stringWithUTF8String:config.font_family ?: ""]; + BOOL rebuild = ![_text isEqualToString:text] || ![_family isEqualToString:family] || + _config.red != config.red || _config.green != config.green || + _config.blue != config.blue || _config.alpha != config.alpha || + _config.font_size != config.font_size || _config.font_weight != config.font_weight || + _config.tile_width != config.tile_width || _config.tile_height != config.tile_height; + [_text release]; + _text = [text copy]; + _config = config; + _config.text = NULL; + _config.font_family = NULL; + [_family release]; + _family = [family copy]; + if (rebuild) { + _tileScale = 0; + } + [self updatePattern]; + [self setNeedsLayout:YES]; + [self layoutSubtreeIfNeeded]; +} + +- (void)viewDidMoveToWindow { + [super viewDidMoveToWindow]; + [self updatePattern]; +} + +- (void)viewDidChangeBackingProperties { + [super viewDidChangeBackingProperties]; + [self updatePattern]; +} + +- (void)updatePattern { + // Wait for the actual backing scale before rasterizing. + if (self.window == nil) { + return; + } + CGFloat scale = self.window.backingScaleFactor; + if (scale <= 0) { + scale = 1; + } + if (_tileScale == scale || _text.length == 0) { + return; + } + size_t width = ceil(_config.tile_width * scale); + size_t height = ceil(_config.tile_height * scale); + if (width == 0 || height == 0 || width > watermarkMaxTileSize || height > watermarkMaxTileSize || width * height > watermarkMaxTilePixels) { + return; + } + CGContextRef context = watermarkCreateTileContext(width, height); + if (context == NULL) { + return; + } + CGColorSpaceRef space = CGBitmapContextGetColorSpace(context); + CGContextScaleCTM(context, scale, scale); + CGFloat channels[] = {_config.red, _config.green, _config.blue, _config.alpha}; + CGColorRef color = CGColorCreate(space, channels); + CTLineRef line = watermarkCreateLine(_text, _family, _config.font_size, _config.font_weight, color); + CGPoint origin = watermarkTextOrigin(line, _config.tile_width, _config.tile_height); + CGContextSetTextPosition(context, origin.x, origin.y); + CTLineDraw(line, context); + CFRelease(line); + CGColorRelease(color); + CGImageRef image = CGBitmapContextCreateImage(context); + CGContextRelease(context); + if (image == NULL) { + return; + } + CGPatternRef pattern = watermarkCreatePattern(image, scale); + if (pattern == NULL) { + CGImageRelease(image); + return; + } + CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); + CGFloat alpha = 1; + CGColorRef patternColor = CGColorCreateWithPattern(patternSpace, pattern, &alpha); + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + _patternLayer.backgroundColor = patternColor; + [CATransaction commit]; + CGColorRelease(patternColor); + CGColorSpaceRelease(patternSpace); + CGPatternRelease(pattern); + _tileScale = scale; +} + +- (void)layout { + [super layout]; + CGFloat width = MAX(0, self.bounds.size.width - _config.left - _config.right); + CGFloat height = MAX(0, self.bounds.size.height - _config.top - _config.bottom); + CGAffineTransform rotation = CGAffineTransformMakeRotation(_config.angle * M_PI / 180); + CGRect bounds = watermarkPatternBounds(width, height, rotation); + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + _clipLayer.frame = CGRectMake(_config.left, _config.top, width, height); + // Anchor pattern coordinate (0,0) at the clip origin. Changing size changes + // only the inverse-rotated coverage rectangle, never the pattern phase. + _patternLayer.bounds = bounds; + _patternLayer.anchorPoint = CGPointMake(bounds.size.width > 0 ? -bounds.origin.x / bounds.size.width : 0, + bounds.size.height > 0 ? -bounds.origin.y / bounds.size.height : 0); + _patternLayer.position = CGPointZero; + _patternLayer.affineTransform = rotation; + [CATransaction commit]; +} +@end + +static VivaWatermarkView *watermarkIn(NSView *host) { + for (NSView *view in host.subviews) { + if ([view isKindOfClass:[VivaWatermarkView class]]) { + return (VivaWatermarkView *)view; + } + } + return nil; +} + +// Native view creators call this after changing the host's view tree. +void viva_raise_watermark(void *value) { + NSView *host = value; + VivaWatermarkView *view = watermarkIn(host); + if (view != nil) { + [host addSubview:view positioned:NSWindowAbove relativeTo:nil]; + } +} + +void viva_watermark_apply(void *value, viva_watermark config) { + NSView *host = value; + if (host == nil) { + return; + } + VivaWatermarkView *view = watermarkIn(host); + if (config.text == NULL || config.text[0] == 0 || config.alpha <= 0) { + [view removeFromSuperview]; + return; + } + if (view == nil) { + view = [[[VivaWatermarkView alloc] initWithFrame:host.bounds] autorelease]; + [host addSubview:view positioned:NSWindowAbove relativeTo:nil]; + } + [view configure:config]; + viva_raise_watermark(host); +} diff --git a/internal/platform/darwin/watermark_darwin_test.go b/internal/platform/darwin/watermark_darwin_test.go new file mode 100644 index 000000000..83a722a0c --- /dev/null +++ b/internal/platform/darwin/watermark_darwin_test.go @@ -0,0 +1,20 @@ +//go:build darwin && !ios + +package darwin + +import ( + "os/exec" + "path/filepath" + "testing" +) + +func TestWatermarkNativeStackingClippingAndInputTransparency(t *testing.T) { + binary := filepath.Join(t.TempDir(), "watermark-views") + command := exec.Command("xcrun", "clang", "-fno-objc-arc", "-Werror", "-framework", "Cocoa", "-framework", "QuartzCore", "-framework", "CoreText", "testdata/watermark.m", "-o", binary) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native watermark view test: %v\n%s", err, output) + } + if output, err := exec.Command(binary).CombinedOutput(); err != nil { + t.Fatalf("native watermark view test: %v\n%s", err, output) + } +} diff --git a/internal/platform/darwin/web_darwin.m b/internal/platform/darwin/web_darwin.m index 504666b12..2d83e850d 100644 --- a/internal/platform/darwin/web_darwin.m +++ b/internal/platform/darwin/web_darwin.m @@ -1,5 +1,6 @@ //go:build !ios +#include "watermark_darwin.h" #import #import #import @@ -687,6 +688,7 @@ static int viva_web_named_store(WKWebViewConfiguration *configuration, const cha web.autoresizingMask = NSViewMinYMargin; web.hidden = YES; [host addSubview:web positioned:NSWindowAbove relativeTo:nil]; + viva_raise_watermark(host); [web release]; // the view hierarchy owns it } else { [controller removeScriptMessageHandlerForName:@"viva"]; diff --git a/internal/platform/watermark.go b/internal/platform/watermark.go new file mode 100644 index 000000000..40090d0de --- /dev/null +++ b/internal/platform/watermark.go @@ -0,0 +1,93 @@ +package platform + +import ( + "fmt" + "math" + "strings" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" +) + +const ( + watermarkMaxFontSize = 4096 + watermarkMaxTileSize = 8192 + watermarkMaxTilePixels = 16 << 20 + watermarkMaxTextBytes = 16 << 10 +) + +// Watermark is an input-transparent, native text pattern above all content. +type Watermark struct { + Text, FontFamily string + Color Color + FontSize, FontWeight, Angle float32 + TileWidth, TileHeight float32 + Insets gfx.Insets +} + +// NormalizeWatermark validates the complete request before changing native state. +func NormalizeWatermark(w Watermark) (Watermark, error) { + if len(w.Text) > watermarkMaxTextBytes || len(w.FontFamily) > 1024 || strings.ContainsAny(w.Text, "\r\n") { + return Watermark{}, fmt.Errorf("watermark: text must be a bounded single line and family name at most 1024 bytes") + } + if !utf8.ValidString(w.Text) || strings.IndexByte(w.Text, 0) >= 0 || !utf8.ValidString(w.FontFamily) || strings.IndexByte(w.FontFamily, 0) >= 0 { + return Watermark{}, fmt.Errorf("watermark: text must be valid UTF-8 without NUL") + } + values := []float32{w.FontSize, w.TileWidth, w.TileHeight, w.Insets.Top, w.Insets.Right, w.Insets.Bottom, w.Insets.Left} + for _, v := range values { + if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) || v < 0 { + return Watermark{}, fmt.Errorf("watermark: dimensions must be finite and nonnegative") + } + } + for _, v := range []float64{float64(w.Angle), float64(w.FontWeight), w.Color.Red, w.Color.Green, w.Color.Blue, w.Color.Alpha} { + if math.IsNaN(v) || math.IsInf(v, 0) { + return Watermark{}, fmt.Errorf("watermark: parameters must be finite") + } + } + if w.Color.Red < 0 || w.Color.Red > 1 || w.Color.Green < 0 || w.Color.Green > 1 || w.Color.Blue < 0 || w.Color.Blue > 1 || w.Color.Alpha < 0 || w.Color.Alpha > 1 { + return Watermark{}, fmt.Errorf("watermark: color components must be between 0 and 1") + } + if w.FontWeight < gfx.WeightLight || w.FontWeight > gfx.WeightBold { + return Watermark{}, fmt.Errorf("watermark: font weight must be between gfx.WeightLight and gfx.WeightBold") + } + if w.Text == "" { + return Watermark{}, nil + } + if w.Color == (Color{}) { + w.Color = Color{Red: 0.5, Green: 0.5, Blue: 0.5, Alpha: 0.12} + } + if w.FontSize == 0 { + w.FontSize = 12 + } + if w.TileWidth == 0 { + w.TileWidth = 240 + } + if w.TileHeight == 0 { + w.TileHeight = 180 + } + // Bound native allocations at every backing scale; the pixel-size helper also + // caps the total area before a platform allocates its retained tile. + if w.FontSize > watermarkMaxFontSize || w.TileWidth > watermarkMaxTileSize || w.TileHeight > watermarkMaxTileSize { + return Watermark{}, fmt.Errorf("watermark: text or tile dimensions exceed limits") + } + return w, nil +} + +// WatermarkTileSize converts logical periods to physical pixels without a 1x intermediate. +func WatermarkTileSize(w Watermark, scale float32) (int, int) { + if scale <= 0 || math.IsNaN(float64(scale)) || math.IsInf(float64(scale), 0) { + return 0, 0 + } + width, height := math.Ceil(float64(w.TileWidth)*float64(scale)), math.Ceil(float64(w.TileHeight)*float64(scale)) + if width <= 0 || height <= 0 || width > watermarkMaxTileSize || height > watermarkMaxTileSize || width*height > watermarkMaxTilePixels { + return 0, 0 + } + return int(width), int(height) +} + +// WatermarkContentRect clips the overlay to client pixels. Insets are logical. +func WatermarkContentRect(size gfx.Size, insets gfx.Insets, scale float32) gfx.Rect { + x, y := float32(math.Ceil(float64(insets.Left*scale))), float32(math.Ceil(float64(insets.Top*scale))) + right, bottom := float32(math.Floor(float64(size.Width-insets.Right*scale))), float32(math.Floor(float64(size.Height-insets.Bottom*scale))) + return gfx.Rect{X: x, Y: y, Width: max(right-x, 0), Height: max(bottom-y, 0)} +} diff --git a/internal/platform/watermark_test.go b/internal/platform/watermark_test.go new file mode 100644 index 000000000..b7b781dde --- /dev/null +++ b/internal/platform/watermark_test.go @@ -0,0 +1,71 @@ +package platform + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" +) + +func TestWatermarkValidationAndDefaults(t *testing.T) { + base := Watermark{Text: "测试用户 10086", Color: Color{Alpha: 0.1}, FontWeight: -0.4} + got, err := NormalizeWatermark(base) + if err != nil || got.FontSize != 12 || got.TileWidth != 240 || got.TileHeight != 180 || got.FontWeight != -0.4 { + t.Fatalf("defaults: %+v, %v", got, err) + } + for name, change := range map[string]func(*Watermark){ + "invalid UTF-8": func(w *Watermark) { w.Text = "\xff" }, + "NUL": func(w *Watermark) { w.Text = "a\x00b" }, + "negative tile": func(w *Watermark) { w.TileWidth = -1 }, + "multiline": func(w *Watermark) { w.Text = "a\nb" }, + "negative weight": func(w *Watermark) { w.FontWeight = -1 }, + "large weight": func(w *Watermark) { w.FontWeight = 1 }, + "large tile": func(w *Watermark) { w.TileWidth = 1 << 25 }, + "invalid family": func(w *Watermark) { w.FontFamily = "bad\x00family" }, + "negative alpha": func(w *Watermark) { w.Color.Alpha = -1 }, + "negative inset": func(w *Watermark) { w.Insets.Top = -1 }, + "NaN": func(w *Watermark) { w.Angle = float32(math.NaN()) }, + "infinite color": func(w *Watermark) { w.Color.Red = math.Inf(1) }, + } { + t.Run(name, func(t *testing.T) { + value := base + change(&value) + if _, err := NormalizeWatermark(value); err == nil { + t.Fatal("invalid request accepted") + } + }) + } + for _, value := range []Watermark{{}} { + normalized, err := NormalizeWatermark(value) + if err != nil || normalized != (Watermark{}) { + t.Fatalf("disabled: %+v, %v", normalized, err) + } + } +} + +func TestWatermarkPixelGeometry(t *testing.T) { + for _, scale := range []float32{1, 1.25, 1.5, 2} { + width, height := WatermarkTileSize(Watermark{TileWidth: 240, TileHeight: 180}, scale) + if width != int(240*scale) || height != int(180*scale) { + t.Fatal("tile was not rasterized at backing scale", scale, width, height) + } + area := WatermarkContentRect(gfx.Size{Width: 1600 * scale, Height: 960 * scale}, gfx.Insets{Top: 42, Left: 120}, scale) + if area.X != 120*scale || area.Width != (1600-120)*scale || area.Y < float32(42)*scale || area.Height <= 0 { + t.Fatal("incorrect content clipping", scale, area) + } + } + area := WatermarkContentRect(gfx.Size{Width: 10, Height: 10}, gfx.Insets{Left: 120, Top: 42}, 2) + if area.Width != 0 || area.Height != 0 { + t.Fatal("insets outside client must hide the overlay", area) + } +} + +func TestWatermarkTextOnlyIsVisibleAndTileAllocationIsBounded(t *testing.T) { + value, err := NormalizeWatermark(Watermark{Text: "DRAFT"}) + if err != nil || value.Color.Alpha <= 0 || value.FontSize <= 0 { + t.Fatal("text-only watermark is invisible", value, err) + } + if width, height := WatermarkTileSize(Watermark{TileWidth: 8192, TileHeight: 8192}, 4); width != 0 || height != 0 { + t.Fatal("oversized backing allocation accepted") + } +} diff --git a/internal/platform/windows/always_on_top_windows.go b/internal/platform/windows/always_on_top_windows.go index 9e0273d2f..75e4d616f 100644 --- a/internal/platform/windows/always_on_top_windows.go +++ b/internal/platform/windows/always_on_top_windows.go @@ -32,5 +32,8 @@ func (state *windowState) setAlwaysOnTop(enabled bool) bool { level = ^uintptr(0) // HWND_TOPMOST } applied, _, _ := setWindowPosition.Call(state.window, level, 0, 0, 0, 0, 0x13) + if applied != 0 { + state.raiseWatermark() + } return applied != 0 } diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index 2ea2b96a8..6181a2ac3 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -174,7 +174,7 @@ func (services *textServices) chosenWeight(weight float32, main, bold uint32) ui return native } -// nativeFontWeight is the DirectWrite weight of a Viva weight: regular, medium, semibold and +// nativeFontWeight is the DirectWrite weight of a Viva weight: light, regular, medium, semibold and // bold are the faces Segoe UI has. A font without one of them, such as Consolas, which has // regular and bold only, is drawn with the face DirectWrite finds nearest. func nativeFontWeight(weight float32) uint32 { @@ -185,6 +185,8 @@ func nativeFontWeight(weight float32) uint32 { return 600 case weight >= 0.10: return 500 + case weight <= -0.2: + return 300 default: return 400 } diff --git a/internal/platform/windows/text_windows_test.go b/internal/platform/windows/text_windows_test.go index f560ecdcb..5b9911aac 100644 --- a/internal/platform/windows/text_windows_test.go +++ b/internal/platform/windows/text_windows_test.go @@ -5,6 +5,7 @@ import ( "runtime" "testing" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" ) @@ -177,3 +178,9 @@ func TestSemiboldIsTheRealSemiboldFace(t *testing.T) { t.Errorf("semibold line is %.3f times as wide as regular, want a real semibold's 1.02 to 1.08", ratio) } } + +func TestLightFontWeight(t *testing.T) { + if got := nativeFontWeight(gfx.WeightLight); got != 300 { + t.Fatalf("light weight = %d, want 300", got) + } +} diff --git a/internal/platform/windows/watermark_windows.go b/internal/platform/windows/watermark_windows.go new file mode 100644 index 000000000..d8cf74232 --- /dev/null +++ b/internal/platform/windows/watermark_windows.go @@ -0,0 +1,342 @@ +package windows + +import ( + "fmt" + "math" + "sync" + "syscall" + "unicode/utf16" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +const ( + wmSetWatermark = 0x8057 // follows wmChangeDecoration + d2dCreateBitmap = 4 + d2dCreateBitmapBrush = 7 + d2dFillRectangle = 17 + watermarkClassName = "VivaWatermark" +) + +var ( + watermarkClass sync.Once + watermarkClassError error + updateWatermarkLayer = user.NewProc("UpdateLayeredWindow") +) + +type watermarkRequest struct { + mu sync.Mutex + handle uintptr + value platform.Watermark + pending bool +} + +func (window *nativeWindow) SetWatermark(value platform.Watermark) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + value, err := platform.NormalizeWatermark(value) + if err != nil { + return err + } + request := &window.state.pendingWatermark + request.mu.Lock() + defer request.mu.Unlock() + if request.handle == 0 { + return fmt.Errorf("windows: window is closed") + } + request.value, request.pending = value, true + // PostMessage never waits for the window thread. Teardown retires this handle + // under the same lock, so background setters never read mutable window state. + if ok, _, err := postMessage.Call(request.handle, wmSetWatermark, 0, 0); ok == 0 { + return fmt.Errorf("windows: post watermark: %w", err) + } + return nil +} + +func (state *windowState) applyWatermark() { + request := &state.pendingWatermark + request.mu.Lock() + value, pending := request.value, request.pending + request.pending = false + request.mu.Unlock() + if !pending { + return + } + previous := state.config.Watermark + state.config.Watermark = value + if err := state.syncWatermark(); err != nil { + state.config.Watermark = previous + if restoreErr := state.syncWatermark(); restoreErr != nil { + platform.ReportFault("restore window watermark", restoreErr) + } + platform.ReportFault("window watermark", err) + } +} + +// watermarkOverlay retains the small text tile independently of the client-sized DIB. +// Moving and ordinary frames never rasterize text or refill the DIB. +type watermarkOverlay struct { + window uintptr + rasterizer *directRasterizer + target *directTarget + bitmap, brush uintptr + config platform.Watermark + scale float32 + width, height int + tileWidth, tileHeight int +} + +func watermarkProc(window, kind, first, second uintptr) uintptr { + switch kind { + case wmNCHitTest: + return ^uintptr(0) // HTTRANSPARENT + case 0x0021: + return 3 // WM_MOUSEACTIVATE -> MA_NOACTIVATE + case wmErase: + return 1 + } + result, _, _ := defaultWindowProc.Call(window, kind, first, second) + return result +} + +func (state *windowState) newWatermark() (*watermarkOverlay, error) { + watermarkClass.Do(func() { + class := windowClass{Size: uint32(unsafe.Sizeof(windowClass{})), Procedure: syscall.NewCallback(watermarkProc), Instance: state.application.instance, Name: wide(watermarkClassName)} + if ok, _, err := registerClass.Call(uintptr(unsafe.Pointer(&class))); ok == 0 { + watermarkClassError = fmt.Errorf("windows: register watermark: %w", err) + } + }) + if watermarkClassError != nil { + return nil, watermarkClassError + } + handle, _, err := createWindow.Call(wsExLayered|wsExTransparent|wsExNoActivate|wsExToolWindow, uintptr(unsafe.Pointer(wide(watermarkClassName))), 0, wsPopup, 0, 0, 1, 1, state.window, 0, state.application.instance, 0) + if handle == 0 { + return nil, fmt.Errorf("windows: create watermark: %w", err) + } + return &watermarkOverlay{window: handle}, nil +} + +func (overlay *watermarkOverlay) suspend() { + showWindow.Call(overlay.window, 0) + release(&overlay.brush) + release(&overlay.bitmap) + if overlay.target != nil { + overlay.target.close() + overlay.target = nil + } + overlay.width, overlay.height = 0, 0 +} +func (overlay *watermarkOverlay) close() { + overlay.suspend() + if overlay.rasterizer != nil { + overlay.rasterizer.close() + overlay.rasterizer = nil + } + if overlay.window != 0 { + destroyWindow.Call(overlay.window) + overlay.window = 0 + } +} + +// raiseWatermark is the only stacking entry point. New native child/owned windows +// must call it after changing the native view tree. +func (state *windowState) raiseWatermark() { + if state.watermark != nil && state.watermark.window != 0 { + level := ^uintptr(1) // HWND_NOTOPMOST: match the owner, including demotion. + if style, err := readDecorationStyle(state.window, ^uintptr(19)); err == nil && style&wsExTopmost != 0 { + level = ^uintptr(0) + } + setWindowPosition.Call(state.watermark.window, level, 0, 0, 0, 0, 0x13) // HWND_TOP, NOMOVE|NOSIZE|NOACTIVATE + } +} + +func (state *windowState) syncWatermark() error { + value := state.config.Watermark + if value.Text == "" || value.Color.Alpha <= 0 { + if state.watermark != nil { + state.watermark.close() + state.watermark = nil + } + return nil + } + if !state.ready || state.window == 0 { + return nil + } + if state.watermark == nil { + overlay, err := state.newWatermark() + if err != nil { + return err + } + state.watermark = overlay + } + overlay := state.watermark + if state.minimized || state.hiddenByShow { + overlay.suspend() + return nil + } + var client rect + if ok, _, err := getClientRect.Call(state.window, uintptr(unsafe.Pointer(&client))); ok == 0 { + return err + } + area := platform.WatermarkContentRect(gfx.Size{Width: float32(client.Right), Height: float32(client.Bottom)}, value.Insets, state.scale) + if area.Width <= 0 || area.Height <= 0 { + overlay.suspend() + return nil + } + origin := point{X: int32(area.X), Y: int32(area.Y)} + if ok, _, err := clientToScreen.Call(state.window, uintptr(unsafe.Pointer(&origin))); ok == 0 { + return err + } + width, height := int(area.Width), int(area.Height) + rebuild := watermarkTileChanged(overlay.config, value) || overlay.scale != state.scale || overlay.rasterizer == nil + if overlay.config != value || overlay.scale != state.scale || overlay.width != width || overlay.height != height || overlay.target == nil { + if err := overlay.render(value, state.scale, width, height, rebuild); err != nil { + overlay.suspend() + return err + } + size := point{X: int32(width), Y: int32(height)} + source := point{} + blend := struct{ Operation, Flags, Alpha, Format byte }{Alpha: 255, Format: 1} + if ok, _, err := updateWatermarkLayer.Call(overlay.window, 0, uintptr(unsafe.Pointer(&origin)), uintptr(unsafe.Pointer(&size)), overlay.target.scratch.dc, uintptr(unsafe.Pointer(&source)), 0, uintptr(unsafe.Pointer(&blend)), 2); ok == 0 { + return fmt.Errorf("windows: present watermark: %w", err) + } + overlay.width, overlay.height = width, height + } else { + // Translation only: keep the retained surface and its z-order. + setWindowPosition.Call(overlay.window, 0, uintptr(origin.X), uintptr(origin.Y), 0, 0, 0x15) + } + showWindow.Call(overlay.window, swShowNoActivate) + state.raiseWatermark() + return nil +} + +// Rotation and clipping change composition, not the retained text tile. +func watermarkTileChanged(previous, next platform.Watermark) bool { + return previous.Text != next.Text || previous.FontFamily != next.FontFamily || previous.Color != next.Color || + previous.FontSize != next.FontSize || previous.FontWeight != next.FontWeight || previous.TileWidth != next.TileWidth || previous.TileHeight != next.TileHeight +} + +func watermarkSRGB(value float64) float32 { + if value <= 0.0031308 { + return float32(12.92 * value) + } + return float32(1.055*math.Pow(value, 1/2.4) - 0.055) +} + +func (overlay *watermarkOverlay) render(value platform.Watermark, scale float32, width, height int, rebuild bool) error { + if overlay.rasterizer == nil { + rasterizer, err := newDirectRasterizer() + if err != nil { + return err + } + overlay.rasterizer = rasterizer + } + if rebuild { + if err := overlay.renderTile(value, scale); err != nil { + return err + } + release(&overlay.brush) + release(&overlay.bitmap) + } + if overlay.target == nil { + target, err := newDirectTarget(overlay.rasterizer.factory, d2dAlphaPremultiplied) + if err != nil { + return err + } + overlay.target = target + } + target := overlay.target + surface, err := target.bind(width, height) + if err != nil { + return err + } + clear(surface.Pixels) + if overlay.brush == 0 { + tile := overlay.rasterizer.translucent.scratch + properties := struct { + Format, AlphaMode uint32 + DPIX, DPIY float32 + }{87, d2dAlphaPremultiplied, 96, 96} + packedSize := uintptr(uint32(overlay.tileWidth)) | uintptr(uint32(overlay.tileHeight))<<32 + if err := hresult(comCall5(target.target, d2dCreateBitmap, packedSize, uintptr(unsafe.Pointer(&tile.Pixels[0])), uintptr(tile.Width*4), uintptr(unsafe.Pointer(&properties)), uintptr(unsafe.Pointer(&overlay.bitmap)))); err != nil { + return fmt.Errorf("windows: create watermark tile: %w", err) + } + brushProperties := struct{ X, Y, Interpolation uint32 }{1, 1, 1} // WRAP, WRAP, LINEAR + if err := hresult(comCall4(target.target, d2dCreateBitmapBrush, overlay.bitmap, uintptr(unsafe.Pointer(&brushProperties)), 0, uintptr(unsafe.Pointer(&overlay.brush)))); err != nil { + return err + } + } + angle := float64(value.Angle) * math.Pi / 180 + matrix := d2dMatrix{M11: float32(math.Cos(angle)), M12: float32(math.Sin(angle)), M21: -float32(math.Sin(angle)), M22: float32(math.Cos(angle))} + comCall1(overlay.brush, 5, uintptr(unsafe.Pointer(&matrix))) // ID2D1Brush.SetTransform + bounds := struct{ Left, Top, Right, Bottom float32 }{Right: float32(width), Bottom: float32(height)} + target.begin(d2dColor{}, d2dAntialiasGrayscale) + comCall2(target.target, d2dFillRectangle, uintptr(unsafe.Pointer(&bounds)), overlay.brush) + if err := target.end(); err != nil { + return err + } + overlay.config, overlay.scale = value, scale + return nil +} + +func (overlay *watermarkOverlay) renderTile(value platform.Watermark, scale float32) error { + width, height := platform.WatermarkTileSize(value, scale) + if width <= 0 || height <= 0 { + return fmt.Errorf("windows: invalid watermark tile") + } + rasterizer := overlay.rasterizer + target := rasterizer.translucent + surface, err := target.bind(width, height) + if err != nil { + return err + } + clear(surface.Pixels) + weight := nativeFontWeight(value.FontWeight) + family := value.FontFamily + if family == "" { + family = "Segoe UI" + } + format, err := rasterizer.services.formatWeight(family, value.FontSize*scale, weight, false) + if err != nil { + return err + } + defer release(&format) + units := utf16.Encode([]rune(value.Text)) + if len(units) == 0 { + return fmt.Errorf("windows: watermark text is empty") + } + var layout uintptr + if err := hresult(rasterizer.services.createLayout(rasterizer.services.write, &units[0], uint32(len(units)), format, 1<<20, 1<<20, &layout)); err != nil { + return err + } + defer release(&layout) + var metrics textMetrics + if err := hresult(comCall1(layout, writeGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil { + return err + } + target.begin(d2dColor{R: watermarkSRGB(value.Color.Red), G: watermarkSRGB(value.Color.Green), B: watermarkSRGB(value.Color.Blue), A: float32(value.Color.Alpha)}, d2dAntialiasGrayscale) + target.pushClip(0, width, height) + target.draw((float32(width)-metrics.WidthTrailing)/2-metrics.Left, (float32(height)-metrics.Height)/2-metrics.Top, layout, 0) + target.popClip() + if err := target.end(); err != nil { + return err + } + overlay.tileWidth, overlay.tileHeight = width, height + return nil +} + +// moveWatermark only translates the retained surface. Resize messages are paced +// separately by serviceResize, including left/top-edge resize drags. +func (state *windowState) moveWatermark() { + if state.watermark == nil || state.minimized || state.hiddenByShow { + return + } + insets := state.config.Watermark.Insets + origin := point{X: int32(math.Ceil(float64(insets.Left * state.scale))), Y: int32(math.Ceil(float64(insets.Top * state.scale)))} + if ok, _, _ := clientToScreen.Call(state.window, uintptr(unsafe.Pointer(&origin))); ok != 0 { + setWindowPosition.Call(state.watermark.window, 0, uintptr(origin.X), uintptr(origin.Y), 0, 0, 0x15) + } +} diff --git a/internal/platform/windows/watermark_windows_test.go b/internal/platform/windows/watermark_windows_test.go new file mode 100644 index 000000000..5a4ff67bf --- /dev/null +++ b/internal/platform/windows/watermark_windows_test.go @@ -0,0 +1,124 @@ +package windows + +import ( + "runtime" + "sync" + "testing" + "time" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// This test needs a Windows desktop. It also reports the bounded resize work +// requested by the native-overlay design; it is not a steady-frame benchmark. +func TestWatermarkWindowTransparencyStackingAndResizeTiming(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{Title: "Watermark native test", Width: 640, Height: 400, ClearColor: platform.Color{Alpha: 1}, Watermark: platform.Watermark{Text: "测试用户 10086", Color: platform.Color{Alpha: .1}, FontWeight: -.4, Angle: -25}}) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + overlay := state.watermark + if overlay == nil || overlay.target == nil { + t.Fatal("initial watermark missing") + } + if watermarkProc(overlay.window, wmNCHitTest, 0, 0) != ^uintptr(0) || watermarkProc(overlay.window, 0x21, 0, 0) != 3 { + t.Fatal("watermark intercepts pointer or activation") + } + // A newly created owned popup may reorder the overlay; restore the invariant. + host := &webHost{state: state} + cover := host.newCover() + if cover == 0 { + t.Fatal("create owned popup") + } + defer destroyWindow.Call(cover) + showWindow.Call(cover, swShowNoActivate) + state.raiseWatermark() + previous, _, _ := user.NewProc("GetWindow").Call(overlay.window, 3) // GW_HWNDPREV + if previous == cover { + t.Fatal("owned popup is above watermark") + } + for _, enabled := range []bool{true, false, true, false} { + if !state.setAlwaysOnTop(enabled) { + t.Fatal("owner topmost change failed") + } + style, err := readDecorationStyle(overlay.window, ^uintptr(19)) + if err != nil || (style&wsExTopmost != 0) != enabled { + t.Fatal("overlay did not follow owner topmost level", enabled, style, err) + } + } + // Concurrent callers only enqueue requests; the window thread applies the latest one. + var jobs sync.WaitGroup + failures := make(chan error, 8) + for range 8 { + jobs.Add(1) + go func() { + defer jobs.Done() + if err := opened.(*nativeWindow).SetWatermark(state.config.Watermark); err != nil { + failures <- err + } + }() + } + jobs.Wait() + close(failures) + for err := range failures { + t.Fatal(err) + } + state.applyWatermark() + retained := overlay.target.scratch + state.moveWatermark() + if overlay.target.scratch != retained { + t.Fatal("translation reallocated surface") + } + if err := overlay.render(state.config.Watermark, 1.5, 320, 200, true); err != nil { + return err + } + for _, size := range []struct{ width, height int }{{1600, 960}, {2560, 1440}} { + start := time.Now() + if err := overlay.render(state.config.Watermark, 1.5, size.width*3/2, size.height*3/2, false); err != nil { + return err + } + destination := point{} + source := point{} + dimensions := point{X: int32(size.width * 3 / 2), Y: int32(size.height * 3 / 2)} + blend := struct{ Operation, Flags, Alpha, Format byte }{Alpha: 255, Format: 1} + if ok, _, err := updateWatermarkLayer.Call(overlay.window, 0, uintptr(unsafe.Pointer(&destination)), uintptr(unsafe.Pointer(&dimensions)), overlay.target.scratch.dc, uintptr(unsafe.Pointer(&source)), 0, uintptr(unsafe.Pointer(&blend)), 2); ok == 0 { + return err + } + t.Logf("resize %dx%d @150%% fill + submit: %v; retained DIB: %d bytes", size.width, size.height, time.Since(start), len(overlay.target.scratch.Pixels)) + } + overlay.suspend() + if overlay.target != nil || overlay.brush != 0 || overlay.bitmap != 0 { + t.Fatal("hidden overlay retained client-sized resources") + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestWatermarkSetterRejectsRetiredHandle(t *testing.T) { + window := &nativeWindow{state: &windowState{}} + if err := window.SetWatermark(platform.Watermark{}); err == nil { + t.Fatal("retired native handle accepted an update") + } +} + +func TestWatermarkCompositionDoesNotRebuildTextTile(t *testing.T) { + original := platform.Watermark{Text: "DRAFT", FontSize: 12, TileWidth: 240, TileHeight: 180} + changed := original + changed.Angle = -25 + changed.Insets.Left = 40 + if watermarkTileChanged(original, changed) { + t.Fatal("composition-only update rebuilt text") + } + changed.FontFamily = "Arial" + if !watermarkTileChanged(original, changed) { + t.Fatal("font family update reused stale text") + } +} diff --git a/internal/platform/windows/web_windows.go b/internal/platform/windows/web_windows.go index 41b4202f2..58a755cc5 100644 --- a/internal/platform/windows/web_windows.go +++ b/internal/platform/windows/web_windows.go @@ -930,6 +930,7 @@ func (w *webHost) layoutCovers(page *windowsWeb, view platform.NativeView) { if sameRects(page.coverSet, w.cuts) { return } + defer w.state.raiseWatermark() page.coverSet = append(page.coverSet[:0], w.cuts...) origin := point{} clientToScreen.Call(w.state.window, uintptr(unsafe.Pointer(&origin))) @@ -969,6 +970,7 @@ func (w *webHost) newCover() uintptr { 0, 0, 1, 1, state.window, 0, state.application.instance, 0) if window != 0 { setLayered.Call(window, 0, 1, 2) + state.raiseWatermark() } return window } diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 90b56b0ee..721e30f12 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -79,6 +79,8 @@ const ( type windowState struct { // pendingTitle is the title SetTitle asked for, applied on the window thread. pendingTitle titleRequest + pendingWatermark watermarkRequest + watermark *watermarkOverlay pendingIcon iconRequest decoration windowDecoration fullscreen atomic.Bool @@ -321,6 +323,11 @@ func RunApplication(start platform.ApplicationStart) error { } func (application *windowsApplication) OpenWindow(config platform.Config) (platform.Window, error) { + watermark, err := platform.NormalizeWatermark(config.Watermark) + if err != nil { + return nil, err + } + config.Watermark = watermark if err := validateTextInput(config.TextInput); err != nil { return nil, err } @@ -474,6 +481,11 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf postMessage.Call(state.window, wmWebReady, 0, 0) } } + state.pendingWatermark.handle = state.window + if err := state.syncWatermark(); err != nil { + destroyWindow.Call(state.window) + return nil, err + } state.testEvents() return &nativeWindow{state: state}, nil } @@ -530,6 +542,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmFullscreen: state.setFullscreen(first != 0) return 0 + case wmSetWatermark: + state.applyWatermark() + return 0 case wmChangeDecoration: state.applyDecoration() return 0 @@ -819,6 +834,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } return 0 case wmMove: + state.moveWatermark() state.refreshResizeTimer() state.reportFrame() if state.web != nil { @@ -831,12 +847,18 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { // own state, which wmSize follows. if second == 0 { state.hiddenByShow = first == 0 + if err := state.syncWatermark(); err != nil { + platform.ReportFault("window watermark", err) + } state.reportVisibility() } case wmSize: if first == 1 { // SIZE_MINIMIZED if !state.minimized { state.minimized = true + if state.watermark != nil { + state.watermark.suspend() + } if state.ready && state.config.OnMinimize != nil { state.config.OnMinimize(true) } @@ -912,6 +934,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { frame, err := state.config.OnResize(state.logicalSize(int(client.Right), int(client.Bottom))) state.frame(frame, err) } + if err := state.syncWatermark(); err != nil { + platform.ReportFault("window watermark", err) + } invalidateRect.Call(window, 0, 0) return 0 case wmLeftDown, wmLeftUp, wmRightDown, wmRightUp, wmMiddleDown, wmMiddleUp, wmXButtonDown, wmXButtonUp, wmMouseMove: @@ -1287,6 +1312,11 @@ func (state *windowState) presentClientSize(width, height int) { } func (state *windowState) layoutClientSize(width, height int) bool { + defer func() { + if err := state.syncWatermark(); err != nil { + platform.ReportFault("window watermark", err) + } + }() if state.config.OnResize != nil { state.resizeEvents++ frame, err := state.config.OnResize(state.logicalSize(width, height)) @@ -1383,6 +1413,14 @@ func (state *windowState) frameWithTextAndCancel(frame platform.Frame, err error // message loop running with no window to show, and the single-instance claim held // by a process nobody can see. func (state *windowState) destroyed(window uintptr) { + request := &state.pendingWatermark + request.mu.Lock() + request.handle, request.pending = 0, false + request.mu.Unlock() + if state.watermark != nil { + state.watermark.close() + state.watermark = nil + } // Native teardown can reenter the dispatcher; retire text callbacks first. state.ready = false if request := state.decoration.close(); request != nil { From 5a57e2424462f4ef2fae9c020417e71c1ccc676a Mon Sep 17 00:00:00 2001 From: Dean Cen Date: Fri, 27 Nov 2026 23:17:21 +0800 Subject: [PATCH 09/29] fix(tooltip): fall back to hover when the focused hit has no Hint --- app/painter.go | 2 +- app/painter_test.go | 34 ++++++++++++++++++ cmd/viva/templates/code_diff.go.txt | 12 ++++--- cmd/viva/templates/code_editor_layout.go.txt | 2 +- cmd/viva/templates/tooltip.go.txt | 36 +++++++++++++------- components/tooltip.go | 36 +++++++++++++------- components/tooltip_hover_test.go | 31 +++++++++++++++++ internal/platform/web/painter.go | 2 +- internal/platform/web/painter_test.go | 28 +++++++++++++++ 9 files changed, 150 insertions(+), 33 deletions(-) diff --git a/app/painter.go b/app/painter.go index a475a19c3..f084502be 100644 --- a/app/painter.go +++ b/app/painter.go @@ -720,7 +720,7 @@ func (painter *painter) key(event platform.KeyEvent) (platform.Frame, error) { activated = true } painter.focus.Refresh() - if event.Key == input.KeyTab { + if !response.Handled && event.Key == input.KeyTab { painter.focus.SetKeyboardFocus(!painter.focus.Focused().IsZero()) } focusChanged := painter.applyEventResult(response) diff --git a/app/painter_test.go b/app/painter_test.go index cbe959775..3f90d2da4 100644 --- a/app/painter_test.go +++ b/app/painter_test.go @@ -1091,6 +1091,40 @@ func TestKeyTabTraversesFocusAndEnterActivates(t *testing.T) { } } +func TestHandledKeyTabDoesNotRevealKeyboardFocus(t *testing.T) { + var canvas gfx.Canvas + config := Config{ + Title: "test", Width: 100, Height: 100, + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(7), gfx.Rect{X: 0, Y: 0, Width: 50, Height: 20}, "Terminal", gfx.HitOptions{Role: gfx.RoleTerminal}) + canvas.HitWithLabel(gfx.Item(8), gfx.Rect{X: 0, Y: 40, Width: 50, Height: 20}, "Cancel") + }, + OnKey: func(event gfx.KeyEvent) gfx.EventResult { + if event.Key == gfx.KeyTab && event.Target == gfx.Item(7) { + return gfx.EventResult{Handled: true} + } + return gfx.EventResult{} + }, + } + painter := newTestPainter(t, &canvas, config) + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerDown, Button: gfx.PointerButtonPrimary, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerUp, Button: gfx.PointerButtonPrimary, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + if painter.focus.Focused() != gfx.Item(7) || painter.focus.KeyboardFocus() { + t.Fatalf("after click: focused=%v keyboard=%v", painter.focus.Focused(), painter.focus.KeyboardFocus()) + } + + if _, err := painter.key(platform.KeyEvent{Key: input.KeyTab}); err != nil { + t.Fatal(err) + } + if painter.focus.Focused() != gfx.Item(7) || painter.focus.KeyboardFocus() || !canvas.FocusVisible().IsZero() { + t.Fatalf("handled Tab changed focus state: focused=%v keyboard=%v visible=%v", painter.focus.Focused(), painter.focus.KeyboardFocus(), canvas.FocusVisible()) + } +} + func TestAccessibilityNodesFollowHitsAndFocus(t *testing.T) { var canvas gfx.Canvas canvas.HitWithLabel(gfx.Item(7), gfx.Rect{X: 0, Y: 0, Width: 50, Height: 20}, "Save") diff --git a/cmd/viva/templates/code_diff.go.txt b/cmd/viva/templates/code_diff.go.txt index d2f5708db..243d3d1d2 100644 --- a/cmd/viva/templates/code_diff.go.txt +++ b/cmd/viva/templates/code_diff.go.txt @@ -866,12 +866,16 @@ func (diff *CodeDiff) linesForValue(value string) ([]string, []int) { // Scroll applies a wheel or touchpad scroll to both panes. Horizontal deltas use // horizontal movement; Shift turns vertical delta into horizontal movement. func (diff *CodeDiff) Scroll(event gfx.ScrollEvent) gfx.EventResult { - diff.scrollX += event.DeltaX + dy := event.DeltaY + if event.Pages != 0 { + dy = event.StepYIn(1, float32(diff.visibleRows)*diff.rowHeight) + } + dx := event.DeltaX if event.Modifiers&gfx.ModifierShift != 0 { - diff.scrollX += event.DeltaY - } else { - diff.scrollY += event.DeltaY + dx, dy = dx+dy, 0 // Shift turns the vertical travel sideways } + diff.scrollX += dx + diff.scrollY += dy diff.clampScroll() return gfx.EventResult{Handled: true, Repaint: true} } diff --git a/cmd/viva/templates/code_editor_layout.go.txt b/cmd/viva/templates/code_editor_layout.go.txt index 7f7ab7342..386fc257a 100644 --- a/cmd/viva/templates/code_editor_layout.go.txt +++ b/cmd/viva/templates/code_editor_layout.go.txt @@ -705,7 +705,7 @@ func (editor *CodeEditor) Scroll(event gfx.ScrollEvent) gfx.EventResult { if !editor.painted { return gfx.EventResult{} } - dx, dy := event.StepX(editor.cellWidth), event.StepY(editor.lineHeight) + dx, dy := event.StepXIn(editor.cellWidth, editor.content.Width), event.StepYIn(editor.lineHeight, editor.content.Height) if event.Modifiers&gfx.ModifierShift != 0 && dx == 0 { dx, dy = dy, 0 } diff --git a/cmd/viva/templates/tooltip.go.txt b/cmd/viva/templates/tooltip.go.txt index 125bb2926..e84631bc3 100644 --- a/cmd/viva/templates/tooltip.go.txt +++ b/cmd/viva/templates/tooltip.go.txt @@ -352,24 +352,20 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g id, immediate = hovered, false } } - if hover.focus && hover.held.IsZero() { - if focused := canvas.FocusVisible(); !focused.IsZero() { - id, immediate = focused, true - } - } - if id.IsZero() { - hover.target, hover.shown = gfx.ID{}, gfx.ID{} - return false - } hits := canvas.Hits() var hit gfx.Hit found := false - for index := len(hits) - 1; index >= 0; index-- { - if hits[index].ID == id && !hits[index].Block { - hit, found = hits[index], hits[index].Hint != "" - break + if hover.focus && hover.held.IsZero() { + if focused := canvas.FocusVisible(); !focused.IsZero() { + if focusHit, ok := hoverHintHit(hits, focused); ok { + id, immediate = focused, true + hit, found = focusHit, true + } } } + if !found { + hit, found = hoverHintHit(hits, id) + } if !found { hover.target, hover.shown = gfx.ID{}, gfx.ID{} return false @@ -396,6 +392,20 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g return true } +// hoverHintHit returns the front-most non-blocking hit for id that declares a +// non-empty Hint. +func hoverHintHit(hits []gfx.Hit, id gfx.ID) (gfx.Hit, bool) { + if id.IsZero() { + return gfx.Hit{}, false + } + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].ID == id && !hits[index].Block { + return hits[index], hits[index].Hint != "" + } + } + return gfx.Hit{}, false +} + // holdByFinger opens the tooltip of a control a finger held long enough to press it as a // right click, when nothing took that press (a control with a context menu takes it, as // on Android a long-click listener keeps the tooltip from showing). diff --git a/components/tooltip.go b/components/tooltip.go index 7d9d52b14..5e1f6ffb2 100644 --- a/components/tooltip.go +++ b/components/tooltip.go @@ -352,24 +352,20 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g id, immediate = hovered, false } } - if hover.focus && hover.held.IsZero() { - if focused := canvas.FocusVisible(); !focused.IsZero() { - id, immediate = focused, true - } - } - if id.IsZero() { - hover.target, hover.shown = gfx.ID{}, gfx.ID{} - return false - } hits := canvas.Hits() var hit gfx.Hit found := false - for index := len(hits) - 1; index >= 0; index-- { - if hits[index].ID == id && !hits[index].Block { - hit, found = hits[index], hits[index].Hint != "" - break + if hover.focus && hover.held.IsZero() { + if focused := canvas.FocusVisible(); !focused.IsZero() { + if focusHit, ok := hoverHintHit(hits, focused); ok { + id, immediate = focused, true + hit, found = focusHit, true + } } } + if !found { + hit, found = hoverHintHit(hits, id) + } if !found { hover.target, hover.shown = gfx.ID{}, gfx.ID{} return false @@ -396,6 +392,20 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g return true } +// hoverHintHit returns the front-most non-blocking hit for id that declares a +// non-empty Hint. +func hoverHintHit(hits []gfx.Hit, id gfx.ID) (gfx.Hit, bool) { + if id.IsZero() { + return gfx.Hit{}, false + } + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].ID == id && !hits[index].Block { + return hits[index], hits[index].Hint != "" + } + } + return gfx.Hit{}, false +} + // holdByFinger opens the tooltip of a control a finger held long enough to press it as a // right click, when nothing took that press (a control with a context menu takes it, as // on Android a long-click listener keeps the tooltip from showing). diff --git a/components/tooltip_hover_test.go b/components/tooltip_hover_test.go index 2fe3a4496..ccc9064bc 100644 --- a/components/tooltip_hover_test.go +++ b/components/tooltip_hover_test.go @@ -117,6 +117,37 @@ func TestHoverTooltipShowsOnKeyboardFocusWhenAsked(t *testing.T) { } } +// When ShowOnFocus is enabled and the keyboard-focused control has no Hint +// (such as a terminal or text field), hovering another control with a Hint must +// still show that hovered control's tooltip. +func TestHoverTooltipFallsBackToHoverWhenFocusedControlHasNoHint(t *testing.T) { + var hover HoverTooltip + hover.ShowOnFocus() + viewport := gfx.Rect{Width: 300, Height: 200} + paint := func(now time.Duration) (*gfx.Canvas, bool) { + var canvas gfx.Canvas + canvas.SetClock(func() time.Duration { return now }) + canvas.BeginFrame() + canvas.HitWithOptions(gfx.Item(9), gfx.Rect{X: 0, Y: 0, Width: 200, Height: 120}, "Terminal", gfx.HitOptions{Role: gfx.RoleTerminal}) + canvas.HitWithOptions(gfx.Item(7), gfx.Rect{X: 220, Y: 10, Width: 28, Height: 28}, "Refresh", gfx.HitOptions{Role: gfx.RoleButton, Hint: "Refresh the list"}) + canvas.SetInteraction(gfx.Item(7), gfx.ID{}, gfx.Item(9), true) + painted := hover.Paint(&canvas, gfx.DarkTheme(), viewport, TooltipOptions{}, testTooltipDelay) + canvas.EndFrame() + return &canvas, painted + } + + if _, painted := paint(0); painted { + t.Fatal("hovered tooltip painted before its delay while focus had no hint") + } + canvas, painted := paint(testTooltipDelay) + if !painted || hover.Showing() != gfx.Item(7) { + t.Fatalf("painted=%v showing=%v, want hovered item 7", painted, hover.Showing()) + } + if _, ok := tooltipText(canvas, "Refresh the list"); !ok { + t.Fatalf("missing hovered tooltip text: %+v", canvas.Texts()) + } +} + // Escape (Dismiss) and a press anywhere hide the shown tooltip until the pointer // leaves the control, as Base UI's tooltip dismiss does. func TestHoverTooltipDismissesOnEscapeAndPress(t *testing.T) { diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index f1b44ea8d..f316c6df2 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -153,7 +153,7 @@ func (p *painter) keyDownCode(event gfx.KeyEvent, code uint32) bool { activated = true } p.focus.Refresh() - if event.Key == gfx.KeyTab { + if !response.Handled && event.Key == gfx.KeyTab { p.focus.SetKeyboardFocus(!p.focus.Focused().IsZero()) } focusChanged := p.applyEventResult(response) diff --git a/internal/platform/web/painter_test.go b/internal/platform/web/painter_test.go index 285903d5c..ca8e78cb7 100644 --- a/internal/platform/web/painter_test.go +++ b/internal/platform/web/painter_test.go @@ -93,6 +93,34 @@ func TestPointerFocusMatchesNativeWithoutRing(t *testing.T) { } } +func TestHandledKeyTabDoesNotRevealKeyboardFocus(t *testing.T) { + var canvas gfx.Canvas + config := Config{ + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{X: 0, Y: 0, Width: 80, Height: 40}, "Terminal", gfx.HitOptions{Role: gfx.RoleTerminal}) + canvas.HitWithLabel(gfx.Item(2), gfx.Rect{X: 100, Y: 0, Width: 80, Height: 40}, "Cancel") + }, + OnKey: func(event gfx.KeyEvent) gfx.EventResult { + if event.Key == gfx.KeyTab && event.Target == gfx.Item(1) { + return gfx.EventResult{Handled: true} + } + return gfx.EventResult{} + }, + } + painter := newPainter(&canvas, &config) + painter.width, painter.height = 200, 100 + painter.repaint() + painter.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: 20, Y: 20}) + painter.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerUp, Button: gfx.PointerButtonPrimary, X: 20, Y: 20}) + if painter.focus.Focused() != gfx.Item(1) || painter.focus.KeyboardFocus() { + t.Fatalf("after click: focused=%v keyboard=%v", painter.focus.Focused(), painter.focus.KeyboardFocus()) + } + painter.keyDown(gfx.KeyEvent{Key: gfx.KeyTab}) + if painter.focus.Focused() != gfx.Item(1) || painter.focus.KeyboardFocus() || !canvas.FocusVisible().IsZero() { + t.Fatalf("handled Tab changed focus state: focused=%v keyboard=%v visible=%v", painter.focus.Focused(), painter.focus.KeyboardFocus(), canvas.FocusVisible()) + } +} + func TestPointerEventsCaptureTargetAndHandledSuppressesClick(t *testing.T) { var canvas gfx.Canvas var events [3]gfx.PointerEvent From 3c5ea400f8384742648572e0de35f9ba5da6e679 Mon Sep 17 00:00:00 2001 From: mirakyux Date: Fri, 27 Nov 2026 23:18:09 +0800 Subject: [PATCH 10/29] fix(app): refresh hover after layout under a stationary pointer Squash of #487 with its installer templates regenerated; applied directly because the contributor's fork rejects maintainer pushes. --- app/painter.go | 112 +++++++++++++++-------- app/painter_test.go | 79 ++++++++++++++++ app/window_edge.go | 6 +- cmd/viva/templates/hierarchy_menu.go.txt | 3 + cmd/viva/templates/multi_select.go.txt | 3 + cmd/viva/templates/single_select.go.txt | 3 + components/hierarchy_menu.go | 3 + components/multi_select.go | 3 + components/single_select.go | 3 + gfx/canvas.go | 41 ++++++--- gfx/embed.go | 1 + 11 files changed, 204 insertions(+), 53 deletions(-) diff --git a/app/painter.go b/app/painter.go index f084502be..42ade8fed 100644 --- a/app/painter.go +++ b/app/painter.go @@ -127,8 +127,16 @@ type painter struct { // coordinates: a hit's position-dependent picture is asked for at this // place, so it follows the pointer without a repaint. pointerAt gfx.Point - scrollX float32 - scrollY float32 + // pointerPresent distinguishes a pointer in the window from the initial + // state and the coordinates carried by an exit. + pointerPresent bool + // hoverFromLayout distinguishes an updated highlight from a pointer entry. + hoverFromLayout bool + // pointerNeedsHit marks a viewport resize, which can move the window edge + // across the pointer even if the page declares the same regions. + pointerNeedsHit bool + scrollX float32 + scrollY float32 // scheduleFrame asks the runtime for one more frame, after at least the // delay, while a transition is in flight or the application asked for one. scheduleFrame func(delay time.Duration) @@ -225,6 +233,7 @@ func (painter *painter) resize(size platform.Size) (platform.Frame, error) { next := gfx.Size{Width: size.Width, Height: size.Height} changed := next != painter.size painter.size, painter.scale = next, size.Scale + painter.pointerNeedsHit = painter.pointerNeedsHit || changed if changed && painter.onResize != nil { painter.onResize(next) } @@ -285,8 +294,8 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo painter.pointer.Exit() event.Kind = platform.PointerExit } - if event.Kind == platform.PointerMove && painter.pointerOutside && - event.X >= 0 && event.Y >= 0 && event.X < painter.size.Width && event.Y < painter.size.Height { + painter.pointerPresent = event.Kind != platform.PointerExit + if event.Kind == platform.PointerMove && painter.pointerOutside && painter.pointerAtInside() { painter.pointerOutside = false } if event.Kind == platform.PointerExit && !painter.pointer.PressTarget().IsZero() { @@ -295,16 +304,16 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo // exactly where the user needs it: past the edge of the terminal, the // list or the window. The exit is delivered when the button is released. painter.pointerOutside = true - painter.onSurface = false - if painter.pointer.Hovered().IsZero() { + painter.trackEdge(false) + if !painter.updateHover(false, false) { 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() - beforeSurface := painter.onSurface + beforeRole, beforeSurface := painter.pointer.HoveredRole(), painter.onSurface + beforeHoverFromLayout := painter.hoverFromLayout && !beforeHovered.IsZero() + painter.hoverFromLayout = false beforeFocus, beforeKeyboard := painter.focus.Focused(), painter.focus.KeyboardFocus() passes := event.Kind == platform.PointerDown && (event.Button == gfx.PointerButtonSecondary && painter.focus.Router().PassesSecondary(event.X, event.Y) || @@ -352,7 +361,8 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo } if painter.pointer.Hovered() == beforeHovered && painter.pointer.Pressed() == beforePressed && - painter.onSurface == beforeSurface && + painter.pointer.HoveredRole() == beforeRole && painter.onSurface == beforeSurface && + !beforeHoverFromLayout && painter.focus.Focused() == beforeFocus && painter.focus.KeyboardFocus() == beforeKeyboard && !focusChanged && !result.Repaint { if edgeChanged { @@ -373,18 +383,10 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo // state, the application and the controls' event pass. It returns what the // 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)) - painter.onSurface = false - if event.Kind != platform.PointerExit { - secondaryPress := event.Kind == platform.PointerDown && event.Button == gfx.PointerButtonSecondary - if target, ok, onSurface := painter.focus.Router().PointerAt(event.X, event.Y, secondaryPress); ok || onSurface { - painter.pointer.SetHovered(target.Target) - painter.pointer.SetHoveredRole(target.Role) - painter.onSurface = onSurface - } - } - edgeChanged = painter.trackEdge(event) + secondaryPress := event.Kind == platform.PointerDown && event.Button == gfx.PointerButtonSecondary + inside := painter.pointerPresent && !painter.pointerOutside && painter.pointerAtInside() + painter.updateHover(inside, secondaryPress) + edgeChanged = painter.trackEdge(inside) if event.Kind == platform.PointerDown { painter.pointer.Down(event.Button) @@ -419,6 +421,26 @@ func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.Eve return result, focusChanged, edgeChanged } +func (painter *painter) pointerAtInside() bool { + return painter.pointerAt.X >= 0 && painter.pointerAt.Y >= 0 && + painter.pointerAt.X < painter.size.Width && painter.pointerAt.Y < painter.size.Height +} + +// updateHover resolves the pointer against the current routing regions. Press +// capture and application pointer events are independent of this lookup. +func (painter *painter) updateHover(inside, secondaryPress bool) bool { + var hit input.Region + var onSurface bool + if inside { + hit, _, onSurface = painter.focus.Router().PointerAt(painter.pointerAt.X, painter.pointerAt.Y, secondaryPress) + } + changed := painter.pointer.Hovered() != hit.Target || painter.pointer.HoveredRole() != hit.Role || painter.onSurface != onSurface + painter.pointer.SetHovered(hit.Target) + painter.pointer.SetHoveredRole(hit.Role) + painter.onSurface = onSurface + return changed +} + // placeCaret puts the caret of the focused text field where a press, or the drag // of one, lands, when the field lays its rows out itself (gfx.TextPlacement): the // platform editor knows one line only and leaves such a field to this. A press @@ -1050,7 +1072,7 @@ func (painter *painter) repaint() (platform.Frame, error) { painter.noteFrameStart() } painter.paintCanvas() - painter.settleFocus() + painter.settleInteraction() frame, err := painter.publish() if err != nil { return platform.Frame{}, err @@ -1094,27 +1116,40 @@ const ( focusReused ) -// maxFocusPasses bounds the paints settleFocus adds to one frame: a page whose -// every paint moves the focus somewhere new shows the last move. -const maxFocusPasses = 2 +// maxInteractionRepaints bounds the work for a page where paint keeps moving +// the focused or hovered target. +const maxInteractionRepaints = 2 -// settleFocus applies the focus changes the paint itself made, by an Autofocus -// hit that appeared, a focus request or release, a returning scope that closed, -// a modal that opened or closed, or a request carried from the event, and paints -// again when the focus moved, so the frame shows the focus it routes keys to. -func (painter *painter) settleFocus() { +// settleInteraction syncs focus and the pointer with the regions just painted. +// A scroll or layout change can move hits under a stationary pointer. Paint +// again if these regions change the state that the frame should show. +func (painter *painter) settleInteraction() { if painter.paint == nil { return } - for range maxFocusPasses { - if !painter.regionsNeedSync() { + needsPointerHit := painter.pointerNeedsHit + painter.pointerNeedsHit = false + synced := false + for pass := 0; ; pass++ { + before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus() + // After an intermediate paint, the router may differ from the last + // published regions even if the new paint restored those regions. + if synced || painter.regionsNeedSync() { + painter.focus.Sync(painter.canvas) + painter.focusSettled = focusSynced + synced = true + } else { painter.focusSettled = focusReused - return } - before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus() - painter.focus.Sync(painter.canvas) - painter.focusSettled = focusSynced - if painter.focus.Focused() == before && painter.focus.KeyboardFocus() == beforeVisible { + hoverChanged := false + if painter.pointerPresent && (synced || needsPointerHit) { + inside := !painter.pointerOutside && painter.pointerAtInside() + hoverChanged = painter.updateHover(inside, false) + painter.hoverFromLayout = painter.hoverFromLayout || hoverChanged + painter.trackEdge(inside) + } + if pass == maxInteractionRepaints || + (!hoverChanged && painter.focus.Focused() == before && painter.focus.KeyboardFocus() == beforeVisible) { return } painter.paintCanvas() @@ -1144,6 +1179,7 @@ func (painter *painter) paintCanvas() { } focused, visible := painter.focus.PaintTarget() painter.canvas.SetInteraction(painter.pointer.Hovered(), painter.pointer.Pressed(), focused, visible) + painter.canvas.SetHoverFromLayout(painter.hoverFromLayout) painter.canvas.SetHoveredRole(painter.pointer.HoveredRole()) painter.canvas.SetPointerOnSurface(painter.onSurface) painter.canvas.SetTitlebarInsets(painter.titlebarInsets()) diff --git a/app/painter_test.go b/app/painter_test.go index 3f90d2da4..75b64ad7a 100644 --- a/app/painter_test.go +++ b/app/painter_test.go @@ -767,6 +767,85 @@ func TestPointerHoverEntersAndExitsOnce(t *testing.T) { } } +func TestStationaryPointerFollowsNewHitGeometry(t *testing.T) { + var canvas gfx.Canvas + var events, paints int + var covered bool + config := Config{Title: "stationary pointer", Width: 100, Height: 100} + config.OnPointer = func(gfx.PointerEvent) gfx.EventResult { + events++ + return gfx.EventResult{} + } + config.Paint = func(canvas *gfx.Canvas, _ gfx.Size) { + paints++ + canvas.HitWithOptions(gfx.Item(7), gfx.Rect{Y: -canvas.ScrollY(), Width: 40, Height: 20}, "First", gfx.HitOptions{Cursor: gfx.PointerCursorHand}) + canvas.HitWithOptions(gfx.Item(8), gfx.Rect{Y: 20 - canvas.ScrollY(), Width: 40, Height: 20}, "Second", gfx.HitOptions{Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText}) + if covered { + canvas.BlockSurface(gfx.Rect{Width: 40, Height: 20}) + } + } + painter := newTestPainter(t, &canvas, config) + check := func(target gfx.ID, role gfx.Role, cursor Cursor, onSurface bool) { + t.Helper() + if canvas.Hovered() != target || canvas.HoveredRole() != role || painter.cursor != cursor || canvas.PointerOnSurface() != onSurface { + t.Fatalf("painted hover = %v, role = %v, cursor = %v, surface = %v, want %v, %v, %v, %v", + canvas.Hovered(), canvas.HoveredRole(), painter.cursor, canvas.PointerOnSurface(), target, role, cursor, onSurface) + } + } + check(gfx.ID{}, 0, CursorArrow, false) + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerMove, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + check(gfx.Item(7), gfx.RoleButton, CursorHand, false) + + if _, err := painter.scroll(platform.ScrollEvent{X: 10, Y: 10, DeltaY: 20}); err != nil { + t.Fatal(err) + } + check(gfx.Item(8), gfx.RoleTextField, CursorText, false) + if canvas.HoverCrossed() || !canvas.HoverFromLayout() { + t.Fatal("scrolling under the pointer should update hover without a pointer entry") + } + + covered = true + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + check(gfx.ID{}, 0, CursorArrow, true) + if events != 1 { + t.Fatalf("scroll and repaints sent pointer events, got %d events", events) + } + before := paints + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + if paints != before+1 { + t.Fatalf("stable geometry required %d paints, want one", paints-before) + } + + covered = false + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + check(gfx.Item(8), gfx.RoleTextField, CursorText, false) + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerMove, X: 11, Y: 10}); err != nil { + t.Fatal(err) + } + if !canvas.HoverCrossed() || canvas.HoverFromLayout() { + t.Fatal("moving over a laid-out hover should register its first pointer entry") + } + + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerExit}); err != nil { + t.Fatal(err) + } + covered = false + // An exit carries no useful coordinates. A later paint must not treat + // its zero position as a pointer that moved onto the exposed item. + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + check(gfx.ID{}, 0, CursorArrow, false) +} + // A drag off a surface and out of the window ends the surface state even when no // hit is hovered: the early return must not leave the host's copy of the flag set // for the next paint. diff --git a/app/window_edge.go b/app/window_edge.go index 20ace7d7f..9b46f2b50 100644 --- a/app/window_edge.go +++ b/app/window_edge.go @@ -5,10 +5,10 @@ import "github.com/vivaui/viva/internal/platform" // trackEdge follows which resize edge of a window with Viva-drawn controls the // pointer is over, and reports whether that changed. The top edge yields to a // control under the pointer, as it does when pressed. -func (painter *painter) trackEdge(event platform.PointerEvent) bool { +func (painter *painter) trackEdge(inside bool) bool { next := platform.EdgeNone - if painter.controls != nil && event.Kind != platform.PointerExit && !painter.controls.maximized() { - next = platform.EdgeAt(event.X, event.Y, painter.size.Width, painter.size.Height, !painter.pointer.Hovered().IsZero()) + if painter.controls != nil && inside && !painter.controls.maximized() { + next = platform.EdgeAt(painter.pointerAt.X, painter.pointerAt.Y, painter.size.Width, painter.size.Height, !painter.pointer.Hovered().IsZero()) } changed := next != painter.edge painter.edge = next diff --git a/cmd/viva/templates/hierarchy_menu.go.txt b/cmd/viva/templates/hierarchy_menu.go.txt index 9461d87ff..41673af9e 100644 --- a/cmd/viva/templates/hierarchy_menu.go.txt +++ b/cmd/viva/templates/hierarchy_menu.go.txt @@ -104,6 +104,9 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } // Move the cursor before any row is painted, as the flat list does. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } level, row, onRow := 0, 0, false if index, ok := hovered.In(o.OptionIDs); ok && index&0xFFFF != hierarchyBarRow { level, row, onRow = index>>16, index&0xFFFF, true diff --git a/cmd/viva/templates/multi_select.go.txt b/cmd/viva/templates/multi_select.go.txt index c4b6648aa..2b1ab9668 100644 --- a/cmd/viva/templates/multi_select.go.txt +++ b/cmd/viva/templates/multi_select.go.txt @@ -155,6 +155,9 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M // Move the cursor before any row is painted: syncing it while the rows are // drawn would tint the previous row and the new one in the same frame. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } if s.AdoptHover(hovered) && !hovered.IsZero() { for i := range choices { if o.OptionIDs.At(i) == hovered && !choices[i].Disabled { diff --git a/cmd/viva/templates/single_select.go.txt b/cmd/viva/templates/single_select.go.txt index 80df14c81..376f20032 100644 --- a/cmd/viva/templates/single_select.go.txt +++ b/cmd/viva/templates/single_select.go.txt @@ -192,6 +192,9 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * // Move the cursor before any row is painted: syncing it while the rows are // drawn would tint the previous row and the new one in the same frame. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } if s.Hover.Entered(hovered) && !hovered.IsZero() { for i := range choices { if o.OptionIDs.At(i) == hovered && !choices[i].Disabled { diff --git a/components/hierarchy_menu.go b/components/hierarchy_menu.go index 55ed916c4..70b47ac66 100644 --- a/components/hierarchy_menu.go +++ b/components/hierarchy_menu.go @@ -104,6 +104,9 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } // Move the cursor before any row is painted, as the flat list does. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } level, row, onRow := 0, 0, false if index, ok := hovered.In(o.OptionIDs); ok && index&0xFFFF != hierarchyBarRow { level, row, onRow = index>>16, index&0xFFFF, true diff --git a/components/multi_select.go b/components/multi_select.go index c822c07c1..b911ca927 100644 --- a/components/multi_select.go +++ b/components/multi_select.go @@ -155,6 +155,9 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M // Move the cursor before any row is painted: syncing it while the rows are // drawn would tint the previous row and the new one in the same frame. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } if s.AdoptHover(hovered) && !hovered.IsZero() { for i := range choices { if o.OptionIDs.At(i) == hovered && !choices[i].Disabled { diff --git a/components/single_select.go b/components/single_select.go index 6e007a313..fad55afe7 100644 --- a/components/single_select.go +++ b/components/single_select.go @@ -192,6 +192,9 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * // Move the cursor before any row is painted: syncing it while the rows are // drawn would tint the previous row and the new one in the same frame. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } if s.Hover.Entered(hovered) && !hovered.IsZero() { for i := range choices { if o.OptionIDs.At(i) == hovered && !choices[i].Disabled { diff --git a/gfx/canvas.go b/gfx/canvas.go index 2e9bf0f16..6a7600376 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -832,13 +832,14 @@ type Canvas struct { touched bool // prevHovered is the hit the pointer was on at the end of the previous // paint, which is what HoverCrossed compares against. - prevHovered ID - pressed ID - focused ID - scrollX float32 - scrollY float32 - trappedScope ID - escapeTarget ID + prevHovered ID + hoverFromLayout, prevHoverFromLayout bool + pressed ID + focused ID + scrollX float32 + scrollY float32 + trappedScope ID + escapeTarget ID // The focus-scope depth each overlay claim was made at. A claim from a // deeper scope (a popup inside a dialog) wins over an outer one however // late the outer overlay finishes painting; equal depths let the later @@ -1117,6 +1118,7 @@ func (canvas *Canvas) Reset() { canvas.focusReturns = canvas.focusReturns[:0] canvas.trapDepth, canvas.escapeDepth, canvas.initialDepth = -1, -1, -1 canvas.prevHovered = canvas.hovered + canvas.prevHoverFromLayout = canvas.hoverFromLayout canvas.listensForClicks = false canvas.listensForPointer = false } @@ -2197,6 +2199,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.hoverFromLayout = false canvas.hoveredRole = 0 canvas.onSurface = false canvas.pressed = pressed @@ -2209,6 +2212,19 @@ func (canvas *Canvas) Hovered() ID { return canvas.hovered } +// HoverFromLayout reports that the current hover was found after layout moved +// hits under a stationary pointer. It can update the highlight without +// moving a menu's keyboard cursor. +func (canvas *Canvas) HoverFromLayout() bool { + return canvas.hoverFromLayout +} + +// SetHoverFromLayout records the source of the hover for this paint. It is +// runtime-facing; application paint code should only read it. +func (canvas *Canvas) SetHoverFromLayout(fromLayout bool) { + canvas.hoverFromLayout = fromLayout +} + // HoveredRole returns the role of the hovered hit, or the zero role when the // runtime did not record one. func (canvas *Canvas) HoveredRole() Role { @@ -2248,12 +2264,13 @@ func (canvas *Canvas) SetTitlebarInsets(leading, trailing float32) { canvas.titlebarLeading, canvas.titlebarTrailing = leading, trailing } -// 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 -// back from the keyboard. +// HoverCrossed reports whether pointer input reached a different hit since the +// previous paint or moved within a hit that layout moved under the pointer. +// Lists use it to move their current row without taking it back from the +// keyboard while the pointer rests in place. func (canvas *Canvas) HoverCrossed() bool { - return canvas.hovered != canvas.prevHovered + return !canvas.hoverFromLayout && (canvas.hovered != canvas.prevHovered || + canvas.prevHoverFromLayout && !canvas.hovered.IsZero()) } // Pressed returns the hit ID currently held down, or the zero ID. diff --git a/gfx/embed.go b/gfx/embed.go index cee227f3e..1b0d88bc5 100644 --- a/gfx/embed.go +++ b/gfx/embed.go @@ -31,6 +31,7 @@ func (canvas *Canvas) BeginEmbedded(parent *Canvas, mount Scope) { canvas.iconCache = parent.icons() tree := canvas.tree canvas.hovered, _ = tree.Local(mount, parent.hovered) + canvas.hoverFromLayout = parent.hoverFromLayout canvas.pressed, _ = tree.Local(mount, parent.pressed) canvas.focused, _ = tree.Local(mount, parent.focused) canvas.focusVisible = parent.focusVisible && !canvas.focused.IsZero() From 13980d0ce43df4ee1ec430bd168fda0131d8d4cb Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 27 Nov 2026 23:20:26 +0800 Subject: [PATCH 11/29] docs(audio): document microphone permission and macOS bundle keys Follow-up to #483: the packager already writes NSMicrophoneUsageDescription from [mac.info] and signs with the [mac] entitlements file, so only the contract was missing. --- audio/input.go | 3 +++ docs/audio.md | 31 ++++++++++++++++++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/audio/input.go b/audio/input.go index 7d5534f97..a00af7bcf 100644 --- a/audio/input.go +++ b/audio/input.go @@ -34,6 +34,9 @@ type Input struct { // OpenInput opens the default input device for format. It returns // ErrInputUnsupported when the platform, the system library, or the system's // default input device cannot capture. +// +// Denied microphone access is not an error: macOS and Windows deliver silence. +// docs/audio.md lists what a macOS bundle must declare. func OpenInput(format Format) (*Input, error) { if err := format.valid(); err != nil { return nil, err diff --git a/docs/audio.md b/docs/audio.md index 0123be2d1..7d8704810 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -1,4 +1,4 @@ -# Audio output +# Audio `audio` plays PCM on the system's default output device. It exists for a stream an application receives from elsewhere — a remote desktop's sound, a @@ -28,10 +28,35 @@ discarded. It is safe to call more than once. - It has no volume control. The stream follows the system's output volume and mute, which is what a remote desktop wants: the machine's own controls stay authoritative. -- It does not capture the microphone. Audio input is a separate capability and - is not implemented. - It does not exist on WebAssembly. `Open` returns `ErrUnsupported`. +## Microphone capture + +`audio.OpenInput` captures the system's default input device as the same +16-bit little-endian PCM. `Input` implements `io.ReadCloser`; nothing is opened +until it is called, and `Close` joins the capture goroutine and releases the +device. If the reader stalls, the oldest quarter-second is dropped rather than +blocking the device. Targets without a backend return `ErrInputUnsupported`. + +Opening the microphone is a privacy decision the operating system gates, so an +application declares it: + +- **macOS** asks the user once per application. The bundle must carry + `NSMicrophoneUsageDescription`, and a hardened-runtime build must be signed + with `com.apple.security.device.audio-input`. Both are project settings, not + code: put the usage string under `[mac.info]` and the entitlement in the + property list that `[mac] entitlements` points to. Without them macOS can + terminate the process or deliver silence, and `OpenInput` reports success + either way, so a capture of all zeros means the permission is missing, not + that the microphone is quiet. +- **Windows** gates desktop applications with Settings > Privacy > Microphone; + when access is off the device delivers silence. +- **Linux** has no per-application prompt; a sandbox such as Flatpak grants + access through its portal. + +An application should say why it listens before it calls `OpenInput`, and +should not open the device before the user asks for sound. + ## Backends | Target | Backend | Format handling | From 1f47eb2f9beb13cbfabd23f7e04b73e5647bb5c3 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 27 Nov 2026 23:31:13 +0800 Subject: [PATCH 12/29] fix(darwin): cast the watermark bitmap info for -Werror builds --- internal/platform/darwin/watermark_darwin.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/platform/darwin/watermark_darwin.m b/internal/platform/darwin/watermark_darwin.m index 65bc6c26b..7ba828dad 100644 --- a/internal/platform/darwin/watermark_darwin.m +++ b/internal/platform/darwin/watermark_darwin.m @@ -39,7 +39,7 @@ static void watermarkReleaseTile(void *info) { // 8-bit components, so use bounded linear sRGB to match the canvas color values. static CGContextRef watermarkCreateTileContext(size_t width, size_t height) { CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceLinearSRGB); - CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGImageAlphaPremultipliedLast); + CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, (CGBitmapInfo)kCGImageAlphaPremultipliedLast); CGColorSpaceRelease(space); return context; } From 467d79a8a53f251cf5d44d09b320739733af36c2 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 27 Nov 2026 23:38:46 +0800 Subject: [PATCH 13/29] docs(release): v0.6.10 notes --- docs/releases/0.6.10.md | 55 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 docs/releases/0.6.10.md diff --git a/docs/releases/0.6.10.md b/docs/releases/0.6.10.md new file mode 100644 index 000000000..9f0a35a1a --- /dev/null +++ b/docs/releases/0.6.10.md @@ -0,0 +1,55 @@ +v0.6.10 是 v0.6.9 之后的版本:加入原生窗口水印、由应用事件循环接管的系统通知激活、跨平台麦克风采集,以及窗口装饰的即时切换;输入、剪贴板与绘制方面修复了 Caps Lock、被平台夺走的按下、Windows 与 GTK 的文件拖放回调、细描边亮度不均、静止指针下的悬停刷新等问题。macOS 是参考平台。 + +v0.6.10 comes after v0.6.9: native window watermarks, system notification activation owned by the application event loop, cross-platform microphone capture and live window decoration changes arrive, and input, clipboard and painting gain fixes for Caps Lock, a press the platform takes away, file-drop callbacks on Windows and GTK, uneven thin-stroke brightness and hover under a stationary pointer. macOS is the reference platform. + +## 拿到它 · Getting it + +`go get github.com/vivaui/viva@v0.6.10`,需要 Go 1.26 或更新;系统依赖与 v0.6.9 相同。每个 Release 附带 `viva` 命令的预编译压缩包、`SHA256SUMS`,以及 Homebrew 与 Scoop 清单(`brew install vivaui/tap/viva`,或 `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` 后 `scoop install viva`)。 + +`go get github.com/vivaui/viva@v0.6.10` needs Go 1.26 or newer; the system requirements are those of v0.6.9. 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`). + +## 有什么 · What is in it + +- `Config.Watermark`、`Window.SetWatermark` 与 `CapabilityWindowWatermark` 在画布和内嵌原生视图(例如 web view)上方叠一层不接收输入的文字水印:macOS 用原生视图叠加,Windows 用点击穿透的分层弹窗,Linux 忽略,headless 只记录状态;自定义 host 可实现可选的 `SetWatermark(app.Watermark)`;`gfx.WeightLight` 补上细字重 (contributed by @darrenjindai) (PR [#462](https://github.com/vivaui/viva/pull/462))。 +- `Application.ShowNotification` 返回可在任意 goroutine 关闭的句柄,`OnActivate` 与 `OnError` 回调排到应用事件循环上执行,点击通知即可恢复或打开窗口,`Close` 撤回通知,权限被拒时报告 `ErrPermissionDenied`;macOS 用 UNUserNotificationCenter,Windows 用唤醒窗口上的托盘气泡,其他平台返回 `ErrUnsupported`,`CapabilityNotificationActivation` 报告平台是否支持 (contributed by @darrenjindai) (PR [#475](https://github.com/vivaui/viva/pull/475))。 +- `audio.OpenInput` 从默认输入设备采集 16 位小端 PCM,`Input` 实现 `io.ReadCloser`;macOS 用 CoreAudio,Windows 用 WASAPI,Linux 用 ALSA,其他平台返回 `ErrInputUnsupported`;macOS 的麦克风授权与 bundle 键见 `docs/audio.md` (contributed by @DeanCen) (PR [#483](https://github.com/vivaui/viva/pull/483))。 +- `Window.SetDecorated` 在已显示的窗口上切换原生装饰,并在确认后通过 `done` 报告一次结果。 +- 窗口可以让控件声明自己的指针光标,指针悬停时跟随命中项的光标图片,状态项在原生悬停时可预览;菜单项可以加字母助记键;`TextArea` 在 `Secure` 时把内容显示为圆点;剪贴板可以放入承诺文件;被省略的标签悬停时显示全文,只读文本可在 `TextSelectionArea` 中选择并复制。 +- 新增 `ui/overflowlist`(折进「更多」菜单的工具栏行)、统计、输入标签、自动补全与指示器控件;`CodeEditor` 增加跟随编辑的折叠状态、可点击的折叠省略徽标、行号栏与字节装饰。 +- `gfx` 可以在设备像素上绘制调用方的位图,`HitOptions` 有了 `IsZero`;颜色选择器的无效 HEX 提示已本地化;headless 脚本可以把复制的文件放上剪贴板。 +- 细描边在三角形与裁剪之间保持均匀覆盖:竖直细线与被裁剪的图标描边不再沿长度方向忽明忽暗 (contributed by @mirakyux) (PR [#488](https://github.com/vivaui/viva/pull/488))。 +- 布局变化后,静止的指针下的控件在同一帧得到悬停与光标,菜单不会因此丢掉键盘的当前行 (contributed by @mirakyux) (PR [#487](https://github.com/vivaui/viva/pull/487))。 +- 工具提示在获得焦点的控件没有 `Hint` 时回退到悬停;被应用处理的 Tab 不再显现键盘焦点 (contributed by @DeanCen) (PR [#481](https://github.com/vivaui/viva/pull/481))。 +- 无填充按钮的焦点环画成光晕而不是盖满表面,`viva add button` 与 `button-group` 装出的代码与参考组件一致 (contributed by @caichangqing1120) (PR [#484](https://github.com/vivaui/viva/pull/484))。 +- Caps Lock 作为按键交给应用;被平台夺走的按下会正常结束;页面按一格滚动时使用区域自己的屏幕。 +- Windows 监听的目录被移走并在原路径重建时,现在会报告 Resync (contributed by @1lck) (PR [#485](https://github.com/vivaui/viva/pull/485));Windows 在首帧前应用显示器的 DPI,`WindowNotification` 的原点以物理像素报告 (contributed by @Ezreal-byte) (PR [#479](https://github.com/vivaui/viva/pull/479)),并在 Windows 与 GTK 上保护文件拖放回调 (contributed by @Ezreal-byte) (PR [#480](https://github.com/vivaui/viva/pull/480))。 +- Windows 在注册字体里绘制回退字形,且剪贴板事务固定在同一个系统线程上;Linux 读取放下选择时带上 `XdndDrop` 时间戳,字体列表包含双宽与未标记的等宽字体,门户的初始目录得到转发。 +- Web 与 dev 构建恢复了光标图片回调 (contributed by @caichangqing1120) (PR [#477](https://github.com/vivaui/viva/pull/477));增量渲染的混合删除与插入不再重建整页,批处理的临时空间在页面缩小后释放,每次绘制只对已发布的命中区域比较一次。 +- `viva init` 与 `viva add` 的组件模板已按源码重新生成。 + +- `Config.Watermark`, `Window.SetWatermark` and `CapabilityWindowWatermark` lay a text watermark over the canvas and over embedded native views such as a web view, without taking input: macOS uses a native overlay view, Windows a click-through layered popup, Linux ignores it, and headless only records the state; a custom host may implement the optional `SetWatermark(app.Watermark)`, and `gfx.WeightLight` adds a light weight (contributed by @darrenjindai) (PR [#462](https://github.com/vivaui/viva/pull/462)). +- `Application.ShowNotification` returns a handle closable from any goroutine; its `OnActivate` and `OnError` callbacks run on the application event loop, so a click can restore or open a window, `Close` withdraws the notification, and a refused permission is reported as `ErrPermissionDenied`; macOS uses UNUserNotificationCenter, Windows a tray balloon on the wake window, other targets return `ErrUnsupported`, and `CapabilityNotificationActivation` reports whether the platform has it (contributed by @darrenjindai) (PR [#475](https://github.com/vivaui/viva/pull/475)). +- `audio.OpenInput` captures 16-bit little-endian PCM from the default input device, and `Input` implements `io.ReadCloser`; macOS uses CoreAudio, Windows WASAPI and Linux ALSA, and other targets return `ErrInputUnsupported`; the macOS microphone permission and bundle keys are in `docs/audio.md` (contributed by @DeanCen) (PR [#483](https://github.com/vivaui/viva/pull/483)). +- `Window.SetDecorated` toggles native decorations on a shown window and reports the confirmed result once through `done`. +- A control can declare its own pointer cursor, the pointer follows a hit's cursor picture, a status item can be previewed on native hover, menu items take letter mnemonics, a `TextArea` shows its value as bullets when `Secure`, promised files can be put on the clipboard, an ellipsized label shows its full text on hover, and read-only text can be selected and copied in a `TextSelectionArea`. +- New are `ui/overflowlist` (a toolbar row that folds into a More menu) and statistic, input tag, autocomplete and indicator controls; `CodeEditor` gains edit-following fold state, a clickable ellipsis badge on folded lines, a gutter and byte decorations. +- `gfx` draws a caller's bitmap on device pixels and `HitOptions` has an `IsZero`; the color picker's invalid HEX message is localized; and a headless script can put copied files on the clipboard. +- A thin stroke keeps uniform coverage across triangles and clips: a thin vertical line or a clipped icon stroke no longer brightens and dims along its length (contributed by @mirakyux) (PR [#488](https://github.com/vivaui/viva/pull/488)). +- After a layout change the control under a stationary pointer takes hover and cursor in the same frame, and menus keep the keyboard's current row (contributed by @mirakyux) (PR [#487](https://github.com/vivaui/viva/pull/487)). +- A tooltip falls back to hover when the focused control has no `Hint`, and a Tab the application handled no longer shows keyboard focus (contributed by @DeanCen) (PR [#481](https://github.com/vivaui/viva/pull/481)). +- An unfilled button's focus ring is drawn as a halo rather than covering its surface, and `viva add button` and `button-group` install what the reference components draw (contributed by @caichangqing1120) (PR [#484](https://github.com/vivaui/viva/pull/484)). +- Caps Lock reaches the application as a key, a press the platform takes away ends cleanly, and a page notch scrolls by the region's own screen. +- A watched directory on Windows that is moved away and recreated at the same path now reports a Resync (contributed by @1lck) (PR [#485](https://github.com/vivaui/viva/pull/485)); Windows applies the monitor's DPI before the first frame and reports the `WindowNotification` origin in physical pixels (contributed by @Ezreal-byte) (PR [#479](https://github.com/vivaui/viva/pull/479)), and file-drop callbacks are guarded on Windows and GTK (contributed by @Ezreal-byte) (PR [#480](https://github.com/vivaui/viva/pull/480)). +- Windows draws fallback glyphs from registered fonts and keeps clipboard transactions on one OS thread; Linux passes the `XdndDrop` timestamp when it reads the drop selection, lists dual-width and unflagged monospace fonts, and forwards the initial directory to the portal. +- The Web and dev builds have their cursor image callbacks back (contributed by @caichangqing1120) (PR [#477](https://github.com/vivaui/viva/pull/477)); incremental rendering applies mixed deletes and inserts without a rebuild, batch scratch is released once the page shrinks, and each paint diffs its hits against the published ones once. +- The component templates `viva init` and `viva add` install are regenerated from the sources. + +## 注意 · Caveats + +- 没有不兼容的 API 变更。 +- 在 macOS 上使用 `audio.OpenInput` 的应用必须在 bundle 中声明 `NSMicrophoneUsageDescription`(`[mac.info]`),启用 hardened runtime 时还要在 `[mac] entitlements` 指向的文件中加入 `com.apple.security.device.audio-input`;缺少时系统可能终止进程或交付静音,而 `OpenInput` 仍报告成功。 +- 水印与通知激活没有在 Linux 上实现;Windows 的水印叠加层 z 序与真机验收尚未验证。 + +- There are no incompatible API changes. +- An application that calls `audio.OpenInput` on macOS must declare `NSMicrophoneUsageDescription` in its bundle (`[mac.info]`) and, under the hardened runtime, `com.apple.security.device.audio-input` in the file `[mac] entitlements` names; without them the system may terminate the process or deliver silence while `OpenInput` still reports success. +- Watermarks and notification activation are not implemented on Linux; the Windows watermark overlay's z-order and real-device behaviour are not yet verified. From bb23a23ae2c35246ccb83d5804712d692bb09ec4 Mon Sep 17 00:00:00 2001 From: Bang Liu <156885173+woliubang256@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:27:36 +0800 Subject: [PATCH 14/29] fix(components): scroll a self-painted input to keep its caret in view --- app/painter.go | 1 + app/text_geometry.go | 7 +- base/field.go | 5 + base/fields.go | 6 ++ base/input_scroll.go | 51 +++++++++ cmd/viva/templates/input.go.txt | 64 ++++++++++-- components/input.go | 64 ++++++++++-- components/input_scroll_test.go | 178 ++++++++++++++++++++++++++++++++ gfx/canvas.go | 14 ++- window/text_input.go | 5 + 10 files changed, 373 insertions(+), 22 deletions(-) create mode 100644 base/input_scroll.go create mode 100644 components/input_scroll_test.go diff --git a/app/painter.go b/app/painter.go index 42ade8fed..623d4a6d0 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1425,6 +1425,7 @@ func (painter *painter) focusedTextField() (TextInputContext, gfx.TextPlacement, Multiline: hit.Multiline, ReadOnly: hit.ReadOnly, Secure: hit.Secure, NavigationKeys: hit.NavigationKeys, TextBounds: text.Bounds, FontSize: text.Size, FontWeight: text.Weight, TextColor: text.Color, Alignment: text.Alignment, + TextScroll: text.Scroll, HideNativeOverlays: hit.HideNativeOverlays, } return context, text.Placement, index diff --git a/app/text_geometry.go b/app/text_geometry.go index 72f06da6d..ceaa96b7e 100644 --- a/app/text_geometry.go +++ b/app/text_geometry.go @@ -24,6 +24,9 @@ type textGeometry struct { alignment gfx.Alignment value string // the field's value shown string // what is drawn: the value, or one bullet per rune + // scroll is how far a field that paints its own line moved it left, so a point in + // the window is measured against the glyphs where they were drawn. + scroll float32 } // focusedTextGeometry is the geometry of the focused field, false when no field with text @@ -44,7 +47,7 @@ func (painter *painter) focusedTextGeometry() (textGeometry, bool) { geometry := textGeometry{ canvas: painter.canvas, placement: placement, bounds: context.TextBounds, style: gfx.TextStyle{Size: context.FontSize, Weight: context.FontWeight}, - alignment: context.Alignment, value: value, shown: value, + alignment: context.Alignment, value: value, shown: value, scroll: context.TextScroll, } if placement == nil && (context.TextBounds.Width <= 0 || context.TextBounds.Height <= 0 || context.FontSize <= 0) { return textGeometry{}, false @@ -98,7 +101,7 @@ func (geometry textGeometry) RangeRects(dst []gfx.Rect, start, end int) []gfx.Re } func (geometry textGeometry) origin() float32 { - return geometry.canvas.LabelOrigin(geometry.shown, geometry.bounds, geometry.style, geometry.alignment) + return geometry.canvas.LabelOrigin(geometry.shown, geometry.bounds, geometry.style, geometry.alignment) - geometry.scroll } // byteOffsetOfRune is the byte offset of rune index in value, clamped to its ends. diff --git a/base/field.go b/base/field.go index 47cfe86ab..6a8020e30 100644 --- a/base/field.go +++ b/base/field.go @@ -76,6 +76,10 @@ type Field struct { // blink is the phase of the caret when the field paints it itself, which a fixed-pitch // field does (see Box.Mono): the platform draws the caret of the others. blink CaretBlink + // scroll keeps a value longer than the field in view of its caret, which the field + // must do itself: it paints its own line (HideEditorText), so the platform editor + // that would have scrolled it draws nothing. + scroll InputScroll // seen is the text as the field was last declared, and changed whether that // declaration found it edited since the one before (Box.Changed). seen string @@ -346,6 +350,7 @@ func (field *Field) Snapshot(f *Frame, ID gfx.ID, Label, placeholder string) Inp // canvas line, which moves the value when the field gains the keyboard. HideEditorText: true, Blink: &field.blink, + Scroll: &field.scroll, } // Where the caret, the selection and the composition are: what a field that paints them // itself needs, and what the platform's own presentation of them does without. diff --git a/base/fields.go b/base/fields.go index de3d2e477..8c37be679 100644 --- a/base/fields.go +++ b/base/fields.go @@ -55,4 +55,10 @@ type InputSnapshot struct { // Blink is the phase of the caret a field paints itself (see InputTextStyle.Mono and // HideEditorText): the caret is drawn only while it is lit. Nil keeps it lit. Blink *CaretBlink + // Scroll keeps a value too long for the field's line in view of its caret, when the + // component paints the line itself (see HideEditorText and InputTextStyle.Mono). A + // field that lets the platform editor paint its text does not need it: the platform + // scrolls the line for its own caret. Nil leaves the line where it is, which is where + // a value that fits stays. + Scroll *InputScroll } diff --git a/base/input_scroll.go b/base/input_scroll.go new file mode 100644 index 000000000..427d5db50 --- /dev/null +++ b/base/input_scroll.go @@ -0,0 +1,51 @@ +package base + +// InputScroll is the horizontal offset of one single-line field's painted line: how +// far the text of a value too long for the field is moved left so that the caret +// stays in view, as a native single-line editor does. The zero value starts at the +// left edge, which is the whole story for a value that fits. +// +// It is held by the field, next to the text it belongs to, and read during the paint +// that draws the field's own glyphs (see InputSnapshot.Scroll): a component that +// paints the text itself must move it with the caret, because the platform editor +// that would have scrolled it draws nothing. It is not safe for concurrent use, and +// one InputScroll serves one field. +type InputScroll struct { + offset float32 +} + +// Follow returns the offset to paint the line with, for a line textWidth wide whose +// caret stands caretX from the line's start, inside a field width across. The offset +// moves only as far as it must: a caret that is still in view leaves the text where +// it is, so typing at the end does not slide the line under a caret that has not +// reached the edge, and End shows the tail of a long value while Home comes back to +// its start. width of zero or less paints nothing, and an offset that no longer +// fits (a shorter value, a wider field) is brought back into range. +func (s *InputScroll) Follow(caretX, textWidth, width float32) float32 { + if width <= 0 { + s.offset = 0 + return 0 + } + // The caret is a stroke one pixel wide, so the room the line has to show its + // glyphs is the field less that stroke: a caret at the right edge is visible. + visible := max(width-1, 1) + most := max(textWidth-visible, 0) + offset := min(max(s.offset, 0), most) + if caretX-offset > visible { + offset = caretX - visible + } else if caretX < offset { + offset = caretX + } + offset = min(max(offset, 0), most) + s.offset = offset + return offset +} + +// Rest puts the line back at the field's start, as a field that loses its value does +// not want the next one scrolled by the last one's caret. +func (s *InputScroll) Rest() { s.offset = 0 } + +// Offset reports how far the line is painted left of the field's start, as the last +// Follow left it. A field reads it for what it must do itself, such as reporting +// where its text sits to the platform. +func (s *InputScroll) Offset() float32 { return s.offset } diff --git a/cmd/viva/templates/input.go.txt b/cmd/viva/templates/input.go.txt index cd2dc536e..1b33faf91 100644 --- a/cmd/viva/templates/input.go.txt +++ b/cmd/viva/templates/input.go.txt @@ -93,8 +93,9 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. if selfPainted && focused && snapshot.ShowCaret && snapshot.Blink != nil { snapshot.ShowCaret = snapshot.Blink.Lit(canvas, snapshot.Caret) } + var scroll float32 if !snapshot.PlatformEditing && content.Width > 0 && content.Height > 0 { - inputPaintText(canvas, theme, content, snapshot, focused) + scroll = inputPaintText(canvas, theme, content, snapshot, focused) } if snapshot.ID.IsZero() { return @@ -106,22 +107,37 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. platformInk = gfx.Color{} } lineTop, lineHeight := inputLineBox(content, size) + // The line is told to the platform where it is painted: a field that scrolled it to + // keep its caret in view hands over that offset, so the pointer that lands in the + // field and the input method's window follow the glyphs the component drew. It is a + // separate value from TextBounds, which a native editor lays its own line out in and + // scrolls for its own caret; moving that box instead would scroll the line twice. textBounds := gfx.Rect{X: content.X, Y: lineTop, Width: content.Width, Height: lineHeight} canvas.HitWithOptions(snapshot.ID, bounds, snapshot.Label, gfx.HitOptions{ Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, Disabled: snapshot.Disabled, ReadOnly: snapshot.ReadOnly, Secure: snapshot.Secure, Invalid: snapshot.Invalid, NavigationKeys: snapshot.NavigationKeys, TextBounds: textBounds, TextSize: size, TextWeight: weight, TextColor: platformInk, TextAlignment: snapshot.Alignment, + TextScroll: snapScrollText(scroll), HideNativeOverlays: selfPainted, }) } +// snapScrollText rounds a line's scroll to whole pixels, so the geometry the pointer is +// mapped through does not shift by a fraction of one on every paint. +func snapScrollText(scroll float32) float32 { + if scroll <= 0 { + return 0 + } + return float32(int(scroll + 0.5)) +} + // inputPaintText paints the value (or the placeholder) of a single-line field // with its selection, composition and caret. A Secure field shows one bullet per // character, and the offsets of the snapshot, which index the real text, are // mapped onto the bullets. InputGroup paints its embedded single-line control // through the same function, so the two cannot drift apart. -func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snapshot InputSnapshot, focused bool) { +func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snapshot InputSnapshot, focused bool) float32 { display := snapshot.DisplayValue if display == "" { display = snapshot.Value @@ -137,10 +153,10 @@ func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snaps snapshot.CompositionStart = inputMaskOffset(snapshot.Value, snapshot.CompositionStart) snapshot.CompositionEnd = inputMaskOffset(snapshot.Value, snapshot.CompositionEnd) } - inputPaintLine(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) + return inputPaintLine(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) } -func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot InputSnapshot, focused bool) { +func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot InputSnapshot, focused bool) float32 { textStyle := snapshot.Text.TextStyle(&theme) fontSize, ink := textStyle.Size, textStyle.Color color := ink @@ -159,9 +175,15 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholderShown := snapshot.Value == "" && snapshot.DisplayValue == "" style := textStyle style.Color = color + // A value longer than the field is moved left so its caret stays in view, as a + // native single-line field scrolls it. Only a field that paints its own line needs + // this: the platform editor scrolls the line it paints for its own caret. + scroll := inputFollowScroll(canvas, bounds, value, textStyle, snapshot, placeholderShown) + line := bounds + line.X -= scroll // 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) + origin := canvas.LabelOrigin(value, line, style, snapshot.Alignment) var ranges [4]gfx.Rect selectionStart, selectionEnd := inputRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) var selections []gfx.Rect @@ -200,10 +222,12 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, // The line is centered in the field like the caret and the selection, but its // box is the text's line box (20px at the 14px body size), not the taller // band the caret and selection fill: accessibility and parity report label - // bounds, and those should describe the glyph line the field draws. + // bounds, and those should describe the glyph line the field draws. It is moved + // with the caret, on the same offset the caret and selection take. lineTop, lineHeight := inputLineBox(bounds, fontSize) - line := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} - canvas.LabelAligned(value, line, style, snapshot.Alignment) + glyphs := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} + glyphs.X -= scroll + canvas.LabelAligned(value, glyphs, style, snapshot.Alignment) for _, selection := range selections { if selection.Width <= 0 { continue @@ -215,10 +239,32 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, } selected := textStyle selected.Color = selectedColor - canvas.LabelAligned(value, line, selected, snapshot.Alignment) + canvas.LabelAligned(value, glyphs, selected, snapshot.Alignment) canvas.Unclip() } canvas.Unclip() + return scroll +} + +// inputFollowScroll is how far the line of a field that paints its own text is moved +// left to keep the caret in view, and asks the field's InputScroll to work it out. +// A field that leaves the line to the platform editor keeps it where it is: that +// editor scrolls its own caret, and moving the glyphs under it would put the two out +// of step. +func inputFollowScroll(canvas *gfx.Canvas, bounds gfx.Rect, value string, style gfx.TextStyle, snapshot InputSnapshot, placeholderShown bool) float32 { + if snapshot.Scroll == nil || !inputSelfPainted(snapshot) || placeholderShown || bounds.Width <= 0 { + return 0 + } + caret := inputBoundary(value, snapshot.Caret) + caretX := canvas.TextCaretStyle(value, style, caret) + return snapshot.Scroll.Follow(caretX, canvas.TextWidthStyle(value, style), bounds.Width) +} + +// inputSelfPainted reports whether the component draws the field's text itself, so the +// platform editor is only where input arrives (see InputSnapshot.HideEditorText and +// InputTextStyle.Mono). +func inputSelfPainted(snapshot InputSnapshot) bool { + return snapshot.Text.Mono || snapshot.HideEditorText } // fillInputSelections paints the bands of the field's selections and returns diff --git a/components/input.go b/components/input.go index 56734cb94..a3d19a58f 100644 --- a/components/input.go +++ b/components/input.go @@ -93,8 +93,9 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. if selfPainted && focused && snapshot.ShowCaret && snapshot.Blink != nil { snapshot.ShowCaret = snapshot.Blink.Lit(canvas, snapshot.Caret) } + var scroll float32 if !snapshot.PlatformEditing && content.Width > 0 && content.Height > 0 { - inputPaintText(canvas, theme, content, snapshot, focused) + scroll = inputPaintText(canvas, theme, content, snapshot, focused) } if snapshot.ID.IsZero() { return @@ -106,22 +107,37 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. platformInk = gfx.Color{} } lineTop, lineHeight := inputLineBox(content, size) + // The line is told to the platform where it is painted: a field that scrolled it to + // keep its caret in view hands over that offset, so the pointer that lands in the + // field and the input method's window follow the glyphs the component drew. It is a + // separate value from TextBounds, which a native editor lays its own line out in and + // scrolls for its own caret; moving that box instead would scroll the line twice. textBounds := gfx.Rect{X: content.X, Y: lineTop, Width: content.Width, Height: lineHeight} canvas.HitWithOptions(snapshot.ID, bounds, snapshot.Label, gfx.HitOptions{ Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, Disabled: snapshot.Disabled, ReadOnly: snapshot.ReadOnly, Secure: snapshot.Secure, Invalid: snapshot.Invalid, NavigationKeys: snapshot.NavigationKeys, TextBounds: textBounds, TextSize: size, TextWeight: weight, TextColor: platformInk, TextAlignment: snapshot.Alignment, + TextScroll: snapScrollText(scroll), HideNativeOverlays: selfPainted, }) } +// snapScrollText rounds a line's scroll to whole pixels, so the geometry the pointer is +// mapped through does not shift by a fraction of one on every paint. +func snapScrollText(scroll float32) float32 { + if scroll <= 0 { + return 0 + } + return float32(int(scroll + 0.5)) +} + // inputPaintText paints the value (or the placeholder) of a single-line field // with its selection, composition and caret. A Secure field shows one bullet per // character, and the offsets of the snapshot, which index the real text, are // mapped onto the bullets. InputGroup paints its embedded single-line control // through the same function, so the two cannot drift apart. -func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snapshot InputSnapshot, focused bool) { +func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snapshot InputSnapshot, focused bool) float32 { display := snapshot.DisplayValue if display == "" { display = snapshot.Value @@ -137,10 +153,10 @@ func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snaps snapshot.CompositionStart = inputMaskOffset(snapshot.Value, snapshot.CompositionStart) snapshot.CompositionEnd = inputMaskOffset(snapshot.Value, snapshot.CompositionEnd) } - inputPaintLine(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) + return inputPaintLine(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) } -func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot InputSnapshot, focused bool) { +func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot InputSnapshot, focused bool) float32 { textStyle := snapshot.Text.TextStyle(&theme) fontSize, ink := textStyle.Size, textStyle.Color color := ink @@ -159,9 +175,15 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholderShown := snapshot.Value == "" && snapshot.DisplayValue == "" style := textStyle style.Color = color + // A value longer than the field is moved left so its caret stays in view, as a + // native single-line field scrolls it. Only a field that paints its own line needs + // this: the platform editor scrolls the line it paints for its own caret. + scroll := inputFollowScroll(canvas, bounds, value, textStyle, snapshot, placeholderShown) + line := bounds + line.X -= scroll // 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) + origin := canvas.LabelOrigin(value, line, style, snapshot.Alignment) var ranges [4]gfx.Rect selectionStart, selectionEnd := inputRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) var selections []gfx.Rect @@ -200,10 +222,12 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, // The line is centered in the field like the caret and the selection, but its // box is the text's line box (20px at the 14px body size), not the taller // band the caret and selection fill: accessibility and parity report label - // bounds, and those should describe the glyph line the field draws. + // bounds, and those should describe the glyph line the field draws. It is moved + // with the caret, on the same offset the caret and selection take. lineTop, lineHeight := inputLineBox(bounds, fontSize) - line := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} - canvas.LabelAligned(value, line, style, snapshot.Alignment) + glyphs := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} + glyphs.X -= scroll + canvas.LabelAligned(value, glyphs, style, snapshot.Alignment) for _, selection := range selections { if selection.Width <= 0 { continue @@ -215,10 +239,32 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, } selected := textStyle selected.Color = selectedColor - canvas.LabelAligned(value, line, selected, snapshot.Alignment) + canvas.LabelAligned(value, glyphs, selected, snapshot.Alignment) canvas.Unclip() } canvas.Unclip() + return scroll +} + +// inputFollowScroll is how far the line of a field that paints its own text is moved +// left to keep the caret in view, and asks the field's InputScroll to work it out. +// A field that leaves the line to the platform editor keeps it where it is: that +// editor scrolls its own caret, and moving the glyphs under it would put the two out +// of step. +func inputFollowScroll(canvas *gfx.Canvas, bounds gfx.Rect, value string, style gfx.TextStyle, snapshot InputSnapshot, placeholderShown bool) float32 { + if snapshot.Scroll == nil || !inputSelfPainted(snapshot) || placeholderShown || bounds.Width <= 0 { + return 0 + } + caret := inputBoundary(value, snapshot.Caret) + caretX := canvas.TextCaretStyle(value, style, caret) + return snapshot.Scroll.Follow(caretX, canvas.TextWidthStyle(value, style), bounds.Width) +} + +// inputSelfPainted reports whether the component draws the field's text itself, so the +// platform editor is only where input arrives (see InputSnapshot.HideEditorText and +// InputTextStyle.Mono). +func inputSelfPainted(snapshot InputSnapshot) bool { + return snapshot.Text.Mono || snapshot.HideEditorText } // fillInputSelections paints the bands of the field's selections and returns diff --git a/components/input_scroll_test.go b/components/input_scroll_test.go new file mode 100644 index 000000000..61ac7c93f --- /dev/null +++ b/components/input_scroll_test.go @@ -0,0 +1,178 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) + +// fixedWidth measures every rune one cell wide, so a test can say where a caret of a +// long value must land without depending on a font. +func fixedWidth(cell float32) *gfx.Canvas { + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(value string, size, weight float32) float32 { + return float32(len([]rune(value))) * cell + }) + return canvas +} + +// caretRect is the caret the field painted: the ink rectangle one pixel wide. +func caretRect(canvas *gfx.Canvas, ink gfx.Color) (gfx.Rectangle, bool) { + var caret gfx.Rectangle + found := false + for _, rectangle := range canvas.Rectangles() { + if rectangle.Bounds.Width == 1 && rectangle.Color == ink { + caret, found = rectangle, true + } + } + return caret, found +} + +// A single-line field that paints its own text must scroll it, as a native one does: +// before this, a value longer than the field kept its start in view however far the +// caret moved, so everything typed past the edge was invisible. +func TestInputScrollsItsOwnLineToKeepTheCaretInView(t *testing.T) { + const cell = 10 + theme := gfx.LightTheme() + ink := theme.Foreground + bounds := gfx.Rect{X: 0, Y: 0, Width: 100, Height: 32} + value := "0123456789abcdefghij" // 20 cells, twice the field + scroll := new(base.InputScroll) + caret := len(value) + + // The caret at the end of the value: the tail must be in view. + canvas := fixedWidth(cell) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: caret, HideEditorText: true, Scroll: scroll, + }) + painted, ok := caretRect(canvas, ink) + if !ok { + t.Fatal("the field painted no caret") + } + if right := painted.Bounds.X + painted.Bounds.Width; right > bounds.X+bounds.Width { + t.Fatalf("the caret at the end of a long value is painted at %v, past the field's right edge %v", painted.Bounds.X, bounds.X+bounds.Width) + } + if painted.Bounds.X < bounds.X { + t.Fatalf("the caret at the end is painted at %v, left of the field", painted.Bounds.X) + } + + // The line itself moved: the glyphs are no longer drawn from the field's start. + var label gfx.Text + for _, text := range canvas.Texts() { + if text.Value == value { + label = text + break + } + } + if label.Bounds.X >= bounds.X { + t.Fatalf("the glyphs still start at %v: a long value did not scroll", label.Bounds.X) + } + + // Home comes back: the caret at the start puts the line back at the field's start. + canvas = fixedWidth(cell) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: 0, HideEditorText: true, Scroll: scroll, + }) + painted, ok = caretRect(canvas, ink) + if !ok { + t.Fatal("the field painted no caret after Home") + } + if painted.Bounds.X != bounds.X { + t.Fatalf("the caret at the start is painted at %v, want the field's start %v", painted.Bounds.X, bounds.X) + } + if got := scroll.Offset(); got != 0 { + t.Fatalf("the line is scrolled %v with the caret at the start, want 0", got) + } +} + +// The scroll follows the caret only as far as it must: a caret still inside the field +// leaves the text where it is, so typing at the end does not slide the line under a +// caret that has not reached the edge. +func TestInputScrollLeavesTheLineInPlaceWhileTheCaretFits(t *testing.T) { + const cell = 10 + scroll := new(base.InputScroll) + width := float32(100) + // A caret at 40 of a 50-wide value, in a 100-wide field: everything fits. + if got := scroll.Follow(40, 50, width); got != 0 { + t.Fatalf("a value that fits is scrolled by %v, want 0", got) + } + // The caret reaches the right edge: the text moves just enough to show it. + if got := scroll.Follow(140, 150, width); got != 140-99 { + t.Fatalf("a caret at the edge leaves the text scrolled by %v, want %v", got, 140-99) + } + // A shorter field start brings the line back: the offset is kept in range. + if got := scroll.Follow(0, 150, width); got != 0 { + t.Fatalf("the caret at the start leaves the text scrolled by %v, want 0", got) + } + // A value that no longer overflows pulls the line back too. + if got := scroll.Follow(10, 20, width); got != 0 { + t.Fatalf("a value that fits again leaves the text scrolled by %v, want 0", got) + } +} + +// A field the platform editor paints scrolls its own line: moving the glyphs under it as +// well would scroll the caret twice. +func TestInputPlatformPaintedLineIsNotScrolled(t *testing.T) { + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 0, Y: 0, Width: 100, Height: 32} + value := "0123456789abcdefghij" + scroll := new(base.InputScroll) + canvas := fixedWidth(10) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: len(value), PlatformEditing: true, Scroll: scroll, + }) + if got := scroll.Offset(); got != 0 { + t.Fatalf("a platform-painted field scrolled its line by %v, want 0", got) + } + var label gfx.Text + for _, text := range canvas.Texts() { + if text.Value == value { + label = text + } + } + if label.Bounds.X != bounds.X { + t.Fatalf("the platform's line starts at %v, want the field's start %v", label.Bounds.X, bounds.X) + } +} + +// The scroll the component paints with is told to the platform, so a press lands where +// the glyphs are and the input method's window follows the caret. +func TestInputScrollIsDeclaredToThePlatform(t *testing.T) { + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 0, Y: 0, Width: 100, Height: 32} + value := "0123456789abcdefghij" + scroll := new(base.InputScroll) + canvas := fixedWidth(10) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: len(value), HideEditorText: true, Scroll: scroll, + }) + hits := canvas.Hits() + if len(hits) != 1 { + t.Fatalf("hits = %d, want 1", len(hits)) + } + text := hitTextAt(canvas, 0) + if want := float32(len(value)*10 - 99); text.Scroll != want { + t.Fatalf("the platform is told the line is scrolled by %v, want %v", text.Scroll, want) + } + if text.Bounds.X != bounds.X || text.Bounds.Width != bounds.Width { + t.Fatalf("the platform's text box is %+v, want the field's own %+v", text.Bounds, bounds) + } +} + +func TestInputScrollOffsetIsBoundedByTheLine(t *testing.T) { + scroll := new(base.InputScroll) + // A negative or zero width paints nothing and scrolls nothing. + if got := scroll.Follow(500, 900, 0); got != 0 { + t.Fatalf("a field with no width scrolls by %v, want 0", got) + } + // The line is never scrolled past its own end. + got := scroll.Follow(1000, 120, 100) + if most := float32(120 - 99); got != most { + t.Fatalf("the line scrolls by %v, want its most %v", got, most) + } +} diff --git a/gfx/canvas.go b/gfx/canvas.go index 6a7600376..f0413f1b8 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -572,6 +572,12 @@ type HitOptions struct { // TextAlignment is the line's placement within TextBounds. Zero preserves // an ordinary input's left alignment; the component resolves its default. TextAlignment Alignment + // TextScroll is how far a field that paints its own line has moved it left to keep + // its caret in view, in pixels. The pointer that lands in the field and the input + // method's window are placed from it, so they follow the glyphs the component drew + // rather than where an unscrolled line would have started. A field the platform + // editor paints scrolls its own line and leaves it 0. + TextScroll float32 // 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 @@ -613,7 +619,7 @@ func (options HitOptions) IsZero() bool { options.Live == 0 && options.Range == (ValueRange{}) && !options.SkipFocus && !options.SkipTab && !options.Backdrop && !options.PassSecondary && !options.PassPrimary && !options.label && !options.Presentational && !options.Autofocus && options.TextBounds == (Rect{}) && options.TextSize == 0 && options.TextWeight == 0 && options.TextColor == (Color{}) && options.TextAlignment == 0 && - !options.HideNativeOverlays && !options.NavigationKeys && !options.TypeAhead && options.Placement == nil + options.TextScroll == 0 && !options.HideNativeOverlays && !options.NavigationKeys && !options.TypeAhead && options.Placement == nil } // TextPlacement is what a text field that lays its own rows out tells the @@ -639,6 +645,9 @@ type HitText struct { Color Color Alignment Alignment Placement TextPlacement + // Scroll is HitOptions.TextScroll: how far a field that paints its own line moved + // it left, which the geometry of the field's text is measured from. + Scroll float32 } // Hit is one pointer interaction region in back-to-front paint order. The zero @@ -1801,10 +1810,11 @@ 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.TextAlignment != 0 || options.Placement != nil { + options.TextColor != (Color{}) || options.TextAlignment != 0 || options.TextScroll != 0 || options.Placement != nil { canvas.hitTexts = append(canvas.hitTexts, HitText{ Bounds: options.TextBounds, Size: options.TextSize, Weight: options.TextWeight, Color: options.TextColor, Alignment: options.TextAlignment, Placement: options.Placement, + Scroll: options.TextScroll, }) text = int32(len(canvas.hitTexts)) } diff --git a/window/text_input.go b/window/text_input.go index 9a3de2cf0..096a6cb14 100644 --- a/window/text_input.go +++ b/window/text_input.go @@ -151,6 +151,11 @@ type TextInputContext struct { FontWeight float32 TextColor gfx.Color Alignment gfx.Alignment + // TextScroll is how far a field that paints its own line moved it left to keep its + // caret in view (gfx.HitOptions.TextScroll): the text the component drew starts that + // far before TextBounds, so the pointer and the input method's window are placed from + // there. It is 0 for a field the platform editor paints, which scrolls its own line. + TextScroll float32 // 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. From d5f9ead2806a469b78b3b5a4aed3a5930874ba86 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 01:55:37 +0800 Subject: [PATCH 15/29] feat(tree): add a full-width row background to TreeItem --- base/tree.go | 5 +++++ cmd/viva/templates/tree.go.txt | 3 +++ components/tree.go | 3 +++ components/tree_test.go | 41 ++++++++++++++++++++++++++++++++++ style/tree.go | 4 ++++ ui/tree_paint.go | 3 +++ 6 files changed, 59 insertions(+) diff --git a/base/tree.go b/base/tree.go index 35b02093c..82566e115 100644 --- a/base/tree.go +++ b/base/tree.go @@ -46,6 +46,11 @@ type TreeState struct { // SelectedColor paints the selected row's background instead of the theme's // Accent. Zero keeps the theme's. SelectedColor gfx.Color + // RowBackground optionally supplies a full-width wash painted behind row i + // (underneath indentation, disclosure arrow, hover and selection highlight) + // so consecutive rows with the same tint form a continuous band. Zero paints + // nothing. + RowBackground func(i int) gfx.Color // DisplayDepth maps a row's Depth to the level the tree indents it by, when // the application compresses deep rows to keep their names in view. Depth // stays the tree's structure, which keyboard movement, typeahead and drops diff --git a/cmd/viva/templates/tree.go.txt b/cmd/viva/templates/tree.go.txt index 173628a5b..73d8fffe3 100644 --- a/cmd/viva/templates/tree.go.txt +++ b/cmd/viva/templates/tree.go.txt @@ -77,6 +77,9 @@ func (tree *Tree) Item(item TreeItem) TreeRow { hovered := enabled && tree.canvas.Hovered() == item.ID focused := enabled && !item.Dragging && tree.canvas.FocusVisible() == item.ID radius := tree.theme.Metrics.RadiusControl + if item.Background.Alpha > 0 { + tree.canvas.Fill(row, item.Background) + } if item.Selected || hovered { background := tree.theme.Muted if item.Selected { diff --git a/components/tree.go b/components/tree.go index 8a3e644fe..7977d0f91 100644 --- a/components/tree.go +++ b/components/tree.go @@ -77,6 +77,9 @@ func (tree *Tree) Item(item TreeItem) TreeRow { hovered := enabled && tree.canvas.Hovered() == item.ID focused := enabled && !item.Dragging && tree.canvas.FocusVisible() == item.ID radius := tree.theme.Metrics.RadiusControl + if item.Background.Alpha > 0 { + tree.canvas.Fill(row, item.Background) + } if item.Selected || hovered { background := tree.theme.Muted if item.Selected { diff --git a/components/tree_test.go b/components/tree_test.go index 0856845cf..993b5f515 100644 --- a/components/tree_test.go +++ b/components/tree_test.go @@ -143,3 +143,44 @@ func TestTreeSelectedRowColourIsTheTrees(t *testing.T) { t.Fatal("a zero SelectedColor did not keep the theme's Accent") } } + +// Background paints a full-width, square-cornered wash behind the entire row +// before any selection highlight so consecutive tinted rows form one continuous band. +func TestTreeItemBackgroundPaintsFullWidthUnderSelection(t *testing.T) { + theme := gfx.LightTheme() + wash := gfx.RGBA(245, 200, 90, 0.25) + var canvas gfx.Canvas + tree := BeginTree(&canvas, theme, gfx.Rect{X: 0, Y: 0, Width: 240, Height: 64}).RowHeight(24) + row1 := tree.Item(TreeItem{ID: gfx.Item(1), Label: "rust", Depth: 1, Branch: true, Expanded: true, Selected: true, Background: wash}) + row2 := tree.Item(TreeItem{ID: gfx.Item(2), Label: "crates", Depth: 2, Branch: true, Background: wash}) + + rects := canvas.Rectangles() + washIdx, selIdx := -1, -1 + washCount := 0 + for i, r := range rects { + if r.Color == wash { + washCount++ + if washIdx < 0 { + washIdx = i + } + if r.Bounds.X != 0 || r.Bounds.Width != 240 || r.Bounds.Height != 24 { + t.Fatalf("wash rect did not span full row: got %+v", r.Bounds) + } + if r.Radius != 0 { + t.Fatalf("wash rect must be square-cornered for seamless bands, got radius %v", r.Radius) + } + } + if r.Color == theme.Accent && selIdx < 0 { + selIdx = i + } + } + if washCount != 2 { + t.Fatalf("expected 2 full-width wash rects, got %d", washCount) + } + if washIdx < 0 || selIdx < 0 || washIdx >= selIdx { + t.Fatalf("expected row background (%d) to paint underneath selection highlight (%d)", washIdx, selIdx) + } + if row1.Bounds.Y+row1.Bounds.Height != row2.Bounds.Y { + t.Fatalf("expected adjacent rows to touch seamlessly: row1=%+v row2=%+v", row1.Bounds, row2.Bounds) + } +} diff --git a/style/tree.go b/style/tree.go index eb9a1db0d..b73e9f075 100644 --- a/style/tree.go +++ b/style/tree.go @@ -21,4 +21,8 @@ type TreeItem struct { // being fetched. Phase is the spinner's frame, 0 to 7. Loading bool Phase uint8 + // Background paints a full-width, square-cornered wash behind the row + // (underneath indentation, disclosure arrow, hover and selection highlight) + // so consecutive tinted rows form one continuous band. Zero paints nothing. + Background gfx.Color } diff --git a/ui/tree_paint.go b/ui/tree_paint.go index 4c6a865bc..973434673 100644 --- a/ui/tree_paint.go +++ b/ui/tree_paint.go @@ -24,6 +24,9 @@ func treeStateRow(s *TreeState, i int, rowBox Box) { if node.Branch { item.DisclosureID = s.GetChevrons().At(key) } + if s.RowBackground != nil { + item.Background = s.RowBackground(i) + } if canvas := f.Surface; canvas != nil && !node.Disabled { if canvas.Clicked(item.ID) { s.SetChosenIndex(i) From ab697bf1c3b6a04030ad9662ad47fb11a789700f Mon Sep 17 00:00:00 2001 From: tudou Date: Sat, 28 Nov 2026 09:30:35 +0800 Subject: [PATCH 16/29] fix(linux): isolate monospace font scanning from Cairo rendering --- .../linux/fonts_concurrent_linux_test.go | 91 +++++++++++++++++++ internal/platform/linux/fonts_linux.go | 2 +- internal/platform/linux/text_linux.go | 27 +++++- 3 files changed, 118 insertions(+), 2 deletions(-) create mode 100644 internal/platform/linux/fonts_concurrent_linux_test.go diff --git a/internal/platform/linux/fonts_concurrent_linux_test.go b/internal/platform/linux/fonts_concurrent_linux_test.go new file mode 100644 index 000000000..cf294a30a --- /dev/null +++ b/internal/platform/linux/fonts_concurrent_linux_test.go @@ -0,0 +1,91 @@ +//go:build !android + +package linux + +import ( + "fmt" + "os" + "os/exec" + "runtime" + "sync" + "testing" + + "github.com/ebitengine/purego" +) + +func TestMonospaceFamiliesConcurrentWithTextRendering(t *testing.T) { + // 原生库崩溃不可 recover,用子进程保护其余测试。 + const probeEnv = "VIVA_TEST_CONCURRENT_FONT_SCAN" + if os.Getenv(probeEnv) != "1" { + command := exec.Command(os.Args[0], "-test.run=^TestMonospaceFamiliesConcurrentWithTextRendering$", "-test.timeout=90s", "-test.v") + command.Env = append(os.Environ(), probeEnv+"=1") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("concurrent font scan: %v\n%s", err, output) + } + return + } + + // 模拟固定在窗口线程上的界面渲染和未绑定线程的后台字体扫描。 + runtime.LockOSThread() + defer runtime.UnlockOSThread() + engine, err := newTextEngine() + if err != nil { + t.Skipf("Pango unavailable: %v", err) + } + defer engine.close() + if len(FontFamilies()) == 0 { + t.Skip("no installed fonts") + } + var workers sync.WaitGroup + start := make(chan struct{}) + for worker := 0; worker < 4; worker++ { + workers.Add(1) + go func() { + defer workers.Done() + <-start + for iteration := 0; iteration < 10; iteration++ { + families := MonospaceFamilies() + if len(families) == 0 { + t.Error("concurrent scan returned no monospace fonts") + return + } + } + }() + } + close(start) + for iteration := 0; iteration < 5000; iteration++ { + width := engine.Width(fmt.Sprintf("Motty font scan %d", iteration), 14, 0) + if width <= 0 { + t.Errorf("text width = %v, want a positive width", width) + break + } + } + workers.Wait() +} + +func TestFontScanServicesOwnIndependentFontMaps(t *testing.T) { + first, err := newFontScanTextServices() + if err != nil { + t.Skipf("PangoFT2 unavailable: %v", err) + } + defer first.close() + second, err := newFontScanTextServices() + if err != nil { + t.Fatal(err) + } + defer second.close() + var contextFontMap func(uintptr) uintptr + purego.RegisterLibFunc(&contextFontMap, first.pango, "pango_context_get_font_map") + firstMap, secondMap := contextFontMap(first.context), contextFontMap(second.context) + if firstMap == 0 || secondMap == 0 || firstMap == secondMap { + t.Fatalf("font scans must own distinct font maps: %x, %x", firstMap, secondMap) + } + // A machine without a monospace alias cannot measure either map; that is the + // environment, not the isolation under test. + if !familyMeasuresMono(first, "monospace") { + t.Skip("no measurable monospace family installed") + } + if !familyMeasuresMono(second, "monospace") { + t.Fatal("an isolated font map must measure the same family as the first") + } +} diff --git a/internal/platform/linux/fonts_linux.go b/internal/platform/linux/fonts_linux.go index b58f6f045..9a77f5adf 100644 --- a/internal/platform/linux/fonts_linux.go +++ b/internal/platform/linux/fonts_linux.go @@ -123,7 +123,7 @@ func fontFamilies(mono bool) []string { for name := range seen { names = append(names, name) } - } else if services, err := newTextServices(); err == nil { + } else if services, err := newFontScanTextServices(); err == nil { defer services.close() names = make([]string, 0, len(seen)) for name := range seen { diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go index 5fd98fa4d..116d2301b 100644 --- a/internal/platform/linux/text_linux.go +++ b/internal/platform/linux/text_linux.go @@ -193,6 +193,15 @@ func loadTextAPI() (*textServices, error) { } func newTextServices() (*textServices, error) { + return newTextServicesWithFontMap(false) +} + +// 字体扫描使用独立的 FT2 字体映射,避免与界面共享 Cairo 的原生字体缓存。 +func newFontScanTextServices() (*textServices, error) { + return newTextServicesWithFontMap(true) +} + +func newTextServicesWithFontMap(isolated bool) (*textServices, error) { systemTextAPI.once.Do(func() { systemTextAPI.api, systemTextAPI.err = loadTextAPI() }) @@ -201,12 +210,28 @@ func newTextServices() (*textServices, error) { } services := *systemTextAPI.api - fontMap := services.fontMapGetDefault() + var fontMap uintptr + if isolated { + // Linux PangoCairo 依赖 PangoFT2;缺少该符号时由调用方退回 Fontconfig。 + symbol, err := purego.Dlsym(services.pangoCairo, "pango_ft2_font_map_new") + if err != nil || symbol == 0 { + return nil, fmt.Errorf("linux: isolated Pango font map is unavailable") + } + var fontMapNew func() uintptr + purego.RegisterFunc(&fontMapNew, symbol) + fontMap = fontMapNew() + } else { + fontMap = services.fontMapGetDefault() + } if fontMap == 0 { services.close() return nil, fmt.Errorf("linux: system Pango font map is unavailable") } services.context = services.fontMapCreateContext(fontMap) + if isolated { + // context 持有自己的引用;无论创建是否成功,都释放构造器返回的引用。 + services.objectUnref(fontMap) + } if services.context == 0 { services.close() return nil, fmt.Errorf("linux: create Pango font context") From 43d451922696f123d38b2b4a6b3f53554617a9b7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 28 Nov 2026 11:50:25 +0800 Subject: [PATCH 17/29] fix(windows): report a credential write that finds no store as unavailable CredWriteW can fail with ERROR_NOT_FOUND on a logon whose credential set cannot be placed. It was mapped to ErrSecretNotFound, which StoreSecret never promises, so an application storing a key on first use surfaced the sentinel as its save error. A write now reports ErrSecretStoreUnavailable; read and delete keep ErrSecretNotFound. Paired with the Motty report t8y2/motty#1513, where saving a password failed with the key is not in the secret store. --- internal/platform/windows/secret_windows.go | 6 +++++ .../platform/windows/secret_windows_test.go | 23 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 internal/platform/windows/secret_windows_test.go diff --git a/internal/platform/windows/secret_windows.go b/internal/platform/windows/secret_windows.go index fa41934f3..3b0591c89 100644 --- a/internal/platform/windows/secret_windows.go +++ b/internal/platform/windows/secret_windows.go @@ -50,6 +50,12 @@ func secretTarget(service, account string) (*uint16, error) { func secretError(operation string, code syscall.Errno) error { switch code { case errorNotFound: + if operation == "write" { + // Nothing was being looked for: a write the store cannot place + // means it has nowhere to keep credentials for this logon, which + // is "no secret store" to the caller, not a missing secret. + return fmt.Errorf("%w: %s: %v", platform.ErrSecretStoreUnavailable, operation, code) + } return platform.ErrSecretNotFound case errorAccessDenied: return fmt.Errorf("%w: %s: %v", platform.ErrSecretDenied, operation, code) diff --git a/internal/platform/windows/secret_windows_test.go b/internal/platform/windows/secret_windows_test.go new file mode 100644 index 000000000..544b843c8 --- /dev/null +++ b/internal/platform/windows/secret_windows_test.go @@ -0,0 +1,23 @@ +package windows + +import ( + "errors" + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +// A write that reports ERROR_NOT_FOUND must not look like a missing secret: +// StoreSecret promises ErrSecretNotFound never comes from it, and an +// application that stores a key on first use would otherwise surface the +// sentinel as its save error. +func TestSecretWriteNotFoundIsAnUnavailableStore(t *testing.T) { + if err := secretError("write", errorNotFound); !errors.Is(err, platform.ErrSecretStoreUnavailable) || errors.Is(err, platform.ErrSecretNotFound) { + t.Fatalf("write not found = %v, want the store unavailable", err) + } + for _, operation := range []string{"read", "delete"} { + if err := secretError(operation, errorNotFound); !errors.Is(err, platform.ErrSecretNotFound) { + t.Fatalf("%s not found = %v, want ErrSecretNotFound", operation, err) + } + } +} From 27054e758785b95ada5f4f606fec854b9dcabf0a Mon Sep 17 00:00:00 2001 From: sunliqiang Date: Sat, 28 Nov 2026 15:40:46 +0800 Subject: [PATCH 18/29] fix(components): enable dragging popup menu scrollbars --- base/menu_state.go | 2 +- components/dropdown_menu.go | 10 ++++ components/dropdown_menu_test.go | 86 ++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+), 1 deletion(-) diff --git a/base/menu_state.go b/base/menu_state.go index 12c15c419..d89629442 100644 --- a/base/menu_state.go +++ b/base/menu_state.go @@ -289,7 +289,7 @@ func (scroll *MenuScroll) Dragging() bool { return scroll.Held } func (scroll *MenuScroll) Drag(event gfx.PointerEvent) bool { switch event.Kind { case gfx.PointerDown: - if scroll.BarID.IsZero() || event.Target != scroll.BarID || scroll.MaxValue <= 0 { + if scroll.BarID.IsZero() || event.Target != scroll.BarID || scroll.MaxValue <= 0 || event.Button > gfx.PointerButtonPrimary { return false } at := scroll.BarTop + (scroll.View-scroll.Thumb)*scroll.Offset/scroll.MaxValue diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index fc1798308..7cd0ce7c4 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -977,6 +977,16 @@ func (menu *menuSurface) end() { 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}) + // A press the pointer pass delivers to the bar drags the thumb: the + // press was taken here, so the runtime captured it and the moves + // follow wherever the pointer goes. Without this ask the bar + // hit-tests and paints its thumb, but nothing ever drags it. A move + // the pointer merely hovers with is not a drag and stays hover. + if event, ok := menu.canvas.PointerOn(scroll.BarID); ok && + ((event.Kind == gfx.PointerDown && event.Button <= gfx.PointerButtonPrimary) || (scroll.Dragging() && event.Kind != gfx.PointerDown)) { + scroll.Drag(event) + menu.canvas.Consume() + } } menu.popOverlay() menu.popClip() diff --git a/components/dropdown_menu_test.go b/components/dropdown_menu_test.go index 56e9cd585..3868e753f 100644 --- a/components/dropdown_menu_test.go +++ b/components/dropdown_menu_test.go @@ -399,6 +399,9 @@ func TestMenuScrollbarIsDraggableAndRowsLeaveItRoom(t *testing.T) { if scroll.Dragging() || scroll.Drag(gfx.PointerEvent{Kind: gfx.PointerMove, Y: 0}) { t.Fatal("moving after release still dragged") } + if scroll.Drag(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonSecondary, Target: scroll.BarID, Y: bar.Y + 2}) || scroll.Dragging() { + t.Fatal("a secondary press started a scrollbar drag") + } // Without a BarID nothing but the rows is declared. plain := MenuScroll{} if _, ok := scrollingMenu(&plain, &canvas, 8, nil)[gfx.Item(9)]; ok || len(nonBlockHits(canvas.Hits())) != 3 { @@ -406,6 +409,89 @@ func TestMenuScrollbarIsDraggableAndRowsLeaveItRoom(t *testing.T) { } } +// The drag goes through the runtime's pointer event pass: the paint asks the +// canvas for the events aimed at the bar, a press on it starts a drag the held +// moves follow, the release ends it, and every event of the press was consumed +// instead of left to become a click. A move the pointer hovers with is neither +// delivered to the drag nor consumed. +func TestMenuScrollbarDragsThroughThePointerEventPass(t *testing.T) { + scroll := MenuScroll{BarID: gfx.Item(9)} + var canvas gfx.Canvas + paint := func(canvas *gfx.Canvas, size gfx.Size) { + menu := BeginDropdownMenu(canvas, gfx.DarkTheme(), gfx.Rect{X: 10, Y: 20, Width: 160, Height: 104}, DropdownMenuOptions{Layer: 7, Scope: gfx.Item(42), Scroll: &scroll}) + for index := range 8 { + menu.AddItem(DropdownMenuItem{ID: gfx.Item(100 + index), Label: "Item"}) + } + menu.End() + } + paint(&canvas, gfx.Size{}) + hits := map[gfx.ID]gfx.Rect{} + for _, hit := range canvas.Hits() { + hits[hit.ID] = hit.Bounds + } + bar, ok := hits[scroll.BarID] + if !ok { + t.Fatal("a scrolling menu with a BarID declares no scrollbar hit") + } + if !canvas.ListensForPointer() { + t.Fatal("a menu with a scrollbar did not ask for pointer events") + } + drag := func(kind gfx.PointerEventKind, y float32) bool { + return canvas.DeliverPointer(gfx.PointerEvent{Kind: kind, Button: gfx.PointerButtonPrimary, X: bar.X + 2, Y: y, Target: scroll.BarID, Captured: kind != gfx.PointerDown}, gfx.Size{Width: 200, Height: 200}, paint) + } + if !drag(gfx.PointerDown, bar.Y+2) || !scroll.Dragging() { + t.Fatal("pressing the thumb neither started a drag nor was consumed") + } + if !drag(gfx.PointerMove, bar.Y+bar.Height+500) || scroll.Offset != scroll.Max() { + t.Fatalf("the held drag left the offset at %v of %v", scroll.Offset, scroll.Max()) + } + if !drag(gfx.PointerUp, bar.Y+bar.Height+500) || scroll.Dragging() { + t.Fatal("the release did not end the drag") + } + if drag(gfx.PointerMove, bar.Y+2) { + t.Fatal("a move the pointer hovers with was delivered to the drag") + } + if canvas.DeliverPointer(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonSecondary, X: bar.X + 2, Y: bar.Y + 2, Target: scroll.BarID}, gfx.Size{Width: 200, Height: 200}, paint) || scroll.Dragging() { + t.Fatal("a secondary press started or consumed a scrollbar drag") + } +} + +func TestMenuScrollbarDragPassAllocatesNothing(t *testing.T) { + scroll := MenuScroll{BarID: gfx.Item(9)} + var canvas gfx.Canvas + paint := func(canvas *gfx.Canvas, size gfx.Size) { + menu := BeginDropdownMenu(canvas, gfx.DarkTheme(), gfx.Rect{X: 10, Y: 20, Width: 160, Height: 104}, DropdownMenuOptions{Layer: 7, Scope: gfx.Item(42), Scroll: &scroll}) + for index := range 8 { + menu.AddItem(DropdownMenuItem{ID: gfx.Item(100 + index), Label: "Item"}) + } + menu.End() + } + paint(&canvas, gfx.Size{}) + hits := canvas.Hits() + var bar gfx.Rect + for _, hit := range hits { + if hit.ID == scroll.BarID { + bar = hit.Bounds + } + } + if bar.Height == 0 { + t.Fatal("a scrolling menu with a BarID declares no scrollbar hit") + } + if !canvas.DeliverPointer(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: bar.X + 2, Y: bar.Y + 2, Target: scroll.BarID}, gfx.Size{Width: 200, Height: 200}, paint) { + t.Fatal("pressing the thumb was not delivered") + } + event := gfx.PointerEvent{Kind: gfx.PointerMove, Button: gfx.PointerButtonPrimary, X: bar.X + 2, Y: bar.Y + 8, Target: scroll.BarID, Captured: true} + if !canvas.DeliverPointer(event, gfx.Size{Width: 200, Height: 200}, paint) { + t.Fatal("the held drag was not delivered") + } + if allocations := testing.AllocsPerRun(100, func() { + canvas.DeliverPointer(event, gfx.Size{Width: 200, Height: 200}, paint) + }); allocations != 0 { + t.Fatalf("a drag pass over the scrollbar allocated %v times", allocations) + } + canvas.DeliverPointer(gfx.PointerEvent{Kind: gfx.PointerUp, Button: gfx.PointerButtonPrimary, Target: scroll.BarID}, gfx.Size{Width: 200, Height: 200}, paint) +} + func TestScrollingMenuAllocatesNothingOncePainted(t *testing.T) { scroll := MenuScroll{BarID: gfx.Item(9)} var canvas gfx.Canvas From 5847af799c3621380b108080d0bd49a057b77014 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 28 Nov 2026 16:38:48 +0800 Subject: [PATCH 19/29] fix(components): sync dropdown menu installer recipe --- cmd/viva/templates/dropdown_menu.go.txt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index 4abfaa507..978586476 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -977,6 +977,16 @@ func (menu *menuSurface) end() { 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}) + // A press the pointer pass delivers to the bar drags the thumb: the + // press was taken here, so the runtime captured it and the moves + // follow wherever the pointer goes. Without this ask the bar + // hit-tests and paints its thumb, but nothing ever drags it. A move + // the pointer merely hovers with is not a drag and stays hover. + if event, ok := menu.canvas.PointerOn(scroll.BarID); ok && + ((event.Kind == gfx.PointerDown && event.Button <= gfx.PointerButtonPrimary) || (scroll.Dragging() && event.Kind != gfx.PointerDown)) { + scroll.Drag(event) + menu.canvas.Consume() + } } menu.popOverlay() menu.popClip() From 97cdc2bd27b792951212d1ec8727f3d560d975c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=88=E7=A7=8B?= <49514152+yiqiui@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:36:48 +0800 Subject: [PATCH 20/29] fix(windows): raise the watermark above the owner's popups --- .../platform/windows/watermark_windows.go | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/internal/platform/windows/watermark_windows.go b/internal/platform/windows/watermark_windows.go index d8cf74232..8d0ed73ee 100644 --- a/internal/platform/windows/watermark_windows.go +++ b/internal/platform/windows/watermark_windows.go @@ -144,13 +144,20 @@ func (overlay *watermarkOverlay) close() { // raiseWatermark is the only stacking entry point. New native child/owned windows // must call it after changing the native view tree. func (state *windowState) raiseWatermark() { - if state.watermark != nil && state.watermark.window != 0 { - level := ^uintptr(1) // HWND_NOTOPMOST: match the owner, including demotion. - if style, err := readDecorationStyle(state.window, ^uintptr(19)); err == nil && style&wsExTopmost != 0 { - level = ^uintptr(0) - } - setWindowPosition.Call(state.watermark.window, level, 0, 0, 0, 0, 0x13) // HWND_TOP, NOMOVE|NOSIZE|NOACTIVATE + if state.watermark == nil || state.watermark.window == 0 { + return } + // The overlay takes its owner's topmost level, at the top of that level. + // HWND_NOTOPMOST would not do alone: it has no effect on a window that is + // not topmost, so a popup shown after the overlay would stay above it and + // see no watermark. HWND_TOP and HWND_TOPMOST always reorder. + level := uintptr(0) // HWND_TOP: the top of the non-topmost group, popup or not. + if style, err := readDecorationStyle(state.window, ^uintptr(19)); err == nil && style&wsExTopmost != 0 { + level = ^uintptr(0) // HWND_TOPMOST: the top of the topmost group, with the bit. + } else if style, err := readDecorationStyle(state.watermark.window, ^uintptr(19)); err == nil && style&wsExTopmost != 0 { + level = ^uintptr(1) // HWND_NOTOPMOST: a stale topmost bit the owner lost is dropped here, above the popups. + } + setWindowPosition.Call(state.watermark.window, level, 0, 0, 0, 0, 0x13) // NOMOVE|NOSIZE|NOACTIVATE } func (state *windowState) syncWatermark() error { From fa31927dcc6c2bd08f13a3d2b32ff44b3712b908 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=88=E7=A7=8B?= <49514152+yiqiui@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:36:56 +0800 Subject: [PATCH 21/29] fix(components): keep anchored turn in place on prepend --- cmd/viva/templates/message_scroller.go.txt | 7 ++++++- components/message_scroller.go | 7 ++++++- components/message_scroller_test.go | 23 ++++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/cmd/viva/templates/message_scroller.go.txt b/cmd/viva/templates/message_scroller.go.txt index 4483a4c67..436f82f99 100644 --- a/cmd/viva/templates/message_scroller.go.txt +++ b/cmd/viva/templates/message_scroller.go.txt @@ -444,10 +444,15 @@ func (state *MessageScrollState) AnchorTurn(top float32) { // Prepended tells the state that height of content was inserted above what it was // showing, older history loaded while the reader looks at the transcript. The offset // moves by the same amount at the next Resolve so the rows on screen stay where they -// are. A transcript that follows its end needs no correction. +// are. A transcript that follows its end needs no correction. While an anchored turn +// holds the viewport, the anchor moves with the insert: the turn sits below the +// history that was loaded, so its content-space top moves down by the same height. func (state *MessageScrollState) Prepended(height float32) { if height > 0 && height == height { state.shift += height + if state.anchoring { + state.anchorTop += height + } } } diff --git a/components/message_scroller.go b/components/message_scroller.go index cfecf32af..3fa75418f 100644 --- a/components/message_scroller.go +++ b/components/message_scroller.go @@ -444,10 +444,15 @@ func (state *MessageScrollState) AnchorTurn(top float32) { // Prepended tells the state that height of content was inserted above what it was // showing, older history loaded while the reader looks at the transcript. The offset // moves by the same amount at the next Resolve so the rows on screen stay where they -// are. A transcript that follows its end needs no correction. +// are. A transcript that follows its end needs no correction. While an anchored turn +// holds the viewport, the anchor moves with the insert: the turn sits below the +// history that was loaded, so its content-space top moves down by the same height. func (state *MessageScrollState) Prepended(height float32) { if height > 0 && height == height { state.shift += height + if state.anchoring { + state.anchorTop += height + } } } diff --git a/components/message_scroller_test.go b/components/message_scroller_test.go index 0802ba0b2..3a5aa29dc 100644 --- a/components/message_scroller_test.go +++ b/components/message_scroller_test.go @@ -167,6 +167,29 @@ func TestMessageScrollStateAnchorsATurnThenHandsOverToTheLiveEdge(t *testing.T) } } +// Loading older history while a turn is anchored keeps the anchored message +// where it sits on screen: its content-space top moves down with the insert. +func TestMessageScrollStatePrependsWhileATurnIsAnchored(t *testing.T) { + state := MessageScrollState{PreviousPeek: MessageScrollPreviousPeek} + state.AnchorTurn(250) + if got := state.Resolve(100, 500); got != 186 { + t.Fatalf("anchored offset = %v, want 186", got) + } + state.Prepended(120) + if got := state.Resolve(100, 620); got != 306 { + t.Fatalf("anchored offset after prepending 120 above = %v, want 306 (the turn kept in place)", got) + } + // An anchor the reader released before the Resolve keeps the plain shift. + scrolled := MessageScrollState{PreviousPeek: MessageScrollPreviousPeek} + scrolled.AnchorTurn(250) + scrolled.Resolve(100, 500) + scrolled.ScrollBy(-20) + scrolled.Prepended(120) + if got := scrolled.Resolve(100, 620); got != 286 { + t.Fatalf("released anchor after prepending 120 = %v, want 286", got) + } +} + func TestMessageScrollStateAllocatesNothing(t *testing.T) { state := MessageScrollState{AutoScroll: true} if allocations := testing.AllocsPerRun(100, func() { From 7ca58030779d120eb920b2a64e739cac0e50897d Mon Sep 17 00:00:00 2001 From: tudou Date: Sat, 28 Nov 2026 20:37:02 +0800 Subject: [PATCH 22/29] fix(linux): respect Num Lock and Shift for keypad input --- internal/platform/linux/input_linux.go | 13 +++++ internal/platform/linux/input_linux_test.go | 55 +++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/internal/platform/linux/input_linux.go b/internal/platform/linux/input_linux.go index cbaf8074f..26c9f52bd 100644 --- a/internal/platform/linux/input_linux.go +++ b/internal/platform/linux/input_linux.go @@ -239,6 +239,12 @@ func (router eventRouter) key(keymap *xcbKeymap, event *xcbInputEvent, repeat bo keyEvent.Text = keymap.text(event.Detail, event.State) } keysym := keymap.keysym(event.Detail, event.State) + // 小键盘按当前 Num Lock 和 Shift 状态区分数字与导航键。 + if isKeypadKeysym(keysym) { + key = normalizedKeysym(keysym) + keyEvent.Key = key + keyEvent.Text = keymap.text(event.Detail, event.State) + } if key.IsModifier() && router.ime != nil { // An input method reads a lone modifier by its press and its release (a bare // Shift switches between Chinese and English), so it gets both. @@ -249,6 +255,10 @@ func (router eventRouter) key(keymap *xcbKeymap, event *xcbInputEvent, repeat bo keyEvent.Code = uint32(event.Detail) keyEvent.Text = keymap.shortcutText(event.Detail, 0) keyEvent.Typed = keymap.text(event.Detail, event.State) + // 清空修饰状态会丢失小键盘数字的身份,需保留实际选中的字符。 + if isKeypadKeysym(keysym) { + keyEvent.Text = keyEvent.Typed + } } if handled, err := router.modifierPress(keyEvent, keysym, uint32(event.Detail)); handled { return err @@ -396,6 +406,9 @@ func (router eventRouter) release(keymap *xcbKeymap, event *xcbInputEvent) error // The symbol at the state without the AltGr level: for the AltGr key itself // that is ISO_Level3_Shift, which is not Alt. keysym := keymap.keysym(event.Detail, event.State&^keymap.level3Mask()) + if isKeypadKeysym(keysym) { + key = normalizedKeysym(keysym) + } modifiers := router.releaseModifiers(xcbModifiers(event.State), key, keysym, uint32(event.Detail)) if !router.wantsKeyReleases() && !router.wantsModifierTap(key) || router.config.OnKey == nil { return nil diff --git a/internal/platform/linux/input_linux_test.go b/internal/platform/linux/input_linux_test.go index b715dc321..e29c72781 100644 --- a/internal/platform/linux/input_linux_test.go +++ b/internal/platform/linux/input_linux_test.go @@ -964,3 +964,58 @@ func TestX11ModifierTapsDeliverOnlyModifiers(t *testing.T) { } } } + +func TestTerminalRawKeypadRespectsNumLock(t *testing.T) { + for _, test := range []struct { + name string + navigation uint32 + digit uint32 + state uint16 + wantKey input.Key + wantText string + }{ + {"digit 0", 0xff9e, 0xffb0, xcbMod2, input.KeyUnknown, "0"}, + {"digit 1", keysymKPEnd, 0xffb1, xcbMod2, input.KeyUnknown, "1"}, + {"digit 2", keysymKPDown, 0xffb2, xcbMod2, input.KeyUnknown, "2"}, + {"digit 3", 0xff9b, 0xffb3, xcbMod2, input.KeyUnknown, "3"}, + {"digit 4", keysymKPLeft, 0xffb4, xcbMod2, input.KeyUnknown, "4"}, + {"digit 5", 0xff9d, 0xffb5, xcbMod2, input.KeyUnknown, "5"}, + {"digit 6", keysymKPRight, 0xffb6, xcbMod2, input.KeyUnknown, "6"}, + {"digit 7", keysymKPHome, 0xffb7, xcbMod2, input.KeyUnknown, "7"}, + {"digit 8", keysymKPUp, 0xffb8, xcbMod2, input.KeyUnknown, "8"}, + {"digit 9", 0xff9a, 0xffb9, xcbMod2, input.KeyUnknown, "9"}, + {"decimal", keysymKPDelete, 0xffae, xcbMod2, input.KeyUnknown, "."}, + {"left", keysymKPLeft, 0xffb4, 0, input.KeyLeft, ""}, + {"right", keysymKPRight, 0xffb6, 0, input.KeyRight, ""}, + {"shift left", keysymKPLeft, 0xffb4, xcbMod2 | xcbModShift, input.KeyLeft, ""}, + {"shift digit", keysymKPLeft, 0xffb4, xcbModShift, input.KeyUnknown, "4"}, + } { + t.Run(test.name, func(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, KeyReleases: true}}, + present: func(platform.Frame) error { return nil }, + modifierKeys: newModifierTracker(), + } + keymap := xcbKeymap{first: 79, last: 79, perKeycode: 2, keysyms: []uint32{test.navigation, test.digit}} + event := xcbInputEvent{Detail: 79, State: test.state} + if err := router.key(&keymap, &event, false); err != nil { + t.Fatal(err) + } + if err := router.release(&keymap, &event); err != nil { + t.Fatal(err) + } + want := []platform.KeyEvent{ + {Key: test.wantKey, Text: test.wantText, Typed: test.wantText, Code: 79, Modifiers: xcbModifiers(test.state)}, + {Key: test.wantKey, Code: 79, Release: true, Modifiers: xcbModifiers(test.state)}, + } + if !reflect.DeepEqual(keys, want) { + t.Fatalf("keys = %+v, want %+v", keys, want) + } + }) + } +} From b53f7fe0b6c87d68b7ee6502daaf6162c32fd898 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=88=E7=A7=8B?= <49514152+yiqiui@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:38:40 +0800 Subject: [PATCH 23/29] fix(patchgen): read a Linux payload's executable from its tar header --- tools/patchgen/patchgen.go | 88 ++++++++++++++++----------- tools/patchgen/patchgen_test.go | 102 +++++++++++++++++++++++++++++++- 2 files changed, 156 insertions(+), 34 deletions(-) diff --git a/tools/patchgen/patchgen.go b/tools/patchgen/patchgen.go index f0a5d5636..aefbb7c1d 100644 --- a/tools/patchgen/patchgen.go +++ b/tools/patchgen/patchgen.go @@ -263,11 +263,12 @@ func extractPayload(archive, goos, arch, executable string) (root, kind string, 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 { + executables, err := extractTarGz(archive, directory) + if err != nil { removeTree() return "", "", nil, err } - program, err := findExecutable(directory, executable) + program, err := findExecutable(directory, executable, executables) if err != nil { removeTree() return "", "", nil, err @@ -287,30 +288,27 @@ func extractPayload(archive, goos, arch, executable string) (root, kind string, } } -// 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) { +// findExecutable finds the program in an unpacked Linux archive, among the +// files the archive's tar headers marked executable (see extractTarGz): the +// header is the only place that fact survives on a host whose file system does +// not keep it, such as Windows, where every regular file reads back mode 0666. +// A named executable wins; otherwise the archive must hold one executable +// besides install.sh. +func findExecutable(root, name string, executables []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 + for _, entry := range executables { + if filepath.Base(entry) == "install.sh" { + continue } - if !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 || entry.Name() == "install.sh" { - return nil + path := filepath.Join(root, filepath.FromSlash(entry)) + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() { + continue } - if name != "" && entry.Name() == name { + if name != "" && filepath.Base(entry) == name { named = append(named, path) } candidates = append(candidates, path) - return nil - }) - if err != nil { - return "", err } if len(named) == 1 { return named[0], nil @@ -380,58 +378,82 @@ func extractZip(archive, destination string) error { } // extractTarGz unpacks a tar.gz, refusing absolute paths and entries that -// climb out of destination. -func extractTarGz(archive, destination string) error { +// climb out of destination. It returns the slash paths of the regular files +// whose header carries an execution bit, in path order: see findExecutable. +func extractTarGz(archive, destination string) ([]string, error) { file, err := os.Open(archive) if err != nil { - return err + return nil, err } defer file.Close() gz, err := gzip.NewReader(file) if err != nil { - return err + return nil, err } defer gz.Close() reader := tar.NewReader(gz) + var marked map[string]bool for { header, err := reader.Next() if err == io.EOF { - return nil + return sortedKeys(marked), nil } if err != nil { - return err + return nil, err } target, err := safeJoin(destination, header.Name) if err != nil { - return err + return nil, err } switch header.Typeflag { case tar.TypeDir: if err := os.MkdirAll(target, 0o755); err != nil { - return err + return nil, err } case tar.TypeReg: if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { - return err + return nil, 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 + return nil, err } _, copyErr := io.Copy(output, reader) closeErr := output.Close() if copyErr != nil { - return copyErr + return nil, copyErr } if closeErr != nil { - return closeErr + return nil, closeErr + } + // The execution bits travel in the header, which is the only record + // of them a host without them (Windows) can consult later. A name + // the archive repeats is the last one's file, so keep only it. + if header.Mode&0o111 != 0 { + if marked == nil { + marked = map[string]bool{} + } + marked[header.Name] = true + } else { + delete(marked, header.Name) } default: - return fmt.Errorf("patchgen: %s is not a regular file or directory", header.Name) + return nil, fmt.Errorf("patchgen: %s is not a regular file or directory", header.Name) } } } +// sortedKeys names the marked entries in path order, the order the tree walk +// they replace reported. +func sortedKeys(marked map[string]bool) []string { + names := make([]string, 0, len(marked)) + for name := range marked { + names = append(names, name) + } + sort.Strings(names) + return names +} + func safeJoin(root, name string) (string, error) { clean := filepath.Clean(filepath.FromSlash(name)) if filepath.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) { diff --git a/tools/patchgen/patchgen_test.go b/tools/patchgen/patchgen_test.go index 750d46990..6ae7d66e2 100644 --- a/tools/patchgen/patchgen_test.go +++ b/tools/patchgen/patchgen_test.go @@ -7,18 +7,35 @@ import ( "compress/gzip" "os" "path/filepath" + "strings" "testing" "github.com/vivaui/viva/update" ) func writeTarGz(t *testing.T, path, root string, files map[string][]byte) { + t.Helper() + modes := make(map[string]int64, len(files)) + for name := range files { + modes[name] = 0o755 + } + writeTarGzModes(t, path, root, files, modes) +} + +// writeTarGzModes writes a tar.gz whose headers carry the given modes, so a +// test decides what the archive says is executable, whatever the host keeps on +// its own file system. +func writeTarGzModes(t *testing.T, path, root string, files map[string][]byte, modes map[string]int64) { 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} + mode, ok := modes[name] + if !ok { + t.Fatalf("%s has no mode", name) + } + header := &tar.Header{Name: root + "/" + name, Mode: mode, Size: int64(len(data)), Typeflag: tar.TypeReg} if err := writer.WriteHeader(header); err != nil { t.Fatal(err) } @@ -109,6 +126,89 @@ func TestWriteLinuxPatch(t *testing.T) { } } +// TestWriteLinuxPatchPicksTheOnlyExecutableByArchiveMode pins what a Windows +// host cannot re-derive by statting the unpacked tree: the execution bits of +// the program come from the tar header, and the one regular file that has them +// (install.sh aside) is the patch's payload with no name in the manifest. +func TestWriteLinuxPatchPicksTheOnlyExecutableByArchiveMode(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") + oldFiles := map[string][]byte{ + "app": []byte("the old program, with a fair amount of content"), + "install.sh": []byte("#!/bin/sh\n"), + "README.txt": []byte("read me"), + } + oldModes := map[string]int64{"app": 0o755, "install.sh": 0o755, "README.txt": 0o644} + newFiles := map[string][]byte{ + "app": []byte("the new program, with a fair amount of content and more"), + "install.sh": []byte("#!/bin/sh\n"), + "README.txt": []byte("read me"), + } + newModes := map[string]int64{"app": 0o755, "install.sh": 0o755, "README.txt": 0o644} + writeTarGzModes(t, oldArchive, "app-1.0.0-linux-amd64", oldFiles, oldModes) + writeTarGzModes(t, newArchive, "app-1.1.0-linux-amd64", newFiles, newModes) + 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, 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) + } +} + +// TestWriteLinuxPatchRefusesAProgramWithoutExecutionBits keeps a file that the +// archive does not mark executable from being picked by name, whatever the +// host's file system would say about the unpacked copy. +func TestWriteLinuxPatchRefusesAProgramWithoutExecutionBits(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "app-1.0.0-linux-amd64.tar.gz") + writeTarGzModes(t, archive, "app-1.0.0-linux-amd64", map[string][]byte{ + "app": []byte("the old program"), + }, map[string]int64{"app": 0o644}) + file, err := os.Create(filepath.Join(dir, "app.patch")) + if err != nil { + t.Fatal(err) + } + defer file.Close() + _, err = Write(Request{ + App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "linux", Arch: "amd64", OldArchive: archive, NewArchive: archive, + Executable: "app", Output: file, + }) + if err == nil || !strings.Contains(err.Error(), "holds no executable") { + t.Fatalf("Write() = %v, want an archive with no executable", err) + } +} + +// TestFindExecutableTrustsTheArchiveNotTheDisk pins the fix's reason to exist: +// an unpacked copy whose file has no execution bit on disk (every file reads +// back 0666 on Windows) is still the program the archive marked executable. +// It holds on every host, so a regression to a disk-mode check fails here too. +func TestFindExecutableTrustsTheArchiveNotTheDisk(t *testing.T) { + dir := t.TempDir() + program := filepath.Join(dir, "app") + if err := os.WriteFile(program, []byte("the program"), 0o644); err != nil { + t.Fatal(err) + } + got, err := findExecutable(dir, "", []string{"app"}) + if err != nil { + t.Fatalf("findExecutable() error = %v", err) + } + if got != program { + t.Fatalf("findExecutable() = %q, want %q", got, program) + } +} + func TestWriteDarwinPatch(t *testing.T) { dir := t.TempDir() oldArchive := filepath.Join(dir, "app-1.0.0-darwin-arm64.zip") From 17b35ae0feadca0f2a75eab75739599e3bd35cbc Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 28 Nov 2026 20:44:10 +0800 Subject: [PATCH 24/29] docs(website): explain notifications and watermarks in guides The site test requires every example program to appear in a guide. The notifications and watermark examples had none, which left main's website job red. Both guides get a section and the example, in English and Chinese, expanded from examples/guides so the shown code is the code that runs. --- .../content/guides/en/system-integration.md | 53 +++++++++++++++++++ website/content/guides/en/windows.md | 31 +++++++++++ .../content/guides/zh/system-integration.md | 53 +++++++++++++++++++ website/content/guides/zh/windows.md | 31 +++++++++++ 4 files changed, 168 insertions(+) diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md index ff2ecdc0a..5d893c329 100644 --- a/website/content/guides/en/system-integration.md +++ b/website/content/guides/en/system-integration.md @@ -269,6 +269,59 @@ func run(application *app.Application) error { } ``` +## Notifications that respond to a click + +`Application.ShowNotification` posts a notification and returns a `NotificationHandle`. `OnActivate` runs when the user clicks it, `OnError` reports delivery failures, and `Close` withdraws it. Check `app.Supports(app.CapabilityNotificationActivation)` first: where the platform cannot report clicks, the notification is not interactive, and the example shows a message instead of controls. On macOS the application must be packaged and allowed to show notifications. + +Run `go run ./examples/guides/notifications` to try the complete example. + + +```go +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +func main() { + err := app.RunApplication(func(application *app.Application) error { + var window *app.Window + var latest *app.NotificationHandle + var err error + window, err = ui.OpenWindow(application, app.Config{Title: "System notifications", Width: 600, Height: 300}, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + if !app.Supports(app.CapabilityNotificationActivation) { + ui.Text(c, "Interactive notifications are not supported on this target.") + return + } + ui.Text(c, "On macOS, run the packaged application and allow system notifications.") + if ui.Button(c, "Show notification").Clicked() { + latest.Close() + latest, err = application.ShowNotification(app.Notification{Title: "Viva", Body: "Click to restore the application window."}, app.NotificationEvents{ + OnActivate: func() { window.Show() }, + OnError: func(err error) { log.Printf("notification delivery: %v", err) }, + }) + if err != nil { + log.Printf("request notification: %v", err) + } + } + if ui.Button(c, "Withdraw notification").Clicked() { + latest.Close() + latest = nil + } + }) + }}) + return err + }) + if err != nil { + log.Fatal(err) + } +} +``` + ## Boundaries worth knowing - Linux file dialogs and notifications use the desktop's portal and notification service over D-Bus, and start an installed desktop utility only on a desktop without them; URL dispatch always does. Viva does not bundle GTK or Qt. diff --git a/website/content/guides/en/windows.md b/website/content/guides/en/windows.md index da6563297..9f32e120c 100644 --- a/website/content/guides/en/windows.md +++ b/website/content/guides/en/windows.md @@ -205,6 +205,37 @@ When a `Menu` is set, a press opens the system's own native menu, built by calli `StatusItem.SetIcon`, `SetTooltip` and `Remove` change or remove the icon later. +## Watermarks + +`Config.Watermark` draws repeated text over the whole window, including embedded native views, without taking input. An empty `Text` turns it off. Native support is reported by `app.Supports(app.CapabilityWindowWatermark)`; hosts without it ignore the setting, so the example sets the watermark only when the capability is present. + +Run `go run ./examples/guides/watermark` to try the complete example. + + +```go +// A native watermark stays above embedded views without receiving input. +package main + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "log" +) + +func main() { + config := app.Config{Title: "Native watermark", Width: 800, Height: 500} + if app.Supports(app.CapabilityWindowWatermark) { + config.Watermark = app.Watermark{Text: "DRAFT", Angle: -25, FontWeight: gfx.WeightLight, Insets: gfx.All(24)} + } + if err := ui.Run(config, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Children(func() { ui.Button(c, "The watermark does not intercept input") }) + }}); err != nil { + log.Fatal(err) + } +} +``` + ## What differs between platforms The same call can only say what the platform can say. A status icon reports its rectangle on macOS and Windows but only the click point on Linux. A panel is dismissed by losing key status, by deactivation or by `FocusOut` respectively. A new icon in a full macOS menu bar can be hidden by the system, notably next to the notch, and Windows 11 shows a new icon in the overflow flyout until the user promotes it. `docs/conformance.md` in the repository lists these, and what must be checked by hand on each platform. diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md index 5fabfecd5..625b59520 100644 --- a/website/content/guides/zh/system-integration.md +++ b/website/content/guides/zh/system-integration.md @@ -259,6 +259,59 @@ func run(application *app.Application) error { } ``` +## 可以响应点击的通知 + +`Application.ShowNotification` 发出通知并返回 `NotificationHandle`。用户点击时执行 `OnActivate`,投递失败通过 `OnError` 报告,`Close` 撤回通知。先用 `app.Supports(app.CapabilityNotificationActivation)` 检查:平台无法回报点击时,通知不可交互,示例会改为显示提示文字而不是控件。macOS 上应用必须打包,并获准显示通知。 + +执行 `go run ./examples/guides/notifications` 可以运行完整示例。 + + +```go +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +func main() { + err := app.RunApplication(func(application *app.Application) error { + var window *app.Window + var latest *app.NotificationHandle + var err error + window, err = ui.OpenWindow(application, app.Config{Title: "System notifications", Width: 600, Height: 300}, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + if !app.Supports(app.CapabilityNotificationActivation) { + ui.Text(c, "Interactive notifications are not supported on this target.") + return + } + ui.Text(c, "On macOS, run the packaged application and allow system notifications.") + if ui.Button(c, "Show notification").Clicked() { + latest.Close() + latest, err = application.ShowNotification(app.Notification{Title: "Viva", Body: "Click to restore the application window."}, app.NotificationEvents{ + OnActivate: func() { window.Show() }, + OnError: func(err error) { log.Printf("notification delivery: %v", err) }, + }) + if err != nil { + log.Printf("request notification: %v", err) + } + } + if ui.Button(c, "Withdraw notification").Clicked() { + latest.Close() + latest = nil + } + }) + }}) + return err + }) + if err != nil { + log.Fatal(err) + } +} +``` + ## 值得了解的边界 - Linux 上的文件对话框、URL 分发和通知,会在用户请求时启动已安装的桌面工具。Viva 不捆绑 GTK、Qt 或 D-Bus 栈。 diff --git a/website/content/guides/zh/windows.md b/website/content/guides/zh/windows.md index b8b1e9165..2ff240380 100644 --- a/website/content/guides/zh/windows.md +++ b/website/content/guides/zh/windows.md @@ -171,6 +171,37 @@ func addTray(application *app.Application, window *app.Window, icon app.StatusIc 之后可以用 `StatusItem.SetIcon`、`SetTooltip` 和 `Remove` 修改或移除图标。 +## 水印 + +`Config.Watermark` 在整个窗口上绘制重复文字,包括嵌入的原生视图,且不接收输入;`Text` 为空时关闭。原生支持由 `app.Supports(app.CapabilityWindowWatermark)` 报告;不支持的宿主会忽略该设置,因此示例只在具备该能力时设置水印。 + +执行 `go run ./examples/guides/watermark` 可以运行完整示例。 + + +```go +// A native watermark stays above embedded views without receiving input. +package main + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "log" +) + +func main() { + config := app.Config{Title: "Native watermark", Width: 800, Height: 500} + if app.Supports(app.CapabilityWindowWatermark) { + config.Watermark = app.Watermark{Text: "DRAFT", Angle: -25, FontWeight: gfx.WeightLight, Insets: gfx.All(24)} + } + if err := ui.Run(config, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Children(func() { ui.Button(c, "The watermark does not intercept input") }) + }}); err != nil { + log.Fatal(err) + } +} +``` + ## 各平台的差异 同一个调用只能说出平台能说的东西。状态栏图标在 macOS 和 Windows 上报告它的矩形,在 Linux 上只报告点击点;面板分别因失去 key 状态、窗口停用或 `FocusOut` 而关闭。在已满的 macOS 菜单栏里,新图标可能被系统隐藏,尤其是刘海旁边;Windows 11 会把新图标放进溢出浮层,直到用户把它提升出来。仓库中的 `docs/conformance.md`列出了这些,以及每个平台必须手动检查的项目。 From b92eb1973375899f7814b709dc656df8797b11db Mon Sep 17 00:00:00 2001 From: tudou Date: Sat, 28 Nov 2026 20:45:17 +0800 Subject: [PATCH 25/29] feat(ui): add live editing to the color picker --- base/color.go | 25 +++++++++ cmd/viva/templates/color_picker.go.txt | 11 +++- components/color_picker.go | 11 +++- ui/color_live_test.go | 71 ++++++++++++++++++++++++++ ui/color_paint.go | 5 +- 5 files changed, 118 insertions(+), 5 deletions(-) create mode 100644 ui/color_live_test.go diff --git a/base/color.go b/base/color.go index 7a2eb5146..0e03fc90d 100644 --- a/base/color.go +++ b/base/color.go @@ -60,6 +60,7 @@ func (b Box) TabStop(on bool) Box { type ColorPickerState struct { open, restoreFocus, applied bool showAlpha bool + live bool draft ColorPickerValue hexEditor text.Editor hex Field @@ -100,6 +101,28 @@ func (s *ColorPickerState) Applied() bool { return applied } +// Live reports whether edits update the bound color immediately. +func (s *ColorPickerState) Live() bool { return s.live } + +// Live makes a ColorPicker update its bound color as it is edited, without +// Clear, Cancel or Apply buttons. Escape and outside clicks close the panel +// without reverting edits. Bind a draft when the application owns Save/Cancel. +func (b Box) Live(on bool) Box { + if extra := b.pickerExtra(); extra != nil { + extra.picker.live = on + } + return b +} + +func (s *ColorPickerState) commitLive() { + if s.live && s.open && !s.invalid && s.target != nil { + color := s.draft.Color() + if *s.target != color { + *s.target, s.applied = color, true + } + } +} + // colorPickerLook is how a ColorPicker looks, set by its Box methods. type ColorPickerLook struct { Label string @@ -247,6 +270,7 @@ func (s *ColorPickerState) SetDraftValue(v ColorPickerValue) { } s.seen, s.invalid = value, false s.Summary = Summary(v) + s.commitLive() } func Summary(v ColorPickerValue) string { @@ -304,5 +328,6 @@ func (s *ColorPickerState) syncHex() { if valid { s.draft = s.draft.WithColor(color) s.Summary = Summary(s.draft) + s.commitLive() } } diff --git a/cmd/viva/templates/color_picker.go.txt b/cmd/viva/templates/color_picker.go.txt index 2b7579886..568afdc3f 100644 --- a/cmd/viva/templates/color_picker.go.txt +++ b/cmd/viva/templates/color_picker.go.txt @@ -29,6 +29,7 @@ type ColorPickerOptions struct { Open, Empty, Disabled, ShowAlpha bool // RoundTrigger renders a circular swatch. TriggerIcon can identify a custom // color action independently of its selected color. + Live bool RoundTrigger bool TriggerIcon *gfx.Icon Viewport gfx.Rect @@ -172,16 +173,19 @@ func (picker ColorPicker) Paint() ColorPickerLayout { alphaHeight = 16 + gap } fixed := float32(16) + 3*gap + 2*control + alphaHeight + errorHeight + if o.Live { + fixed -= control + gap + } overhead := 2*theme.Metrics.PadSurface + popoverHeaderHeight(theme.Metrics, 0) + popoverBodyGap(theme.Metrics) + 16 planeHeight := min(float32(160), max(0, o.Viewport.Height-fixed-overhead)) popover := BeginPopover(c, theme, o.Viewport, picker.bounds, PopoverOptions{ - Layer: o.Layer, Scope: o.Scope, DismissID: o.IDs.Dismiss, AnchorDismiss: true, ConsumeOutsidePress: true, + Layer: o.Layer, Scope: o.Scope, DismissID: o.IDs.Dismiss, AnchorDismiss: true, ConsumeOutsidePress: !o.Live, Instant: o.Live, Align: PopoverAlignEnd, SideOffset: 6, ContentSize: gfx.Size{Width: 280}, BodyHeight: planeHeight + fixed, InitialFocusID: o.IDs.Saturation, }) body := popover.Begin(labels.Color, "").Body defer popover.End() - if !o.Scope.IsZero() { + if !o.Scope.IsZero() && !o.Live { c.TrapFocus(o.Scope) } l.Content = body @@ -225,6 +229,9 @@ func (picker ColorPicker) Paint() ColorPickerLayout { c.Label(o.Error, gfx.Rect{X: body.X, Y: y, Width: body.Width, Height: errorHeight - gap}, gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.Danger}) y += errorHeight } + if o.Live { + return l + } width := max(0, (body.Width-2*gap)/3) BeginButton(c, theme, o.IDs.Clear, gfx.Rect{X: body.X, Y: y, Width: width, Height: control}).Ghost(labels.Clear) BeginButton(c, theme, o.IDs.Cancel, gfx.Rect{X: body.X + width + gap, Y: y, Width: width, Height: control}).Outline(labels.Cancel) diff --git a/components/color_picker.go b/components/color_picker.go index 635ab34d5..05aed8a86 100644 --- a/components/color_picker.go +++ b/components/color_picker.go @@ -29,6 +29,7 @@ type ColorPickerOptions struct { Open, Empty, Disabled, ShowAlpha bool // RoundTrigger renders a circular swatch. TriggerIcon can identify a custom // color action independently of its selected color. + Live bool RoundTrigger bool TriggerIcon *gfx.Icon Viewport gfx.Rect @@ -172,16 +173,19 @@ func (picker ColorPicker) Paint() ColorPickerLayout { alphaHeight = 16 + gap } fixed := float32(16) + 3*gap + 2*control + alphaHeight + errorHeight + if o.Live { + fixed -= control + gap + } overhead := 2*theme.Metrics.PadSurface + popoverHeaderHeight(theme.Metrics, 0) + popoverBodyGap(theme.Metrics) + 16 planeHeight := min(float32(160), max(0, o.Viewport.Height-fixed-overhead)) popover := BeginPopover(c, theme, o.Viewport, picker.bounds, PopoverOptions{ - Layer: o.Layer, Scope: o.Scope, DismissID: o.IDs.Dismiss, AnchorDismiss: true, ConsumeOutsidePress: true, + Layer: o.Layer, Scope: o.Scope, DismissID: o.IDs.Dismiss, AnchorDismiss: true, ConsumeOutsidePress: !o.Live, Instant: o.Live, Align: PopoverAlignEnd, SideOffset: 6, ContentSize: gfx.Size{Width: 280}, BodyHeight: planeHeight + fixed, InitialFocusID: o.IDs.Saturation, }) body := popover.Begin(labels.Color, "").Body defer popover.End() - if !o.Scope.IsZero() { + if !o.Scope.IsZero() && !o.Live { c.TrapFocus(o.Scope) } l.Content = body @@ -225,6 +229,9 @@ func (picker ColorPicker) Paint() ColorPickerLayout { c.Label(o.Error, gfx.Rect{X: body.X, Y: y, Width: body.Width, Height: errorHeight - gap}, gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.Danger}) y += errorHeight } + if o.Live { + return l + } width := max(0, (body.Width-2*gap)/3) BeginButton(c, theme, o.IDs.Clear, gfx.Rect{X: body.X, Y: y, Width: width, Height: control}).Ghost(labels.Clear) BeginButton(c, theme, o.IDs.Cancel, gfx.Rect{X: body.X + width + gap, Y: y, Width: width, Height: control}).Outline(labels.Cancel) diff --git a/ui/color_live_test.go b/ui/color_live_test.go new file mode 100644 index 000000000..cfa708f28 --- /dev/null +++ b/ui/color_live_test.go @@ -0,0 +1,71 @@ +package ui_test + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "testing" +) + +func TestColorPickerLiveEditsBoundDraft(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(255, 0, 0) + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.ColorPicker(c, &state, &color, "Accent").Live(true) + }) + }) + d.click("Accent") + for _, hit := range d.driver.Snapshot().Hits { + if hit.Label == "OK" || hit.Label == "Cancel" || hit.Label == "Clear" { + t.Fatalf("live picker exposes confirmation action %q", hit.Label) + } + } + d.click("Saturation and brightness") + if color == gfx.RGB(255, 0, 0) || !state.Applied() || !state.Open() { + t.Fatal("plane did not update the bound draft while keeping the picker open") + } + before := color + d.key(gfx.KeyRight) + if color == before || !state.Applied() { + t.Fatal("keyboard adjustment did not update the draft") + } + d.click("Hex color") + state.SetHexText("#123456") + d.key(gfx.KeyEnter) + if uint8(color.Red*255+.5) != 18 || uint8(color.Green*255+.5) != 52 || uint8(color.Blue*255+.5) != 86 || state.Open() { + t.Fatalf("hex edit = %v, open = %v", color, state.Open()) + } + d.click("Accent") + d.click("Hue") + before = color + d.key(gfx.KeyEscape) + if state.Open() || color != before { + t.Fatal("Escape did not retain the live edit") + } +} + +func TestColorPickerLiveInsideDialogKeepsDraftAndOutsideAction(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(255, 0, 0) + saved := false + d := openPage(t, func(c ui.C) { + dialog := ui.Dialog(c, ui.DialogSpec{Title: "Theme editor", Width: 480, Height: 500, Layer: 600}) + dialog.Body(func() { + ui.ColorPicker(c, &state, &color, "Accent").Live(true) + }) + dialog.Footer(func() { + if ui.Button(c, "Save theme").Clicked() { + saved = true + } + }) + }) + d.click("Accent") + d.click("Saturation and brightness") + if color == gfx.RGB(255, 0, 0) { + t.Fatal("dialog picker did not edit draft") + } + d.click("Save theme") + if !saved || state.Open() { + t.Fatal("outside action did not save and close picker") + } +} diff --git a/ui/color_paint.go b/ui/color_paint.go index 6c21c4303..74eae18bc 100644 --- a/ui/color_paint.go +++ b/ui/color_paint.go @@ -55,12 +55,15 @@ func paintColorPickerPanel(s *ColorPickerState, d *DrawContext, c C, ID gfx.ID, } empty = empty || look.GetEmpty() options := components.ColorPickerOptions{ - IDs: ids, Labels: labels, Value: value, Open: s.GetOpen(), Empty: empty, ShowAlpha: s.ShowsAlpha(), + IDs: ids, Labels: labels, Value: value, Open: s.GetOpen(), Empty: empty, ShowAlpha: s.ShowsAlpha(), Live: s.Live(), RoundTrigger: look.GetRound(), TriggerIcon: look.GetIcon(), SaturationText: s.Summary, Viewport: Rect{Width: c.Bounds().Width, Height: c.Bounds().Height}, Layer: s.GetLayer(), } if s.GetOpen() { options.Scope = s.GetHandlers().GetParts().At(8) + if s.Live() { + options.Scope = canvas.FocusScope() + } options.Hex = s.HexPtr().Snapshot(c.GetF(), ids.Hex, labels.Hex, "#3B82F6") if s.GetInvalid() { options.Error = labels.InvalidColor From c21745f44af2ec5acff562a08450ebc762368aad Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 28 Nov 2026 22:26:40 +0800 Subject: [PATCH 26/29] feat(windows): report the graphics path through diagnostics When the first Direct3D device is made, the render subsystem reports the driver behind it (hardware or WARP), the adapter as DXGI names it, the feature level and whether DirectComposition or the window's own swap chain presents, once per process. A DirectComposition that could not be made is reported as a warning with its error instead of leaving the fallback silent. TestNativeStructureABI now checks that DXGI_ADAPTER_DESC keeps its ABI. Companion Motty commit routes the stream into motty.log. --- internal/platform/windows/api_windows_test.go | 1 + .../platform/windows/composition_windows.go | 1 + internal/platform/windows/device_windows.go | 68 +++++++++++++++++++ .../platform/windows/materials_windows.go | 13 +++- internal/platform/windows/renderer_windows.go | 10 ++- 5 files changed, 90 insertions(+), 3 deletions(-) diff --git a/internal/platform/windows/api_windows_test.go b/internal/platform/windows/api_windows_test.go index be8262130..a40824281 100644 --- a/internal/platform/windows/api_windows_test.go +++ b/internal/platform/windows/api_windows_test.go @@ -39,6 +39,7 @@ func TestNativeStructureABI(t *testing.T) { {"D3D11_SUBRESOURCE_DATA", unsafe.Sizeof(resourceData{}), 16}, {"D3D11_SHADER_RESOURCE_VIEW_DESC", unsafe.Sizeof(resourceViewDesc{}), 24}, {"DXGI_SWAP_CHAIN_DESC1", unsafe.Sizeof(swapChainDesc1{}), 48}, + {"DXGI_ADAPTER_DESC", unsafe.Sizeof(adapterDesc{}), 312}, {"D3D11_RENDER_TARGET_BLEND_DESC", unsafe.Sizeof(renderBlend{}), 32}, {"D3D11_BLEND_DESC", unsafe.Sizeof(blendDesc{}), 264}, {"D3D11_RASTERIZER_DESC", unsafe.Sizeof(rasterDesc{}), 40}, diff --git a/internal/platform/windows/composition_windows.go b/internal/platform/windows/composition_windows.go index 33246c8db..7e8c6acab 100644 --- a/internal/platform/windows/composition_windows.go +++ b/internal/platform/windows/composition_windows.go @@ -48,6 +48,7 @@ func (renderer *renderer) createCompositionDevice(software bool) error { for _, driver := range drivers { status, _, _ = createD3DDevice.Call(0, driver, 0, 0x20, uintptr(unsafe.Pointer(&levels[0])), 1, 7, uintptr(unsafe.Pointer(&renderer.device)), 0, uintptr(unsafe.Pointer(&renderer.context))) if hresult(status) == nil { + renderer.software = driver == 5 break } release(&renderer.context) diff --git a/internal/platform/windows/device_windows.go b/internal/platform/windows/device_windows.go index 834fc182d..8d6e095bd 100644 --- a/internal/platform/windows/device_windows.go +++ b/internal/platform/windows/device_windows.go @@ -2,6 +2,8 @@ package windows import ( "fmt" + "sync" + "syscall" "time" "unsafe" @@ -15,6 +17,72 @@ import ( // what the window shows is in memory in the renderer, so the device is made again // and the scene drawn once more, instead of closing the window. +var describeDeviceOnce sync.Once + +// describeDevice reports the graphics path once per process: which driver and +// adapter stand behind the Direct3D device, its feature level, and whether +// DirectComposition or the window's own swap chain presents. Every window makes +// its own device the same way, so the first one speaks for the rest. +func (renderer *renderer) describeDevice() { + describeDeviceOnce.Do(func() { + if !diag.Enabled(diag.Info) { + return + } + driver, present := "hardware", "window" + if renderer.software { + driver = "warp" + } + if renderer.usesComposition() { + present = "direct-composition" + } + attrs := []diag.Attr{ + diag.String("driver", driver), + diag.String("present", present), + diag.String("feature-level", featureLevelName(uint32(comCall0(renderer.device, 37)))), // ID3D11Device::GetFeatureLevel + } + if name, ok := renderer.adapterName(); ok { + attrs = append(attrs, diag.String("adapter", name)) + } + diag.Report(diag.Info, "render", "device", "the window draws with Direct3D 11", attrs...) + }) +} + +// featureLevelName spells a D3D_FEATURE_LEVEL the way the SDK does: 0xb000 is 11_0. +func featureLevelName(level uint32) string { + return fmt.Sprintf("%d_%d", level>>12, level>>8&0xf) +} + +var dxgiDeviceIID = guid{0x54ec77fa, 0x1377, 0x44e6, [8]byte{0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}} + +// adapterDesc is DXGI_ADAPTER_DESC. +type adapterDesc struct { + Description [128]uint16 + Vendor, Device, Subsystem, Revision uint32 + Video, System, Shared uintptr + LUID [2]uint32 + Flags uint32 +} + +// adapterName is the adapter the device draws with, as DXGI names it: a display +// driver by its model, or "Microsoft Basic Render Driver" for WARP. +func (renderer *renderer) adapterName() (string, bool) { + var device, adapter uintptr + if renderer.device == 0 || hresult(comCall2(renderer.device, 0, uintptr(unsafe.Pointer(&dxgiDeviceIID)), uintptr(unsafe.Pointer(&device)))) != nil { + return "", false + } + defer release(&device) + // IDXGIDevice::GetAdapter, IDXGIAdapter::GetDesc. + if hresult(comCall1(device, 7, uintptr(unsafe.Pointer(&adapter)))) != nil { + return "", false + } + defer release(&adapter) + var desc adapterDesc + if hresult(comCall1(adapter, 8, uintptr(unsafe.Pointer(&desc)))) != nil { + return "", false + } + return syscall.UTF16ToString(desc.Description[:]), true +} + // deviceLost reports whether the renderer's device is gone. It asks the device // itself (ID3D11Device::GetDeviceRemovedReason), which any failing call can then // be blamed on. diff --git a/internal/platform/windows/materials_windows.go b/internal/platform/windows/materials_windows.go index 15ac77f0d..d12423027 100644 --- a/internal/platform/windows/materials_windows.go +++ b/internal/platform/windows/materials_windows.go @@ -3,6 +3,7 @@ package windows import ( "unsafe" + "github.com/vivaui/viva/internal/diag" "github.com/vivaui/viva/internal/platform" ) @@ -74,8 +75,11 @@ func (renderer *renderer) initializeComposition(software bool) bool { if !renderer.composition { return false } - if err := renderer.createCompositionDevice(software); err == nil { - if err := renderer.createResources(); err == nil { + err := renderer.createCompositionDevice(software) + if err == nil { + err = renderer.createResources() + if err == nil { + renderer.describeDevice() return true } } @@ -83,6 +87,11 @@ func (renderer *renderer) initializeComposition(software bool) bool { renderer.releaseDevice() renderer.composition = false restoreWindowRedirection(renderer.window) + if diag.Enabled(diag.Warn) { + diag.Report(diag.Warn, "render", "composition-fallback", + "DirectComposition could not be made, so the window presents through its own swap chain", + diag.String("error", err.Error())) + } return false } diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 770453f5c..f2cfc6989 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -129,6 +129,9 @@ func rectangleScissor(batch compositingBatch, scale float32, width, height int) type renderer struct { drawScratch drawScratch // what draw hands Direct3D by address compositionState + // software says the device is WARP, Microsoft's software rasterizer, rather + // than the display driver, when the driver could not be used or was skipped. + software bool window, device, context, swap, target uintptr rectangleVertex, rectangleFragment, textVertex, textFragment uintptr buffer, view, constants, blend, textBlend, raster, sampler uintptr @@ -260,6 +263,7 @@ func (renderer *renderer) createDeviceAndResources(software bool) error { release(&renderer.device) continue } + renderer.software = driver == 5 if err := renderer.createWindowSwapChain(); err != nil { failure = err release(&renderer.context) @@ -267,7 +271,11 @@ func (renderer *renderer) createDeviceAndResources(software bool) error { release(&renderer.swap) continue } - return renderer.createResources() + err := renderer.createResources() + if err == nil { + renderer.describeDevice() + } + return err } if failure == nil { failure = fmt.Errorf("no Direct3D driver type was tried") From ca01419ebf542f74cf2d92032603a4d980a3838c Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 28 Nov 2026 22:59:00 +0800 Subject: [PATCH 27/29] fix(input): keep an overlap when a region scrolls by a page A wheel set to one screen per notch moved a region by its whole viewport, so the rows at the edge it left were gone at the next page and a reader lost their place. A page is now gfx.ScrollPage of the viewport, seven eighths of it as browsers page, rounded down to whole rows, and ScrollState's PageUp and PageDown take the same page instead of their own nine tenths. Every region that resolves a page notch goes through StepYIn and StepXIn, so the framework's regions and Motty's own painted ones keep the same overlap; Motty's companion commit adapts its tests to it. Refs: t8y2/motty#1794 --- base/scroll.go | 12 +++++----- base/scroll_test.go | 24 ++++++++++--------- gfx/input.go | 16 +++++++++---- gfx/scroll_test.go | 56 +++++++++++++++++++++++++++++++++------------ 4 files changed, 73 insertions(+), 35 deletions(-) diff --git a/base/scroll.go b/base/scroll.go index a164d3a7d..f23f1cb47 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -362,11 +362,11 @@ func (s *ScrollState) relax(canvas *gfx.Canvas) { // Key applies the keyboard's scrolling to the area, from the content and viewport // of its last layout: Left and Right move a Sideways area by step, Up and Down -// vertically by step, PageUp and PageDown by a viewport, and Home and End to the -// start and the end. A step of zero or less is 32 pixels, one line. It reports a -// recognized key as handled even when the area was already at that end, so the -// caller stops there rather than looking for another area, and Repaint only when -// the offsets moved. +// vertically by step, PageUp and PageDown by gfx.ScrollPage of the viewport, and +// Home and End to the start and the end. A step of zero or less is 32 pixels, +// one line. It reports a recognized key as handled even when the area was +// already at that end, so the caller stops there rather than looking for another +// area, and Repaint only when the offsets moved. // // It is for a page that gives the keyboard to the area itself, as one does to a // terminal or a log beside a control: a List and a Table scroll with the arrow @@ -378,7 +378,7 @@ func (s *ScrollState) Key(event gfx.KeyEvent, step float32) gfx.EventResult { if step <= 0 { step = 32 } - page := max(s.Viewport*0.9, step) + page := max(gfx.ScrollPage(s.Viewport), step) before, beforeX := s.Offset, s.OffsetX switch event.Key { case gfx.KeyLeft: diff --git a/base/scroll_test.go b/base/scroll_test.go index f183d14a6..5f333e5da 100644 --- a/base/scroll_test.go +++ b/base/scroll_test.go @@ -292,7 +292,7 @@ func TestScrollPaintsOnWholeLogicalPixels(t *testing.T) { } // ScrollState.Key is the keyboard's counterpart of Wheel: a page that owns an -// area's focus moves it with the arrow keys, a viewport at a time with PageUp and +// area's focus moves it with the arrow keys, a page at a time with PageUp and // PageDown, and to either end with Home and End, never past them. func TestScrollStateKeyScrollsWithinItsContent(t *testing.T) { var view View @@ -304,7 +304,7 @@ func TestScrollStateKeyScrollsWithinItsContent(t *testing.T) { }{ {gfx.KeyDown, 32}, {gfx.KeyUp, 0}, - {gfx.KeyPageDown, 90}, + {gfx.KeyPageDown, gfx.ScrollPage(state.Viewport)}, {gfx.KeyPageUp, 0}, {gfx.KeyEnd, 200}, {gfx.KeyHome, 0}, @@ -324,8 +324,8 @@ func TestScrollStateKeyScrollsWithinItsContent(t *testing.T) { if result := state.Key(gfx.KeyEvent{Key: gfx.KeyDown, Release: true}, 32); result.Handled || state.Offset != 0 { t.Errorf("a key release moved the area to %v, handled %v", state.Offset, result.Handled) } - if result := state.Key(gfx.KeyEvent{Key: gfx.KeyPageDown}, 32); result.Handled && state.Offset != 90 { - t.Errorf("a zero step paged to %v, want 90", state.Offset) + if result := state.Key(gfx.KeyEvent{Key: gfx.KeyPageDown}, 32); result.Handled && state.Offset != gfx.ScrollPage(state.Viewport) { + t.Errorf("a zero step paged to %v, want %v", state.Offset, gfx.ScrollPage(state.Viewport)) } state.ScrollTo(state.Max()) if result := state.Key(gfx.KeyEvent{Key: gfx.KeyDown}, 32); !result.Handled || result.Repaint { @@ -369,19 +369,21 @@ func TestAWheelPageMovesTheAreasOwnPage(t *testing.T) { state := view.ScrollState(listID) window := gfx.Size{Width: 800, Height: 1000} // The system asks for a screen per notch: the event's delta is a screen of - // the window, and the area moves a screen of its own instead. + // the window, and the area moves a page of its own instead, short of its + // whole viewport so the edge it leaves stays in view. if result := state.Wheel(gfx.ScrollEvent{DeltaY: 1000, Pages: 1, Viewport: window}); !result.Handled { t.Fatal("a page notch was not handled") } - if state.Offset != 100 { - t.Fatalf("one page notch moved the area to %v, want its own page 100, not the window's", state.Offset) + page := state.Offset + if page <= state.Viewport/2 || page >= state.Viewport { + t.Fatalf("one page notch moved the area %v of its %v viewport, want most of it with an overlap, not the window's", page, state.Viewport) } state.Wheel(gfx.ScrollEvent{DeltaY: 1000, Pages: 1, Viewport: window}) - if state.Offset != 200 { - t.Fatalf("the second page notch left the area at %v, want 200", state.Offset) + if state.Offset != 2*page { + t.Fatalf("the second page notch left the area at %v, want %v", state.Offset, 2*page) } state.Wheel(gfx.ScrollEvent{DeltaY: -1000, Pages: -1, Viewport: window}) - if state.Offset != 100 { - t.Fatalf("a page notch up left the area at %v, want 100", state.Offset) + if state.Offset != page { + t.Fatalf("a page notch up left the area at %v, want %v", state.Offset, page) } } diff --git a/gfx/input.go b/gfx/input.go index 4bdc1eeed..98456f5fc 100644 --- a/gfx/input.go +++ b/gfx/input.go @@ -298,9 +298,9 @@ func (e ScrollEvent) StepY(unit float32) float32 { // StepYIn is StepY for content of unit-sized rows inside a scroll region whose // visible height is viewport. When the system asks for whole screens, the notch -// moves as many of the region's pages as Pages says, rounded down to whole rows, -// rather than the window-sized distance DeltaY carries; that is one screen of -// the region, which is a screen of the rows a user sees in it. +// moves as many of the region's pages, ScrollPage of its viewport, as Pages +// says, rounded down to whole rows, rather than the window-sized distance +// DeltaY carries; the rows at the edge it leaves stay in view at the other. func (e ScrollEvent) StepYIn(unit, viewport float32) float32 { if e.Pages == 0 || unit <= 0 || e.DeltaY == 0 { return e.StepY(unit) @@ -322,13 +322,21 @@ func (e ScrollEvent) StepXIn(unit, viewport float32) float32 { return pageStep(e.DeltaX, e.Pages, unit, viewport) } +// ScrollPage is how far a page of scrolling moves a region whose visible extent +// along the axis is viewport: seven eighths of it, as browsers page, so the +// last lines of one page are still in view at the top of the next and a reader +// keeps their place. A page key and a wheel set to whole screens both move it. +func ScrollPage(viewport float32) float32 { + return max(viewport, 0) * 7 / 8 +} + // pageStep is how far pages of a region of viewport units-by-unit move it in the // direction of delta. func pageStep(delta, pages, unit, viewport float32) float32 { if pages < 0 { pages = -pages } - units := float32(int(pages * viewport / unit)) + units := float32(int(pages * ScrollPage(viewport) / unit)) if units < 1 { units = 1 } diff --git a/gfx/scroll_test.go b/gfx/scroll_test.go index cd05518fb..a5e0da234 100644 --- a/gfx/scroll_test.go +++ b/gfx/scroll_test.go @@ -26,30 +26,58 @@ func TestScrollStepRaisesClassicWheelToOneUnit(t *testing.T) { func TestPageStepMovesOnePageOfTheRegion(t *testing.T) { // A page notch reports the window as pixels and the region's own page is - // what moves: whole rows that fit in the region, not the window's. + // what moves: whole rows of the region, not the window's, and fewer than it + // shows, so the rows at the edge it leaves are still in view. cases := []struct { name string event ScrollEvent unit float32 view float32 - want float32 }{ - {"a page down in a short list", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 300, 300}, - {"a page up in a short list", ScrollEvent{DeltaY: -900, Pages: -1}, 30, 300, -300}, - {"rows that do not fit whole are left out", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 305, 300}, - {"two pages", ScrollEvent{DeltaY: 1800, Pages: 2}, 24, 200, 384}, - {"half a page of a trackpad setting", ScrollEvent{DeltaY: 450, Pages: 0.5}, 24, 200, 96}, - {"a region shorter than one row still moves a row", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 10, 30}, - {"a line notch is not a page", ScrollEvent{DeltaY: 48}, 30, 300, 48}, - {"a zero viewport keeps a row", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 0, 30}, + {"a page down in a short list", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 300}, + {"a page up in a short list", ScrollEvent{DeltaY: -900, Pages: -1}, 30, 300}, + {"rows that do not fit whole", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 305}, + {"a terminal screen", ScrollEvent{DeltaY: -900, Pages: -1}, 17, 40 * 17}, + {"a two-row region", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 60}, + {"a pane in pixels", ScrollEvent{DeltaY: 900, Pages: 1}, 1, 420}, } for _, c := range cases { - if got := c.event.StepYIn(c.unit, c.view); got != c.want { - t.Errorf("%s: StepYIn(%v, %v) = %v, want %v", c.name, c.unit, c.view, got, c.want) + got := c.event.StepYIn(c.unit, c.view) + if (got < 0) != (c.event.DeltaY < 0) { + t.Errorf("%s: StepYIn = %v, against the direction of %v", c.name, got, c.event.DeltaY) + } + step := got + if step < 0 { + step = -step + } + if rows := step / c.unit; rows != float32(int(rows)) { + t.Errorf("%s: StepYIn = %v, not whole rows of %v", c.name, got, c.unit) + } + if step >= c.view || step < c.view/2 { + t.Errorf("%s: StepYIn = %v, want most of the %v viewport with an overlap", c.name, got, c.view) + } + if step != float32(int(ScrollPage(c.view)/c.unit))*c.unit { + t.Errorf("%s: StepYIn = %v, not the rows of ScrollPage(%v)", c.name, got, c.view) } } - if got := (ScrollEvent{DeltaX: 900, Pages: 1}).StepXIn(10, 50); got != 50 { - t.Errorf("StepXIn = %v, want 50", got) + one := (ScrollEvent{DeltaY: 900, Pages: 1}).StepYIn(24, 200) + if two := (ScrollEvent{DeltaY: 1800, Pages: 2}).StepYIn(24, 200); two < 2*one || two > 2*one+24 { + t.Errorf("two pages = %v, want twice a page of %v", two, one) + } + if half := (ScrollEvent{DeltaY: 450, Pages: 0.5}).StepYIn(24, 200); half <= 0 || half > one { + t.Errorf("half a page = %v, want a part of a page of %v", half, one) + } + if got := (ScrollEvent{DeltaY: 900, Pages: 1}).StepYIn(30, 10); got != 30 { + t.Errorf("a region shorter than one row moved %v, want a row of 30", got) + } + if got := (ScrollEvent{DeltaY: 900, Pages: 1}).StepYIn(30, 0); got != 30 { + t.Errorf("a zero viewport moved %v, want a row of 30", got) + } + if got := (ScrollEvent{DeltaY: 48}).StepYIn(30, 300); got != 48 { + t.Errorf("a line notch moved %v, want its own 48", got) + } + if got := (ScrollEvent{DeltaX: 900, Pages: 1}).StepXIn(10, 80); got <= 0 || got >= 80 { + t.Errorf("StepXIn = %v, want most of the 80 width", got) } // A page setting does not turn a horizontal delta into a vertical page. if got := (ScrollEvent{DeltaY: 900, Pages: 1}).StepXIn(10, 50); got != 0 { From 7ac5ef119d3ef2c9244fb372f8da8a8dbb3dea24 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 23:15:33 +0800 Subject: [PATCH 28/29] fix(ui): let ScrollTo leave the end of a following List --- base/list.go | 14 +++++++++-- ui/list_follow_test.go | 54 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/base/list.go b/base/list.go index 6c40cde31..f27fea8fe 100644 --- a/base/list.go +++ b/base/list.go @@ -218,7 +218,9 @@ func (s *ListState) HasFocus() bool { // list has not laid out is placed at the average height of the rows it has, so the // request stays for the paints that show the rows around the target and measure // them, and goes once the offset no longer moves; the list asks for those paints -// itself, and lets the request go if anything else moves the list first. +// itself, and lets the request go if anything else moves the list first. On a list +// that follows its end, a row away from the end leaves the end, as a scroll by the +// user does; ScrollToEnd follows it again. func (s *ListState) ScrollTo(row int, align ListAlign) { kind := listScrollStart switch align { @@ -910,7 +912,9 @@ func (p *Page) ListArea(c C, state *ListState, n int, horizontal bool, row func( id := p.ID(at) // Follow is declared on the area the List returns, after its rows: whether the area // keeps to its end is what the paint before left it, as ScrollState.Pinned says. - pinned := c.f.Scrolls.get(id).pinned() + // ScrollArea forgets whether it follows until that declaration, so it is kept here. + prev := c.f.Scrolls.get(id) + pinned, followed := prev.pinned(), prev.follow area := c.f.ScrollArea(id) p.SetNode(area.i, at) in := &state.list @@ -918,11 +922,17 @@ func (p *Page) ListArea(c C, state *ListState, n int, horizontal bool, row func( state.resize(n) scroll := c.f.Exts[c.f.Nodes[area.i].Ext].scrollState in.Scroll = scroll + // The request settles against the follow the paint before declared: a ScrollTo + // away from the end of a following list leaves the end, as a scroll by the user + // does, instead of the Follow(true) after the rows pulling the list back to it. + scroll.follow = followed if state.applyScrollRequest(c.f) { // The area was declared at the offset it had; the layout reads the node, so it // takes the requested one too, which the rows are placed for below (as ScrollAt). c.f.Nodes[area.i].Scroll = scroll.Offset + pinned = scroll.pinned() } + scroll.follow = false viewport := scroll.Viewport if viewport <= 0 { viewport = c.f.bounds.Height diff --git a/ui/list_follow_test.go b/ui/list_follow_test.go index 8afb14d56..4545dd4a5 100644 --- a/ui/list_follow_test.go +++ b/ui/list_follow_test.go @@ -100,3 +100,57 @@ func TestListFollowReachesTheEndOfALongListItStartsWith(t *testing.T) { t.Fatalf("the last row painted %v (Visible %v, at the end %v)", d.has("row 4999"), visibleOf(&m.list), m.list.AtEnd()) } } + +// ScrollTo on a List that follows its end leaves the end, as a scroll by the user +// does: the request is applied when the list is declared, before the Box it returns +// says Follow(true) again, and the rows that arrive after it do not pull the list +// back to the end. ScrollToEnd follows the end again. +func TestListScrollToLeavesTheEndOfAFollowingList(t *testing.T) { + m := newLogRows(400) + d := openPage(t, followingRows(m)) + settle := func(step string) { + t.Helper() + for frames := 0; d.driver.Transitioning(); frames++ { + if frames == 10 { + t.Fatalf("%s: the list asked for ten paints", step) + } + if err := d.driver.Advance(16 * time.Millisecond); err != nil { + t.Fatal(err) + } + } + d.repaint() + } + d.repaint() + settle("start") + if !m.list.AtEnd() { + t.Fatalf("the following list did not start at its end (Visible %v)", visibleOf(&m.list)) + } + const target = 20 + label := "row " + strconv.Itoa(target) + m.list.ScrollTo(target, ui.ListStart) + d.repaint() + settle("ScrollTo") + if !d.has(label) || m.list.AtEnd() { + t.Fatalf("after ScrollTo(%d) %s painted %v, at the end %v (Visible %v)", target, label, d.has(label), m.list.AtEnd(), visibleOf(&m.list)) + } + area := d.ListArea("Rows") + if top := d.hit(label).Bounds.Y - area.Y; top < -2 || top > 2 { + t.Fatalf("row %d is %v px from the top of the list, want it at the top", target, top) + } + m.n += 5 + d.repaint() + settle("rows arrived") + if !d.has(label) || m.list.AtEnd() { + t.Fatalf("rows that arrived after ScrollTo moved the list: %s painted %v, at the end %v (Visible %v)", label, d.has(label), m.list.AtEnd(), visibleOf(&m.list)) + } + m.list.ScrollToEnd() + d.repaint() + settle("ScrollToEnd") + m.n += 5 + d.repaint() + settle("rows arrived at the end") + last := "row " + strconv.Itoa(m.n-1) + if !d.has(last) || !m.list.AtEnd() { + t.Fatalf("after ScrollToEnd the list did not follow its end: %s painted %v, at the end %v (Visible %v)", last, d.has(last), m.list.AtEnd(), visibleOf(&m.list)) + } +} From a1af7583a5657ba0362c9548f1aa6b5c82f156aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=88=E7=A7=8B?= <49514152+yiqiui@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:19:27 +0800 Subject: [PATCH 29/29] fix(components): let CarouselStepForKey follow the reading direction --- cmd/viva/templates/carousel.go.txt | 96 +++++++++++++++++++++++++---- components/carousel.go | 96 +++++++++++++++++++++++++---- components/carousel_test.go | 98 ++++++++++++++++++++++++++++-- ui/carousel/carousel.go | 23 +++++-- ui/carousel/carousel_test.go | 39 ++++++++++++ 5 files changed, 316 insertions(+), 36 deletions(-) diff --git a/cmd/viva/templates/carousel.go.txt b/cmd/viva/templates/carousel.go.txt index e4a801a59..76f3abac5 100644 --- a/cmd/viva/templates/carousel.go.txt +++ b/cmd/viva/templates/carousel.go.txt @@ -1,6 +1,9 @@ package {{PACKAGE}} -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) // carouselControlOffset is the 16px between the viewport and a button (-left-12 // puts a size-8 button 48px out). @@ -61,6 +64,7 @@ type Carousel struct { contentExtent float32 offset float32 orientation CarouselOrientation + direction Direction previousID gfx.ID previousLabel string nextID gfx.ID @@ -88,6 +92,17 @@ func (carousel Carousel) Vertical() Carousel { return carousel } +// Direction sets the reading direction of a horizontal carousel. The zero +// value is LTR. Under RTL the content reads right to left: the first slide +// sits at the viewport's right edge and the offset reveals slides on its left, +// the previous control stands on the right of the viewport and the next one on +// the left, and a vertical carousel ignores it, since the block axis has no +// reading direction. +func (carousel Carousel) Direction(direction Direction) Carousel { + carousel.direction = direction + return carousel +} + // Controls assigns stable previous and next action IDs and accessible labels. func (carousel Carousel) Controls(previousID gfx.ID, previousLabel string, nextID gfx.ID, nextLabel string) Carousel { carousel.previousID = previousID @@ -104,19 +119,43 @@ func (carousel Carousel) Label(label string) Carousel { } // CarouselStepForKey is the carousel region's keyboard movement: Left/Up go to -// the previous slide, Right/Down to the next, and Home/End to the ends. The -// caller owns the index and does not move past either end. -func CarouselStepForKey(key gfx.Key, index, count int, direction Direction) (int, bool) { +// the previous slide, Right/Down to the next, and Home/End to the ends. In a +// horizontal carousel Left and Right follow the reading direction, as the +// framework's other horizontal roving keys do (TabsKeyDown, CalendarFocusForKey): +// an RTL carousel reads Left as the next slide and Right as the previous one. A +// vertical carousel ignores the direction, as Carousel.Direction says, so its +// Left and Right keep the previous and next meaning. The caller owns the index +// and does not move past either end. +func CarouselStepForKey(key gfx.Key, index, count int, orientation CarouselOrientation, direction Direction) (int, bool) { if count <= 0 || index < 0 || index >= count { return index, false } + rtl := direction.IsRTL() && orientation == CarouselHorizontal switch key { - case gfx.KeyLeft, gfx.KeyUp: + case gfx.KeyLeft: + step := -1 + if rtl { + step = 1 + } + if next := index + step; next >= 0 && next < count { + return next, true + } + return index, true + case gfx.KeyRight: + step := 1 + if rtl { + step = -1 + } + if next := index + step; next >= 0 && next < count { + return next, true + } + return index, true + case gfx.KeyUp: if index > 0 { return index - 1, true } return index, true - case gfx.KeyRight, gfx.KeyDown: + case gfx.KeyDown: if index < count-1 { return index + 1, true } @@ -170,8 +209,7 @@ func (carousel Carousel) Geometry() CarouselGeometry { } geometry := CarouselGeometry{ Bounds: viewport, Viewport: viewport, - Content: gfx.Rect{X: viewport.X - offset, Y: viewport.Y, Width: contentExtent, Height: viewport.Height}, - Offset: offset, MaxOffset: maximum, Index: index, ItemCount: itemCount, + Offset: offset, MaxOffset: maximum, Index: index, ItemCount: itemCount, CanPrevious: !carousel.disabled && itemCount > 0 && index > 0, CanNext: !carousel.disabled && itemCount > 0 && index+1 < itemCount, } @@ -188,20 +226,36 @@ func (carousel Carousel) Geometry() CarouselGeometry { } return geometry } + // LTR content grows to the right and the offset moves it left; RTL content + // grows to the left from the viewport's right edge and the offset moves it + // right, so the logical [offset, offset+viewportExtent] window of the + // content shows through the viewport either way. + contentX := viewport.X - offset + if base.WritingDirection(carousel.direction).IsRTL() { + contentX = viewport.X + offset + viewport.Width - contentExtent + } + geometry.Content = gfx.Rect{X: contentX, Y: viewport.Y, Width: contentExtent, Height: viewport.Height} + // The previous control stands at the content's inline start and the next one + // at its inline end: left and right in LTR, right and left in RTL. + previousX, nextX := viewport.X-carouselControlOffset-controlSize, viewport.X+viewport.Width+carouselControlOffset + if base.WritingDirection(carousel.direction).IsRTL() { + previousX, nextX = nextX, previousX + } geometry.PreviousButton = gfx.Rect{ - X: viewport.X - carouselControlOffset - controlSize, - Y: viewport.Y + (viewport.Height-controlSize)/2, + X: previousX, Y: viewport.Y + (viewport.Height-controlSize)/2, Width: controlSize, Height: controlSize, } geometry.NextButton = gfx.Rect{ - X: viewport.X + viewport.Width + carouselControlOffset, Y: geometry.PreviousButton.Y, + X: nextX, Y: geometry.PreviousButton.Y, Width: controlSize, Height: controlSize, } return geometry } // ItemGeometry translates one caller-supplied slide offset and extent along -// the carousel axis. It does not retain, measure, or virtualize the item. +// the carousel axis, placing it at the reading direction's edge of the content: +// its left edge in LTR and its right edge in RTL. It does not retain, measure, +// or virtualize the item. func (carousel Carousel) ItemGeometry(index int, contentOffset, extent float32) CarouselItemGeometry { geometry := carousel.Geometry() contentOffset = carouselFiniteNonNegative(contentOffset) @@ -210,6 +264,9 @@ func (carousel Carousel) ItemGeometry(index int, contentOffset, extent float32) X: geometry.Content.X + contentOffset, Y: geometry.Content.Y, Width: extent, Height: geometry.Viewport.Height, } + if base.WritingDirection(carousel.direction).IsRTL() && carousel.orientation != CarouselVertical { + bounds.X = geometry.Content.X + geometry.Content.Width - contentOffset - extent + } if carousel.orientation == CarouselVertical { bounds = gfx.Rect{ X: geometry.Content.X, Y: geometry.Content.Y + contentOffset, @@ -274,6 +331,9 @@ func (carousel Carousel) paintControl(bounds gfx.Rect, id gfx.ID, label string, border.Alpha *= 0.50 } carousel.canvas.RoundedBorder(bounds, radius, 1, border, background) + // The arrow points along the reading direction: back toward the previous + // slide's edge and forward toward the next one's, mirrored under RTL. + rtl := base.WritingDirection(carousel.direction).IsRTL() && carousel.orientation != CarouselVertical icon := &carouselArrowRight switch { case carousel.orientation == CarouselVertical && previous: @@ -281,7 +341,17 @@ func (carousel Carousel) paintControl(bounds gfx.Rect, id gfx.ID, label string, case carousel.orientation == CarouselVertical: icon = &carouselArrowDown case previous: - icon = &carouselArrowLeft + if rtl { + icon = &carouselArrowRight + } else { + icon = &carouselArrowLeft + } + default: + if rtl { + icon = &carouselArrowLeft + } else { + icon = &carouselArrowRight + } } paintChevronSized(carousel.canvas, icon, bounds, 16, foreground) carousel.canvas.HitWithOptions(id, bounds, label, gfx.HitOptions{ diff --git a/components/carousel.go b/components/carousel.go index 7a33e6bc2..f540b9572 100644 --- a/components/carousel.go +++ b/components/carousel.go @@ -1,6 +1,9 @@ package components -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) // carouselControlOffset is the 16px between the viewport and a button (-left-12 // puts a size-8 button 48px out). @@ -61,6 +64,7 @@ type Carousel struct { contentExtent float32 offset float32 orientation CarouselOrientation + direction Direction previousID gfx.ID previousLabel string nextID gfx.ID @@ -88,6 +92,17 @@ func (carousel Carousel) Vertical() Carousel { return carousel } +// Direction sets the reading direction of a horizontal carousel. The zero +// value is LTR. Under RTL the content reads right to left: the first slide +// sits at the viewport's right edge and the offset reveals slides on its left, +// the previous control stands on the right of the viewport and the next one on +// the left, and a vertical carousel ignores it, since the block axis has no +// reading direction. +func (carousel Carousel) Direction(direction Direction) Carousel { + carousel.direction = direction + return carousel +} + // Controls assigns stable previous and next action IDs and accessible labels. func (carousel Carousel) Controls(previousID gfx.ID, previousLabel string, nextID gfx.ID, nextLabel string) Carousel { carousel.previousID = previousID @@ -104,19 +119,43 @@ func (carousel Carousel) Label(label string) Carousel { } // CarouselStepForKey is the carousel region's keyboard movement: Left/Up go to -// the previous slide, Right/Down to the next, and Home/End to the ends. The -// caller owns the index and does not move past either end. -func CarouselStepForKey(key gfx.Key, index, count int, direction Direction) (int, bool) { +// the previous slide, Right/Down to the next, and Home/End to the ends. In a +// horizontal carousel Left and Right follow the reading direction, as the +// framework's other horizontal roving keys do (TabsKeyDown, CalendarFocusForKey): +// an RTL carousel reads Left as the next slide and Right as the previous one. A +// vertical carousel ignores the direction, as Carousel.Direction says, so its +// Left and Right keep the previous and next meaning. The caller owns the index +// and does not move past either end. +func CarouselStepForKey(key gfx.Key, index, count int, orientation CarouselOrientation, direction Direction) (int, bool) { if count <= 0 || index < 0 || index >= count { return index, false } + rtl := direction.IsRTL() && orientation == CarouselHorizontal switch key { - case gfx.KeyLeft, gfx.KeyUp: + case gfx.KeyLeft: + step := -1 + if rtl { + step = 1 + } + if next := index + step; next >= 0 && next < count { + return next, true + } + return index, true + case gfx.KeyRight: + step := 1 + if rtl { + step = -1 + } + if next := index + step; next >= 0 && next < count { + return next, true + } + return index, true + case gfx.KeyUp: if index > 0 { return index - 1, true } return index, true - case gfx.KeyRight, gfx.KeyDown: + case gfx.KeyDown: if index < count-1 { return index + 1, true } @@ -170,8 +209,7 @@ func (carousel Carousel) Geometry() CarouselGeometry { } geometry := CarouselGeometry{ Bounds: viewport, Viewport: viewport, - Content: gfx.Rect{X: viewport.X - offset, Y: viewport.Y, Width: contentExtent, Height: viewport.Height}, - Offset: offset, MaxOffset: maximum, Index: index, ItemCount: itemCount, + Offset: offset, MaxOffset: maximum, Index: index, ItemCount: itemCount, CanPrevious: !carousel.disabled && itemCount > 0 && index > 0, CanNext: !carousel.disabled && itemCount > 0 && index+1 < itemCount, } @@ -188,20 +226,36 @@ func (carousel Carousel) Geometry() CarouselGeometry { } return geometry } + // LTR content grows to the right and the offset moves it left; RTL content + // grows to the left from the viewport's right edge and the offset moves it + // right, so the logical [offset, offset+viewportExtent] window of the + // content shows through the viewport either way. + contentX := viewport.X - offset + if base.WritingDirection(carousel.direction).IsRTL() { + contentX = viewport.X + offset + viewport.Width - contentExtent + } + geometry.Content = gfx.Rect{X: contentX, Y: viewport.Y, Width: contentExtent, Height: viewport.Height} + // The previous control stands at the content's inline start and the next one + // at its inline end: left and right in LTR, right and left in RTL. + previousX, nextX := viewport.X-carouselControlOffset-controlSize, viewport.X+viewport.Width+carouselControlOffset + if base.WritingDirection(carousel.direction).IsRTL() { + previousX, nextX = nextX, previousX + } geometry.PreviousButton = gfx.Rect{ - X: viewport.X - carouselControlOffset - controlSize, - Y: viewport.Y + (viewport.Height-controlSize)/2, + X: previousX, Y: viewport.Y + (viewport.Height-controlSize)/2, Width: controlSize, Height: controlSize, } geometry.NextButton = gfx.Rect{ - X: viewport.X + viewport.Width + carouselControlOffset, Y: geometry.PreviousButton.Y, + X: nextX, Y: geometry.PreviousButton.Y, Width: controlSize, Height: controlSize, } return geometry } // ItemGeometry translates one caller-supplied slide offset and extent along -// the carousel axis. It does not retain, measure, or virtualize the item. +// the carousel axis, placing it at the reading direction's edge of the content: +// its left edge in LTR and its right edge in RTL. It does not retain, measure, +// or virtualize the item. func (carousel Carousel) ItemGeometry(index int, contentOffset, extent float32) CarouselItemGeometry { geometry := carousel.Geometry() contentOffset = carouselFiniteNonNegative(contentOffset) @@ -210,6 +264,9 @@ func (carousel Carousel) ItemGeometry(index int, contentOffset, extent float32) X: geometry.Content.X + contentOffset, Y: geometry.Content.Y, Width: extent, Height: geometry.Viewport.Height, } + if base.WritingDirection(carousel.direction).IsRTL() && carousel.orientation != CarouselVertical { + bounds.X = geometry.Content.X + geometry.Content.Width - contentOffset - extent + } if carousel.orientation == CarouselVertical { bounds = gfx.Rect{ X: geometry.Content.X, Y: geometry.Content.Y + contentOffset, @@ -274,6 +331,9 @@ func (carousel Carousel) paintControl(bounds gfx.Rect, id gfx.ID, label string, border.Alpha *= 0.50 } carousel.canvas.RoundedBorder(bounds, radius, 1, border, background) + // The arrow points along the reading direction: back toward the previous + // slide's edge and forward toward the next one's, mirrored under RTL. + rtl := base.WritingDirection(carousel.direction).IsRTL() && carousel.orientation != CarouselVertical icon := &carouselArrowRight switch { case carousel.orientation == CarouselVertical && previous: @@ -281,7 +341,17 @@ func (carousel Carousel) paintControl(bounds gfx.Rect, id gfx.ID, label string, case carousel.orientation == CarouselVertical: icon = &carouselArrowDown case previous: - icon = &carouselArrowLeft + if rtl { + icon = &carouselArrowRight + } else { + icon = &carouselArrowLeft + } + default: + if rtl { + icon = &carouselArrowLeft + } else { + icon = &carouselArrowRight + } } paintChevronSized(carousel.canvas, icon, bounds, 16, foreground) carousel.canvas.HitWithOptions(id, bounds, label, gfx.HitOptions{ diff --git a/components/carousel_test.go b/components/carousel_test.go index 158ec10e2..7e1c38727 100644 --- a/components/carousel_test.go +++ b/components/carousel_test.go @@ -22,6 +22,55 @@ func TestCarouselHorizontalGeometryClampsIndexOffsetAndItems(t *testing.T) { } } +// An RTL carousel mirrors the layout: the first slide sits at the viewport's +// right edge, the offset reveals slides on its left, the previous control +// stands on the right of the viewport and the next one on the left, and the +// arrows point back the other way. The selected slide still fills the viewport. +func TestCarouselRTLGeometryMirrorsTheReadingDirection(t *testing.T) { + var canvas gfx.Canvas + carousel := BeginCarousel(&canvas, gfx.LightTheme(), gfx.Rect{X: 100, Y: 40, Width: 300, Height: 180}, 3, 1). + Content(900, 300).Direction(RTL).Controls(gfx.Item(41), "Previous slide", gfx.Item(42), "Next slide") + geometry := carousel.BeginContent() + // Offset 300 shows the second slide: its content window [300, 600) lands on + // the viewport [100, 400), and the content's right edge — the first slide's + // inline start — stands 300 past the viewport's right edge, at x=700. + if geometry.Content.X != 100+300+300-900 || geometry.Content.Width != 900 { + t.Fatalf("RTL content = %+v, want X %v", geometry.Content, 100+300+300-900) + } + first := carousel.ItemGeometry(0, 0, 300) + if first.Bounds.X != 400 || first.Bounds.X+first.Bounds.Width != 700 || first.Visible { + t.Fatalf("RTL first slide = %+v, want it outside the right edge at [400, 700)", first.Bounds) + } + second := carousel.ItemGeometry(1, 300, 300) + if second.Bounds != geometry.Viewport || !second.Visible || !second.Selected { + t.Fatalf("RTL selected slide = %+v viewport=%+v", second.Bounds, geometry.Viewport) + } + third := carousel.ItemGeometry(2, 600, 300) + if third.Bounds.X != -200 || third.Visible { + t.Fatalf("RTL last slide = %+v, want it outside the left edge at [-200, 100)", third.Bounds) + } + // The controls swap sides: previous on the right of the viewport, next on + // the left, and each arrow points back toward its own slide. + if geometry.PreviousButton.X != geometry.Viewport.X+geometry.Viewport.Width+carouselControlOffset { + t.Fatalf("RTL previous button = %+v, want it right of the viewport", geometry.PreviousButton) + } + if geometry.NextButton.X+geometry.NextButton.Width+carouselControlOffset != geometry.Viewport.X { + t.Fatalf("RTL next button = %+v, want it left of the viewport", geometry.NextButton) + } + carousel.EndContent() + hits := canvas.Hits() + if len(hits) != 2 || hits[0].Bounds != geometry.PreviousButton || hits[1].Bounds != geometry.NextButton { + t.Fatalf("RTL control hits = %+v geometry=%+v", hits, geometry) + } + // Vertical keeps its own axis: the direction does not move anything. + vertical := BeginCarousel(nil, gfx.LightTheme(), gfx.Rect{X: 50, Y: 60, Width: 180, Height: 240}, 3, 1). + Content(900, 300).Vertical().Direction(RTL) + verticalGeometry := vertical.Geometry() + if verticalGeometry.Content.Y != 60-300 || verticalGeometry.PreviousButton.X != 50+(180-verticalGeometry.PreviousButton.Width)/2 { + t.Fatalf("RTL vertical carousel = %+v", verticalGeometry) + } +} + func TestCarouselVerticalGeometryAndClipping(t *testing.T) { var canvas gfx.Canvas carousel := BeginCarousel(&canvas, gfx.LightTheme(), gfx.Rect{X: 50, Y: 60, Width: 180, Height: 240}, 4, 1). @@ -87,19 +136,58 @@ func TestCarouselDeterministicStreamAndNoRepeatedPaintAllocations(t *testing.T) // The carousel region moves one slide with the arrows and to the ends with // Home/End, without wrapping. func TestCarouselStepForKey(t *testing.T) { - if next, ok := CarouselStepForKey(gfx.KeyRight, 0, 3, LTR); !ok || next != 1 { + if next, ok := CarouselStepForKey(gfx.KeyRight, 0, 3, CarouselHorizontal, LTR); !ok || next != 1 { t.Fatalf("Right = %v, %v", next, ok) } - if next, ok := CarouselStepForKey(gfx.KeyLeft, 0, 3, LTR); !ok || next != 0 { + if next, ok := CarouselStepForKey(gfx.KeyLeft, 0, 3, CarouselHorizontal, LTR); !ok || next != 0 { t.Fatalf("Left at start = %v, %v", next, ok) } - if next, ok := CarouselStepForKey(gfx.KeyEnd, 0, 3, LTR); !ok || next != 2 { + if next, ok := CarouselStepForKey(gfx.KeyEnd, 0, 3, CarouselHorizontal, LTR); !ok || next != 2 { t.Fatalf("End = %v, %v", next, ok) } - if next, ok := CarouselStepForKey(gfx.KeyHome, 2, 3, LTR); !ok || next != 0 { + if next, ok := CarouselStepForKey(gfx.KeyHome, 2, 3, CarouselHorizontal, LTR); !ok || next != 0 { t.Fatalf("Home = %v, %v", next, ok) } - if _, ok := CarouselStepForKey(gfx.KeyEnter, 0, 3, LTR); ok { + if _, ok := CarouselStepForKey(gfx.KeyEnter, 0, 3, CarouselHorizontal, LTR); ok { t.Fatal("Enter is not a carousel movement") } } + +// An RTL carousel reads right to left: Left shows the next slide and Right the +// previous one, while the vertical keys and the ends keep their meaning. +func TestCarouselStepForKeyFollowsTheReadingDirection(t *testing.T) { + if next, ok := CarouselStepForKey(gfx.KeyLeft, 1, 3, CarouselHorizontal, RTL); !ok || next != 2 { + t.Fatalf("RTL Left = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyRight, 1, 3, CarouselHorizontal, RTL); !ok || next != 0 { + t.Fatalf("RTL Right = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyLeft, 2, 3, CarouselHorizontal, RTL); !ok || next != 2 { + t.Fatalf("RTL Left at the last slide = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyRight, 0, 3, CarouselHorizontal, RTL); !ok || next != 0 { + t.Fatalf("RTL Right at the first slide = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyUp, 1, 3, CarouselHorizontal, RTL); !ok || next != 0 { + t.Fatalf("RTL Up = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyDown, 1, 3, CarouselHorizontal, RTL); !ok || next != 2 { + t.Fatalf("RTL Down = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyHome, 2, 3, CarouselHorizontal, RTL); !ok || next != 0 { + t.Fatalf("RTL Home = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyEnd, 0, 3, CarouselHorizontal, RTL); !ok || next != 2 { + t.Fatalf("RTL End = %v, %v", next, ok) + } + // A vertical carousel ignores the direction: Left and Right keep the previous + // and next meaning whichever direction the caller passes. + for _, direction := range []Direction{LTR, RTL} { + if next, ok := CarouselStepForKey(gfx.KeyLeft, 1, 3, CarouselVertical, direction); !ok || next != 0 { + t.Fatalf("vertical %v Left = %v, %v", direction, next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyRight, 1, 3, CarouselVertical, direction); !ok || next != 2 { + t.Fatalf("vertical %v Right = %v, %v", direction, next, ok) + } + } +} diff --git a/ui/carousel/carousel.go b/ui/carousel/carousel.go index ccd56eba2..78a10edba 100644 --- a/ui/carousel/carousel.go +++ b/ui/carousel/carousel.go @@ -56,6 +56,11 @@ type Geometry = components.CarouselGeometry type State struct { // Orientation selects the content axis. The zero value is horizontal. Orientation components.CarouselOrientation + // Direction sets the reading direction of a horizontal carousel. The zero + // value is LTR. Under RTL the slides read right to left, the offset reveals + // slides on the left of the first one, and the previous and next controls + // swap sides; see components.Carousel.Direction. + Direction components.Direction // ItemCount is the number of caller-owned slides. ItemCount int // Index is the selected slide. It is clamped by the component. @@ -170,6 +175,9 @@ func (c *State) draw(d *ui.DrawContext) { if c.Orientation == components.CarouselVertical { strip = strip.Vertical() } + if c.Direction != 0 { + strip = strip.Direction(c.Direction) + } if c.Disabled { strip = strip.Disabled() } @@ -187,10 +195,11 @@ func (c *State) draw(d *ui.DrawContext) { func (c *State) Geometry() components.CarouselGeometry { return c.geometry } // ItemBounds maps one slide of an evenly divided content extent to page -// coordinates: Index along the axis, the viewport extent across it. It returns -// an empty rectangle for an index outside the item count. Use it in Draw for -// the common one-slide-per-view layout; a caller with items of different -// extents maps them from Geometry.Content instead. +// coordinates: Index along the axis at the reading direction's edge of the +// content — its left in LTR and its right in RTL — and the viewport extent +// across it. It returns an empty rectangle for an index outside the item count. +// Use it in Draw for the common one-slide-per-view layout; a caller with items +// of different extents maps them from Geometry.Content instead. func (c *State) ItemBounds(geometry components.CarouselGeometry, index int) gfx.Rect { if index < 0 || index >= c.ItemCount || c.ItemCount <= 0 { return gfx.Rect{} @@ -207,8 +216,12 @@ func (c *State) ItemBounds(geometry components.CarouselGeometry, index int) gfx. Width: geometry.Viewport.Width, Height: itemExtent, } } + x := content.X + float32(index)*itemExtent + if c.Direction.IsRTL() { + x = content.X + content.Width - float32(index+1)*itemExtent + } return gfx.Rect{ - X: content.X + float32(index)*itemExtent, Y: content.Y, + X: x, Y: content.Y, Width: itemExtent, Height: geometry.Viewport.Height, } } diff --git a/ui/carousel/carousel_test.go b/ui/carousel/carousel_test.go index 66c73504b..2d1638351 100644 --- a/ui/carousel/carousel_test.go +++ b/ui/carousel/carousel_test.go @@ -3,6 +3,7 @@ package carousel_test import ( "testing" + "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/carousel" @@ -145,6 +146,44 @@ func TestViewPaintsGeometryAndRoutesInput(t *testing.T) { } } +// An RTL state mirrors the placed slides and the controls: the selected slide +// keeps the viewport, the first slide stands at the viewport's right edge, and +// the previous control stands right of the viewport with the next one on its +// left. +func TestRTLDirectionMirrorsSlidesAndControls(t *testing.T) { + m := new(model) + m.open(t, carousel.Horizontal) + m.view.Direction = components.RTL + draw(m.page, m.canvas, m.viewPage) + + geometry := m.view.Geometry() + if geometry.Content.Width != 960 || geometry.Offset != 320 { + t.Fatalf("RTL content = %+v offset %g, want 960 and 320", geometry.Content, geometry.Offset) + } + // The selected slide still fills the viewport; the first one sits entirely + // to the right of it and the last one entirely to its left. + selected := m.view.ItemBounds(geometry, 1) + if selected != geometry.Viewport { + t.Fatalf("RTL selected slide = %+v, want the viewport", selected) + } + first := m.view.ItemBounds(geometry, 0) + if first.X != geometry.Viewport.X+geometry.Viewport.Width || first.Width != 320 { + t.Fatalf("RTL first slide = %+v, want one viewport right of it", first) + } + last := m.view.ItemBounds(geometry, 2) + if last.X+last.Width != geometry.Viewport.X { + t.Fatalf("RTL last slide = %+v, want one viewport left of it", last) + } + previous := hit(t, m.canvas, "Previous slide") + next := hit(t, m.canvas, "Next slide") + if previous.Bounds.X < geometry.Viewport.X+geometry.Viewport.Width { + t.Fatalf("RTL previous control = %+v, want it right of the viewport", previous.Bounds) + } + if next.Bounds.X+next.Bounds.Width > geometry.Viewport.X { + t.Fatalf("RTL next control = %+v, want it left of the viewport", next.Bounds) + } +} + // A click on a navigation control is read with Clicked after View, and a // different identity is not reported. func TestViewReportsClicksForCallerIdentities(t *testing.T) {