From 18b303811917c66e95865410e899aaec692affb7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 21 Nov 2026 00:48:41 +0800 Subject: [PATCH 01/16] feat(ui): drive buttons from the engine and link declared controls Keep a Button a Button when it is given Children, so its identity, focus, disabled state, hit options and keyboard behavior survive caller content; give the engine the recipe defaults the painter used to compute (explicit FontSize and Weight, Pad per side, recipe order, content clipping, inherited content color, baseline through the content) so the default label and Children agree. Install a control's painter and measurer as the page declares it instead of installing every control from ui's init: a page links only the controls it uses. A direct host of package base calls ui.InstallPainters, and a control declared without an installation now stops with a diagnostic naming it rather than laying out or painting as nothing. Release hello sizes fall from the parent commit: darwin/arm64 4,325,346 to 4,176,498, linux/amd64 5,583,077 to 5,386,469, windows/amd64 5,262,336 to 5,073,920, removing the 16,528-byte step the Button migration added. See ../motty for the companion CI revision pin. --- base/baseline_test.go | 37 +++++ base/box.go | 16 +- base/button_contract_test.go | 123 ++++++++++++++++ base/elements.go | 5 +- base/frame.go | 19 ++- base/layout.go | 65 ++++++-- base/paint.go | 90 ++++++++++- base/painter_install_test.go | 88 +++++++++++ base/recipe.go | 87 +++++++---- base/style.go | 6 + cmd/viva/templates/button.go.txt | 50 +++---- cmd/viva/templates/select.go.txt | 12 +- components/button.go | 50 +++---- docs/upgrading.md | 8 + gfx/replay.go | 10 ++ ui/app_facade.go | 1 + ui/controls_baseline.go | 13 +- ui/controls_paint.go | 246 ++++++++++++++++++------------- ui/doc.go | 4 +- ui/facade.go | 43 +++--- ui/hooks_install.go | 130 +++++++++++++--- 21 files changed, 841 insertions(+), 262 deletions(-) create mode 100644 base/button_contract_test.go create mode 100644 base/painter_install_test.go diff --git a/base/baseline_test.go b/base/baseline_test.go index aab690d63..a1f8734d2 100644 --- a/base/baseline_test.go +++ b/base/baseline_test.go @@ -41,6 +41,43 @@ func TestButtonBaselineMatchesItsLabelRow(t *testing.T) { } } +// Caller-owned button content keeps its actual text baseline when a row asks +// for baseline alignment, rather than using the bottom edge of the button. +func TestButtonChildrenBaselineMatchesItsText(t *testing.T) { + canvas := testCanvas() + var view View + var sibling, label Box + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 80}) + f.Row().Height(80).Items(Baseline).Children(func() { + sibling = f.Text("Text").FontSize(20) + f.Button(save, "Save").FontSize(20).Children(func() { + label = f.Text("Save") + }) + }) + f.End() + got := canvas.LabelBaseline(label.Rect(), gfx.TextStyle{Size: 20}) + want := canvas.LabelBaseline(sibling.Rect(), gfx.TextStyle{Size: 20}) + if d := got - want; d > 0.01 || d < -0.01 { + t.Fatalf("caller-owned button text baseline %v, sibling baseline %v", got, want) + } +} + +func TestDisabledButtonCannotAutofocusDescendants(t *testing.T) { + var view View + f := view.Begin(testCanvas(), gfx.LightTheme(), gfx.Rect{Width: 400, Height: 80}) + blocked, available := gfx.Item(101), gfx.Item(102) + row := f.Row().Children(func() { + f.Button(save, "Disabled").Disabled(true).Children(func() { + f.Button(blocked, "Nested") + }) + f.Button(available, "Available") + }) + if got := f.FirstControl(row.i); got != available { + t.Fatalf("dialog autofocus candidate = %v, want enabled sibling %v", got, available) + } + f.End() +} + // A Mono text stands on its own font's baseline and a proportional one on // LabelBaseline's row; Baseline alignment lines the two rows up anyway, so a // code line and the prose beside it share one baseline. diff --git a/base/box.go b/base/box.go index 8a419b5d9..e92d88d9e 100644 --- a/base/box.go +++ b/base/box.go @@ -43,12 +43,10 @@ const ( // the button's row, with the theme's look, its focus and its keyboard, around content of // the caller's own, and Pad, Gap, Items and the rest are the row's. func (b Box) Children(fn func()) Box { - if b.N().Kind == kindButton { - b.f.buttonHoldsChildren(b.i) - } + n := b.N() saved := b.f.Parent b.f.Parent = b.i - b.N().Flags |= flagChildren + n.Flags |= flagChildren fn() b.f.Parent = saved return b @@ -69,7 +67,7 @@ func (b Box) Clicked() bool { if n.Ext != 0 && b.f.Exts[n.Ext].bind != 0 { b.f.settleFn(b.f, b.i) // a bound value is written before the caller reads it } - return b.f.Surface != nil && n.Flags&flagVeto == 0 && b.f.Surface.Clicked(n.ID) + return b.f.Surface != nil && n.Flags&flagVeto == 0 && b.f.Surface.Clicked(n.ID) && !b.f.Disabled(n) } // Hit makes the element's whole rectangle a pointer target named id, with the @@ -325,13 +323,17 @@ func (b Box) Clip() Box { b.N().Flags |= flagClip; return b } // place of the theme's body size. func (b Box) FontSize(v float32) Box { n := b.N() - n.FontSize = v + n.FontSize, n.FontSet = v, v > 0 if n.Kind == kindSelect { b.f.sizeSelectList(n) } return b } -func (b Box) Weight(v float32) Box { b.N().Weight = v; return b } +func (b Box) Weight(v float32) Box { + n := b.N() + n.Weight, n.WeightSet = v, true + return b +} // LineHeight sets the height of each line of a Text or Paragraph, in pixels: the // default is the font size plus seven, as in the components. diff --git a/base/button_contract_test.go b/base/button_contract_test.go new file mode 100644 index 000000000..d9eb7af2b --- /dev/null +++ b/base/button_contract_test.go @@ -0,0 +1,123 @@ +package base_test + +import ( + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +func TestButtonChildrenInheritTypographyWithoutLosingIdentity(t *testing.T) { + plain := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Label").FontSize(24).Weight(gfx.WeightBold) }) + children := probeButton(t, nil, func(f *Frame) Box { + return f.Button(save, "Label").FontSize(24).Weight(gfx.WeightBold).Children(func() { f.Text("Label") }) + }) + if plain.box != children.box || plain.label.Style.Size != children.label.Style.Size || plain.label.Style.Weight != children.label.Style.Weight { + t.Fatalf("default and Children disagree: plain %v %+v, children %v %+v", plain.box, plain.label.Style, children.box, children.label.Style) + } + own := probeButton(t, nil, func(f *Frame) Box { + return f.Button(save, "Label").FontSize(24).Weight(gfx.WeightBold).Children(func() { f.Text("Label").FontSize(12).Weight(gfx.WeightRegular) }) + }) + if own.label.Style.Size != 12 || own.label.Style.Weight != gfx.WeightRegular { + t.Fatalf("explicit child typography ignored: %+v", own.label.Style) + } +} + +func TestButtonRecipeDoesNotDependOnChildrenOrder(t *testing.T) { + green := gfx.Color{Green: 1, Alpha: 1} + recipe := func(theme gfx.Theme, v style.Variant, s gfx.State) style.ButtonLook { + look := components.ButtonRecipe(theme, v, s) + look.Background = green + return look + } + a := probeButton(t, nil, func(f *Frame) Box { + return f.Button(save, "Label").ButtonRecipe(recipe).Children(func() { f.Text("Label") }) + }) + b := probeButton(t, nil, func(f *Frame) Box { + return f.Button(save, "Label").Children(func() { f.Text("Label") }).ButtonRecipe(recipe) + }) + if a.canvas.Rectangles()[0].Color != green || b.canvas.Rectangles()[0].Color != green { + t.Fatal("Children changed the button's recipe eligibility") + } +} + +func TestButtonCanExplicitlyUseRegularWeight(t *testing.T) { + p := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Label").Weight(gfx.WeightRegular) }) + if p.label.Style.Weight != gfx.WeightRegular { + t.Fatalf("regular weight is a choice, got %v", p.label.Style.Weight) + } +} + +func TestButtonHitOptionsSurviveDefaultAndCustomContent(t *testing.T) { + for _, children := range []bool{false, true} { + p := probeButton(t, nil, func(f *Frame) Box { + b := f.Button(save, "Label").HitWith(save, "Label", gfx.HitOptions{Role: gfx.RoleButton, Selected: true, Hint: "details"}) + if children { + b = b.Children(func() { f.Text("Label") }) + } + return b + }) + hits := p.canvas.Hits() + if len(hits) != 1 || !hits[0].Selected || hits[0].Hint != "details" { + t.Fatalf("children=%v: %+v", children, hits) + } + } +} + +func TestButtonClipsOverflowInsideItsContentArea(t *testing.T) { + for _, children := range []bool{false, true} { + p := probeButton(t, nil, func(f *Frame) Box { + b := f.Button(save, "Long label").Width(20).PadX(4) + if children { + b = b.Children(func() { f.Text("Long label") }) + } + return b + }) + for _, text := range p.canvas.Texts() { + if !text.HasClip || text.ClipOf.X <= p.box.X || text.ClipOf.Right() >= p.box.Right() { + t.Fatalf("children=%v: overflow not clipped inside padding: %+v", children, text) + } + } + } +} + +func TestButtonNarrowerThanPaddingRetainsLeadingIcon(t *testing.T) { + icon := gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(4, 4), gfx.LineTo(20, 20)}} + p := probeButton(t, nil, func(f *Frame) Box { + return f.Button(save, "Edit").Icon(icon).Width(12).PadX(10) + }) + if len(p.canvas.Triangles()) == 0 { + t.Fatal("the icon disappeared when the content area became narrower than the padding") + } + for _, triangle := range p.canvas.Triangles() { + for _, point := range triangle.Points { + if point.X < p.box.X-0.001 || point.X > p.box.Right()+0.001 { + t.Fatalf("icon escaped its button: %v outside %v", point, p.box) + } + } + } +} + +func TestDisabledButtonDoesNotExposeActiveDescendants(t *testing.T) { + p := probeButton(t, nil, func(f *Frame) Box { + return f.Button(save, "Outer").Disabled(true).Children(func() { f.Button(ctlFirst, "Inner") }) + }) + for _, hit := range p.canvas.Hits() { + if !hit.Disabled || hit.Focusable { + t.Fatalf("active descendant in disabled button: %+v", hit) + } + } + var view View + canvas := testCanvas() + canvas.BeginEventPass(ctlFirst, gfx.ClickInfo{}) + defer canvas.EndEventPass() + clicked := false + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 160}, func(f *Frame) { + f.Button(save, "Outer").Disabled(true).Children(func() { clicked = f.Button(ctlFirst, "Inner").Clicked() }) + }) + if clicked { + t.Fatal("a queued child click escaped the disabled ancestor") + } +} diff --git a/base/elements.go b/base/elements.go index 5211a1a8d..4578f044b 100644 --- a/base/elements.go +++ b/base/elements.go @@ -490,7 +490,10 @@ func (f *Frame) focusFirstControl(dialog Box) { func (f *Frame) FirstControl(i int32) gfx.ID { for c := f.Nodes[i].First; c >= 0; c = f.Nodes[c].Next { n := &f.Nodes[c] - if n.Flags&flagDisabled == 0 && !n.ID.IsZero() { + if n.Flags&flagDisabled != 0 { + continue // an unavailable group has no autofocus candidate beneath it + } + if !n.ID.IsZero() { switch n.Kind { case kindButton, kindSplitButton, kindCheckbox, kindSwitch, kindInput, kindTextarea, kindSlider: return n.ID diff --git a/base/frame.go b/base/frame.go index ccf84897c..e60a624e2 100644 --- a/base/frame.go +++ b/base/frame.go @@ -94,9 +94,10 @@ const ( // without the garbage collector seeing it. Anything with two numbers, one for // each axis, is indexed by axisX or axisY, so the layout is written once. type Node struct { - Kind Kind - Dir direction - Flags uint32 + Kind Kind + Dir direction + PadSet uint8 // bit i records Pad[i] explicitly set; fits existing header alignment + Flags uint32 Parent, First, Last, Next int32 @@ -123,7 +124,6 @@ type Node struct { ButtonSize style.Size RowSpan uint8 // the rows a Grid child covers; zero is one OutOfFlow uint8 // absolute positioning: see absolute.go - PadSet uint8 // the sides of Pad the caller set, bit i for Pad[i]: a themed control's recipe pads the rest MaxLines int32 // a wrapped Text breaks into at most this many lines LineFirst, LineCount int32 // its lines, in frame.lines @@ -146,10 +146,13 @@ type Node struct { Raw [2]float32 // pref before Min/Max, the size growth starts from GrowNow, ShrinkNow float32 Base, Want, Bounded float32 // while flexible lengths are resolved - Frozen bool - Rect Rect - Band uint16 // the compositing band the subtree paints on (Overlay); zero is the page's - FocusScope gfx.ID // the focus scope the subtree paints in, when it is not the page's + // FontSet and WeightSet distinguish inherited defaults from explicit text + // styling, including the valid zero value of regular weight. + FontSet, WeightSet bool + Frozen bool + Rect Rect + Band uint16 // the compositing band the subtree paints on (Overlay); zero is the page's + FocusScope gfx.ID // the focus scope the subtree paints in, when it is not the page's } // placement says where a Popup goes. diff --git a/base/layout.go b/base/layout.go index b0e57cca7..bc03d8b30 100644 --- a/base/layout.go +++ b/base/layout.go @@ -51,6 +51,12 @@ func (n *Node) marginOn(axis int) (start, end float32) { return n.Margin[startEdge(axis)], n.Margin[endEdge(axis)] } +// isContainer describes layout, independently of the control's semantic kind. +// A Button keeps its button identity when it holds caller-owned children. +func (n *Node) isContainer() bool { + return n.Kind == kindContainer || n.Kind == kindButton && n.Flags&flagChildren != 0 +} + // flows reports whether a container lays its children out along axis. A Flow does // across, as a Row does, and wraps onto lines down (see flow.go). func (n *Node) flows(axis int) bool { @@ -73,7 +79,7 @@ func (f *Frame) measure(axis int) { f.wrapCursor = 0 for i := len(f.Nodes) - 1; i >= 0; i-- { n := &f.Nodes[i] - if axis == AxisX && n.Kind != kindContainer { + if axis == AxisX && !n.isContainer() { f.measureLeaf(n) } if n.Kind == kindText && n.Flags&flagWrap != 0 && axis == AxisY { @@ -88,7 +94,7 @@ func (f *Frame) measure(axis int) { n.LineFirst, n.LineCount = first, int32(len(f.Lines))-first n.Pref[AxisY] = float32(n.LineCount)*n.leading() + n.PadY() } - if n.Kind == kindContainer { + if n.isContainer() { f.measureContainer(n, axis) } if d := n.Size[axis]; d.Kind == dimPx { @@ -115,9 +121,18 @@ func (f *Frame) measureLeaf(n *Node) { f.Palette = saved } -// controlMeasurer measures a control: its geometry comes from the style layer, -// as its painting does, so the engine can sit below the styled controls. -var ControlMeasurer func(f *Frame, n *Node) +// controlMeasurers measures a control of each kind: its geometry comes from the +// style layer, as its painting does, so the engine can sit below the styled +// controls and a page links only the kinds it declares. +var controlMeasurers [controlKindCount]func(f *Frame, n *Node) + +// SetControlMeasurer installs the measurement of one control kind. It is a +// bridge for the styled layer; callers of the page API never need it. +func SetControlMeasurer(kind Kind, measurer func(f *Frame, n *Node)) { + if int(kind) < len(controlMeasurers) { + controlMeasurers[kind] = measurer + } +} func (f *Frame) measureLeafIn(n *Node) { switch n.Kind { @@ -136,9 +151,13 @@ func (f *Frame) measureLeafIn(n *Node) { case kindIcon, kindImage: n.Pref = [2]float32{16, 16} default: - if ControlMeasurer != nil { - ControlMeasurer(f, n) + if int(n.Kind) < len(controlMeasurers) { + if measurer := controlMeasurers[n.Kind]; measurer != nil { + measurer(f, n) + return + } } + requireInstall(n.Kind, "measurer") } } @@ -533,12 +552,15 @@ func (f *Frame) measureBaseline(n *Node) { } n.Baseline = top + row case kindButton: - if ControlBaseline != nil { - n.Baseline = ControlBaseline(f, n) + if n.Flags&flagChildren == 0 { + if ControlBaseline != nil { + n.Baseline = ControlBaseline(f, n) + } + break } + fallthrough case kindContainer: n.Baseline = n.Pref[AxisY] - is, _ := n.Inset(AxisY) for c := n.First; c >= 0; c = f.Nodes[c].Next { child := &f.Nodes[c] if n.Dir == flow && child.GridRow != 0 { @@ -547,11 +569,10 @@ func (f *Frame) measureBaseline(n *Node) { if child.Kind == kindContainer && child.Baseline == child.Pref[AxisY] && child.First < 0 { continue } - value := is + child.Margin[0] + child.Baseline + value := f.childBaseline(n, child) if n.Dir == row || n.Dir == flow { for k := n.First; k >= 0 && (n.Dir == row || f.Nodes[k].GridRow == 0); k = f.Nodes[k].Next { - other := &f.Nodes[k] - value = max(value, is+other.Margin[0]+other.Baseline) + value = max(value, f.childBaseline(n, &f.Nodes[k])) } } n.Baseline = value @@ -561,3 +582,21 @@ func (f *Frame) measureBaseline(n *Node) { n.Baseline = n.Pref[AxisY] } } + +// childBaseline uses the same cross-axis alignment and available height as +// solveAcross, so a centered child reports the row it will actually draw on. +func (f *Frame) childBaseline(parent, child *Node) float32 { + inset, end := parent.Inset(AxisY) + baseline := inset + child.Margin[0] + child.Baseline + if parent.Dir != row && parent.Dir != flow { + return baseline + } + align := child.alignOn(parent) + if align == Baseline { + return baseline + } + avail := max(parent.Pref[AxisY]-inset-end, 0) + margin := avail - child.Margin[0] - child.Margin[2] + height := crossSize(child, AxisY, margin, align, f.maxOn(child, AxisY, margin)) + return baseline + offset(align, margin-height) +} diff --git a/base/paint.go b/base/paint.go index 46ad483b1..fa9b133cd 100644 --- a/base/paint.go +++ b/base/paint.go @@ -2,6 +2,7 @@ package base import ( "github.com/vivaui/viva/gfx" + controlstyle "github.com/vivaui/viva/style" ) func (f *Frame) PaintChild(i int32) { @@ -48,7 +49,7 @@ func (f *Frame) PaintChild(i int32) { s.scope = canvas.FocusScope() } style := f.resolve(n, extra) - if n.Kind == kindContainer && n.Flags&flagThemed != 0 { + if n.Kind == kindButton && n.Flags&flagChildren != 0 { defer func(color Color, has bool) { f.inherited, f.hasInherited = color, has }(f.inherited, f.hasInherited) f.inherited, f.hasInherited = style.Color, true } @@ -113,7 +114,7 @@ func (f *Frame) PaintChild(i int32) { group = canvas.Mark() } // A ColorSwatch declares its own hit, as a radio, under whatever id Hit gave it. - if hasHit && !extra.swatch && (n.Kind == kindContainer || n.Kind == kindText || n.Kind == kindIcon || n.Kind == kindSlot) { + if hasHit && !extra.swatch && (n.Kind == kindButton || n.Kind == kindContainer || n.Kind == kindText || n.Kind == kindIcon || n.Kind == kindSlot) { h := extra.hitOut hit := Rect{X: r.X - h[3], Y: r.Y - h[0], Width: r.Width + h[1] + h[3], Height: r.Height + h[0] + h[2]} if n.Flags&flagLabelFor != 0 { @@ -124,10 +125,18 @@ func (f *Frame) PaintChild(i int32) { canvas.HitLabel(n.ID, hit, text, n.Flags&flagDisabled != 0) } else { options := extra.hit + if n.Kind == kindButton { + if options.Role == 0 { + options.Role = gfx.RoleButton + } + if options.Hint == "" && n.ButtonSize >= controlstyle.SizeIcon { + options.Hint = n.Label + } + } // Disabled on the element is the control's own: a Base that was told it is // unavailable says so to assistive technology and leaves the Tab order, // as the control with a look does. - options.Disabled = options.Disabled || n.Flags&flagDisabled != 0 + options.Disabled = options.Disabled || f.Disabled(n) canvas.HitWithOptions(n.ID, hit, n.Label, options) } } @@ -145,6 +154,15 @@ func (f *Frame) PaintChild(i int32) { } n.Color = color + disableContents := n.Kind == kindButton && n.Flags&flagChildren != 0 && f.Disabled(n) + var contentsMark gfx.Mark + if disableContents { + contentsMark = canvas.Mark() + } + clipContents := n.Kind == kindButton && n.Flags&flagChildren != 0 + if clipContents { + canvas.Clip(f.ContentRect(n)) + } var hooks drawHooks if extra.Draws != 0 { hooks = f.Draws[extra.Draws-1] @@ -161,6 +179,12 @@ func (f *Frame) PaintChild(i int32) { if hooks.over != nil { f.runDraw(n, hooks.over) } + if clipContents { + canvas.Unclip() + } + if disableContents { + canvas.DisableHitsSince(contentsMark) + } if s := extra.scrollState; s != nil && s.bars && canvas != nil { f.paintBarsFn(f, n, s) // over the content, inside the area's clip } @@ -218,9 +242,69 @@ func (f *Frame) paintControl(n *Node, r Rect) { if int(n.Kind) < len(controlPainters) { if painter := controlPainters[n.Kind]; painter != nil { painter(f, n, r) + return } } + requireInstall(n.Kind, "painter") + } +} + +// engineKind is a kind the engine paints, measures or lays out itself, so no +// layer above installs a painter or a measurer for it. +func engineKind(k Kind) bool { + switch k { + case kindContainer, kindText, kindSpacer, kindIcon, kindSlot, kindImage: + return true + } + return false +} + +// controlNames names the kinds a styled layer installs, in Kind order. +var controlNames = [...]string{ + KindContainer: "Container", + KindText: "Text", + KindSpacer: "Spacer", + KindButton: "Button", + KindCheckbox: "Checkbox", + KindSwitch: "Switch", + KindIcon: "Icon", + KindSlot: "Slot", + KindInput: "Input", + KindInputGroup: "InputGroup", + KindTextarea: "Textarea", + KindSegmented: "Segmented", + KindTable: "Table", + KindTabs: "Tabs", + KindSelect: "Select", + KindProgress: "Progress", + KindSpinner: "Spinner", + KindSplitter: "Splitter", + KindSlider: "Slider", + KindImage: "Image", + KindSplitButton: "SplitButton", + KindBadge: "Badge", + KindToggle: "Toggle", + KindPagination: "Pagination", +} + +// controlName is the name a diagnostic calls the kind by. +func controlName(k Kind) string { + if int(k) < len(controlNames) && controlNames[k] != "" { + return controlNames[k] + } + return "Control" +} + +// requireInstall stops a control that would otherwise paint or measure nothing: +// the styled layer installs each control kind as the page declares it, and a +// host that drives package base directly installs every one with +// ui.InstallPainters. A missing installation is a wiring bug, not an empty +// control, so it panics with the kind's name instead of drawing silence. +func requireInstall(k Kind, what string) { + if engineKind(k) || int(k) >= len(controlPainters) { + return } + panic("ui: a " + controlName(k) + " has no " + what + " installed: a host that drives package base directly must call ui.InstallPainters(); a page that declares controls through ui.* functions installs each kind as it is declared") } func (f *Frame) paintText(n *Node) { diff --git a/base/painter_install_test.go b/base/painter_install_test.go new file mode 100644 index 000000000..1936a0a0f --- /dev/null +++ b/base/painter_install_test.go @@ -0,0 +1,88 @@ +package base + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// drawButton declares a button and lays the page out, which is enough to reach +// both the measurer and the painter. +func drawButton() { + var view View + view.Draw(testCanvas(), gfx.LightTheme(), gfx.Rect{Width: 200, Height: 80}, func(f *Frame) { + f.Button(gfx.ID{}, "Save") + }) +} + +// A control the styled layer did not install stops the page with the kind's +// name and the one call that fixes it, instead of painting or measuring +// nothing. A host driving package base directly installs every kind with +// ui.InstallPainters; the ui constructors install the kinds a page declares. +func TestUninstalledControlFailsFast(t *testing.T) { + savedPainter, savedMeasurer := controlPainters[KindButton], controlMeasurers[KindButton] + t.Cleanup(func() { + controlPainters[KindButton], controlMeasurers[KindButton] = savedPainter, savedMeasurer + }) + + cases := []struct { + name string + setup func() + want string + }{ + {"measurer", func() { controlMeasurers[KindButton] = nil }, "Button has no measurer installed"}, + {"painter", func() { controlMeasurers[KindButton] = savedMeasurer; controlPainters[KindButton] = nil }, "Button has no painter installed"}, + } + for _, tc := range cases { + controlPainters[KindButton], controlMeasurers[KindButton] = savedPainter, savedMeasurer + tc.setup() + t.Run(tc.name, func(t *testing.T) { + defer func() { + got := recover() + msg, ok := got.(string) + if !ok { + t.Fatalf("drawing a %s without its %s recovered %v, want the diagnostic panic", controlName(KindButton), tc.name, got) + } + if !strings.Contains(msg, tc.want) || !strings.Contains(msg, "ui.InstallPainters") { + t.Fatalf("diagnostic = %q, want it to name %q and ui.InstallPainters", msg, tc.want) + } + }() + drawButton() + }) + } +} + +// The engine's own kinds are laid out and painted without an installation: +// a Spacer reserves space and a slot takes its size, so requiring an installer +// for them would break a page that only declares layout. +func TestEngineKindsNeedNoInstallation(t *testing.T) { + savedPainter, savedMeasurer := controlPainters[KindButton], controlMeasurers[KindButton] + t.Cleanup(func() { + controlPainters[KindButton], controlMeasurers[KindButton] = savedPainter, savedMeasurer + }) + controlPainters[KindButton], controlMeasurers[KindButton] = nil, nil + + var view View + view.Draw(testCanvas(), gfx.LightTheme(), gfx.Rect{Width: 200, Height: 80}, func(f *Frame) { + f.Row().Children(func() { + f.Spacer() + f.Slot().Size(20, 20) + }) + }) +} + +// The kind a diagnostic names reads as the Go name of the control. +func TestControlNameIsReadable(t *testing.T) { + for kind, want := range map[Kind]string{ + KindButton: "Button", + KindInputGroup: "InputGroup", + KindSplitButton: "SplitButton", + KindPagination: "Pagination", + KindContainer: "Container", + } { + if got := controlName(kind); got != want { + t.Errorf("controlName(%v) = %q, want %q", kind, got, want) + } + } +} diff --git a/base/recipe.go b/base/recipe.go index 09d62d0fb..2e6b592dc 100644 --- a/base/recipe.go +++ b/base/recipe.go @@ -54,26 +54,25 @@ func (f *Frame) applyRecipes() { if n.Kind == kindTextarea && n.MinS[AxisY] == 0 { n.MinS[AxisY] = 64 // the official minimum height } - case kindButton, kindContainer: + case kindButton: f.applyButtonRecipe(n) } } } -// applyButtonRecipe gives a themed button the measurements its size and recipe have: the -// corners and the padding either side of its content. It is a button whether it paints its -// own label and icon (a kindButton) or holds children (a container Children turned it -// into). What the caller set (Radius, Pad on a side) is left alone, so a button is -// restyled with the calls any element takes. Its border is not a measurement: it is drawn -// over the control's edge, as a focus border is, so the recipe's never takes room. +// applyButtonRecipe supplies layout defaults while the control keeps its button +// kind. Caller-owned content uses the same typography as the default label. func (f *Frame) applyButtonRecipe(n *Node) { theme := f.RecipeTheme(n, &f.scratch.theme) if n.Flags&flagHasRadius == 0 { n.Radius = f.buttonLook(n, theme, gfx.State{}).Radius } - _, padding, _, iconOnly := style.ButtonGeometry(theme.Metrics, n.ButtonSize) - if iconOnly && n.Kind == kindButton { - padding = 0 // the icon alone is centered in a square + height, padding, fontSize, iconOnly := style.ButtonGeometry(theme.Metrics, n.ButtonSize) + if n.FontSize > 0 { + fontSize = n.FontSize + } + if iconOnly { + padding = 0 } if n.PadSet&padRight == 0 { n.Pad[1] = padding @@ -81,17 +80,47 @@ func (f *Frame) applyButtonRecipe(n *Node) { if n.PadSet&padLeft == 0 { n.Pad[3] = padding } - if n.Kind != kindContainer || n.Size[AxisY].Kind != dimAuto { + if n.Flags&flagChildren == 0 { return } - // A button that holds children is as tall as its size says, as a shadcn button is, and - // grows with its content only once the caller has padded it. - height, _, _, _ := style.ButtonGeometry(theme.Metrics, n.ButtonSize) - if n.Flags&flagSetPad != 0 { - n.MinS[AxisY] = max(n.MinS[AxisY], height) - return + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + f.buttonTextDefaults(n, fontSize, weight, n.LineH) + if n.Size[AxisY].Kind == dimAuto && n.MinS[AxisY] == 0 { + n.MinS[AxisY] = height + } +} + +// Explicit child typography wins over the button's inherited defaults. A +// nested control owns its own defaults rather than borrowing the outer label's. +func (f *Frame) buttonTextDefaults(parent *Node, fontSize, weight, lineHeight float32) { + for i := parent.First; i >= 0; i = f.Nodes[i].Next { + n := &f.Nodes[i] + if n.Kind == kindButton { + continue + } + font, stroke, leading := fontSize, weight, lineHeight + if n.FontSet { + font = n.FontSize + } else if n.Kind == kindText { + n.FontSize = font + } + if n.WeightSet { + stroke = n.Weight + } else if n.Kind == kindText { + n.Weight = stroke + } + if n.LineH > 0 { + leading = n.LineH + } else if n.Kind == kindText { + n.LineH = leading + } + if n.First >= 0 { + f.buttonTextDefaults(n, font, stroke, leading) + } } - n.Size[AxisY] = Dimension{dimPx, height} } // themedDefaults fills in, for the state the element is in now, the colors of the resolved @@ -99,7 +128,7 @@ func (f *Frame) applyButtonRecipe(n *Node) { func (f *Frame) themedDefaults(n *Node, Extra *Extra, s *resolved) { var state gfx.State switch n.Kind { - case kindButton, kindContainer: + case kindButton: f.themedButtonDefaults(n, Extra, s) return case kindInput: @@ -182,7 +211,7 @@ func (f *Frame) themedButtonDefaults(n *Node, Extra *Extra, s *resolved) { if c := f.Surface; c != nil && !n.ID.IsZero() { state = gfx.State{Hovered: c.Hovered() == n.ID, Pressed: c.Pressed() == n.ID, FocusVisible: c.FocusVisible() == n.ID} } - state.Disabled = n.Flags&flagDisabled != 0 + state.Disabled = f.Disabled(n) look := f.buttonLook(n, theme, state) f.buttonPainted = look if n.Flags&flagSetBackground == 0 { @@ -222,12 +251,16 @@ func (f *Frame) themedButtonDefaults(n *Node, Extra *Extra, s *resolved) { } } -// buttonHoldsChildren turns a button that is given children into the row that holds them: -// the same themed element, with the same size, variant, recipe and keyboard, whose content -// is the caller's and is laid out as any container's is. -func (f *Frame) buttonHoldsChildren(i int32) { - f.Nodes[i].Kind = kindContainer - if e := f.Extra(i); e.hit.Role == 0 { - e.hit.Role = gfx.RoleButton +// Disabled includes disabled ancestors, so rebuilding a descendant cannot +// reactivate a click or focus stop inside an unavailable control. +func (f *Frame) Disabled(n *Node) bool { + for { + if n.Flags&flagDisabled != 0 { + return true + } + if n.Parent < 0 { + return false + } + n = &f.Nodes[n.Parent] } } diff --git a/base/style.go b/base/style.go index 3480ad069..c119e5932 100644 --- a/base/style.go +++ b/base/style.go @@ -321,6 +321,12 @@ func (f *Frame) resolve(n *Node, Extra *Extra) resolved { canvas := f.Surface focus, hover, pressed := target(canvas.FocusVisible() == source), target(canvas.Hovered() == source), target(canvas.Pressed() == source) focused := target(canvas.Focused() == source) + if f.Disabled(n) { + hover, pressed = 0, 0 + if !Extra.hit.FocusableWhenDisabled { + focus, focused = 0, 0 + } + } if looks.animated { focused = canvas.Animate(source, slotFocused, focused, looks.motion) focus = canvas.Animate(source, slotFocus, focus, looks.motion) diff --git a/cmd/viva/templates/button.go.txt b/cmd/viva/templates/button.go.txt index 017e57471..c5c749ff8 100644 --- a/cmd/viva/templates/button.go.txt +++ b/cmd/viva/templates/button.go.txt @@ -130,10 +130,9 @@ func (button Button) Height(height float32) Button { } // FontSize paints the label size points instead of the size the button's size -// gives, for a button that sits among text of its own size. The height, the -// padding and the corner radius stay those of the size; a label grows the -// button's width through SizeToFit and Paint as usual. A size of zero or less -// is the size's own. +// gives, for a button that sits among text of its own size. The padding and +// corner radius stay the size's; its natural height grows if the label needs it. +// An explicit Height stays fixed. A size of zero or less is the size's own. func (button Button) FontSize(size float32) Button { button.fontSize = max(size, 0) return button @@ -398,31 +397,27 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { } else if style.filled { button.canvas.Rounded(button.bounds, radius, style.background) } - hint := "" - if button.hasIcon() { - size := min(buttonIconExtent(height), button.bounds.Width) - width := size - if !iconOnly && label != "" { - width = min(button.bounds.Width, width+buttonIconGap+button.canvas.TextWidthWeight(label, fontSize, gfx.WeightMedium)) + area := button.bounds + _, padding, _, _ := button.geometry() + if !iconOnly && padding > 0 { + content := gfx.Rect{X: area.X + padding, Y: area.Y, Width: max(area.Width-2*padding, 0), Height: area.Height} + need := button.canvas.TextWidthWeight(label, fontSize, gfx.WeightMedium) + if button.hasIcon() { + need += buttonIconExtent(height) + if label != "" { + need += buttonIconGap + } } - x := button.bounds.X + (button.bounds.Width-width)/2 - if size > 0 { - button.canvas.DrawIconTransformed( - button.icon, - gfx.Rect{X: x, Y: button.bounds.Y + (height-size)/2, Width: size, Height: size}, - style.foreground, - button.iconTransform, - ) + if content.Width > 0 && need > content.Width { + button.canvas.Clip(content) + defer button.canvas.Unclip() } - if iconOnly { - hint = label - } else if label != "" { - text := gfx.Rect{X: x + size + buttonIconGap, Y: button.bounds.Y, Width: max(0, width-size-buttonIconGap), Height: height} - paintButtonLabel(button.canvas, label, text, fontSize, gfx.WeightMedium, style) - } - } else { - paintButtonLabel(button.canvas, label, button.bounds, fontSize, gfx.WeightMedium, style) } + 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, + }) if !button.id.IsZero() { button.canvas.HitWithOptions(button.id, button.bounds, label, gfx.HitOptions{ Role: gfx.RoleButton, Disabled: button.disabled, Hint: hint, Invalid: button.state.Invalid, @@ -439,6 +434,9 @@ func (button Button) geometry() (height, padding, fontSize float32, iconOnly boo if button.fontSize > 0 { fontSize = button.fontSize } + if button.height <= 0 && !iconOnly { + height = max(height, fontSize+7) + } return height, padding, fontSize, iconOnly } diff --git a/cmd/viva/templates/select.go.txt b/cmd/viva/templates/select.go.txt index 366b62fdd..231af10c8 100644 --- a/cmd/viva/templates/select.go.txt +++ b/cmd/viva/templates/select.go.txt @@ -92,6 +92,10 @@ const ( selectIconGap = 8 ) +// SelectIconSpan is the room an icon takes before a select's value or an +// option's label: the icon and the gap after it. +const SelectIconSpan = selectIconSize + selectIconGap + // selectTriggerSize is the height of a trigger and the type step of its value. // Only the extra-small step changes the type, as in Button: a compact control // keeps the body size and just gets shorter. @@ -301,8 +305,8 @@ func (selectControl Select) paintTrigger() { inset := selectControl.theme.Metrics.TextInsetX() textX, textWidth := bounds.X+inset, bounds.Width-inset-chevronSpan-6 if paintSelectIcon(canvas, options.Icon, options.IconImage, options.IconText, gfx.Rect{X: textX, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, foreground, selectControl.textSize) { - textX += selectIconSize + selectIconGap - textWidth -= selectIconSize + selectIconGap + textX += SelectIconSpan + textWidth -= SelectIconSpan } canvas.Label(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.textSize, Weight: gfx.WeightRegular, Color: foreground, @@ -331,8 +335,8 @@ func (selectControl *Select) paintItem(bounds gfx.Rect, item SelectItem) { foreground := look.Foreground textX, textWidth := bounds.X+8, bounds.Width-40 if paintSelectIcon(selectControl.canvas, item.Icon, item.IconImage, item.IconText, gfx.Rect{X: textX, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, foreground, selectControl.theme.Metrics.FontSizeM) { - textX += selectIconSize + selectIconGap - textWidth -= selectIconSize + selectIconGap + textX += SelectIconSpan + textWidth -= SelectIconSpan } selectControl.canvas.Label(item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, diff --git a/components/button.go b/components/button.go index f1313490d..6cc6934f4 100644 --- a/components/button.go +++ b/components/button.go @@ -130,10 +130,9 @@ func (button Button) Height(height float32) Button { } // FontSize paints the label size points instead of the size the button's size -// gives, for a button that sits among text of its own size. The height, the -// padding and the corner radius stay those of the size; a label grows the -// button's width through SizeToFit and Paint as usual. A size of zero or less -// is the size's own. +// gives, for a button that sits among text of its own size. The padding and +// corner radius stay the size's; its natural height grows if the label needs it. +// An explicit Height stays fixed. A size of zero or less is the size's own. func (button Button) FontSize(size float32) Button { button.fontSize = max(size, 0) return button @@ -398,31 +397,27 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { } else if style.filled { button.canvas.Rounded(button.bounds, radius, style.background) } - hint := "" - if button.hasIcon() { - size := min(buttonIconExtent(height), button.bounds.Width) - width := size - if !iconOnly && label != "" { - width = min(button.bounds.Width, width+buttonIconGap+button.canvas.TextWidthWeight(label, fontSize, gfx.WeightMedium)) + area := button.bounds + _, padding, _, _ := button.geometry() + if !iconOnly && padding > 0 { + content := gfx.Rect{X: area.X + padding, Y: area.Y, Width: max(area.Width-2*padding, 0), Height: area.Height} + need := button.canvas.TextWidthWeight(label, fontSize, gfx.WeightMedium) + if button.hasIcon() { + need += buttonIconExtent(height) + if label != "" { + need += buttonIconGap + } } - x := button.bounds.X + (button.bounds.Width-width)/2 - if size > 0 { - button.canvas.DrawIconTransformed( - button.icon, - gfx.Rect{X: x, Y: button.bounds.Y + (height-size)/2, Width: size, Height: size}, - style.foreground, - button.iconTransform, - ) + if content.Width > 0 && need > content.Width { + button.canvas.Clip(content) + defer button.canvas.Unclip() } - if iconOnly { - hint = label - } else if label != "" { - text := gfx.Rect{X: x + size + buttonIconGap, Y: button.bounds.Y, Width: max(0, width-size-buttonIconGap), Height: height} - paintButtonLabel(button.canvas, label, text, fontSize, gfx.WeightMedium, style) - } - } else { - paintButtonLabel(button.canvas, label, button.bounds, fontSize, gfx.WeightMedium, style) } + 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, + }) if !button.id.IsZero() { button.canvas.HitWithOptions(button.id, button.bounds, label, gfx.HitOptions{ Role: gfx.RoleButton, Disabled: button.disabled, Hint: hint, Invalid: button.state.Invalid, @@ -439,6 +434,9 @@ func (button Button) geometry() (height, padding, fontSize float32, iconOnly boo if button.fontSize > 0 { fontSize = button.fontSize } + if button.height <= 0 && !iconOnly { + height = max(height, fontSize+7) + } return height, padding, fontSize, iconOnly } diff --git a/docs/upgrading.md b/docs/upgrading.md index 351d798c3..a47c4c70a 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -124,6 +124,14 @@ See the [v0.6.0 migration notes](releases/0.6.0.md#迁移--migration) for custom controls, layout and host routing. When jumping from an older version, also apply the v0.4.0 and v0.3.0 changes below. +A host that drives `package base` directly, through `base.NewPage` and a +`base.View`/`base.Frame` (the `ui.View` and `ui.Frame` aliases are the same +type), must call `ui.InstallPainters()` once. The `ui.*` constructors install +each control kind as a page declares it, which is what lets an application link +only the controls it uses; a control declared from `package base` without that +installation now stops the page with a diagnostic naming the control, instead +of laying it out or painting it as nothing. + #### Custom renderers: block elements become cell glyphs The former `ui.ReplaceBlockElements` function and `ui.Canvas.BlockRectangles` diff --git a/gfx/replay.go b/gfx/replay.go index dac77c679..4666f3143 100644 --- a/gfx/replay.go +++ b/gfx/replay.go @@ -283,6 +283,16 @@ func (canvas *Canvas) HitsSince(from Mark) []Hit { return canvas.hits[from.hits:] } +// DisableHitsSince makes every descendant region declared after from inert. +// A child's own opt-in focusability cannot escape a disabled ancestor. +func (canvas *Canvas) DisableHitsSince(from Mark) { + for i := range canvas.HitsSince(from) { + hit := &canvas.hits[int(from.hits)+i] + hit.Disabled, hit.Focusable, hit.SkipTab = true, false, true + hit.FocusableDisabled, hit.SecondaryWhenDisabled = false, false + } +} + // HintSince gives the hits named id that the canvas took since from the Hint // hint: the tooltip and accessibility description of a control whose painter // declared its hit without one. diff --git a/ui/app_facade.go b/ui/app_facade.go index dd1bb9611..77e20ed5c 100644 --- a/ui/app_facade.go +++ b/ui/app_facade.go @@ -23,6 +23,7 @@ import ( // appearance watch. OnClosed cancels the page's effects and stops that watch // before it runs base's OnClosed. Nothing else is touched. func Configure(page *Page, base app.Config) app.Config { + useTooltip() if page.GetConfig().View == nil { panic("ui: Configure needs PageConfig.View, the function that declares the page") } diff --git a/ui/controls_baseline.go b/ui/controls_baseline.go index 393bd0b89..6ddfed724 100644 --- a/ui/controls_baseline.go +++ b/ui/controls_baseline.go @@ -1,20 +1,25 @@ package ui import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) // controlBaseline is the label's baseline of a button, for a row that lines -// elements up by it. The engine asks the hook; the control layer answers. +// elements up by it. The engine asks the hook; the control layer answers with +// the label size the button's size gives, which is the size both its +// measurement and its painting use. var controlBaseline = func(f *Frame, n *Node) float32 { theme := f.Palette if n.HasOwnTheme() { theme = f.OwnTheme(n) } - button := components.BeginButton(f.Surface, theme, gfx.ID{}, Rect{}).Size(n.ButtonSize) + _, _, fontSize, _ := style.ButtonGeometry(theme.Metrics, n.ButtonSize) + if n.FontSize > 0 { + fontSize = n.FontSize + } return f.Surface.LabelBaseline( gfx.Rect{Height: n.Pref[AxisY]}, - gfx.TextStyle{Size: button.LabelFontSize()}, + gfx.TextStyle{Size: fontSize}, ) } diff --git a/ui/controls_paint.go b/ui/controls_paint.go index 61dfc9131..463cf626d 100644 --- a/ui/controls_paint.go +++ b/ui/controls_paint.go @@ -108,109 +108,129 @@ func paintSegmented(f *Frame, v ControlView) { control.Paint() } -// measureControls measures the controls: each kind's geometry, from package -// components for the ones that ship with a theme. -func measureControls(f *Frame, n *Node) { - switch n.Kind { - case KindButton: - n.Pref = measureButton(f, n) - case KindBadge: - w, h := components.BadgeExtent(f.Surface, f.Palette, n.Text) - n.Pref = [2]float32{w, h} - case KindPagination: - w, h := components.PaginationExtent(f.Surface, f.Palette, f.PaginationItems(n)) - n.Pref = [2]float32{w, h} - case KindSplitButton: - button := components.BeginButton(f.Surface, f.Palette, gfx.ID{}, Rect{}).Size(n.ButtonSize).SizeToFit(n.Label) - trigger := base.WidgetsOf(f).GetSplitButtons()[n.Aux].GetTriggerWidth() - if trigger <= 0 { - trigger = SplitButtonTrigger - } - n.Pref = [2]float32{button.BoundsWidth() + trigger, button.BoundsHeight()} - case KindCheckbox: - w, h := components.CheckboxHitExtent(f.Palette) - n.Pref = [2]float32{w, h} - if n.Text != "" { - n.Pref[AxisX] = components.CheckboxExtent(f.Palette) + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), gfx.WeightMedium) - } - case KindSwitch: - w, h := components.SwitchHitExtent(f.Palette, n.Flags&FlagSmall != 0) - n.Pref = [2]float32{w, h} - if n.Text != "" { - control, _ := components.SwitchExtent(f.Palette, n.Flags&FlagSmall != 0) - n.Pref[AxisX] = control + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), gfx.WeightMedium) - } - case KindToggle: - toggle := components.BeginToggle(f.Surface, f.Palette, gfx.ID{}, Rect{}, false) - if n.ButtonSize == style.SizeSmall { - toggle = toggle.Small() - } else if n.ButtonSize == style.SizeLarge { - toggle = toggle.Large() - } - label := n.Text - if label == "" { - label = n.Label - } - toggle = toggle.SizeToFit(label) - height := f.Palette.Metrics.ControlHeight - if n.ButtonSize == style.SizeSmall { - height -= 4 - } else if n.ButtonSize == style.SizeLarge { - height += 4 - } - n.Pref = [2]float32{toggle.BoundsWidth(), height} - case KindSegmented: - var width float32 = 8 - for _, option := range base.WidgetsOf(f).GetSegmented()[n.Aux].GetOptions() { - width += f.Surface.TextWidthWeight(option.Label, f.Palette.Metrics.FontSizeM, gfx.WeightMedium) + 28 - } - n.Pref = [2]float32{width, f.Palette.Metrics.ControlHeight} - case KindInput: - n.Pref = [2]float32{n.PadX(), f.InputLine(n) + n.PadY()} - if n.Flags&FlagThemed != 0 { - n.Pref = [2]float32{0, f.Palette.Metrics.ControlHeight} - } - case KindInputGroup: +// measureButtonNode sizes a button that paints its own label and icon. +func measureButtonNode(f *Frame, n *Node) { n.Pref = measureButton(f, n) } + +// measureBadgeNode gives a Badge the extent its component wants. +func measureBadgeNode(f *Frame, n *Node) { + w, h := components.BadgeExtent(f.Surface, f.Palette, n.Text) + n.Pref = [2]float32{w, h} +} + +// measurePaginationNode gives a Pagination the extent its items want. +func measurePaginationNode(f *Frame, n *Node) { + w, h := components.PaginationExtent(f.Surface, f.Palette, f.PaginationItems(n)) + n.Pref = [2]float32{w, h} +} + +// measureSplitButtonNode gives a SplitButton its label's width and its trigger. +func measureSplitButtonNode(f *Frame, n *Node) { + button := components.BeginButton(f.Surface, f.Palette, gfx.ID{}, Rect{}).Size(n.ButtonSize).SizeToFit(n.Label) + trigger := base.WidgetsOf(f).GetSplitButtons()[n.Aux].GetTriggerWidth() + if trigger <= 0 { + trigger = SplitButtonTrigger + } + n.Pref = [2]float32{button.BoundsWidth() + trigger, button.BoundsHeight()} +} + +func measureCheckboxNode(f *Frame, n *Node) { + w, h := components.CheckboxHitExtent(f.Palette) + n.Pref = [2]float32{w, h} + if n.Text != "" { + n.Pref[AxisX] = components.CheckboxExtent(f.Palette) + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), gfx.WeightMedium) + } +} + +func measureSwitchNode(f *Frame, n *Node) { + w, h := components.SwitchHitExtent(f.Palette, n.Flags&FlagSmall != 0) + n.Pref = [2]float32{w, h} + if n.Text != "" { + control, _ := components.SwitchExtent(f.Palette, n.Flags&FlagSmall != 0) + n.Pref[AxisX] = control + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), gfx.WeightMedium) + } +} + +func measureToggleNode(f *Frame, n *Node) { + toggle := components.BeginToggle(f.Surface, f.Palette, gfx.ID{}, Rect{}, false) + if n.ButtonSize == style.SizeSmall { + toggle = toggle.Small() + } else if n.ButtonSize == style.SizeLarge { + toggle = toggle.Large() + } + label := n.Text + if label == "" { + label = n.Label + } + toggle = toggle.SizeToFit(label) + height := f.Palette.Metrics.ControlHeight + if n.ButtonSize == style.SizeSmall { + height -= 4 + } else if n.ButtonSize == style.SizeLarge { + height += 4 + } + n.Pref = [2]float32{toggle.BoundsWidth(), height} +} + +func measureSegmentedNode(f *Frame, n *Node) { + var width float32 = 8 + for _, option := range base.WidgetsOf(f).GetSegmented()[n.Aux].GetOptions() { + width += f.Surface.TextWidthWeight(option.Label, f.Palette.Metrics.FontSizeM, gfx.WeightMedium) + 28 + } + n.Pref = [2]float32{width, f.Palette.Metrics.ControlHeight} +} + +func measureInputNode(f *Frame, n *Node) { + n.Pref = [2]float32{n.PadX(), f.InputLine(n) + n.PadY()} + if n.Flags&FlagThemed != 0 { n.Pref = [2]float32{0, f.Palette.Metrics.ControlHeight} - if n.Kind == KindInputGroup && base.WidgetsOf(f).GetGroups()[n.Aux].Multiline { - n.Pref[AxisY] = 64 - } - case KindTextarea: - n.Pref = [2]float32{n.PadX(), f.Palette.Metrics.FontSizeM + 7 + n.PadY()} - if n.Flags&FlagThemed != 0 { - n.Pref = [2]float32{0, 64} - } - if n.MaxLines > 0 { - // AutoGrow: the rows measured by the same layout the paint will use, - // capped at n.MaxLines rows and never below the control's minimum. - // The width is the one the last layout gave the box, which the first - // paint records and then asks for before it is shown. - snapshot := &base.WidgetsOf(f).GetTextareas()[n.Aux] - if layout := snapshot.Layout; layout != nil { - if width := layout.BoxWidth(); width > 0 { - height := layout.ContentHeight(f.Surface, f.Palette, snapshot.LayoutText(), width, snapshot.NoWrap) - maxHeight := float32(n.MaxLines)*(f.Palette.Metrics.FontSizeM+7) + 2*base.TextareaPadY - n.Pref[AxisY] = max(64, min(height, maxHeight)) - } + } +} + +func measureInputGroupNode(f *Frame, n *Node) { + n.Pref = [2]float32{0, f.Palette.Metrics.ControlHeight} + if base.WidgetsOf(f).GetGroups()[n.Aux].Multiline { + n.Pref[AxisY] = 64 + } +} + +func measureTextareaNode(f *Frame, n *Node) { + n.Pref = [2]float32{n.PadX(), f.Palette.Metrics.FontSizeM + 7 + n.PadY()} + if n.Flags&FlagThemed != 0 { + n.Pref = [2]float32{0, 64} + } + if n.MaxLines > 0 { + // AutoGrow: the rows measured by the same layout the paint will use, + // capped at n.MaxLines rows and never below the control's minimum. + // The width is the one the last layout gave the box, which the first + // paint records and then asks for before it is shown. + snapshot := &base.WidgetsOf(f).GetTextareas()[n.Aux] + if layout := snapshot.Layout; layout != nil { + if width := layout.BoxWidth(); width > 0 { + height := layout.ContentHeight(f.Surface, f.Palette, snapshot.LayoutText(), width, snapshot.NoWrap) + maxHeight := float32(n.MaxLines)*(f.Palette.Metrics.FontSizeM+7) + 2*base.TextareaPadY + n.Pref[AxisY] = max(64, min(height, maxHeight)) } } - case KindTable, KindTabs, KindSelect: - f.MeasureWidget(n) - case KindProgress: - n.Pref = [2]float32{ProgressWidth, ProgressHeight} - case KindSpinner: - n.Pref = [2]float32{16, 16} - case KindSplitter: - f.MeasureSplitter(n) - case KindSlider: - f.MeasureSlider(n) } } +// measureWidgetNode gives a Table, Tabs or Select the size its widget wants. +func measureWidgetNode(f *Frame, n *Node) { f.MeasureWidget(n) } + +func measureProgressNode(f *Frame, n *Node) { + n.Pref = [2]float32{ProgressWidth, ProgressHeight} +} + +func measureSpinnerNode(f *Frame, n *Node) { n.Pref = [2]float32{16, 16} } + +func measureSplitterNode(f *Frame, n *Node) { f.MeasureSplitter(n) } + +func measureSliderNode(f *Frame, n *Node) { f.MeasureSlider(n) } + // buttonWeight is the weight of a button's label: the one the element asks for, or the // medium weight the control has. func buttonWeight(n *Node) float32 { - if n.Weight > 0 { + if n.WeightSet || n.Weight != 0 { return n.Weight } return gfx.WeightMedium @@ -223,6 +243,9 @@ func buttonWeight(n *Node) float32 { // side by the caller, it grows to hold its label and the padding. func measureButton(f *Frame, n *Node) [2]float32 { height, _, fontSize, _ := style.ButtonGeometry(f.Palette.Metrics, n.ButtonSize) + if n.FontSize > 0 { + fontSize = n.FontSize + } if d := n.Size[AxisY]; d.Kind == DimPx { height = d.Value } @@ -236,9 +259,11 @@ func measureButton(f *Frame, n *Node) [2]float32 { width += n.Gap } } - if n.Flags&FlagSetPad != 0 { - height = max(height, fontSize+7+n.PadY()) + leading := fontSize + 7 + if n.LineH > 0 { + leading = n.LineH } + height = max(height, leading+n.PadY()) return [2]float32{width, height} } @@ -256,20 +281,35 @@ func buttonContentArea(f *Frame, n *Node) Rect { // paintButton paints the content of a button that paints its own: its icon and its label, // in the room its Pad and Border leave. The surface is the element's, dressed by the // button's recipe before this runs, and the label takes the color the recipe gives it in -// the state the button is in unless the element has one of its own. +// the state the button is in unless the element has one of its own. Content the caller +// makes wider than the room inside the padding is cut at the content edge. func paintButton(f *Frame, n *Node) { + if n.Flags&FlagChildren != 0 { + return + } extra := &f.Exts[n.Ext] _, _, fontSize, iconOnly := style.ButtonGeometry(f.Palette.Metrics, n.ButtonSize) - hint := components.PaintButtonContent(f.Surface, buttonContentArea(f, n), components.ButtonContent{ + if n.FontSize > 0 { + fontSize = n.FontSize + } + area := buttonContentArea(f, n) + room := f.ContentRect(n) + need := f.Surface.TextWidthWeight(n.Label, fontSize, buttonWeight(n)) + if icon := extra.GetIcon(); len(icon.Commands) != 0 || len(icon.Layers) != 0 { + need += style.ButtonIconExtent(n.Rect.Height) + if n.Label != "" { + need += n.Gap + } + } + if room.Width > 0 && need > room.Width { + f.Surface.Clip(room) + defer f.Surface.Unclip() + } + components.PaintButtonContent(f.Surface, area, components.ButtonContent{ Label: n.Label, Icon: extra.GetIcon(), IconTransform: extra.GetIconTransform(), FontSize: fontSize, Weight: buttonWeight(n), Color: n.Color, Gap: n.Gap, Height: n.Rect.Height, IconOnly: iconOnly, Underlined: f.GetButtonLook().Underlined, }) - if !n.ID.IsZero() { - f.Surface.HitWithOptions(n.ID, n.Rect, n.Label, gfx.HitOptions{ - Role: gfx.RoleButton, Disabled: n.Flags&FlagDisabled != 0, Hint: hint, - }) - } } func paintInput(f *Frame, n *Node) { diff --git a/ui/doc.go b/ui/doc.go index d772fc285..1278b61de 100644 --- a/ui/doc.go +++ b/ui/doc.go @@ -33,7 +33,9 @@ // // The styled layer's painters are installed by the constructors as a page // declares the features it uses, so an application links only the painters it -// uses. A host that drives package base directly calls InstallPainters. +// uses. A host that drives package base directly calls InstallPainters; a +// control declared without its installation stops the page with a message +// naming it, instead of laying out or painting nothing. // // Layout is CSS flexbox's, from a declaration instead of coordinates. // A Row lays its children out left to right, a Column top to bottom, a Stack on diff --git a/ui/facade.go b/ui/facade.go index c8ce72a9c..78711ce49 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -133,71 +133,76 @@ func Icon(c C, icon gfx.Icon) Box { return base.Icon(c, icon) } func Image(c C, bitmap gfx.Bitmap) Box { return base.Image(c, bitmap) } -func Progress(c C, fraction float32) Box { return base.Progress(c, fraction) } +func Progress(c C, fraction float32) Box { useIndicators(); return base.Progress(c, fraction) } -func Spinner(c C) Box { return base.Spinner(c) } +func Spinner(c C) Box { useIndicators(); return base.Spinner(c) } func Kbd(c C, keys ...string) Box { return base.Kbd(c, keys...) } // Controls and their bases. -func Badge(c C, Label string) Box { return base.Badge(c, Label) } +func Badge(c C, Label string) Box { useBadge(); return base.Badge(c, Label) } -func Button(c C, Label string) Box { return base.Button(c, Label) } +func Button(c C, Label string) Box { useButton(); return base.Button(c, Label) } -func ButtonBase(c C, Label string) Box { return base.ButtonBase(c, Label) } +func ButtonBase(c C, Label string) Box { useButton(); return base.ButtonBase(c, Label) } func Checkbox(c C, Value *bool, Label string) Box { + useCheckbox() return base.Checkbox(c, Value, Label) } func CheckboxBase(c C, Value *bool, Label string) Box { + useCheckbox() return base.CheckboxBase(c, Value, Label) } -func Switch(c C, Value *bool, Label string) Box { return base.Switch(c, Value, Label) } +func Switch(c C, Value *bool, Label string) Box { useSwitch(); return base.Switch(c, Value, Label) } func SwitchBase(c C, Value *bool, Label string) Box { + useSwitch() return base.SwitchBase(c, Value, Label) } func ToggleBase(c C, Value *bool, Label string) Box { + useToggle() return base.ToggleBase(c, Value, Label) } -func Toggle(c C, Value *bool, Label string) Box { return base.Toggle(c, Value, Label) } +func Toggle(c C, Value *bool, Label string) Box { useToggle(); return base.Toggle(c, Value, Label) } func DisclosureBase(c C, Value *bool, Label string) Box { + useToggle() return base.DisclosureBase(c, Value, Label) } -func Control(c C, Label string, h *Handlers) Box { useControls(); return base.Control(c, Label, h) } +func Control(c C, Label string, h *Handlers) Box { return base.Control(c, Label, h) } func FormField(c C, state *FormFieldState, Label string) Box { - useControls() return base.FormField(c, state, Label) } func Choice[T comparable](c C, Value *T, choices []T, Label func(T) string) Box { + useSegmented() return base.Choice(c, Value, choices, Label) } func Radio[T comparable](c C, Value *T, option T, Label string) Box { - useControls() + useCheckbox() return base.Radio(c, Value, option, Label) } func RadioID[T comparable](c C, ID gfx.ID, Value *T, option T, Label string) Box { - useControls() + useCheckbox() return base.RadioID(c, ID, Value, option, Label) } func RadioBase[T comparable](c C, Value *T, option T, Label string) Box { - useControls() + useCheckbox() return base.RadioBase(c, Value, option, Label) } -func RadioGroup(c C) Box { useControls(); return base.RadioGroup(c) } +func RadioGroup(c C) Box { return base.RadioGroup(c) } func TabBase[T comparable](c C, Value *T, tab T, Label string) Box { useTabs() @@ -246,9 +251,9 @@ func ColorPickerID(c C, ID gfx.ID, state *ColorPickerState, Color *Color, Label return base.ColorPickerID(c, ID, state, Color, Label) } -func Slider(c C, state *SliderState) Box { return base.Slider(c, state) } +func Slider(c C, state *SliderState) Box { useSlider(); return base.Slider(c, state) } -func SliderBase(c C, state *SliderState) Box { return base.SliderBase(c, state) } +func SliderBase(c C, state *SliderState) Box { useSlider(); return base.SliderBase(c, state) } // NewRangeSliderState returns a range slider holding low and high. func NewRangeSliderState(low, high float32) *RangeSliderState { @@ -274,11 +279,11 @@ func RangeSlider(c C, state *RangeSliderState) Box { Draw(state.DrawFunc()) } -func Splitter(c C, state *SplitterState) Box { return base.Splitter(c, state) } +func Splitter(c C, state *SplitterState) Box { useSplitter(); return base.Splitter(c, state) } -func SplitButton(c C, spec SplitButtonSpec) Box { return base.SplitButton(c, spec) } +func SplitButton(c C, spec SplitButtonSpec) Box { useSplitButton(); return base.SplitButton(c, spec) } -func Pagination(c C, Items []PaginationItem) Box { return base.Pagination(c, Items) } +func Pagination(c C, Items []PaginationItem) Box { usePagination(); return base.Pagination(c, Items) } // Fields and text entry. @@ -434,7 +439,7 @@ func NavigateTree(items []TreeNavigationItem, current int, key gfx.Key, pageRows func ID(c C) gfx.ID { return base.ID(c) } -func NewPage(config PageConfig) *Page { return base.NewPage(config) } +func NewPage(config PageConfig) *Page { useTooltip(); return base.NewPage(config) } func Shortcut(c C, modifiers gfx.Modifiers, key string) bool { return base.Shortcut(c, modifiers, key) diff --git a/ui/hooks_install.go b/ui/hooks_install.go index 44ef2d3de..ee667a9d8 100644 --- a/ui/hooks_install.go +++ b/ui/hooks_install.go @@ -12,56 +12,135 @@ import ( // installs the hooks of the features it declares, so an application links only // the painters it uses. InstallPainters installs all of them, for a host that // drives base directly or for the engine's own tests. -var installControls, installField, installSelect, installTabs, installTable, installTree, - installMenu, installDialog, installAlert, installDrawer, installPopover, installColor, installCombo, installScroll sync.Once +var installButton, installBadge, installPagination, installSplitButton, + installCheckbox, installSwitch, installToggle, installSegmented, + installTextEntry, installIndicators, installSplitter, installSlider, + installTooltip, installField, installSelect, installTabs, installTable, + installTree, installMenu, installDialog, installAlert, installDrawer, + installPopover, installColor, installCombo, installScroll sync.Once -func init() { useControls() } +// useTooltip installs the tooltip painter. Any element can be given a tooltip, +// so a page asks for it once when it is made rather than through a control. +func useTooltip() { installTooltip.Do(func() { base.PaintTooltip = paintTooltip }) } -func useControls() { - installControls.Do(func() { +func useButton() { + installButton.Do(func() { base.SetControlPainter(KindButton, paintButtonControl) + base.SetControlMeasurer(KindButton, measureButtonNode) + base.ControlBaseline = controlBaseline + base.ButtonLookFn = frameButtonLook + }) +} + +func useBadge() { + installBadge.Do(func() { + base.SetControlPainter(KindBadge, paintBadgeControl) + base.SetControlMeasurer(KindBadge, measureBadgeNode) + }) +} + +func usePagination() { + installPagination.Do(func() { + base.SetControlPainter(KindPagination, paintPaginationControl) + base.SetControlMeasurer(KindPagination, measurePaginationNode) + }) +} + +func useSplitButton() { + installSplitButton.Do(func() { + base.SetControlPainter(KindSplitButton, paintSplitButtonControl) + base.SetControlMeasurer(KindSplitButton, measureSplitButtonNode) + }) +} + +func useCheckbox() { + installCheckbox.Do(func() { base.SetControlPainter(KindCheckbox, paintCheckboxControl) + base.SetControlMeasurer(KindCheckbox, measureCheckboxNode) + }) +} + +func useSwitch() { + installSwitch.Do(func() { base.SetControlPainter(KindSwitch, paintSwitchControl) + base.SetControlMeasurer(KindSwitch, measureSwitchNode) + }) +} + +func useToggle() { + installToggle.Do(func() { base.SetControlPainter(KindToggle, paintToggleControl) + base.SetControlMeasurer(KindToggle, measureToggleNode) + }) +} + +func useSegmented() { + installSegmented.Do(func() { + base.SetControlPainter(KindSegmented, paintSegmentedControl) + base.SetControlMeasurer(KindSegmented, measureSegmentedNode) + }) +} + +// useTextEntry installs the looks and measurements of the text-entry controls: +// a single-line field, a field with addons, and the rows of a textarea. +func useTextEntry() { + installTextEntry.Do(func() { base.SetControlPainter(KindInput, paintInputControl) + base.SetControlMeasurer(KindInput, measureInputNode) base.SetControlPainter(KindInputGroup, paintInputGroupControl) + base.SetControlMeasurer(KindInputGroup, measureInputGroupNode) base.SetControlPainter(KindTextarea, paintTextareaControl) - base.SetControlPainter(KindSegmented, paintSegmentedControl) + base.SetControlMeasurer(KindTextarea, measureTextareaNode) + }) +} + +func useIndicators() { + installIndicators.Do(func() { base.SetControlPainter(KindProgress, paintProgressControl) + base.SetControlMeasurer(KindProgress, measureProgressNode) base.SetControlPainter(KindSpinner, paintSpinnerControl) + base.SetControlMeasurer(KindSpinner, measureSpinnerNode) + }) +} + +func useSplitter() { + installSplitter.Do(func() { base.SetControlPainter(KindSplitter, paintSplitterControl) + base.SetControlMeasurer(KindSplitter, measureSplitterNode) + }) +} + +func useSlider() { + installSlider.Do(func() { base.SetControlPainter(KindSlider, paintSliderControl) - base.SetControlPainter(KindSplitButton, paintSplitButtonControl) - base.SetControlPainter(KindBadge, paintBadgeControl) - base.SetControlPainter(KindPagination, paintPaginationControl) - base.ControlMeasurer = measureControls - base.ControlBaseline = controlBaseline - base.ButtonLookFn = frameButtonLook + base.SetControlMeasurer(KindSlider, measureSliderNode) base.SliderPointer = sliderPointer - base.PaintTooltip = paintTooltip }) } func useField() { - useControls() + useTextEntry() installField.Do(func() { base.EntryLook = frameTextEntryLook; base.PaintAddons = paintAddons }) } func useSelect() { - useControls() installSelect.Do(func() { base.SetControlPainter(KindSelect, paintWidgetControl) + base.SetControlMeasurer(KindSelect, measureWidgetNode) base.PaintSelect = paintSelect base.MeasureSelect = measureSelect }) } func useTabs() { - useControls() - installTabs.Do(func() { base.SetControlPainter(KindTabs, paintWidgetControl); base.PaintTabs = paintTabs }) + installTabs.Do(func() { + base.SetControlPainter(KindTabs, paintWidgetControl) + base.SetControlMeasurer(KindTabs, measureWidgetNode) + base.PaintTabs = paintTabs + }) } func useTable() { - useControls() installTable.Do(func() { base.SetControlPainter(KindTable, paintWidgetControl) + base.SetControlMeasurer(KindTable, measureWidgetNode) base.PaintTableRows = paintTableRows base.PaintTableHeaderRow = paintTableHeaderRow base.PaintTableScrollbars = paintTableScrollbars @@ -84,15 +163,26 @@ func usePopover() { installPopover.Do(func() { base.BuildPopover = framePopover func useColor() { installColor.Do(func() { base.PaintSwatch = paintSwatch; base.PaintPickerPanel = paintColorPickerPanel }) } -func useCombo() { useControls(); installCombo.Do(func() { base.PaintCombo = comboStateDraw }) } +func useCombo() { useField(); installCombo.Do(func() { base.PaintCombo = comboStateDraw }) } func useScroll() { installScroll.Do(func() { base.PaintScrollbars = paintScrollbars }) } // InstallPainters installs every painter the styled layer owns. Applications // get what they use from the ui constructors; this is for a host that drives // base directly, and for the engine's tests. func InstallPainters() { - useControls() + useButton() + useBadge() + usePagination() + useSplitButton() + useCheckbox() + useSwitch() + useToggle() + useSegmented() useField() + useIndicators() + useSplitter() + useSlider() + useTooltip() useSelect() useTabs() useTable() From 0bc32656fd0667e94603bb0ffca93b033a6a3e0c Mon Sep 17 00:00:00 2001 From: ezreal <71426102+Ezreal-byte@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:01:47 +0800 Subject: [PATCH 02/16] feat(app): update the window icon and Windows taskbar resources --- .github/workflows/ci.yml | 4 +- app/application_native.go | 9 ++ app/window_icon.go | 42 ++++++++- app/window_icon_update_test.go | 76 +++++++++++++++++ headless/application.go | 14 ++- internal/platform/contract.go | 6 ++ internal/platform/darwin/status_item_darwin.h | 2 + internal/platform/darwin/status_item_darwin.m | 43 ++++++---- .../darwin/status_item_darwin_test.go | 22 +++++ .../platform/darwin/testdata/status_item.m | 27 ++++++ .../platform/darwin/window_icon_darwin.go | 19 ++++- internal/platform/linux/gtk_icon_linux.go | 37 ++++++-- .../platform/linux/gtk_icon_linux_test.go | 70 +++++++++++++++ internal/platform/linux/gtk_window_linux.go | 5 +- internal/platform/linux/status_item_linux.go | 2 + internal/platform/linux/window_icon_linux.go | 34 +++++++- .../linux/window_icon_update_linux_test.go | 83 ++++++++++++++++++ internal/platform/linux/window_linux.go | 3 + internal/platform/window_icon.go | 2 + .../platform/windows/taskbar_icon_windows.go | 85 +++++++++++++++++++ .../window_icon_update_windows_test.go | 84 ++++++++++++++++++ .../platform/windows/window_icon_windows.go | 49 ++++++++++- internal/platform/windows/window_windows.go | 6 ++ tools/dmg/build.go | 6 +- 24 files changed, 699 insertions(+), 31 deletions(-) create mode 100644 app/window_icon_update_test.go create mode 100644 internal/platform/linux/gtk_icon_linux_test.go create mode 100644 internal/platform/linux/window_icon_update_linux_test.go create mode 100644 internal/platform/windows/taskbar_icon_windows.go create mode 100644 internal/platform/windows/window_icon_update_windows_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 926747fc0..20907cc6f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -132,7 +132,7 @@ jobs: run: | sudo apt-get install -y xvfb xdotool libx11-xcb1 || { sudo apt-get update && sudo apt-get install -y xvfb xdotool libx11-xcb1; } - xvfb-run -a go test ./internal/platform/linux -run '^TestNativeX11GlobalShortcut$' -count=1 -v + xvfb-run -a go test ./internal/platform/linux -run '^TestNativeX11(GlobalShortcut|WindowIconPropertyUpdates)$' -count=1 -v # The browser target is a release target: it compiles every package, runs the # shared tests under GOOS=js, and builds the browser entry points and a guide. @@ -304,6 +304,8 @@ jobs: run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|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)' -count=1 -v - name: Terminal keyboard routing run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v + - name: Native window and grouped taskbar icons + run: go test ./internal/platform/windows -run '^TestWindowIconUpdatesOnTheWindowThread$' -count=1 -v - name: Native Windows global shortcut env: VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1' diff --git a/app/application_native.go b/app/application_native.go index b6836e62f..7abf1b4b8 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -87,6 +87,7 @@ var _ fullscreenControl = resultWindow{} var _ alwaysOnTopControl = resultWindow{} var _ shortcutCapturer = resultWindow{} var _ titleControl = resultWindow{} +var _ windowIconControl = resultWindow{} var _ platform.WindowMover = resultWindow{} // What OpenWindow looks for in a host's window control. @@ -125,6 +126,14 @@ func (window resultWindow) SetTitle(title string) error { return control.SetTitle(title) } +func (window resultWindow) SetIcon(icon WindowIcon) error { + control, ok := window.WindowControl.(platform.WindowIconSetter) + if !ok { + return fmt.Errorf("%w: window icons", ErrUnsupported) + } + return control.SetIcon(icon.platform()) +} + func (window resultWindow) SetAlwaysOnTop(enabled bool) error { control, ok := window.WindowControl.(alwaysOnTopControl) if !ok { diff --git a/app/window_icon.go b/app/window_icon.go index cd4866dbb..f3ad06963 100644 --- a/app/window_icon.go +++ b/app/window_icon.go @@ -2,7 +2,9 @@ package app import ( "fmt" + "path/filepath" "runtime" + "strings" "github.com/vivaui/viva/internal/platform" ) @@ -18,6 +20,40 @@ type WindowIcon struct { Size int // RGBA is Size*Size straight (not premultiplied) 8-bit pixels, top row first. RGBA []byte + // ResourcePath optionally names a persistent, absolute .ico file on Windows. + // With Config.Class set, it also supplies the taskbar group's and newly + // pinned shortcut's icon. The caller owns this file and must keep it after + // exit. Other platforms ignore it. Existing shortcuts are not edited. + ResourcePath string +} + +type windowIconControl interface { + SetIcon(WindowIcon) error +} + +// SetIcon replaces the running window's title-bar and task-switcher icon. On +// macOS it replaces the application's Dock icon, including in an .app bundle; +// on Windows, see ResourcePath for grouped/pinned taskbar icons; on Wayland the +// compositor may keep the desktop entry's icon. Installed launchers and signed +// application resources are not changed. Calls are safe +// from any goroutine. The pixels are copied before returning. An empty or +// invalid icon changes nothing; unsupported hosts return ErrUnsupported. +func (window *Window) SetIcon(icon WindowIcon) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("app: window is closed") + } + if err := icon.validate(); err != nil { + return err + } + if icon.Size == 0 { + return fmt.Errorf("app: window icon must not be empty") + } + control, ok := window.control.(windowIconControl) + if !ok { + return fmt.Errorf("%w: window icons", ErrUnsupported) + } + icon.RGBA = append([]byte(nil), icon.RGBA...) + return control.SetIcon(icon) } // StatusIcon is the picture as a status-area icon of size pixels, in the form @@ -36,6 +72,10 @@ func (icon WindowIcon) StatusIcon(size int) StatusIcon { } func (icon WindowIcon) validate() error { + if runtime.GOOS == "windows" && icon.ResourcePath != "" && + (!filepath.IsAbs(icon.ResourcePath) || strings.ContainsRune(icon.ResourcePath, 0)) { + return fmt.Errorf("app: icon resource must be an absolute path without NUL") + } if icon.Size == 0 && len(icon.RGBA) == 0 { return nil } @@ -46,5 +86,5 @@ func (icon WindowIcon) validate() error { } func (icon WindowIcon) platform() platform.WindowIcon { - return platform.WindowIcon{Size: icon.Size, RGBA: icon.RGBA} + return platform.WindowIcon{Size: icon.Size, RGBA: icon.RGBA, ResourcePath: icon.ResourcePath} } diff --git a/app/window_icon_update_test.go b/app/window_icon_update_test.go new file mode 100644 index 000000000..51e2dbe3f --- /dev/null +++ b/app/window_icon_update_test.go @@ -0,0 +1,76 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "path/filepath" + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +type iconTestControl struct { + fakeWindow + icon WindowIcon +} + +func (control *iconTestControl) SetIcon(icon WindowIcon) error { + control.icon = icon + return nil +} + +func TestWindowIconUpdateValidatesAndCopiesPixels(t *testing.T) { + control := &iconTestControl{} + window := &Window{control: control} + icon := WindowIcon{Size: 1, RGBA: []byte{30, 100, 220, 255}} + if err := window.SetIcon(icon); err != nil { + t.Fatal(err) + } + icon.RGBA[0] = 200 + if control.icon.RGBA[0] != 30 { + t.Fatal("the host retained caller-owned pixels") + } + for _, invalid := range []WindowIcon{{}, {Size: 1}, {Size: 1025}} { + if err := window.SetIcon(invalid); err == nil || control.icon.RGBA[0] != 30 { + t.Fatal("an invalid update changed the icon") + } + } + window.closed.Store(true) + if err := window.SetIcon(icon); err == nil { + t.Fatal("a closed window accepted an icon") + } + var missing *Window + if err := missing.SetIcon(icon); err == nil { + t.Fatal("a nil window accepted an icon") + } + if err := (&Window{control: &fakeWindow{}}).SetIcon(icon); !errors.Is(err, ErrUnsupported) { + t.Fatalf("unsupported window: %v", err) + } +} + +type nativeIconTestControl struct { + fakeWindow + icon platform.WindowIcon +} + +func (control *nativeIconTestControl) SetIcon(icon platform.WindowIcon) error { + control.icon = icon + return nil +} + +func TestResultWindowForwardsIconUpdates(t *testing.T) { + native := &nativeIconTestControl{} + window := &Window{control: resultWindow{WindowControl: native}} + resource := filepath.Join(t.TempDir(), "logo.ico") + if err := window.SetIcon(WindowIcon{Size: 1, RGBA: []byte{1, 2, 3, 255}, ResourcePath: resource}); err != nil { + t.Fatal(err) + } + if native.icon.Size != 1 || native.icon.RGBA[2] != 3 || native.icon.ResourcePath != resource { + t.Fatalf("native icon = %+v", native.icon) + } + window = &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := window.SetIcon(WindowIcon{Size: 1, RGBA: make([]byte, 4)}); !errors.Is(err, ErrUnsupported) { + t.Fatalf("wrapped unsupported window: %v", err) + } +} diff --git a/headless/application.go b/headless/application.go index dd7dac503..eb6786654 100644 --- a/headless/application.go +++ b/headless/application.go @@ -25,6 +25,7 @@ type applicationWindow struct { invalidator *app.Invalidator id uint64 title string + icon app.WindowIcon panel bool hidden bool session *Session @@ -85,7 +86,7 @@ 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{} + entry := &applicationWindow{icon: config.Icon} if config.Invalidator == nil { config.Invalidator = &app.Invalidator{} } @@ -191,6 +192,17 @@ func (window *headlessWindow) SetTitle(title string) error { return nil } +func (window *headlessWindow) SetIcon(icon app.WindowIcon) error { + 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.icon = icon + return nil +} + func (window *headlessWindow) Fullscreen() bool { window.application.mu.Lock() entry := window.application.windows[window.id] diff --git a/internal/platform/contract.go b/internal/platform/contract.go index d0799704b..73d855e2f 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -193,6 +193,12 @@ type Window interface { Frame() (gfx.Rect, bool) } +// WindowIconSetter updates a running window's desktop icon. The caller owns +// validation and transfers an immutable copy of the pixels to the adapter. +type WindowIconSetter interface { + SetIcon(WindowIcon) error +} + // WindowMover is implemented by the windows of an adapter that can put a window // somewhere without the user dragging it. MoveTo puts the top-left of the // content area at origin, in the screen coordinates of Window.Frame. It is diff --git a/internal/platform/darwin/status_item_darwin.h b/internal/platform/darwin/status_item_darwin.h index 8c08a1169..be6d005c4 100644 --- a/internal/platform/darwin/status_item_darwin.h +++ b/internal/platform/darwin/status_item_darwin.h @@ -23,6 +23,8 @@ typedef struct { /* Sets the Dock icon of a program that is not in an .app bundle. Returns 0 when * it did not. Main thread only. */ int viva_application_set_icon(viva_status_icon icon); +/* Replaces the Dock icon even in an .app bundle. Marshals to the main thread. */ +int viva_application_update_icon(viva_status_icon icon); void *viva_status_item_create(const char *tooltip, viva_status_icon icon, uintptr_t callback_handle, int has_menu); int viva_status_item_set_icon(void *item, viva_status_icon icon); void viva_status_item_set_tooltip(void *item, const char *tooltip); diff --git a/internal/platform/darwin/status_item_darwin.m b/internal/platform/darwin/status_item_darwin.m index d3c4dbfbc..36422da08 100644 --- a/internal/platform/darwin/status_item_darwin.m +++ b/internal/platform/darwin/status_item_darwin.m @@ -1,4 +1,5 @@ #import +#import #include @@ -215,23 +216,35 @@ - (void)clicked:(id)sender { static void viva_status_item_remove_now(void *item); static void viva_status_items_remove_all(void); -int viva_application_set_icon(viva_status_icon icon) { - @autoreleasepool { - /* A bundle's own icon is the application's; this is for a program run - * from a build directory, which the Dock would show as a plain - * executable. */ - if ([[[NSBundle mainBundle] bundlePath] hasSuffix:@".app"]) { - return 0; - } - /* The Dock draws an icon at up to 128 points, on a 2x screen from twice - * the pixels, so the image is declared at half its pixel size. */ - NSImage *image = viva_icon_image(icon, icon.size / 2.0); - if (image == nil) { - return 0; +int viva_application_update_icon(viva_status_icon icon) { + __block int result = 0; + void (^work)(void) = ^{ + @autoreleasepool { + /* The Dock draws an icon at up to 128 points, on a 2x screen from twice + * the pixels, so the image is declared at half its pixel size. */ + NSImage *image = viva_icon_image(icon, icon.size / 2.0); + if (image == nil) { + return; + } + [NSApp setApplicationIconImage:image]; + result = 1; } - [NSApp setApplicationIconImage:image]; - return 1; + }; + if ([NSThread isMainThread]) { + work(); + } else { + dispatch_sync(dispatch_get_main_queue(), work); + } + return result; +} + +int viva_application_set_icon(viva_status_icon icon) { + /* At startup a bundle keeps its packaged icon. Explicit user changes use + * viva_application_update_icon and apply to bundled applications too. */ + if ([[[NSBundle mainBundle] bundlePath] hasSuffix:@".app"]) { + return 0; } + return viva_application_update_icon(icon); } void *viva_status_item_create(const char *tooltip, viva_status_icon icon, uintptr_t callback_handle, int has_menu) { diff --git a/internal/platform/darwin/status_item_darwin_test.go b/internal/platform/darwin/status_item_darwin_test.go index 6f0b52e6f..50582a53d 100644 --- a/internal/platform/darwin/status_item_darwin_test.go +++ b/internal/platform/darwin/status_item_darwin_test.go @@ -3,6 +3,7 @@ package darwin import ( + "os" "os/exec" "path/filepath" "testing" @@ -22,4 +23,25 @@ func TestNativeStatusItemMenuDelegateAndSelection(t *testing.T) { if output, err := exec.Command(executable).CombinedOutput(); err != nil { t.Fatalf("native status item: %v\n%s", err, output) } + // Exercise the .app launch path too: startup may retain a bundled icon, but + // an explicit preference must still override the running Dock image. + bundle := filepath.Join(t.TempDir(), "IconTest.app", "Contents") + if err := os.MkdirAll(filepath.Join(bundle, "MacOS"), 0700); err != nil { + t.Fatal(err) + } + info := `CFBundleExecutablestatus-itemCFBundleIdentifierdev.viva.icon-testCFBundlePackageTypeAPPL` + if err := os.WriteFile(filepath.Join(bundle, "Info.plist"), []byte(info), 0600); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(executable) + if err != nil { + t.Fatal(err) + } + bundled := filepath.Join(bundle, "MacOS", "status-item") + if err := os.WriteFile(bundled, data, 0700); err != nil { + t.Fatal(err) + } + if output, err := exec.Command(bundled).CombinedOutput(); err != nil { + t.Fatalf("bundled Dock/status icon: %v\n%s", err, output) + } } diff --git a/internal/platform/darwin/testdata/status_item.m b/internal/platform/darwin/testdata/status_item.m index 32402837b..4030f411d 100644 --- a/internal/platform/darwin/testdata/status_item.m +++ b/internal/platform/darwin/testdata/status_item.m @@ -57,6 +57,29 @@ int main(void) { } viva_status_icon icon = {18, rgba, 0}; + NSImage *originalIcon = [[NSApp applicationIconImage] retain]; + for (int color = 0; color < 2; color++) { + for (int i = 0; i < 18 * 18 * 4; i += 4) { + rgba[i] = color == 0 ? 255 : 0; + rgba[i + 1] = 0; + rgba[i + 2] = color == 0 ? 0 : 255; + } + check(viva_application_update_icon(icon) == 1, "Dock update accepted"); + NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[[NSApp applicationIconImage] TIFFRepresentation]]; + NSColor *pixel = [[rep colorAtX:rep.pixelsWide / 2 y:rep.pixelsHigh / 2] + colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]]; + int matches = pixel != nil && (color == 0 ? pixel.redComponent > 0.9 && pixel.blueComponent < 0.1 + : pixel.blueComponent > 0.9 && pixel.redComponent < 0.1); + if (!matches) { + fprintf(stderr, "Dock image %ldx%ld center: %s\n", (long)rep.pixelsWide, (long)rep.pixelsHigh, + [[pixel description] UTF8String]); + } + check(matches, + "Dock stores the new pixels, including a second change"); + } + [NSApp setApplicationIconImage:originalIcon]; + [originalIcon release]; + // 1. Create status item with Menu void *item = viva_status_item_create("Test Tooltip", icon, 1234, 1); check(item != NULL, "item created"); @@ -66,6 +89,10 @@ int main(void) { check(statusItem != nil, "NSStatusItem exists"); check([statusItem.button.toolTip isEqualToString:@"Test Tooltip"], "tooltip set"); + icon.template_image = 1; + check(viva_status_item_set_icon(item, icon) == 1, "menu bar template update accepted"); + check(statusItem.button.image.isTemplate, "menu bar preserves system monochrome template policy"); + NSMenu *menu = statusItem.menu; check(menu != nil, "NSStatusItem has menu"); check(menu.delegate == (id)item, "NSMenu delegate is item"); diff --git a/internal/platform/darwin/window_icon_darwin.go b/internal/platform/darwin/window_icon_darwin.go index 2d8dd5dea..d54d5deb9 100644 --- a/internal/platform/darwin/window_icon_darwin.go +++ b/internal/platform/darwin/window_icon_darwin.go @@ -8,7 +8,24 @@ package darwin */ import "C" -import "github.com/vivaui/viva/internal/platform" +import ( + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +func (window *nativeWindow) SetIcon(icon platform.WindowIcon) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("darwin: window is closed") + } + tile := icon.Tile(dockIconPixels, platform.MacInset) + pixels := C.CBytes(tile.RGBA) + defer C.free(pixels) + if C.viva_application_update_icon(C.viva_status_icon{size: C.int(tile.Size), rgba: (*C.uchar)(pixels)}) == 0 { + return fmt.Errorf("darwin: could not update Dock icon") + } + return nil +} // dockIconPixels is the size the Dock icon is made at: 256 points on a 2x screen. const dockIconPixels = 512 diff --git a/internal/platform/linux/gtk_icon_linux.go b/internal/platform/linux/gtk_icon_linux.go index e855dbf06..9f6996466 100644 --- a/internal/platform/linux/gtk_icon_linux.go +++ b/internal/platform/linux/gtk_icon_linux.go @@ -3,12 +3,27 @@ package linux import ( + "fmt" "math" + "unsafe" "github.com/ebitengine/purego" "github.com/vivaui/viva/internal/platform" ) +func (w *gtkWindow) SetIcon(icon platform.WindowIcon) error { + if w == nil || w.app == nil { + return fmt.Errorf("linux: window is closed") + } + w.app.enqueue(func() { + if !w.closed { + w.config.Icon = icon + w.setIcon() + } + }) + return nil +} + // setIcon gives the window the application's picture where the desktop shows one (the title bar and // the task switcher on X11; Wayland takes the icon of the application's desktop entry instead). func (w *gtkWindow) setIcon() { @@ -17,12 +32,17 @@ func (w *gtkWindow) setIcon() { return } g := w.g - var newFromData func(data *byte, colorspace, alpha, bits, width, height, stride int32, destroy, destroyData uintptr) uintptr + var newPixbuf func(colorspace, alpha, bits, width, height int32) uintptr + var pixbufPixels func(uintptr) *byte + var pixbufStride func(uintptr) int32 library, err := purego.Dlopen("libgdk_pixbuf-2.0.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL) - if err != nil || !g.lookup(&newFromData, "gdk_pixbuf_new_from_data") { + if err != nil { + return + } + defer purego.Dlclose(library) + if !g.lookup(&newPixbuf, "gdk_pixbuf_new") || !g.lookup(&pixbufPixels, "gdk_pixbuf_get_pixels") || !g.lookup(&pixbufStride, "gdk_pixbuf_get_rowstride") { return } - _ = library var list uintptr var pixbufs []uintptr for _, size := range netWMIconSizes { @@ -35,9 +55,16 @@ func (w *gtkWindow) setIcon() { if !tile.Valid() { continue } - w.iconData = append(w.iconData, tile.RGBA) - pixbuf := newFromData(&tile.RGBA[0], 0, 1, 8, int32(tile.Size), int32(tile.Size), int32(tile.Size*4), 0, 0) + pixbuf := newPixbuf(0, 1, 8, int32(tile.Size), int32(tile.Size)) if pixbuf != 0 { + // GTK can retain a pixbuf after the window replaces its icon. Give + // it native-owned pixels instead of retaining Go slices indefinitely + // or releasing them while another GTK object still reads them. + stride := int(pixbufStride(pixbuf)) + pixels := unsafe.Slice(pixbufPixels(pixbuf), (tile.Size-1)*stride+tile.Size*4) + for row := 0; row < tile.Size; row++ { + copy(pixels[row*stride:row*stride+tile.Size*4], tile.RGBA[row*tile.Size*4:(row+1)*tile.Size*4]) + } pixbufs = append(pixbufs, pixbuf) list = g.listAppend(list, pixbuf) } diff --git a/internal/platform/linux/gtk_icon_linux_test.go b/internal/platform/linux/gtk_icon_linux_test.go new file mode 100644 index 000000000..e4b6bde2e --- /dev/null +++ b/internal/platform/linux/gtk_icon_linux_test.go @@ -0,0 +1,70 @@ +//go:build linux && vivagtk + +package linux + +import ( + "runtime" + "testing" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/internal/platform" +) + +func TestGTKIconPixbufKeepsItsPixelsAfterReplacement(t *testing.T) { + g := >kLibrary{} + for _, name := range []string{"libgdk_pixbuf-2.0.so.0", "libgobject-2.0.so.0", "libglib-2.0.so.0"} { + library, err := purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + t.Skipf("native pixbuf test needs %s: %v", name, err) + } + g.libraries = append(g.libraries, library) + t.Cleanup(func() { purego.Dlclose(library) }) + } + g.bind(&g.listAppend, "g_list_append") + g.bind(&g.listFree, "g_list_free") + g.bind(&g.objectRef, "g_object_ref") + g.bind(&g.objectUnref, "g_object_unref") + var pixels func(uintptr) *byte + var stride func(uintptr) int32 + var listData func(uintptr, uint32) uintptr + g.bind(&pixels, "gdk_pixbuf_get_pixels") + g.bind(&stride, "gdk_pixbuf_get_rowstride") + g.bind(&listData, "g_list_nth_data") + if g.err != nil { + t.Fatal(g.err) + } + var retained []uintptr + g.windowSetIconList = func(_ uintptr, list uintptr) { + // Hold a reference as another GTK object could, after the window has + // replaced its icon list. + pixbuf := listData(list, 0) + retained = append(retained, g.objectRef(pixbuf)) + } + t.Cleanup(func() { + for _, pixbuf := range retained { + g.objectUnref(pixbuf) + } + }) + w := >kWindow{g: g, toplevel: 1} + for _, red := range []byte{50, 200} { + data := make([]byte, 16*16*4) + for index := 0; index < len(data); index += 4 { + copy(data[index:], []byte{red, 100, 30, 255}) + } + w.config.Icon = platform.WindowIcon{Size: 16, RGBA: data} + w.setIcon() + } + if len(retained) != 2 { + t.Fatalf("retained %d pixbufs, want two icon updates", len(retained)) + } + runtime.GC() + for index, red := range []byte{50, 200} { + pixbuf := retained[index] + data := unsafe.Slice(pixels(pixbuf), 15*int(stride(pixbuf))+16*4) + center := 8*int(stride(pixbuf)) + 8*4 + if data[center] != red || data[center+3] != 255 { + t.Fatalf("retained icon %d lost its native pixels: %v", index, data[center:center+4]) + } + } +} diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index 40196d337..1d927b829 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -60,9 +60,8 @@ type gtkWindow struct { regionsDirty bool // dragging and dropping follow a drag of files over the window. dragging, dropping bool - // iconData keeps the pixels the window's icon pixbufs point at; originPending says the window - // was asked to open at a place and has not been checked there yet. - iconData [][]byte + // originPending says the window was asked to open at a place and has not + // been checked there yet. originPending bool // cursors are the GDK cursors made so far, by shape; cursorShape is the one in use plus one. cursors [len(cursorNames) + 1]uintptr // the last is the hidden one diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 1753b0646..94eb75af3 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -147,6 +147,8 @@ func (state *linuxWindowState) command(command uint32, data []byte) error { switch command { case commandSetTitle: win.applyPendingTitle() + case commandSetIcon: + win.applyPendingIcon() case commandSetSize: if len(data) < 12 || win.frame.maximized || win.minimized || win.fullscreen.Load() { return nil diff --git a/internal/platform/linux/window_icon_linux.go b/internal/platform/linux/window_icon_linux.go index ccef7c0e9..d93ae4fb9 100644 --- a/internal/platform/linux/window_icon_linux.go +++ b/internal/platform/linux/window_icon_linux.go @@ -1,6 +1,38 @@ package linux -import "github.com/vivaui/viva/internal/platform" +import ( + "fmt" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +func (window *nativeWindow) SetIcon(icon platform.WindowIcon) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("linux: window is closed") + } + win := window.state.win + win.iconMu.Lock() + win.pendingIcon = icon + win.iconMu.Unlock() + win.postClientMessage(win.commandAtom, commandSetIcon) + return nil +} + +func (win *window) applyPendingIcon() { + win.iconMu.Lock() + icon := win.pendingIcon + win.pendingIcon = platform.WindowIcon{} + win.iconMu.Unlock() + data := netWMIcon(icon) + if len(data) == 0 { + return + } + if atom, err := win.api.atom(win.connection, "_NET_WM_ICON"); err == nil { + win.api.changeProperty(win.connection, xcbPropertyReplace, win.id, atom, xcbAtomCardinal, 32, uint32(len(data)), unsafe.Pointer(&data[0])) + win.api.flush(win.connection) + } +} // netWMIconSizes are the sizes offered in _NET_WM_ICON: a panel, a title bar and // Alt+Tab each take the one nearest what they draw. A size above the source's own diff --git a/internal/platform/linux/window_icon_update_linux_test.go b/internal/platform/linux/window_icon_update_linux_test.go new file mode 100644 index 000000000..1896cca33 --- /dev/null +++ b/internal/platform/linux/window_icon_update_linux_test.go @@ -0,0 +1,83 @@ +package linux + +import ( + "encoding/binary" + "os" + "slices" + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +func TestNativeX11WindowIconPropertyUpdates(t *testing.T) { + if os.Getenv("DISPLAY") == "" { + t.Skip("requires X11 or Xvfb") + } + win, err := openWindow(platform.Config{Title: "Viva icon property test", Width: 120, Height: 80}) + if err != nil { + t.Fatal(err) + } + defer win.close() + window := &nativeWindow{state: &linuxWindowState{win: win}} + for _, color := range []byte{50, 210} { + icon := platform.WindowIcon{Size: 16, RGBA: make([]byte, 16*16*4)} + for i := 0; i < len(icon.RGBA); i += 4 { + copy(icon.RGBA[i:], []byte{color, 40, 70, 255}) + } + if err := window.SetIcon(icon); err != nil { + t.Fatal(err) + } + if err := window.state.command(commandSetIcon, nil); err != nil { + t.Fatal(err) + } + data, format := windowProperty(t, win, "_NET_WM_ICON", xcbAtomCardinal) + want := netWMIcon(icon) + if format != 32 || len(data) != len(want)*4 { + t.Fatalf("native icon property: format %d, %d bytes", format, len(data)) + } + for i, pixel := range want { + if got := binary.LittleEndian.Uint32(data[i*4:]); got != pixel { + t.Fatalf("native property pixel %d: %#x, want %#x", i, got, pixel) + } + } + } +} + +func TestWindowIconUpdateWritesTheLatestIconOnTheEventLoop(t *testing.T) { + var ignored []titleProperty + win := newTitleTestWindow(t, &ignored) + win.api.free = func(unsafe.Pointer) {} + var written []uint32 + win.api.internAtom = func(uintptr, uint8, uint16, *byte) xcbAtomCookie { + return xcbAtomCookie{Sequence: 73} + } + win.api.changeProperty = func(_ uintptr, _ uint8, _ uint32, property, kind uint32, format uint8, length uint32, data unsafe.Pointer) xcbVoidCookie { + if property != 73 || kind != xcbAtomCardinal || format != 32 { + t.Fatalf("wrong icon property: %d %d %d", property, kind, format) + } + written = slices.Clone(unsafe.Slice((*uint32)(data), int(length))) + return xcbVoidCookie{} + } + window := &nativeWindow{state: &linuxWindowState{win: win}} + var last platform.WindowIcon + for _, red := range []byte{100, 200} { + last = platform.WindowIcon{Size: 1, RGBA: []byte{red, 20, 30, 255}} + if err := window.SetIcon(last); err != nil { + t.Fatal(err) + } + } + if written != nil { + t.Fatal("the caller wrote X11 properties outside the event loop") + } + if err := window.state.command(commandSetIcon, nil); err != nil { + t.Fatal(err) + } + if !slices.Equal(written, netWMIcon(last)) { + t.Fatal("the event loop did not publish the latest icon") + } + window.closed.Store(true) + if err := window.SetIcon(last); err == nil { + t.Fatal("a closed window accepted an icon") + } +} diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 8e83b3645..5235e23f6 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -38,6 +38,8 @@ type window struct { // has not written to the window yet. titleMu sync.Mutex pendingTitle string + iconMu sync.Mutex + pendingIcon platform.WindowIcon moveResizeAtom uint32 cursor uint32 // themed is the cursor theme's loader, tried once. @@ -208,6 +210,7 @@ const ( commandSetSize commandSetTitle commandPost + commandSetIcon ) type nativeWindow struct { diff --git a/internal/platform/window_icon.go b/internal/platform/window_icon.go index 2fbe38aa8..c26912811 100644 --- a/internal/platform/window_icon.go +++ b/internal/platform/window_icon.go @@ -14,6 +14,8 @@ type WindowIcon struct { Size int // RGBA is Size*Size straight (not premultiplied) 8-bit pixels, top row first. RGBA []byte + // ResourcePath is an optional persistent Windows taskbar icon (.ico). + ResourcePath string } // MacInset is the share of the canvas a macOS icon's tile fills. diff --git a/internal/platform/windows/taskbar_icon_windows.go b/internal/platform/windows/taskbar_icon_windows.go new file mode 100644 index 000000000..dfca1d39c --- /dev/null +++ b/internal/platform/windows/taskbar_icon_windows.go @@ -0,0 +1,85 @@ +package windows + +import ( + "syscall" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +var getWindowPropertyStore = shell.NewProc("SHGetPropertyStoreForWindow") +var iidPropertyStore = guid{0x886d8eeb, 0x8cf2, 0x4446, [8]byte{0x8d, 0x02, 0xcd, 0xba, 0x1d, 0xbd, 0xcf, 0x99}} +var appModelKey = guid{0x9f4c2855, 0x9f79, 0x4b39, [8]byte{0xa8, 0xd0, 0xe1, 0xd4, 0x2d, 0xe1, 0xd5, 0xf3}} + +type propertyKey struct { + Format guid + ID uint32 +} + +// PROPVARIANT's union is 16 bytes on Win64, 8 on Win32. The string pointer is +// borrowed only for SetValue, which copies it; it must not be PropVariantClear'd. +type stringProperty struct { + Kind uint16 + Reserved [3]uint16 + Text *uint16 + Tail uintptr +} + +func setStringProperty(store uintptr, id uint32, text string) error { + encoded, err := syscall.UTF16PtrFromString(text) + if err != nil { + return err + } + key := propertyKey{Format: appModelKey, ID: id} + value := stringProperty{Kind: 31 /* VT_LPWSTR */, Text: encoded} + return hresult(comCall(store, 6 /* SetValue */, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&value)))) +} + +// WM_SETICON supplies an individual window. Explorer reads the group's picture +// from its shortcut or these properties instead. Set the icon before the +// window AppID: assigning the AppID tells the shell to refresh the button. +// Called only on the window thread, including before its first ShowWindow. +func (state *windowState) setTaskbarIcon(path string) error { + id := platform.AppUserModelID(state.config.Class) + if id == "" { + return nil + } + var store uintptr + status, _, _ := getWindowPropertyStore.Call(state.window, uintptr(unsafe.Pointer(&iidPropertyStore)), uintptr(unsafe.Pointer(&store))) + if err := hresult(status); err != nil { + return err + } + defer release(&store) + // Also clear a partially applied update if a later SetValue fails. + state.taskbarIconSet = true + for _, property := range []struct { + id uint32 + text string + }{ + {3, path + ",0"}, + {5, id}, + } { + if err := setStringProperty(store, property.id, property.text); err != nil { + return err + } + } + return nil // HWND property stores apply SetValue immediately; no Commit. +} + +func (state *windowState) clearTaskbarIcon() { + if !state.taskbarIconSet { + return + } + var store uintptr + status, _, _ := getWindowPropertyStore.Call(state.window, uintptr(unsafe.Pointer(&iidPropertyStore)), uintptr(unsafe.Pointer(&store))) + if hresult(status) != nil { + return + } + defer release(&store) + for _, id := range []uint32{3, 5} { + key := propertyKey{Format: appModelKey, ID: id} + var empty stringProperty // VT_EMPTY releases the window's stored value. + comCall(store, 6, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&empty))) + } + state.taskbarIconSet = false +} diff --git a/internal/platform/windows/window_icon_update_windows_test.go b/internal/platform/windows/window_icon_update_windows_test.go new file mode 100644 index 000000000..d3368fb7a --- /dev/null +++ b/internal/platform/windows/window_icon_update_windows_test.go @@ -0,0 +1,84 @@ +package windows + +import ( + "os" + "path/filepath" + "runtime" + "syscall" + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" +) + +func TestWindowIconUpdatesOnTheWindowThread(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva icon test", Class: "dev.viva.icon-test", Width: 320, Height: 200, + OnResize: func(platform.Size) (platform.Frame, error) { + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + }, + }) + if err != nil { + return err + } + defer opened.Close() + window := opened.(*nativeWindow) + for _, value := range []byte{50, 200, 80} { + icon := platform.WindowIcon{Size: 1, RGBA: []byte{value, 100, 30, 255}} + // Explorer reads a separate property from WM_GETICON. Assert that the + // new resource and explicit *window* AppID reach the real shell store. + icon.ResourcePath = filepath.Join(t.TempDir(), "color.ico") + if err := os.WriteFile(icon.ResourcePath, []byte("property test"), 0600); err != nil { + t.Fatal(err) + } + previous := window.state.icons + if err := window.SetIcon(icon); err != nil { + t.Fatal(err) + } + if window.state.icons != previous { + t.Fatal("the caller changed icons outside the window loop") + } + pumpWindowMessages() + var store uintptr + status, _, _ := getWindowPropertyStore.Call(window.state.window, uintptr(unsafe.Pointer(&iidPropertyStore)), uintptr(unsafe.Pointer(&store))) + if err := hresult(status); err != nil { + t.Fatal(err) + } + for id, want := range map[uint32]string{3: icon.ResourcePath + ",0", 5: "dev.viva.icon-test"} { + key := propertyKey{Format: appModelKey, ID: id} + var got stringProperty + if err := hresult(comCall(store, 5 /* GetValue */, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&got)))); err != nil { + t.Fatal(err) + } + if got.Kind != 31 || syscall.UTF16ToString(unsafe.Slice(got.Text, len(want)+1)) != want { + t.Fatalf("shell property %d did not change", id) + } + ole.NewProc("PropVariantClear").Call(uintptr(unsafe.Pointer(&got))) + } + release(&store) + if window.state.icons[0] == 0 || window.state.icons[1] == 0 || window.state.icons[1] == previous[1] { + t.Fatalf("native icon handles did not change: %v -> %v", previous, window.state.icons) + } + for kind, handle := range window.state.icons { + got, _, _ := sendMessage.Call(window.state.window, 0x007f /* WM_GETICON */, uintptr(kind), 0) + if got != handle { + t.Fatalf("Windows icon %d = %d, want %d", kind, got, handle) + } + } + if previous[1] != 0 { + if copied, _, _ := user.NewProc("CopyIcon").Call(previous[1]); copied != 0 { + destroyIcon.Call(copied) + t.Fatal("replacing the window icon leaked the previous handle") + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/platform/windows/window_icon_windows.go b/internal/platform/windows/window_icon_windows.go index 204462c93..7c6e45e59 100644 --- a/internal/platform/windows/window_icon_windows.go +++ b/internal/platform/windows/window_icon_windows.go @@ -1,6 +1,12 @@ package windows -import "github.com/vivaui/viva/internal/platform" +import ( + "fmt" + "log" + "sync" + + "github.com/vivaui/viva/internal/platform" +) const ( wmSetIcon = 0x0080 @@ -12,6 +18,38 @@ const ( var sendMessage = user.NewProc("SendMessageW") +const wmUpdateIcon = 0x8055 // after wmDragEnded + +type iconRequest struct { + mu sync.Mutex + icon platform.WindowIcon +} + +func (window *nativeWindow) SetIcon(icon platform.WindowIcon) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + request := &window.state.pendingIcon + request.mu.Lock() + request.icon = icon + request.mu.Unlock() + if ok, _, err := postMessage.Call(window.state.window, wmUpdateIcon, 0, 0); ok == 0 { + return fmt.Errorf("windows: request icon: %w", err) + } + return nil +} + +func (state *windowState) applyIcon() { + request := &state.pendingIcon + request.mu.Lock() + icon := request.icon + request.icon = platform.WindowIcon{} + request.mu.Unlock() + if icon.Valid() && state.window != 0 { + state.setIcons(icon) + } +} + // setIcons gives the window the application's picture: the small one for its // title bar and the big one for the taskbar button and Alt+Tab. Windows asks // the window for these; the executable has no icon resource of its own. @@ -19,6 +57,11 @@ func (state *windowState) setIcons(icon platform.WindowIcon) { if !icon.Valid() { return } + if icon.ResourcePath != "" { + if err := state.setTaskbarIcon(icon.ResourcePath); err != nil { + log.Printf("viva: update taskbar icon: %v", err) + } + } for kind, metric := range [...]uintptr{smSmallIconWidth, smIconWidth} { size, _, _ := getSystemMetrics.Call(metric) if kind == iconBig { @@ -33,8 +76,12 @@ func (state *windowState) setIcons(icon platform.WindowIcon) { if err != nil { continue } + previous := state.icons[kind] state.icons[kind] = handle sendMessage.Call(state.window, wmSetIcon, uintptr(kind), handle) + if previous != 0 { + destroyIcon.Call(previous) + } } } diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index a0b6e5879..bc3cc8280 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -79,6 +79,7 @@ const ( type windowState struct { // pendingTitle is the title SetTitle asked for, applied on the window thread. pendingTitle titleRequest + pendingIcon iconRequest fullscreen atomic.Bool fullscreenChanging bool fullscreenStyle uint32 @@ -147,6 +148,7 @@ type windowState struct { pendingKey pendingKey deadKey bool icons [2]uintptr + taskbarIconSet bool drop *dropTarget wheel wheelSettings devices platform.DeviceRecovery @@ -509,6 +511,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmSetTitle: state.applyTitle() return 0 + case wmUpdateIcon: + state.applyIcon() + return 0 case wmSysCommand: if state.fullscreen.Load() { switch first & 0xfff0 { @@ -1319,6 +1324,7 @@ func (state *windowState) destroyed(window uintptr) { state.config.Waker.Unbind() } state.destroyIcons() + state.clearTaskbarIcon() removeNotificationIcon(window) release() if state.application.firstErr == nil && state.err != nil { diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 261363dea..41fa11467 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -236,8 +236,10 @@ var ( // busyAttempts is how many times a command that finds the system busy is run: the // disk image service is shared with whatever else on the machine is making or -// mounting images, and refuses with "Resource busy" while it is. -const busyAttempts = 5 +// mounting images, and refuses with "Resource busy" while it is. The increasing +// waits total at most 45 seconds: hosted macOS runners can retain an image's +// resources beyond the previous ten-second window after detaching its volume. +const busyAttempts = 10 func hdiutilOutput(arguments ...string) (string, error) { for attempt := 1; ; attempt++ { From a6ae841ade62e883e9b0223528650f1352be398d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 21 Nov 2026 09:26:02 +0800 Subject: [PATCH 03/16] fix(linux): compose through Fcitx 4 as well as IBus The X11 backend only spoke IBus, so a desktop whose input method is Fcitx 4 (Kylin with Sogou, for instance) got keys but never marked text or a commit: the engine was never asked. Add internal/fcitx, a pure-Go client for Fcitx 4's own session-bus interface, and a daemon seam in the Linux backend so IBus and Fcitx 4 share the field state machine. The backend follows XMODIFIERS when the session names a framework, then falls back to IBus and Fcitx 4, so a Fcitx 4 desktop is not captured by an IBus daemon the desktop still runs. Keys carry the raw X keycode, symbol, state and event time; the IBus adapter converts to IBus's keycode base and release mask. Fcitx 4 has no native preedit modes, so its contexts keep the field's input through legacy marked text. Motty needs no code change: it builds against this checkout through go.mod and its terminals and text fields use the same native text input. Refs: t8y2/motty#1165 --- README.md | 3 +- docs/conformance.md | 2 +- internal/fcitx/fcitx.go | 527 ++++++++++++++++++ internal/fcitx/fcitx_test.go | 411 ++++++++++++++ internal/fcitx/native_test.go | 98 ++++ .../platform/linux/ime_composition_linux.go | 57 +- internal/platform/linux/ime_daemon_linux.go | 194 +++++++ .../platform/linux/ime_daemon_linux_test.go | 77 +++ internal/platform/linux/ime_linux.go | 73 +-- internal/platform/linux/ime_linux_test.go | 57 +- .../platform/linux/ime_native_linux_test.go | 6 +- .../linux/ime_retirement_linux_test.go | 2 +- .../linux/ime_tentative_linux_test.go | 2 +- internal/platform/linux/window_linux.go | 25 +- website/content/guides/en/text-input.md | 2 +- website/content/guides/zh/text-input.md | 2 +- 16 files changed, 1422 insertions(+), 116 deletions(-) create mode 100644 internal/fcitx/fcitx.go create mode 100644 internal/fcitx/fcitx_test.go create mode 100644 internal/fcitx/native_test.go create mode 100644 internal/platform/linux/ime_daemon_linux.go create mode 100644 internal/platform/linux/ime_daemon_linux_test.go diff --git a/README.md b/README.md index 94826fbee..4d97909a7 100644 --- a/README.md +++ b/README.md @@ -161,7 +161,8 @@ WebView and no bundled rendering runtime. - Focus-driven dynamic native text editors on macOS, Windows, and Linux, with explicit enable/replace/disable frame updates. macOS and Windows caret timers exist only while an editable field is focused. Linux composes through the IBus - protocol (IBus and Fcitx5's IBus frontend); XIM is still open. + protocol (IBus and Fcitx5's IBus frontend) or Fcitx 4's own protocol; XIM is + still open. - A separate retained semantic accessibility tree. - Direct CoreText shaping, system-font fallback, GPU-composited text textures, and a bounded measurement cache. diff --git a/docs/conformance.md b/docs/conformance.md index b97b69829..bf175450c 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -105,7 +105,7 @@ mistakes an absence for an oversight. Items marked *measured* were tried or size | AppImage | Linux | AppImage needs an external runtime binary. `viva package` makes tar.gz, .deb, a PKGBUILD for Arch, and (with `--format rpm`) an .rpm. The .rpm is checked with rpm 6's `rpm -qpl`, `rpm -qpi` and `rpm -K --nosignature`, and installed on Fedora 44 aarch64 with dnf (install, `rpm -V`, run, desktop-file-validate, remove). The GUI and amd64 on Fedora are not yet run. | | Native text events in `viva dev` | all | The worker protocol does not carry them; native Canvas examples do not run under `viva dev`. | | A flat accessibility tree | Windows, macOS | Every node hangs from the window; Linux derives parents from geometry. | -| XIM input | Linux | Composition goes through IBus (IBus and Fcitx5's IBus frontend); XIM-only applications cannot compose. | +| XIM input | Linux | Composition goes through IBus (IBus and Fcitx5's IBus frontend) or Fcitx 4's own protocol; XIM-only applications cannot compose. | | Text in arbitrary quads | Windows, Linux, Web, headless | `Canvas.LabelQuad` warps a line into a general quad on macOS and WebGL2. Canvas2D approximates it with horizontal strips and a corner-to-corner tint gradient. Windows, Linux and headless paint the line axis-aligned in its bounds, readable but unwarped. `Canvas.FillQuad` is two triangles and draws on every backend. | ## Test environments diff --git a/internal/fcitx/fcitx.go b/internal/fcitx/fcitx.go new file mode 100644 index 000000000..37981cdc6 --- /dev/null +++ b/internal/fcitx/fcitx.go @@ -0,0 +1,527 @@ +//go:build unix + +// Package fcitx is the client half of the Fcitx 4 input method protocol: what a +// window needs to let the user compose Chinese, Japanese or Korean text with an +// input method engine that runs in another process. +// +// Fcitx 4 is a daemon on the user's session bus. A client asks it for an input +// context, tells it about every key the user presses while a text field has +// focus, and tells it where the caret is so its panel can place the candidate +// window. The engine answers each key with an integer saying whether it took +// the key and, as it composes, sends back the marked text still being composed +// (with the clause being converted) and the text the user chose. Candidate +// lists are drawn by the daemon's own panel, so the client needs none. +// +// Fcitx 5 speaks its own protocol and also offers an IBus frontend, which the +// ibus package covers; this package speaks only the Fcitx 4 interface. +// +// A Bus is driven by one thread. It exposes a file descriptor to wait on, +// Dispatch to read what arrived, and Deadline and Expire so a daemon that stops +// answering cannot hold the keyboard: after a bounded wait every pending key is +// released as "not handled" and the bus is closed, and the caller carries on +// without an input method. Nothing here starts a goroutine or a timer. +package fcitx + +import ( + "errors" + "os" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/vivaui/viva/internal/dbus" +) + +const ( + service = "org.fcitx.Fcitx" + imPath = "/inputmethod" + imIface = "org.fcitx.Fcitx.InputMethod" + icIface = "org.fcitx.Fcitx.InputContext" + icPrefix = "/inputcontext_" + dbusIface = "org.freedesktop.DBus" + dbusPath = "/org/freedesktop/DBus" + + // Capacities this client declares. Preedit text means the client draws the + // composition itself instead of in the daemon's input window; the + // formatted form carries the clause being converted; unfocus commit means + // the client settles a composition when focus leaves rather than the + // daemon committing it on the client's behalf; surrounding text lets the + // engine see and replace the text around the caret for a reconversion. + CapPreedit uint32 = 1 << 1 + CapFormattedPreedit uint32 = 1 << 4 + CapClientUnfocusCommit uint32 = 1 << 5 + CapSurroundingText uint32 = 1 << 6 + + // preeditHighlight is set on the preedit segments the engine is converting. + // The other format bits describe underline and color; marked text is + // always drawn underlined, so only the highlighted clause is of use here. + preeditHighlight int32 = 1 << 4 + + // keyTimeout is how long a key waits for the engine before the bus is given + // up. An engine answers in milliseconds; this is for one that has hung. + keyTimeout = 2 * time.Second +) + +// ErrClosed is returned once the bus has failed or been closed. +var ErrClosed = errors.New("fcitx: the connection is closed") + +// transport is the part of a D-Bus connection the client uses. +type transport interface { + Call(destination, path, iface, member, signature string, body []byte) (*dbus.Message, error) + Send(destination, path, iface, member, signature string, body []byte) (uint32, error) + Receive() ([]*dbus.Message, error) + FD() int + Close() +} + +// Handler receives what the engine sends for one input context. Its methods run +// inside Dispatch, in the order the engine produced them, and a key's answer +// arrives after the text the key produced. +type Handler struct { + // Commit delivers text the user has chosen. + Commit func(text string) + // Preedit reports the marked text and the clause being converted. + Preedit func(PreeditEvent) + // DeleteSurrounding asks the client to delete count characters of the text + // around the caret, starting offset characters from it (a negative offset is + // before it). The engine does so to replace text it is about to convert again. + DeleteSurrounding func(offset, count int) + // Forward asks the client to treat a key as if it had been typed, which an + // engine does for a key it took apart (an Enter that ends a composition). + Forward func(keysym, state uint32, release bool) +} + +// Range is a span of characters: Start is inclusive and End exclusive. +type Range struct { + Start, End int +} + +// PreeditEvent is the marked text an engine is composing. Empty Text means the +// composition was cleared. +type PreeditEvent struct { + Text string + // Cursor is the caret within Text, counted in characters rather than bytes. + Cursor int + // Visible is whether Text is meant to be shown. + Visible bool + // Selection is the clause the engine is converting, in characters; a zero + // width Selection is a caret alone. + Selection Range +} + +// Bus is a connection to the Fcitx daemon. +type Bus struct { + conn transport + contexts map[string]*Context + pending []*pendingKey + err error + now func() time.Time + dispatching bool + redispatch bool +} + +type pendingKey struct { + serial uint32 + done func(handled bool) + deadline time.Time + answered bool + handled bool +} + +// Context is one input context: the engine's view of a single text field. +type Context struct { + bus *Bus + path string + handler Handler +} + +// Dial connects to the running daemon, or reports why it cannot. A machine +// without Fcitx is the usual reason, not an error worth showing. +func Dial() (*Bus, error) { + conn, err := dbus.DialSession() + if err != nil { + return nil, err + } + var body dbus.Encoder + body.String(service) + reply, err := conn.Call(dbusIface, dbusPath, dbusIface, "NameHasOwner", "s", body.Bytes()) + if err != nil { + conn.Close() + return nil, err + } + owned := reply.Args().Bool() + reply.CloseFDs() + if !owned { + conn.Close() + return nil, errors.New("fcitx: no daemon on the session bus") + } + return newBus(conn), nil +} + +func newBus(conn transport) *Bus { + bus := &Bus{conn: conn, contexts: map[string]*Context{}, now: time.Now} + // Fcitx broadcasts its context signals, so the bus needs a match rule for + // them; the daemon addresses its replies to this connection already. + var rule dbus.Encoder + rule.String("type='signal',interface='" + icIface + "'") + _, _ = conn.Call(dbusIface, dbusPath, dbusIface, "AddMatch", "s", rule.Bytes()) + return bus +} + +// FD is the socket to wait on for readability. +func (bus *Bus) FD() int { return bus.conn.FD() } + +// Err reports why the bus is no longer usable, or nil. +func (bus *Bus) Err() error { return bus.err } + +// Close ends the connection. Keys still waiting are released as not handled. +func (bus *Bus) Close() { + bus.fail(ErrClosed) +} + +func (bus *Bus) fail(err error) { + if bus.err != nil { + return + } + bus.err = err + bus.conn.Close() + pending := bus.pending + bus.pending = nil + for _, key := range pending { + if key.done != nil { + key.done(false) + } + } + clear(bus.contexts) +} + +// NewContext creates an input context whose output goes to handler. The caller +// reports focus with FocusIn and FocusOut, keys with ProcessKey and the caret +// with SetCursorLocation. +func (bus *Bus) NewContext(name string, handler Handler) (*Context, error) { + if bus.err != nil { + return nil, ErrClosed + } + var body dbus.Encoder + body.String(name) + body.Int32(int32(os.Getpid())) + reply, err := bus.conn.Call(service, imPath, imIface, "CreateICv3", "si", body.Bytes()) + if err != nil { + bus.fail(err) + return nil, err + } + args := reply.Args() + id := args.Int32() + _ = args.Bool() // whether the engine starts with the method enabled + args.Uint32() // the two trigger keys the daemon suggests + args.Uint32() + args.Uint32() + args.Uint32() + reply.CloseFDs() + if args.Err() != nil { + bus.fail(args.Err()) + return nil, args.Err() + } + path := icPrefix + strconv.Itoa(int(id)) + context := &Context{bus: bus, path: path, handler: handler} + bus.contexts[path] = context + var capacities dbus.Encoder + capacities.Uint32(CapPreedit | CapFormattedPreedit | CapClientUnfocusCommit | CapSurroundingText) + if err := context.send("SetCapacity", "u", capacities.Bytes()); err != nil { + return nil, err + } + // The daemon may have sent signals for this context before its answer was + // read; deliver them now, while the context is still the caller's. + if err := bus.Dispatch(); err != nil { + return nil, err + } + return context, nil +} + +// Dispatch reads what the daemon has sent and runs the handlers it calls for. +func (bus *Bus) Dispatch() error { + if bus.err != nil { + return bus.err + } + if bus.dispatching { + bus.redispatch = true + return nil + } + bus.dispatching = true + defer func() { bus.dispatching = false }() + for { + bus.redispatch = false + messages, err := bus.conn.Receive() + if err != nil { + bus.fail(err) + return err + } + for _, message := range messages { + switch message.Type { + case dbus.TypeSignal: + if context := bus.contexts[message.Path]; context != nil && message.Interface == icIface { + context.signal(message) + } + case dbus.TypeReturn, dbus.TypeError: + bus.answer(message) + } + if bus.err != nil { + return bus.err + } + } + // A synchronous call in a handler may have read newer messages. Finish + // this batch before delivering them, even when Dispatch was reentered. + if !bus.redispatch { + return nil + } + } +} + +// answer records the engine's verdict on a key and releases the verdicts that +// are ready, oldest first, so keys reach the application in the order typed. +func (bus *Bus) answer(message *dbus.Message) { + for _, key := range bus.pending { + if key.serial != message.ReplySerial { + continue + } + key.answered = true + if message.Type == dbus.TypeReturn && message.Signature == "i" { + key.handled = message.Args().Int32() != 0 + } + break + } + for len(bus.pending) > 0 && bus.pending[0].answered { + key := bus.pending[0] + bus.pending = bus.pending[1:] + if key.done != nil { + key.done(key.handled) + } + } +} + +// Deadline is when the oldest unanswered key gives up on the engine, or false +// when no key is waiting. A loop that waits on FD should wait no longer. +func (bus *Bus) Deadline() (time.Time, bool) { + if len(bus.pending) == 0 { + return time.Time{}, false + } + return bus.pending[0].deadline, true +} + +// Expire gives up on an engine that has not answered in time: every waiting +// key is released as not handled and the bus closes. +func (bus *Bus) Expire() { + if deadline, waiting := bus.Deadline(); waiting && !bus.now().Before(deadline) { + bus.fail(errors.New("fcitx: the daemon did not answer a key in time")) + } +} + +func (context *Context) send(member, signature string, body []byte) error { + if context.bus.err != nil || context.bus.contexts[context.path] != context { + return ErrClosed + } + if _, err := context.bus.conn.Send(service, context.path, icIface, member, signature, body); err != nil { + context.bus.fail(err) + return err + } + return nil +} + +// Key is one key press or release as the X server reports it: the keysym and +// keycode, the modifier state and the X event time, which an engine uses to tell +// a key it repeats from a second tap of the same key. +type Key struct { + Keysym uint32 + Keycode uint32 + State uint32 + Time uint32 + Release bool +} + +// ProcessKey gives the engine a key. done is called, in order with the other +// keys, with whether the engine consumed it; a key it did not consume is the +// application's to handle. +func (context *Context) ProcessKey(key Key, done func(handled bool)) error { + if context.bus.err != nil || context.bus.contexts[context.path] != context { + return ErrClosed + } + var body dbus.Encoder + body.Uint32(key.Keysym) + body.Uint32(key.Keycode) + body.Uint32(key.State) + kind := int32(0) + if key.Release { + kind = 1 + } + body.Int32(kind) + body.Uint32(key.Time) + serial, err := context.bus.conn.Send(service, context.path, icIface, "ProcessKeyEvent", "uuuiu", body.Bytes()) + if err != nil { + context.bus.fail(err) + return err + } + context.bus.pending = append(context.bus.pending, &pendingKey{serial: serial, done: done, deadline: context.bus.now().Add(keyTimeout)}) + return nil +} + +// FocusIn tells the engine the text field has the keyboard. +func (context *Context) FocusIn() error { return context.send("FocusIn", "", nil) } + +// FocusOut tells the engine the text field lost the keyboard. +func (context *Context) FocusOut() error { return context.send("FocusOut", "", nil) } + +// Reset abandons the composition in progress. +func (context *Context) Reset() error { return context.send("Reset", "", nil) } + +// SetSurroundingText tells the engine the text around the caret. cursor and +// anchor are character offsets into text: the caret, and the other end of the +// selection (the same as cursor when nothing is selected). +func (context *Context) SetSurroundingText(text string, cursor, anchor uint32) error { + var body dbus.Encoder + body.String(text) + body.Uint32(cursor) + body.Uint32(anchor) + return context.send("SetSurroundingText", "suu", body.Bytes()) +} + +// SetCursorLocation tells the panel where the caret is, in root window +// coordinates, so the candidate window opens beside it. +func (context *Context) SetCursorLocation(x, y, width, height int32) error { + var body dbus.Encoder + body.Int32(x) + body.Int32(y) + body.Int32(width) + body.Int32(height) + return context.send("SetCursorRect", "iiii", body.Bytes()) +} + +// Close destroys the input context. +func (context *Context) Close() { + if context.bus.contexts[context.path] != context { + return + } + delete(context.bus.contexts, context.path) + if context.bus.err == nil { + if _, err := context.bus.conn.Send(service, context.path, icIface, "DestroyIC", "", nil); err != nil { + context.bus.fail(err) + } + } +} + +func (context *Context) signal(message *dbus.Message) { + args := message.Args() + switch message.Member { + case "CommitString": + if message.Signature != "s" { + return + } + value := args.String() + if args.Err() != nil { + return + } + if context.handler.Commit != nil { + context.handler.Commit(value) + } + case "UpdateFormattedPreedit": + if context.handler.Preedit == nil || message.Signature != "a(si)i" { + return + } + event, ok := readFormattedPreedit(args) + if ok { + context.handler.Preedit(event) + } + case "UpdatePreedit": + // The daemon sends this plain form instead of the formatted one when the + // formatted capacity was refused. + if context.handler.Preedit == nil || message.Signature != "si" { + return + } + value := args.String() + cursor := int(args.Int32()) + if args.Err() != nil { + return + } + context.handler.Preedit(plainPreedit(value, cursor)) + case "DeleteSurroundingText": + if context.handler.DeleteSurrounding == nil || message.Signature != "iu" { + return + } + offset := int(args.Int32()) + count := int(args.Uint32()) + if args.Err() == nil { + context.handler.DeleteSurrounding(offset, count) + } + case "ForwardKey": + if context.handler.Forward == nil || message.Signature != "uui" { + return + } + keysym, state := args.Uint32(), args.Uint32() + release := args.Int32() != 0 + if args.Err() == nil { + context.handler.Forward(keysym, state, release) + } + } +} + +// readFormattedPreedit reads a(si) segments and the caret's byte offset, joining +// the segments and marking the clause the engine highlights. Fcitx counts the +// caret in UTF-8 bytes; characters are what a text field indexes. +func readFormattedPreedit(args *dbus.Decoder) (PreeditEvent, bool) { + // An array of structs aligns its elements on eight bytes, as every struct is. + end := args.ArrayLength(8) + var builder strings.Builder + selection := Range{} + selected := false + chars := 0 + for args.Err() == nil && args.Pos() < end { + args.Align(8) + segment := args.String() + format := args.Int32() + start := chars + chars += utf8.RuneCountInString(segment) + builder.WriteString(segment) + if format&preeditHighlight != 0 && chars > start { + if !selected { + selection.Start = start + selected = true + } + selection.End = chars + } + } + caret := int(args.Int32()) + if args.Err() != nil || !args.Done() { + return PreeditEvent{}, false + } + value := builder.String() + cursor := runeOffset(value, caret) + event := PreeditEvent{Text: value, Cursor: cursor, Visible: value != ""} + if selected { + event.Selection = selection + } else if value != "" { + event.Selection = Range{Start: cursor, End: cursor} + } + return event, true +} + +// plainPreedit is the UpdatePreedit form: one string and a byte offset. +func plainPreedit(value string, caret int) PreeditEvent { + cursor := runeOffset(value, caret) + event := PreeditEvent{Text: value, Cursor: cursor, Visible: value != ""} + if value != "" { + event.Selection = Range{Start: cursor, End: cursor} + } + return event +} + +// runeOffset converts a byte offset into value to a character offset, clamping +// it to the string. +func runeOffset(value string, bytes int) int { + if bytes <= 0 { + return 0 + } + if bytes >= len(value) { + return utf8.RuneCountInString(value) + } + return utf8.RuneCountInString(value[:bytes]) +} diff --git a/internal/fcitx/fcitx_test.go b/internal/fcitx/fcitx_test.go new file mode 100644 index 000000000..081f6f79f --- /dev/null +++ b/internal/fcitx/fcitx_test.go @@ -0,0 +1,411 @@ +//go:build unix + +package fcitx + +import ( + "errors" + "testing" + "time" + + "github.com/vivaui/viva/internal/dbus" +) + +// fakeTransport is a daemon the test scripts: it records the calls the client +// sends and hands back the messages the test queues. +type fakeTransport struct { + serial uint32 + sent []sentCall + incoming []*dbus.Message + closed bool + sendErr error + id int32 +} + +type sentCall struct { + serial uint32 + path, iface, member, signature string + body []byte +} + +func (f *fakeTransport) Call(destination, path, iface, member, signature string, body []byte) (*dbus.Message, error) { + f.sent = append(f.sent, sentCall{path: path, iface: iface, member: member, signature: signature, body: body}) + switch member { + case "AddMatch", "SetCapacity": + return &dbus.Message{Type: dbus.TypeReturn}, nil + case "CreateICv3": + var reply dbus.Encoder + reply.Int32(f.id) + reply.Bool(true) + reply.Uint32(32) + reply.Uint32(4) + reply.Uint32(0) + reply.Uint32(0) + return &dbus.Message{Type: dbus.TypeReturn, Signature: "ibuuuu", Body: reply.Bytes()}, nil + } + return nil, errors.New("unexpected call " + member) +} + +func (f *fakeTransport) Send(destination, path, iface, member, signature string, body []byte) (uint32, error) { + if f.sendErr != nil { + return 0, f.sendErr + } + f.serial++ + f.sent = append(f.sent, sentCall{serial: f.serial, path: path, iface: iface, member: member, signature: signature, body: body}) + return f.serial, nil +} + +func (f *fakeTransport) Receive() ([]*dbus.Message, error) { + messages := f.incoming + f.incoming = nil + return messages, nil +} + +func (f *fakeTransport) FD() int { return 7 } +func (f *fakeTransport) Close() { f.closed = true } + +func (f *fakeTransport) calls(member string) []sentCall { + var found []sentCall + for _, call := range f.sent { + if call.member == member { + found = append(found, call) + } + } + return found +} + +func commitSignal(path, text string) *dbus.Message { + var body dbus.Encoder + body.String(text) + return &dbus.Message{Type: dbus.TypeSignal, Path: path, Interface: icIface, Member: "CommitString", Signature: "s", Body: body.Bytes()} +} + +type preeditSegment struct { + text string + format int32 +} + +func formattedPreeditSignal(path string, segments []preeditSegment, caret int32) *dbus.Message { + var body dbus.Encoder + array := body.BeginArray(8) + for _, segment := range segments { + body.Align(8) + body.String(segment.text) + body.Int32(segment.format) + } + body.EndArray(array) + body.Int32(caret) + return &dbus.Message{Type: dbus.TypeSignal, Path: path, Interface: icIface, Member: "UpdateFormattedPreedit", Signature: "a(si)i", Body: body.Bytes()} +} + +func plainPreeditSignal(path, text string, caret int32) *dbus.Message { + var body dbus.Encoder + body.String(text) + body.Int32(caret) + return &dbus.Message{Type: dbus.TypeSignal, Path: path, Interface: icIface, Member: "UpdatePreedit", Signature: "si", Body: body.Bytes()} +} + +func keyReply(serial uint32, handled bool) *dbus.Message { + var body dbus.Encoder + if handled { + body.Int32(1) + } else { + body.Int32(0) + } + return &dbus.Message{Type: dbus.TypeReturn, ReplySerial: serial, Signature: "i", Body: body.Bytes()} +} + +func newTestContext(t *testing.T, fake *fakeTransport) *Context { + t.Helper() + bus := newBus(fake) + context, err := bus.NewContext("viva-test", Handler{}) + if err != nil { + t.Fatal(err) + } + return context +} + +func TestNewContextCreatesAnInputContextAndDeclaresCapacities(t *testing.T) { + fake := &fakeTransport{id: 7} + context := newTestContext(t, fake) + if context.path != "/inputcontext_7" { + t.Fatalf("context path = %q", context.path) + } + created := fake.calls("CreateICv3") + if len(created) != 1 || created[0].path != imPath || created[0].iface != imIface || created[0].signature != "si" { + t.Fatalf("CreateICv3 calls = %+v", created) + } + args := dbus.NewDecoder(created[0].body) + if name := args.String(); name != "viva-test" { + t.Fatalf("app name = %q", name) + } + if pid := args.Int32(); pid <= 0 { + t.Fatalf("pid = %d", pid) + } + capacities := fake.calls("SetCapacity") + if len(capacities) != 1 || capacities[0].signature != "u" { + t.Fatalf("SetCapacity calls = %+v", capacities) + } + if got := dbus.NewDecoder(capacities[0].body).Uint32(); got != CapPreedit|CapFormattedPreedit|CapClientUnfocusCommit|CapSurroundingText { + t.Fatalf("capacities = %#x; the client draws preedit and settles it on unfocus", got) + } +} + +func TestEngineTextArrivesBeforeTheKeysAnswer(t *testing.T) { + fake := &fakeTransport{id: 3} + path := "/inputcontext_3" + var events []string + var handled []bool + bus := newBus(fake) + context, err := bus.NewContext("viva-test", Handler{ + Commit: func(value string) { events = append(events, "commit:"+value) }, + Preedit: func(event PreeditEvent) { + events = append(events, "preedit:"+event.Text) + }, + }) + if err != nil { + t.Fatal(err) + } + if err := context.ProcessKey(Key{Keysym: 'n', Keycode: 57}, func(value bool) { + handled = append(handled, value) + events = append(events, "answer") + }); err != nil { + t.Fatal(err) + } + if len(handled) != 0 { + t.Fatal("the engine answered before it was given the key") + } + serial := fake.calls("ProcessKeyEvent")[0].serial + fake.incoming = []*dbus.Message{ + formattedPreeditSignal(path, []preeditSegment{{text: "n", format: 1 << 3}}, 1), + commitSignal(path, "你"), + keyReply(serial, true), + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + want := []string{"preedit:n", "commit:你", "answer"} + for index, value := range want { + if index >= len(events) || events[index] != value { + t.Fatalf("events = %v; want the engine's text before its answer, in order %v", events, want) + } + } + if !handled[0] { + t.Fatal("the engine took the key") + } +} + +func TestReleaseKeyIsSentAsARelease(t *testing.T) { + fake := &fakeTransport{id: 0} + context := newTestContext(t, fake) + if err := context.ProcessKey(Key{Keysym: 'n', Keycode: 57, Time: 99, Release: true}, nil); err != nil { + t.Fatal(err) + } + calls := fake.calls("ProcessKeyEvent") + if len(calls) != 1 || calls[0].signature != "uuuiu" { + t.Fatalf("ProcessKeyEvent calls = %+v", calls) + } + args := dbus.NewDecoder(calls[0].body) + if keysym, keycode, state := args.Uint32(), args.Uint32(), args.Uint32(); keysym != 'n' || keycode != 57 || state != 0 { + t.Fatalf("key = %#x %d %#x", keysym, keycode, state) + } + if kind := args.Int32(); kind != 1 { + t.Fatalf("key type = %d; want a release", kind) + } + if at := args.Uint32(); at != 99 { + t.Fatalf("event time = %d; want the X event time", at) + } + if args.Err() != nil || !args.Done() { + t.Fatalf("ProcessKeyEvent body = %x", calls[0].body) + } +} + +func TestFormattedPreeditJoinsSegmentsAndCountsTheCaretInCharacters(t *testing.T) { + fake := &fakeTransport{id: 1} + path := "/inputcontext_1" + var got PreeditEvent + bus := newBus(fake) + if _, err := bus.NewContext("viva-test", Handler{Preedit: func(event PreeditEvent) { got = event }}); err != nil { + t.Fatal(err) + } + // "你" is three bytes and one character; the caret sits after "h" in "hao". + fake.incoming = []*dbus.Message{formattedPreeditSignal(path, []preeditSegment{ + {text: "你", format: 1 << 3}, + {text: "hao", format: 1<<3 | preeditHighlight}, + }, 1+3)} + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if got.Text != "你hao" || !got.Visible { + t.Fatalf("preedit = %+v", got) + } + if got.Cursor != 2 { + t.Fatalf("caret = %d; want 2 characters", got.Cursor) + } + if got.Selection != (Range{Start: 1, End: 4}) { + t.Fatalf("selection = %+v; want the highlighted clause in characters", got.Selection) + } + fake.incoming = []*dbus.Message{formattedPreeditSignal(path, nil, 0)} + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if got.Text != "" || got.Visible { + t.Fatalf("cleared preedit = %+v", got) + } +} + +func TestPlainPreeditIsUnderstood(t *testing.T) { + fake := &fakeTransport{id: 2} + var got PreeditEvent + bus := newBus(fake) + if _, err := bus.NewContext("viva-test", Handler{Preedit: func(event PreeditEvent) { got = event }}); err != nil { + t.Fatal(err) + } + fake.incoming = []*dbus.Message{plainPreeditSignal("/inputcontext_2", "nǐhǎo", 3)} + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if got.Text != "nǐhǎo" || got.Cursor != 2 || got.Selection != (Range{Start: 2, End: 2}) { + t.Fatalf("preedit = %+v", got) + } +} + +func TestDeleteSurroundingAndForwardAreDelivered(t *testing.T) { + fake := &fakeTransport{id: 4} + var deletes [][2]int + var forwards [][3]uint32 + var releases []bool + bus := newBus(fake) + if _, err := bus.NewContext("viva-test", Handler{ + DeleteSurrounding: func(offset, count int) { deletes = append(deletes, [2]int{offset, count}) }, + Forward: func(keysym, state uint32, release bool) { + forwards = append(forwards, [3]uint32{keysym, state, 0}) + releases = append(releases, release) + }, + }); err != nil { + t.Fatal(err) + } + var deleteBody dbus.Encoder + deleteBody.Int32(-2) + deleteBody.Uint32(3) + var forwardBody dbus.Encoder + forwardBody.Uint32(0xff0d) + forwardBody.Uint32(0) + forwardBody.Int32(1) + fake.incoming = []*dbus.Message{ + {Type: dbus.TypeSignal, Path: "/inputcontext_4", Interface: icIface, Member: "DeleteSurroundingText", Signature: "iu", Body: deleteBody.Bytes()}, + {Type: dbus.TypeSignal, Path: "/inputcontext_4", Interface: icIface, Member: "ForwardKey", Signature: "uui", Body: forwardBody.Bytes()}, + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if len(deletes) != 1 || deletes[0] != [2]int{-2, 3} { + t.Fatalf("deletes = %v", deletes) + } + if len(forwards) != 1 || forwards[0] != [3]uint32{0xff0d, 0, 0} || !releases[0] { + t.Fatalf("forwards = %v releases = %v", forwards, releases) + } +} + +func TestSignalsForAnotherContextAreIgnored(t *testing.T) { + fake := &fakeTransport{id: 5} + commits := 0 + bus := newBus(fake) + if _, err := bus.NewContext("viva-test", Handler{Commit: func(string) { commits++ }}); err != nil { + t.Fatal(err) + } + fake.incoming = []*dbus.Message{ + commitSignal("/inputcontext_99", "stray"), + {Type: dbus.TypeSignal, Path: "/inputcontext_5", Interface: "org.example.Other", Member: "CommitString", Signature: "s"}, + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + if commits != 0 { + t.Fatalf("a context got %d commits meant for another", commits) + } +} + +func TestExpiredKeyIsNotHandledAndClosesTheBus(t *testing.T) { + fake := &fakeTransport{id: 6} + bus := newBus(fake) + bus.now = func() time.Time { return time.Unix(100, 0) } + context, err := bus.NewContext("viva-test", Handler{}) + if err != nil { + t.Fatal(err) + } + answered := -1 + if err := context.ProcessKey(Key{Keysym: 'n', Keycode: 57}, func(handled bool) { + if handled { + answered = 1 + } else { + answered = 0 + } + }); err != nil { + t.Fatal(err) + } + if deadline, waiting := bus.Deadline(); !waiting || !deadline.Equal(time.Unix(100, 0).Add(keyTimeout)) { + t.Fatalf("deadline = %v, waiting = %t", deadline, waiting) + } + bus.now = func() time.Time { return time.Unix(100, 0).Add(keyTimeout) } + bus.Expire() + if answered != 0 { + t.Fatalf("expired key answered = %d; want a release as not handled", answered) + } + if bus.Err() == nil || !fake.closed { + t.Fatalf("bus error = %v, closed = %t", bus.Err(), fake.closed) + } + if err := context.ProcessKey(Key{Keysym: 'n', Keycode: 57}, nil); err != ErrClosed { + t.Fatalf("a key after the deadline returned %v", err) + } +} + +func TestCloseDestroysTheContext(t *testing.T) { + fake := &fakeTransport{id: 8} + context := newTestContext(t, fake) + context.Close() + fake.incoming = []*dbus.Message{commitSignal("/inputcontext_8", "late")} + commits := 0 + context.handler.Commit = func(string) { commits++ } + if err := context.bus.Dispatch(); err != nil { + t.Fatal(err) + } + if commits != 0 { + t.Fatal("a closed context still received its engine's text") + } + if calls := fake.calls("DestroyIC"); len(calls) != 1 || calls[0].path != "/inputcontext_8" { + t.Fatalf("DestroyIC calls = %+v", calls) + } +} + +func BenchmarkProcessKey(b *testing.B) { + fake := &fakeTransport{id: 9} + bus := newBus(fake) + bus.now = func() time.Time { return time.Unix(100, 0) } + context, err := bus.NewContext("viva-bench", Handler{}) + if err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for index := 0; index < b.N; index++ { + fake.incoming = append(fake.incoming[:0], keyReply(fake.serial+1, false)) + if err := context.ProcessKey(Key{Keysym: 'n', Keycode: 57}, nil); err != nil { + b.Fatal(err) + } + if err := bus.Dispatch(); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkFormattedPreedit(b *testing.B) { + message := formattedPreeditSignal("/inputcontext_9", []preeditSegment{ + {text: "zhong", format: 1 << 3}, + {text: "guo", format: 1<<3 | preeditHighlight}, + }, 10) + b.ReportAllocs() + for index := 0; index < b.N; index++ { + if _, ok := readFormattedPreedit(message.Args()); !ok { + b.Fatal("preedit was not read") + } + } +} diff --git a/internal/fcitx/native_test.go b/internal/fcitx/native_test.go new file mode 100644 index 000000000..1fcaf9b02 --- /dev/null +++ b/internal/fcitx/native_test.go @@ -0,0 +1,98 @@ +//go:build unix + +package fcitx + +import ( + "os" + "testing" + "time" + "unicode" +) + +// TestNativeComposition drives a real Fcitx 4 daemon: it asks for an input +// context, turns the Chinese engine on with its trigger key, types a pinyin +// syllable and chooses the first candidate. It runs where a Fcitx 4 daemon is +// already running and VIVA_FCITX_NATIVE=1, which the test environments set. +func TestNativeComposition(t *testing.T) { + if os.Getenv("VIVA_FCITX_NATIVE") != "1" { + t.Skip("native Fcitx probe requires a running daemon and VIVA_FCITX_NATIVE=1") + } + bus, err := Dial() + if err != nil { + t.Fatal(err) + } + defer bus.Close() + committed := 0 + var preedits []string + pending := 0 + context, err := bus.NewContext("viva-native-probe", Handler{ + Commit: func(value string) { + for _, r := range value { + if unicode.Is(unicode.Han, r) { + committed++ + } + } + }, + Preedit: func(event PreeditEvent) { + if event.Visible { + preedits = append(preedits, event.Text) + } + }, + }) + if err != nil { + t.Fatal(err) + } + defer context.Close() + if err := context.FocusIn(); err != nil { + t.Fatal(err) + } + if err := context.SetCursorLocation(100, 100, 2, 20); err != nil { + t.Fatal(err) + } + clock := uint32(1000) + send := func(keysym, keycode, state uint32) { + t.Helper() + clock++ + pending++ + if err := context.ProcessKey(Key{Keysym: keysym, Keycode: keycode, State: state, Time: clock}, func(bool) { + pending-- + }); err != nil { + t.Fatal(err) + } + drain(t, bus, func() bool { return pending == 0 }) + } + // Ctrl+Space is the daemon's trigger key: it switches the context from the + // keyboard to the Chinese engine. + send(' ', 65, 4) + for _, key := range []struct{ keysym, keycode uint32 }{ + {'n', 57}, {'i', 31}, {'h', 43}, {'a', 38}, {'o', 32}, + } { + send(key.keysym, key.keycode, 0) + } + if len(preedits) == 0 { + t.Fatalf("the engine committed no preedit; commits=%d", committed) + } + send(' ', 65, 0) + if committed == 0 { + t.Fatalf("choosing the first candidate committed no Chinese; preedits=%v", preedits) + } +} + +// drain lets the bus deliver what the engine sent until done holds. +func drain(t *testing.T, bus *Bus, done func() bool) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for !done() { + if time.Now().After(deadline) { + t.Fatal("the engine did not answer in time") + } + if err := bus.Dispatch(); err != nil { + t.Fatal(err) + } + bus.Expire() + if err := bus.Err(); err != nil { + t.Fatal(err) + } + time.Sleep(time.Millisecond) + } +} diff --git a/internal/platform/linux/ime_composition_linux.go b/internal/platform/linux/ime_composition_linux.go index bc0dd3422..eb60f12e3 100644 --- a/internal/platform/linux/ime_composition_linux.go +++ b/internal/platform/linux/ime_composition_linux.go @@ -36,48 +36,39 @@ func (ime *linuxIME) current() bool { ime.app.firstErr == nil && !ime.app.quit && ime.sameOwner() } +// contextCurrent reports whether a context opened in epoch still belongs to the +// field. It does not require the context to be published on ime yet: a daemon +// can send the first update while the context is still being created. +func (ime *linuxIME) contextCurrent(epoch uint64) bool { + return ime.epoch == epoch && !ime.dead && !ime.text.closed && ime.text.enabled && + ime.app.firstErr == nil && !ime.app.quit && ime.sameOwner() +} + func (ime *linuxIME) keyCurrent(epoch uint64) bool { return ime.epoch == epoch && !ime.text.closed && ime.text.enabled && (ime.phase == nil || ime.active || ime.dead) && ime.app.firstErr == nil && !ime.app.quit && ime.sameOwner() } func (ime *linuxIME) open() bool { - bus := ime.app.inputMethodBus() - if bus == nil { + daemon := ime.app.inputMethodDaemon() + if daemon == nil { return false } ime.bindOwner() ime.epoch++ - epoch := ime.epoch - valid := func() bool { return ime.epoch == epoch && ime.current() } - context, err := bus.NewContext("viva", ibus.Handler{ - Commit: func(value string) { - if valid() { - ime.commit(value) - } - }, - Preedit: func(event ibus.PreeditEvent) { - if valid() { - ime.nativePreedit(event) - } - }, - Forward: func(symbol, code, state uint32) { - if valid() { - ime.forward(symbol, code, state) - } - }, - DeleteSurrounding: func(offset, count int) { - if valid() { - ime.deleteSurrounding(offset, count) - } - }, - }) + context, err := daemon.open(ime) if err != nil { ime.app.checkInputMethod() return false } ime.context = context - ime.negotiateTentative(context) + if negotiator, ok := context.(interface{ SetClientCommitPreedit(bool) error }); ok { + ime.negotiateTentative(negotiator) + } else { + // Fcitx 4 has no native preedit modes; the context keeps the field's + // input through legacy marked-text events. + ime.phase = nil + } return true } @@ -124,7 +115,9 @@ func (ime *linuxIME) nativePreedit(event ibus.PreeditEvent) { return } if ime.phase == nil { - ime.preedit(event.Text, event.Cursor, event.Visible, event.Attributes) + length := utf8.RuneCountInString(event.Text) + cursor := min(max(event.Cursor, 0), length) + ime.preedit(event.Text, event.Cursor, event.Visible, preeditSelection(length, cursor, event.Attributes)) return } phase := ime.phase @@ -156,7 +149,7 @@ func (ime *linuxIME) reset() error { return ime.app.firstErr } if ime.dead || ime.context == nil || ime.text.closed || ime.app.quit || !ime.sameOwner() { - return ibus.ErrClosed + return errors.New("linux: the input method is closed") } context, epoch := ime.context, ime.epoch if ime.pendingKeys != 0 { @@ -188,10 +181,10 @@ func (ime *linuxIME) reset() error { return nil } -func (ime *linuxIME) sendKey(symbol, code, state uint32) error { +func (ime *linuxIME) sendKey(key inputMethodKey) error { epoch := ime.epoch ime.pendingKeys++ - err := ime.context.ProcessKey(symbol, code, state, func(bool) { + err := ime.context.ProcessKey(key, func(bool) { if ime.answerKey(epoch) { ime.finishKey(epoch) } @@ -207,7 +200,7 @@ func (ime *linuxIME) answerKey(epoch uint64) bool { return false } ime.pendingKeys-- - if ime.app.ibus != nil && ime.app.ibus.Err() != nil { + if ime.app.inputMethod != nil && ime.app.inputMethod.Err() != nil { ime.app.checkInputMethod() if !ime.dead { ime.lost() diff --git a/internal/platform/linux/ime_daemon_linux.go b/internal/platform/linux/ime_daemon_linux.go new file mode 100644 index 000000000..d266c049c --- /dev/null +++ b/internal/platform/linux/ime_daemon_linux.go @@ -0,0 +1,194 @@ +package linux + +import ( + "os" + "strings" + "time" + + "github.com/vivaui/viva/internal/fcitx" + "github.com/vivaui/viva/internal/ibus" + "github.com/vivaui/viva/text" +) + +// inputMethodDaemon is the connection to the input method framework the session +// runs, shared by the windows that take text. The X11 backend speaks the +// framework's own client protocol, so the same field code drives either. +type inputMethodDaemon interface { + FD() int + Dispatch() error + Err() error + Deadline() (time.Time, bool) + Expire() + // open creates one window's input context, whose engine output goes to ime + // while the epoch it was opened in is current. + open(ime *linuxIME) (inputMethodContext, error) +} + +// inputMethodDaemon connects to a daemon the first time a window can take text, +// and not again: a machine without one is the usual case, and a daemon that +// starts later is picked up by the next run. +func (application *linuxApplication) inputMethodDaemon() inputMethodDaemon { + if !application.inputMethodTried { + application.inputMethodTried = true + application.inputMethod = dialInputMethod(os.Getenv) + } + return application.inputMethod +} + +// dialInputMethod connects to the input method framework in use. XMODIFIERS is +// how an X11 session names it, so a desktop with several daemons installed uses +// the one the user configured; a Fcitx 4 session sets @im=fcitx even when an +// IBus daemon also runs. Without a name, IBus is tried first and Fcitx 4 second, +// as Fcitx 4 itself has no IBus frontend while Fcitx 5 is served by IBus. +func dialInputMethod(getenv func(string) string) inputMethodDaemon { + return dialPreferred(inputMethodFramework(getenv), dialIBus, dialFcitx) +} + +// dialPreferred connects to the daemon the session names, then to the other. +func dialPreferred(framework string, ibus, fcitx func() inputMethodDaemon) inputMethodDaemon { + if framework == "fcitx" { + if daemon := fcitx(); daemon != nil { + return daemon + } + } + if daemon := ibus(); daemon != nil { + return daemon + } + return fcitx() +} + +// inputMethodFramework is the XIM name XMODIFIERS selects, lowercased. +func inputMethodFramework(getenv func(string) string) string { + fields := strings.FieldsFunc(getenv("XMODIFIERS"), func(r rune) bool { return r == ';' || r == ',' }) + for _, field := range fields { + if value, ok := strings.CutPrefix(strings.TrimSpace(field), "@im="); ok { + return strings.ToLower(strings.TrimSpace(value)) + } + } + return "" +} + +func dialIBus() inputMethodDaemon { + bus, err := ibus.Dial() + if err != nil { + return nil + } + return ibusDaemon{bus} +} + +func dialFcitx() inputMethodDaemon { + bus, err := fcitx.Dial() + if err != nil { + return nil + } + return fcitxDaemon{bus} +} + +// ibusDaemon is the IBus client behind the daemon interface. +type ibusDaemon struct{ bus *ibus.Bus } + +func (daemon ibusDaemon) FD() int { return daemon.bus.FD() } +func (daemon ibusDaemon) Dispatch() error { return daemon.bus.Dispatch() } +func (daemon ibusDaemon) Err() error { return daemon.bus.Err() } +func (daemon ibusDaemon) Deadline() (time.Time, bool) { return daemon.bus.Deadline() } +func (daemon ibusDaemon) Expire() { daemon.bus.Expire() } + +func (daemon ibusDaemon) open(ime *linuxIME) (inputMethodContext, error) { + epoch := ime.epoch + valid := func() bool { return ime.contextCurrent(epoch) } + context, err := daemon.bus.NewContext("viva", ibus.Handler{ + Commit: func(value string) { + if valid() { + ime.commit(value) + } + }, + Preedit: func(event ibus.PreeditEvent) { + if valid() { + ime.nativePreedit(event) + } + }, + Forward: func(keysym, _, state uint32) { + if valid() { + ime.forward(keysym, state&ibus.ReleaseMask != 0, state) + } + }, + DeleteSurrounding: func(offset, count int) { + if valid() { + ime.deleteSurrounding(offset, count) + } + }, + }) + if err != nil { + return nil, err + } + return ibusContext{context}, nil +} + +// ibusContext is an IBus context behind the daemon interface. IBus counts +// keycodes from the first non-modifier key and marks a release in the state +// mask; the window reports keys as the X server does. +type ibusContext struct{ *ibus.Context } + +func (context ibusContext) ProcessKey(key inputMethodKey, done func(handled bool)) error { + // IBus counts keycodes from the first non-modifier key on the keyboard, so + // the X keycode less 8; Fcitx wants the X keycode itself. + keycode := key.keycode + if keycode >= 8 { + keycode -= 8 + } + state := key.state + if key.release { + state |= ibus.ReleaseMask + } + return context.Context.ProcessKey(key.keysym, keycode, state, done) +} + +// fcitxDaemon is the Fcitx 4 client behind the daemon interface. +type fcitxDaemon struct{ bus *fcitx.Bus } + +func (daemon fcitxDaemon) FD() int { return daemon.bus.FD() } +func (daemon fcitxDaemon) Dispatch() error { return daemon.bus.Dispatch() } +func (daemon fcitxDaemon) Err() error { return daemon.bus.Err() } +func (daemon fcitxDaemon) Deadline() (time.Time, bool) { return daemon.bus.Deadline() } +func (daemon fcitxDaemon) Expire() { daemon.bus.Expire() } + +func (daemon fcitxDaemon) open(ime *linuxIME) (inputMethodContext, error) { + epoch := ime.epoch + valid := func() bool { return ime.contextCurrent(epoch) } + context, err := daemon.bus.NewContext("viva", fcitx.Handler{ + Commit: func(value string) { + if valid() { + ime.commit(value) + } + }, + Preedit: func(event fcitx.PreeditEvent) { + if valid() { + ime.preedit(event.Text, event.Cursor, event.Visible, text.Range{Start: event.Selection.Start, End: event.Selection.End}) + } + }, + Forward: func(keysym, state uint32, release bool) { + if valid() { + ime.forward(keysym, release, state) + } + }, + DeleteSurrounding: func(offset, count int) { + if valid() { + ime.deleteSurrounding(offset, count) + } + }, + }) + if err != nil { + return nil, err + } + return fcitxContext{context}, nil +} + +// fcitxContext is a Fcitx context behind the daemon interface. Fcitx wants the +// raw X keycode and the event time with each key. +type fcitxContext struct{ *fcitx.Context } + +func (context fcitxContext) ProcessKey(key inputMethodKey, done func(handled bool)) error { + return context.Context.ProcessKey(fcitx.Key{ + Keysym: key.keysym, Keycode: key.keycode, State: key.state, Time: key.time, Release: key.release, + }, done) +} diff --git a/internal/platform/linux/ime_daemon_linux_test.go b/internal/platform/linux/ime_daemon_linux_test.go new file mode 100644 index 000000000..b15f263de --- /dev/null +++ b/internal/platform/linux/ime_daemon_linux_test.go @@ -0,0 +1,77 @@ +package linux + +import ( + "testing" + "time" +) + +// stubDaemon stands in for a framework's connection in a selection test. +type stubDaemon struct{ name string } + +func (stubDaemon) FD() int { return -1 } +func (stubDaemon) Dispatch() error { return nil } +func (stubDaemon) Err() error { return nil } +func (stubDaemon) Deadline() (time.Time, bool) { return time.Time{}, false } +func (stubDaemon) Expire() {} +func (stubDaemon) open(*linuxIME) (inputMethodContext, error) { return nil, nil } + +func TestInputMethodFrameworkFollowsXModifiers(t *testing.T) { + for value, want := range map[string]string{ + "@im=fcitx": "fcitx", + "@im=ibus": "ibus", + " @im=fcitx ": "fcitx", + "@im=FCITX": "fcitx", + "@im=fcitx;@im=ibus": "fcitx", + "@im=xic": "xic", + "": "", + "@im": "", + "@im=fcitx, @im=ibus": "fcitx", + "gtk-im-context-simple": "", + } { + getenv := func(name string) string { + if name == "XMODIFIERS" { + return value + } + return "" + } + if got := inputMethodFramework(getenv); got != want { + t.Errorf("XMODIFIERS=%q framework=%q, want %q", value, got, want) + } + } +} + +func TestDialPrefersTheFrameworkTheSessionNames(t *testing.T) { + ibus := func() inputMethodDaemon { return stubDaemon{"ibus"} } + fcitx := func() inputMethodDaemon { return stubDaemon{"fcitx"} } + cases := []struct { + framework string + want string + }{ + {"fcitx", "fcitx"}, + {"ibus", "ibus"}, + {"", "ibus"}, + {"xic", "ibus"}, + } + for _, test := range cases { + daemon := dialPreferred(test.framework, ibus, fcitx) + if daemon == nil || daemon.(stubDaemon).name != test.want { + t.Errorf("framework=%q chose %v, want %s", test.framework, daemon, test.want) + } + } +} + +func TestDialFallsBackWhenTheNamedFrameworkIsAbsent(t *testing.T) { + missing := func() inputMethodDaemon { return nil } + present := func(name string) func() inputMethodDaemon { + return func() inputMethodDaemon { return stubDaemon{name} } + } + if daemon := dialPreferred("fcitx", present("ibus"), missing); daemon == nil || daemon.(stubDaemon).name != "ibus" { + t.Fatalf("a named Fcitx that is not running did not fall back to IBus: %v", daemon) + } + if daemon := dialPreferred("ibus", missing, present("fcitx")); daemon == nil || daemon.(stubDaemon).name != "fcitx" { + t.Fatalf("a named IBus that is not running did not fall back to Fcitx: %v", daemon) + } + if daemon := dialPreferred("", missing, missing); daemon != nil { + t.Fatalf("no daemon was reported as %v", daemon) + } +} diff --git a/internal/platform/linux/ime_linux.go b/internal/platform/linux/ime_linux.go index dd0ab89f3..c823063e5 100644 --- a/internal/platform/linux/ime_linux.go +++ b/internal/platform/linux/ime_linux.go @@ -10,11 +10,11 @@ import ( "github.com/vivaui/viva/text" ) -// linuxIME connects one window's focused text field to an input method running -// in the IBus daemon (or in Fcitx5, which speaks the same protocol): the keys the -// field would receive go to the engine first, and what the engine composes comes -// back as the same text events a native editor produces, so the field shows the -// marked text and commits the choice exactly as it does on the other platforms. +// linuxIME connects one window's focused text field to an input method daemon +// (IBus, Fcitx5 through its IBus frontend, or Fcitx 4): the keys the field would +// receive go to the engine first, and what the engine composes comes back as the +// same text events a native editor produces, so the field shows the marked text +// and commits the choice exactly as it does on the other platforms. // // The engine owns the candidate window. All this side does is say when the field // has the keyboard and where the caret is. @@ -57,10 +57,22 @@ type linuxIME struct { hasSources bool } -// inputMethodContext is the input context as the window uses it. *ibus.Context -// is the real one; the interface is the seam tests replace it at. +// inputMethodKey is one key press or release as the X server reported it: the +// symbol and keycode, the modifier state, the event time and whether the key +// came up. +type inputMethodKey struct { + keysym uint32 + keycode uint32 + state uint32 + time uint32 + release bool +} + +// inputMethodContext is the input context as the window uses it. *fcitx.Context +// and *ibus.Context (behind a wrapper) are the real ones; the interface is the +// seam tests replace it at. type inputMethodContext interface { - ProcessKey(keysym, keycode, state uint32, done func(handled bool)) error + ProcessKey(key inputMethodKey, done func(handled bool)) error FocusIn() error FocusOut() error Reset() error @@ -71,7 +83,7 @@ type inputMethodContext interface { // newIME gives a window an input context, or nil when there is no daemon. func (application *linuxApplication) newIME(win *window, textInput *linuxTextInput, router eventRouter) *linuxIME { - if application.inputMethodBus() == nil { + if application.inputMethodDaemon() == nil { return nil } ime := &linuxIME{app: application, text: textInput, router: router, origin: win.contentOrigin} @@ -82,23 +94,10 @@ func (application *linuxApplication) newIME(win *window, textInput *linuxTextInp return ime } -// inputMethodBus connects to the daemon the first time a window can take text, -// and not again: a machine without one is the usual case, and a daemon that -// starts later is picked up by the next run. -func (application *linuxApplication) inputMethodBus() *ibus.Bus { - if !application.ibusTried { - application.ibusTried = true - if bus, err := ibus.Dial(); err == nil { - application.ibus = bus - } - } - return application.ibus -} - // serveInputMethod reads what the daemon sent. func (application *linuxApplication) serveInputMethod() { - if application.ibus != nil { - _ = application.ibus.Dispatch() + if application.inputMethod != nil { + _ = application.inputMethod.Dispatch() application.checkInputMethod() } } @@ -106,10 +105,10 @@ func (application *linuxApplication) serveInputMethod() { // checkInputMethod lets go of a daemon that has failed, or has stopped answering: // every window goes back to receiving its keys directly. func (application *linuxApplication) checkInputMethod() { - if application.ibus == nil || application.ibus.Err() == nil { + if application.inputMethod == nil || application.inputMethod.Err() == nil { return } - application.ibus = nil + application.inputMethod = nil for _, state := range application.windows { if state.router.ime != nil { state.router.ime.lost() @@ -322,7 +321,7 @@ func (ime *linuxIME) processKeyWithShortcut(keysym uint32, event *xcbInputEvent, } epoch := ime.epoch ime.pendingKeys++ - err := ime.context.ProcessKey(keysym, uint32(event.Detail)-8, uint32(event.State), func(handled bool) { + err := ime.context.ProcessKey(inputMethodKey{keysym: keysym, keycode: uint32(event.Detail), state: uint32(event.State), time: event.Time}, func(handled bool) { if !ime.answerKey(epoch) { return } @@ -361,7 +360,7 @@ func (ime *linuxIME) pressModifier(keysym uint32, event *xcbInputEvent) { if !ime.current() || !ime.active || !ime.focused || event.Detail < 8 || keysym == 0 { return } - if err := ime.sendKey(keysym, uint32(event.Detail)-8, uint32(event.State)); err != nil { + if err := ime.sendKey(inputMethodKey{keysym: keysym, keycode: uint32(event.Detail), state: uint32(event.State), time: event.Time}); err != nil { ime.app.checkInputMethod() } } @@ -376,7 +375,7 @@ func (ime *linuxIME) release(keymap *xcbKeymap, event *xcbInputEvent) { if keysym == 0 { return } - if err := ime.sendKey(keysym, uint32(event.Detail)-8, uint32(event.State)|ibus.ReleaseMask); err != nil { + if err := ime.sendKey(inputMethodKey{keysym: keysym, keycode: uint32(event.Detail), state: uint32(event.State), time: event.Time, release: true}); err != nil { ime.app.checkInputMethod() } } @@ -395,8 +394,9 @@ func (ime *linuxIME) commit(value string) { ime.apply(event) } -// preedit shows the text being composed as marked text, or removes it. -func (ime *linuxIME) preedit(value string, cursor int, visible bool, attrs []ibus.Attribute) { +// preedit shows the text being composed as marked text, or removes it. Selection +// is the clause being converted, in characters. +func (ime *linuxIME) preedit(value string, cursor int, visible bool, selection text.Range) { if !visible || value == "" { ime.engineComposing = false if ime.text.state.Composing { @@ -408,7 +408,12 @@ func (ime *linuxIME) preedit(value string, cursor int, visible bool, attrs []ibu ime.engineComposing = true length := utf8.RuneCountInString(value) cursor = min(max(cursor, 0), length) - ime.apply(platform.TextEvent{Kind: platform.TextSetMarked, Text: value, MarkedSelection: preeditSelection(length, cursor, attrs)}) + selection.Start = min(max(selection.Start, 0), length) + selection.End = min(max(selection.End, 0), length) + if selection.End < selection.Start { + selection.Start, selection.End = selection.End, selection.Start + } + ime.apply(platform.TextEvent{Kind: platform.TextSetMarked, Text: value, MarkedSelection: selection}) } // preeditSelection is the part of the marked text to show as selected: the clause @@ -430,8 +435,8 @@ func preeditSelection(length, cursor int, attrs []ibus.Attribute) text.Range { // forward delivers a key the engine took apart and gave back, such as the Enter // that ends a composition, past the engine. -func (ime *linuxIME) forward(keysym, _ uint32, state uint32) { - if state&ibus.ReleaseMask != 0 { +func (ime *linuxIME) forward(keysym uint32, release bool, state uint32) { + if release { return } event := platform.KeyEvent{Key: normalizedKeysym(keysym), Modifiers: xcbModifiers(uint16(state))} diff --git a/internal/platform/linux/ime_linux_test.go b/internal/platform/linux/ime_linux_test.go index e7c91f359..faadaab2a 100644 --- a/internal/platform/linux/ime_linux_test.go +++ b/internal/platform/linux/ime_linux_test.go @@ -11,8 +11,8 @@ import ( "github.com/vivaui/viva/text" ) -// fakeIMEContext stands in for an IBus input context: it records the calls and -// lets a test answer the keys it was given. +// fakeIMEContext stands in for a daemon's input context: it records the calls +// and lets a test answer the keys it was given. type fakeIMEContext struct { calls []string keys []fakeIMEKey @@ -26,6 +26,7 @@ type fakeIMEContext struct { type fakeIMEKey struct { keysym, keycode, state uint32 + release bool done func(bool) } @@ -37,11 +38,11 @@ func (f *fakeIMEContext) record(name string) error { return f.err } -func (f *fakeIMEContext) ProcessKey(keysym, keycode, state uint32, done func(bool)) error { +func (f *fakeIMEContext) ProcessKey(key inputMethodKey, done func(bool)) error { if f.err != nil { return f.err } - f.keys = append(f.keys, fakeIMEKey{keysym, keycode, state, done}) + f.keys = append(f.keys, fakeIMEKey{key.keysym, key.keycode, key.state, key.release, done}) return nil } func (f *fakeIMEContext) FocusIn() error { return f.record("FocusIn") } @@ -106,12 +107,12 @@ func newIMEHarness(t testing.TB) *imeHarness { _, _, err := harness.input.prepare(frame) return err } - // ibusTried keeps a present() that defers sync from dialing the host's + // inputMethodTried keeps a present() that defers sync from dialing the host's // daemon: these tests are about the state machine, and a machine with a // reachable IBus address would otherwise get a fresh native context in the // middle of an assertion. harness.ime = &linuxIME{ - app: &linuxApplication{ibusTried: true}, text: harness.input, router: router, context: harness.context, + app: &linuxApplication{inputMethodTried: true}, text: harness.input, router: router, context: harness.context, origin: func() (int32, int32) { return harness.origin[0], harness.origin[1] }, } router.ime = harness.ime @@ -181,8 +182,8 @@ func TestIMEKeyTheEngineTakesNeverReachesTheField(t *testing.T) { t.Fatal("the key was not given to the engine") } key := h.context.keys[0] - if key.keysym != 'N' || key.keycode != 57-8 || key.state != 0x1 { - t.Fatalf("key = %+v; IBus counts keycodes from the X keycode less 8, and wants the shifted symbol", key) + if key.keysym != 'N' || key.keycode != 57 || key.state != 0x1 || key.release { + t.Fatalf("key = %+v; the engine wants the X keycode and the shifted symbol", key) } key.done(true) if len(h.delivered) != 0 || h.editor.String() != "" { @@ -205,7 +206,7 @@ func TestIMEKeyTheEngineDeclinesIsTypedIntoTheField(t *testing.T) { } func TestIMENoDaemonKeepsWindowConstructionAllocationFree(t *testing.T) { - app := &linuxApplication{ibusTried: true} + app := &linuxApplication{inputMethodTried: true} win := &window{} field := &linuxTextInput{} allocations := testing.AllocsPerRun(100, func() { @@ -303,7 +304,7 @@ func TestIMEKeysAreDeliveredInTypedOrderWhateverTheAnswerOrder(t *testing.T) { func TestIMEPreeditIsMarkedTextAndCommitReplacesIt(t *testing.T) { h := newIMEHarness(t) h.focus(t) - h.ime.preedit("nǐhǎo", 3, true, nil) + h.ime.preedit("nǐhǎo", 3, true, text.Range{Start: 3, End: 3}) composition, composing := h.editor.Composition() if !composing || composition != (text.Range{Start: 0, End: 5}) || h.editor.String() != "nǐhǎo" { t.Fatalf("composition = %+v, %v, text %q", composition, composing, h.editor.String()) @@ -311,7 +312,7 @@ func TestIMEPreeditIsMarkedTextAndCommitReplacesIt(t *testing.T) { if caret := h.editor.Selection(); caret != (text.Range{Start: 3, End: 3}) { t.Fatalf("the engine put its cursor at 3 characters, the field has %+v", caret) } - h.ime.preedit("你好", 2, true, nil) + h.ime.preedit("你好", 2, true, text.Range{Start: 2, End: 2}) if h.editor.String() != "你好" { t.Fatalf("a new preedit must replace the last, got %q", h.editor.String()) } @@ -328,14 +329,14 @@ func TestIMEHidingThePreeditRemovesTheMarkedText(t *testing.T) { h := newIMEHarness(t) h.focus(t) h.editor.Insert("keep ") - h.ime.preedit("nihao", 5, true, nil) - h.ime.preedit("nihao", 5, false, nil) + h.ime.preedit("nihao", 5, true, text.Range{Start: 5, End: 5}) + h.ime.preedit("nihao", 5, false, text.Range{Start: 5, End: 5}) if _, composing := h.editor.Composition(); composing || h.editor.String() != "keep " { t.Fatalf("text %q composing %v; cancelling must leave only what was typed before", h.editor.String(), composing) } // An empty preedit with nothing composing changes nothing, and in particular // does not leave an empty composition behind. - h.ime.preedit("", 0, true, nil) + h.ime.preedit("", 0, true, text.Range{Start: 0, End: 0}) if _, composing := h.editor.Composition(); composing { t.Fatal("an empty preedit started a composition") } @@ -344,11 +345,11 @@ func TestIMEHidingThePreeditRemovesTheMarkedText(t *testing.T) { func TestIMEPreeditCursorIsClampedToTheText(t *testing.T) { h := newIMEHarness(t) h.focus(t) - h.ime.preedit("ab", 99, true, nil) + h.ime.preedit("ab", 99, true, text.Range{Start: 99, End: 99}) if caret := h.editor.Selection(); caret.End != 2 { t.Fatalf("caret = %+v for a cursor beyond the end", caret) } - h.ime.preedit("ab", -4, true, nil) + h.ime.preedit("ab", -4, true, text.Range{Start: -4, End: -4}) if caret := h.editor.Selection(); caret.Start != 0 { t.Fatalf("caret = %+v for a negative cursor", caret) } @@ -357,7 +358,7 @@ func TestIMEPreeditCursorIsClampedToTheText(t *testing.T) { func TestIMEResetsTheEngineWhenTheFieldStopsComposingWithoutIt(t *testing.T) { h := newIMEHarness(t) h.focus(t) - h.ime.preedit("nihao", 5, true, nil) + h.ime.preedit("nihao", 5, true, text.Range{Start: 5, End: 5}) // A click puts the caret elsewhere, which ends the field's composition. h.editor.SetSelection(text.Range{Start: 0, End: 0}) h.input.state.Composing = false @@ -373,7 +374,7 @@ func TestIMEResetsTheEngineWhenTheFieldStopsComposingWithoutIt(t *testing.T) { func TestIMELeavingTheFieldAbandonsAnOpenComposition(t *testing.T) { h := newIMEHarness(t) h.focus(t) - h.ime.preedit("nihao", 5, true, nil) + h.ime.preedit("nihao", 5, true, text.Range{Start: 5, End: 5}) h.input.enabled = false h.ime.sync() calls := h.context.calls @@ -385,24 +386,24 @@ func TestIMELeavingTheFieldAbandonsAnOpenComposition(t *testing.T) { func TestIMEForwardedKeyBypassesTheEngine(t *testing.T) { h := newIMEHarness(t) h.focus(t) - h.ime.forward(0xff0d, 28, 0) // Return + h.ime.forward(0xff0d, false, 0) // Return if len(h.delivered) != 1 || h.delivered[0].Key != input.KeyEnter { t.Fatalf("delivered = %+v", h.delivered) } if len(h.context.keys) != 0 { t.Fatal("a forwarded key went back to the engine, which would loop") } - h.ime.forward(0xff0d, 28, ibus.ReleaseMask) + h.ime.forward(0xff0d, true, 0) if len(h.delivered) != 1 { t.Fatal("a forwarded release was delivered as a key press") } - h.ime.forward('a', 38, 0) + h.ime.forward('a', false, 0) if h.editor.String() != "a" { t.Fatalf("a forwarded character was not typed: %q", h.editor.String()) } } -func TestIMEReleaseGoesToTheEngineWithTheReleaseMask(t *testing.T) { +func TestIMEReleaseGoesToTheEngineAsARelease(t *testing.T) { h := newIMEHarness(t) keymap, event := letterKey(0) h.ime.release(keymap, event) @@ -411,7 +412,7 @@ func TestIMEReleaseGoesToTheEngineWithTheReleaseMask(t *testing.T) { } h.focus(t) h.ime.release(keymap, event) - if got := h.context.keys[0]; got.state != ibus.ReleaseMask || got.keysym != 'n' { + if got := h.context.keys[0]; !got.release || got.state != 0 || got.keysym != 'n' { t.Fatalf("release = %+v", got) } if done := h.context.keys[0].done; done != nil { @@ -440,7 +441,7 @@ func TestIMEKeysAreNotGivenToTheEngineWithoutAnActiveField(t *testing.T) { func TestIMELostDaemonKeepsTheTextAndReturnsKeysToTheField(t *testing.T) { h := newIMEHarness(t) h.focus(t) - h.ime.preedit("nihao", 5, true, nil) + h.ime.preedit("nihao", 5, true, text.Range{Start: 5, End: 5}) callsBefore := len(h.context.calls) h.ime.lost() composition, composing := h.editor.Composition() @@ -523,7 +524,7 @@ func TestIMETellsTheEngineTheTextAroundTheCaretAndOnlyWhenItChanges(t *testing.T if len(h.context.surrounds) != before { t.Fatal("unchanged text was told to the engine again") } - h.ime.preedit("ni", 2, true, nil) + h.ime.preedit("ni", 2, true, text.Range{Start: 2, End: 2}) if got := h.context.surrounds[len(h.context.surrounds)-1]; got != (fakeSurround{"你好", 2, 2}) { t.Fatalf("the engine was told its own preedit: %+v", got) } @@ -559,11 +560,11 @@ func TestIMEDeleteSurroundingRemovesTheTextTheEngineAsksFor(t *testing.T) { func TestIMEPreeditShowsTheClauseBeingConvertedAsSelected(t *testing.T) { h := newIMEHarness(t) h.focus(t) - h.ime.preedit("きょうは", 4, true, []ibus.Attribute{{Kind: ibus.AttrUnderline, Value: 1, Start: 0, End: 4}, {Kind: ibus.AttrBackground, Start: 0, End: 3}}) + h.ime.nativePreedit(ibus.PreeditEvent{Text: "きょうは", Cursor: 4, Visible: true, Attributes: []ibus.Attribute{{Kind: ibus.AttrUnderline, Value: 1, Start: 0, End: 4}, {Kind: ibus.AttrBackground, Start: 0, End: 3}}}) if selection := h.editor.Selection(); selection != (text.Range{Start: 0, End: 3}) { t.Fatalf("selection = %+v, want the converted clause", selection) } - h.ime.preedit("きょうは", 4, true, []ibus.Attribute{{Kind: ibus.AttrUnderline, Value: 1, Start: 0, End: 4}}) + h.ime.nativePreedit(ibus.PreeditEvent{Text: "きょうは", Cursor: 4, Visible: true, Attributes: []ibus.Attribute{{Kind: ibus.AttrUnderline, Value: 1, Start: 0, End: 4}}}) if selection := h.editor.Selection(); selection != (text.Range{Start: 4, End: 4}) { t.Fatalf("selection = %+v, want the caret", selection) } @@ -582,7 +583,7 @@ func TestIMEModifierPressReachesTheEngineAndDeliversNothing(t *testing.T) { if len(h.context.keys) != 1 { t.Fatalf("keys sent to the engine = %d, want the Shift press", len(h.context.keys)) } - if got := h.context.keys[0]; got.keysym != 0xffe1 || got.keycode != 50-8 || got.state&ibus.ReleaseMask != 0 { + if got := h.context.keys[0]; got.keysym != 0xffe1 || got.keycode != 50 || got.release { t.Fatalf("press = %+v", got) } if done := h.context.keys[0].done; done != nil { diff --git a/internal/platform/linux/ime_native_linux_test.go b/internal/platform/linux/ime_native_linux_test.go index 50a4d723e..108d9f663 100644 --- a/internal/platform/linux/ime_native_linux_test.go +++ b/internal/platform/linux/ime_native_linux_test.go @@ -42,7 +42,7 @@ func TestNativeIBusFactoryDeclinedShortcut(t *testing.T) { shortcuts++ return platform.Frame{}, true, nil } - app := &linuxApplication{ibus: bus, ibusTried: true} + app := &linuxApplication{inputMethod: ibusDaemon{bus}, inputMethodTried: true} ime := app.newIME(&window{}, h.input, router) if ime == nil { t.Fatal("native factory returned no context") @@ -129,7 +129,7 @@ func TestNativeIBusFrontend(t *testing.T) { if _, _, err := h.input.prepare(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}); err != nil { t.Fatal(err) } - app := &linuxApplication{ibus: bus, ibusTried: true} + app := &linuxApplication{inputMethod: ibusDaemon{bus}, inputMethodTried: true} router := h.ime.router router.ime = nil ime := app.newIME(&window{}, h.input, router) @@ -313,7 +313,7 @@ func TestNativeIBusOwnerReactivation(t *testing.T) { if _, _, err := h.input.prepare(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}); err != nil { t.Fatal(err) } - app := &linuxApplication{ibus: bus, ibusTried: true} + app := &linuxApplication{inputMethod: ibusDaemon{bus}, inputMethodTried: true} router := h.ime.router router.ime = nil ime := app.newIME(&window{}, h.input, router) diff --git a/internal/platform/linux/ime_retirement_linux_test.go b/internal/platform/linux/ime_retirement_linux_test.go index 074923053..684e98444 100644 --- a/internal/platform/linux/ime_retirement_linux_test.go +++ b/internal/platform/linux/ime_retirement_linux_test.go @@ -95,7 +95,7 @@ func TestNativeIBusUnsupportedModeRetirement(t *testing.T) { } defer bus.Close() h := newTentativeIMEHarness(t) - app := &linuxApplication{ibus: bus, ibusTried: true} + app := &linuxApplication{inputMethod: ibusDaemon{bus}, inputMethodTried: true} router := h.ime.router router.ime = nil ime := app.newIME(&window{}, h.input, router) diff --git a/internal/platform/linux/ime_tentative_linux_test.go b/internal/platform/linux/ime_tentative_linux_test.go index 3b9863167..1191ac003 100644 --- a/internal/platform/linux/ime_tentative_linux_test.go +++ b/internal/platform/linux/ime_tentative_linux_test.go @@ -392,7 +392,7 @@ func TestIBusPublicBaseTentativePreeditUsesExplicitPhases(t *testing.T) { if frontend, ok := any(h.ime).(interface{ nativePreedit(ibus.PreeditEvent) }); ok { frontend.nativePreedit(ibus.PreeditEvent{Text: "ni", Cursor: 2, Visible: true, HasMode: true, Mode: ibus.PreeditModeClear}) } else { - h.ime.preedit("ni", 2, true, nil) + h.ime.preedit("ni", 2, true, text.Range{Start: 2, End: 2}) } h.ime.commit("z") if len(events) != 2 || h.editor.String() != "azc" { diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 5235e23f6..0daebe6fc 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -14,7 +14,6 @@ import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/diag" - "github.com/vivaui/viva/internal/ibus" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" ) @@ -179,10 +178,10 @@ type linuxApplication struct { // desktop's settings and the accessibility bridge. desktopServices - // ibus is the connection to the input method daemon, shared by the windows - // that take text; ibusTried says it has been looked for. - ibus *ibus.Bus - ibusTried bool + // inputMethod is the connection to the input method daemon, shared by the + // windows that take text; inputMethodTried says it has been looked for. + inputMethod inputMethodDaemon + inputMethodTried bool // live is every window that can still be posted to, for requests that come // from another goroutine (see post); the loop's own slice is not safe to read @@ -265,9 +264,9 @@ func RunApplication(start platform.ApplicationStart) error { application.fail(fmt.Errorf("linux: poll X11 connections failed (errno %d)", *application.windows[0].win.api.errnoLocation())) break } - if application.ibus != nil { + if application.inputMethod != nil { // A key the input method never answered gives up here, not before. - application.ibus.Expire() + application.inputMethod.Expire() application.checkInputMethod() } for index, descriptor := range fds { @@ -277,7 +276,7 @@ func RunApplication(start platform.ApplicationStart) error { state := states[index] if state == nil { switch { - case application.ibus != nil && int(descriptor.FD) == application.ibus.FD(): + case application.inputMethod != nil && int(descriptor.FD) == application.inputMethod.FD(): application.serveInputMethod() case application.desktop != nil && int(descriptor.FD) == application.desktop.conn.FD(): application.serveDesktop() @@ -439,7 +438,7 @@ func (application *linuxApplication) rebuildPoll() { if application.status != nil { count++ } - if application.ibus != nil { + if application.inputMethod != nil { count++ } if application.desktop != nil { @@ -459,8 +458,8 @@ func (application *linuxApplication) rebuildPoll() { application.pollFDs[next] = pollFD{FD: int32(application.status.conn.FD()), Events: 1} next++ } - if application.ibus != nil { - application.pollFDs[next] = pollFD{FD: int32(application.ibus.FD()), Events: 1} + if application.inputMethod != nil { + application.pollFDs[next] = pollFD{FD: int32(application.inputMethod.FD()), Events: 1} next++ } if application.desktop != nil { @@ -480,8 +479,8 @@ func (application *linuxApplication) sleepsUntilWoken() bool { return false } // or a desktop retry has a bounded deadline. func (application *linuxApplication) pollTimeout() int32 { timeout := int32(-1) - if application.ibus != nil { - if deadline, waiting := application.ibus.Deadline(); waiting { + if application.inputMethod != nil { + if deadline, waiting := application.inputMethod.Deadline(); waiting { timeout = int32(max(time.Until(deadline).Milliseconds()+1, 0)) } } diff --git a/website/content/guides/en/text-input.md b/website/content/guides/en/text-input.md index 57d9621af..226986c70 100644 --- a/website/content/guides/en/text-input.md +++ b/website/content/guides/en/text-input.md @@ -128,6 +128,6 @@ Offsets stay UTF-8 byte offsets into the text the application holds. While an in ## What is verified where -Native editing is implemented on macOS, with real Chinese input-method composition, grapheme-aware editing and click, drag and select-all handling. Windows has a native editor with Microsoft Pinyin composition and its candidate window. On Linux an input method running under IBus, or Fcitx5 with its IBus frontend, composes in the field, and the engine's own panel draws the candidates. In the browser, the catalog's Input example is wired to the same editor and everything else is visual only. See [Platforms](/en/docs/platforms/). +Native editing is implemented on macOS, with real Chinese input-method composition, grapheme-aware editing and click, drag and select-all handling. Windows has a native editor with Microsoft Pinyin composition and its candidate window. On Linux an input method running under IBus, Fcitx5 with its IBus frontend, or Fcitx 4 composes in the field, and the engine's own panel draws the candidates. In the browser, the catalog's Input example is wired to the same editor and everything else is visual only. See [Platforms](/en/docs/platforms/). The wrapping Textarea described above was exercised on macOS, through the headless driver; the matching Windows and Linux paths (no platform caret placement, the input-method window at the painted caret) are written but not yet run on real windows, and the browser still uses its own text box for it. diff --git a/website/content/guides/zh/text-input.md b/website/content/guides/zh/text-input.md index 9e12cdc1c..7b3c78ee5 100644 --- a/website/content/guides/zh/text-input.md +++ b/website/content/guides/zh/text-input.md @@ -128,6 +128,6 @@ func (m *model) page(c ui.C) { ## 各平台验证到什么程度 -原生编辑在 macOS 上已实现,包括真实的中文输入法组合、按字形簇的编辑,以及点击、拖动和全选。Windows 有原生编辑器,支持微软拼音的组合输入与候选窗。Linux 上,运行在 IBus(或带 IBus 前端的 Fcitx5)下的输入法可以在文本框中组合,候选由输入法自己的面板绘制。在浏览器里,目录中的 Input 示例接到了同一个编辑器,其余都只是视觉展示。见[平台](/zh/docs/platforms/)。 +原生编辑在 macOS 上已实现,包括真实的中文输入法组合、按字形簇的编辑,以及点击、拖动和全选。Windows 有原生编辑器,支持微软拼音的组合输入与候选窗。Linux 上,运行在 IBus(或带 IBus 前端的 Fcitx5、Fcitx 4)下的输入法可以在文本框中组合,候选由输入法自己的面板绘制。在浏览器里,目录中的 Input 示例接到了同一个编辑器,其余都只是视觉展示。见[平台](/zh/docs/platforms/)。 上面描述的软换行 Textarea 在 macOS 上通过无头驱动验证;Windows 与 Linux 的对应路径(平台不再自行定位光标、输入法窗口跟随已绘制的光标)已经写好,但还没有在真实窗口里运行;浏览器里仍由它自己的文本框处理。 From 8a48f1732165756d157cbdd4032d589cf8e30712 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 21 Nov 2026 10:38:58 +0800 Subject: [PATCH 04/16] feat(ui): drive themed controls from the engine and check attributes in dev ADR 0089 stages 2 and 3. The default look of Badge, Toggle, the Tabs strip, the Select trigger, Input and Textarea, and the box and caption of Checkbox and Switch now come from their recipes and the element's own attributes, so Pad, FontSize, Weight, Color, Radius, Background, Height and Children mean the same thing on them as on any element. A control keeps its own graphic (the check, the thumb, the chevron) and keeps its hit, focus and disabled state on its root; a Select, Checkbox and Switch still declare their hit under their own identity. A dev build (-tags dev or vivadev) now reports a generic attribute an element cannot use, instead of ignoring it: Children on a control without a content slot, Gap or Items on an element that lays out nothing, a state look with no identity, Pad on an Image, Scroll* off a scroll area, Hit(ID) on a control that declares its own hit, and the attributes the self-painted widgets never read. Release builds carry neither the rules nor their messages; a CI job proves that. VIVA_ATTR_CHECK=warn reports without stopping, for sweeping an existing page. Fixes found along the way: Frame.Select copied its node and lost the themed flag, a disabled Splitter could still be dragged, a Checkbox or Switch under a disabled ancestor dimmed but still took clicks, and Image.Radius did nothing. Behavior changes: Switch Width/Height now size the track, and a larger Input FontSize grows the field instead of clipping its text. Size: hello grows 16.5 KiB on darwin, 20 KiB on linux and 15.5 KiB on windows against the commit before this one; it is still 130 KiB below the size before the Button migration. A steady button page still allocates nothing per frame and a Node is still 360 bytes, but the heap in use after warming that page measured 96 KiB higher (1,384 to 1,480 KiB). The Button page benchmark is within the noise of a loaded machine (best of 15: 179 us before, 166 us after); a quiet-machine comparison is still owed. Companion commit in Motty drops the Select Hit(ID) calls this makes an error; the Motty change does not alter any paint record. --- .github/workflows/ci.yml | 38 +- base/accessors.go | 14 + base/attrcheck_dev.go | 516 +++++++++++++++++++++++ base/attrcheck_dev_test.go | 188 +++++++++ base/attrcheck_release.go | 10 + base/attrcheck_release_test.go | 21 + base/attrs.go | 21 + base/badge.go | 4 + base/badge_node_test.go | 248 +++++++++++ base/box.go | 29 +- base/caption.go | 17 +- base/checkbox_switch_node_test.go | 205 +++++++++ base/elements.go | 2 +- base/frame.go | 69 +-- base/hooks.go | 43 +- base/layout.go | 7 +- base/paint.go | 43 +- base/recipe.go | 333 ++++++++++++++- base/scroll.go | 8 + base/select.go | 7 +- base/select_node_test.go | 172 ++++++++ base/splitter.go | 16 +- base/style_look_identity_dev_test.go | 28 ++ base/style_look_identity_release_test.go | 26 ++ base/style_test.go | 15 - base/styles.go | 9 + base/table_test.go | 13 +- base/tabs.go | 35 +- base/tabs_node_test.go | 120 ++++++ base/text_entry_node_test.go | 146 +++++++ base/textarea.go | 4 + base/toggle_node_test.go | 257 +++++++++++ cmd/viva/templates/badge.go.txt | 45 +- cmd/viva/templates/checkbox.go.txt | 35 +- cmd/viva/templates/select.go.txt | 88 +++- cmd/viva/templates/switch.go.txt | 52 ++- cmd/viva/templates/tabs.go.txt | 201 +++++++-- cmd/viva/templates/textarea.go.txt | 27 +- cmd/viva/templates/toggle.go.txt | 129 +++--- components/badge.go | 45 +- components/badge_recipe_test.go | 76 ++++ components/checkbox.go | 35 +- components/select.go | 88 +++- components/switch.go | 52 ++- components/tabs.go | 201 +++++++-- components/textarea.go | 27 +- components/toggle.go | 129 +++--- components/toggle_recipe_test.go | 119 ++++++ style/badge.go | 12 + style/select.go | 40 ++ style/tabs.go | 29 ++ style/toggle.go | 21 + ui/badge_page_test.go | 190 +++++++++ ui/badge_paint.go | 45 +- ui/choice_page_test.go | 187 ++++++++ ui/controls_baseline.go | 18 +- ui/controls_paint.go | 229 +++++++--- ui/controls_table.go | 8 +- ui/hooks_install.go | 10 + ui/message/message.go | 2 +- ui/select_page_test.go | 166 ++++++++ ui/select_paint.go | 74 +++- ui/tabs_page_test.go | 141 +++++++ ui/tabs_paint.go | 32 +- ui/text_entry_page_test.go | 122 ++++++ ui/toggle_page_test.go | 196 +++++++++ ui/toggle_paint.go | 51 +++ 67 files changed, 5164 insertions(+), 422 deletions(-) create mode 100644 base/attrcheck_dev.go create mode 100644 base/attrcheck_dev_test.go create mode 100644 base/attrcheck_release.go create mode 100644 base/attrcheck_release_test.go create mode 100644 base/attrs.go create mode 100644 base/badge_node_test.go create mode 100644 base/checkbox_switch_node_test.go create mode 100644 base/select_node_test.go create mode 100644 base/style_look_identity_dev_test.go create mode 100644 base/style_look_identity_release_test.go create mode 100644 base/tabs_node_test.go create mode 100644 base/text_entry_node_test.go create mode 100644 base/toggle_node_test.go create mode 100644 components/badge_recipe_test.go create mode 100644 components/toggle_recipe_test.go create mode 100644 style/badge.go create mode 100644 style/select.go create mode 100644 style/tabs.go create mode 100644 style/toggle.go create mode 100644 ui/badge_page_test.go create mode 100644 ui/choice_page_test.go create mode 100644 ui/select_page_test.go create mode 100644 ui/tabs_page_test.go create mode 100644 ui/text_entry_page_test.go create mode 100644 ui/toggle_page_test.go create mode 100644 ui/toggle_paint.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 20907cc6f..def71def6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,6 +90,42 @@ jobs: - name: API discipline run: go run ./tools/apicheck ./ui ./components ./app ./gfx + # The attribute rules (ADR 0089 stage 3) exist only in the dev build: they + # report a generic attribute that an element cannot use instead of letting it + # be silently ignored. The release build must not carry the rules or their + # messages, so this job tests the dev variant and proves the release one has + # neither. + dev-attributes: + needs: changes + if: needs.changes.outputs.code == 'true' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: vet the dev build + run: go vet -tags dev ./... + - name: test the dev build + run: go test -tags dev ./base ./ui ./components -count=1 + - name: prove the release build has no attribute rules + run: | + if go list -f '{{.GoFiles}}' ./base | grep -q attrcheck_dev.go; then + echo "the release build compiles the dev attribute rules" >&2 + exit 1 + fi + go build -o /tmp/base-release.a ./base + if grep -aq 'does not support' /tmp/base-release.a; then + echo "the release build carries the dev attribute messages" >&2 + exit 1 + fi + go build -tags dev -o /tmp/base-dev.a ./base + if ! grep -aq 'does not support' /tmp/base-dev.a; then + echo "the dev build does not carry the attribute rules" >&2 + exit 1 + fi + # Every target Viva ships for must at least type-check, tests included. The # targets do not depend on each other, so they run at the same time on one # runner: asking for four runners to do what one can finish in the same minute @@ -374,7 +410,7 @@ jobs: passed: name: ci passed if: always() - needs: [changes, lint, cross-vet, web, web-browser, test, darwin, windows-materials, windows-arm64-text, benchmarks] + needs: [changes, lint, dev-attributes, cross-vet, web, web-browser, test, darwin, windows-materials, windows-arm64-text, benchmarks] runs-on: ubuntu-latest steps: - name: every job this change needed passed diff --git a/base/accessors.go b/base/accessors.go index f51583bf1..226b818c5 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -240,6 +240,12 @@ func (x *Extra) GetBorder() Color { return x.border } // GetBorderDashed reads the borderDashed of Extra for the styled painting layer. func (x *Extra) GetBorderDashed() bool { return x.borderDashed } +// GetSelectColors reads the colors the recipe gave the Select trigger being +// painted, for the styled painting layer. +func (f *Frame) GetSelectColors() (foreground, chevron Color) { + return f.selectForeground, f.selectChevron +} + // GetButtonRecipe reads the buttonRecipe of Extra for the styled painting layer. func (x *Extra) GetButtonRecipe() func(gfx.Theme, style.Variant, gfx.State) style.ButtonLook { return x.buttonRecipe @@ -383,6 +389,14 @@ func (x *Frame) GetAddons() []FieldAddons { return x.addons } // GetBounds reads the bounds of Frame for the styled painting layer. func (x *Frame) GetBounds() Rect { return x.bounds } +// GetCheckboxLook reads the look the recipe gave the checkbox box being +// painted, for the styled painting layer's mark. +func (f *Frame) GetCheckboxLook() style.CheckboxLook { return f.checkboxPainted } + +// GetSwitchLook reads the look the recipe gave the switch being painted, for the +// styled painting layer's thumb. +func (f *Frame) GetSwitchLook() style.SwitchLook { return f.switchPainted } + // GetCaptionFn reads the captionFn of Frame for the styled painting layer. func (x *Frame) GetCaptionFn() func(f *Frame, n *Node, control Rect) { return x.captionFn } diff --git a/base/attrcheck_dev.go b/base/attrcheck_dev.go new file mode 100644 index 000000000..4d454bea0 --- /dev/null +++ b/base/attrcheck_dev.go @@ -0,0 +1,516 @@ +//go:build dev || vivadev + +package base + +import ( + "os" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +// attrCheckWarn makes the rules report and continue instead of stopping the +// first declaration error: a sweep of a whole page is how the existing pages are +// cleaned when a rule is added. +var attrCheckWarn = os.Getenv("VIVA_ATTR_CHECK") == "warn" + +// checkAttributes reports the generic attributes a declared element cannot use, +// so a page learns at declaration time that the attribute would have had no +// effect instead of finding out later. It runs only in dev builds; the release +// build has an empty implementation, so the rules cost nothing shipped. +func (f *Frame) checkAttributes() { + for i := range f.Nodes { + f.checkAttributesOf(&f.Nodes[i]) + } +} + +// markAttr records that the caller set a generic attribute whose value the +// element cannot be asked to tell apart from its default. +func (n *Node) markAttr(a uint8) { n.attrs |= a } + +// checkAttributesOf reports the generic attributes n cannot use. +func (f *Frame) checkAttributesOf(n *Node) { + name := kindAttributeName(n) + if n.Flags&FlagChildren != 0 && !f.attributeChildContainer(n) { + f.badAttribute(n, name, "Children", "only containers and the controls with a content slot take Children; use Label, Caption or the control's own content") + } + // Gap, Items and Justify place the children of a layout container. A control + // with a content slot is a Row while it holds children, so it takes them too. + layouts := n.Kind == kindContainer || n.isContainer() || n.Kind == kindTabs || n.Kind == kindSelect + // A Button with an icon spaces the icon from its label with Gap; with + // Children it is a Row, which spans the gap between its children. + takesGap := layouts + if n.Kind == kindButton && hasIcon(f, n) { + takesGap = true + } + switch n.Kind { + case kindSwitch, kindCheckbox: + // Their own rules below say why Gap does nothing. + default: + if n.attrs&attrGap != 0 && (!takesGap || !gapDirection(n.Dir)) { + f.badAttribute(n, name, "Gap", "Gap spaces the children of a Row, Column, Flow or Grid; this element lays no children out that way") + } + } + if n.attrs&attrItems != 0 && (!layouts || !itemsDirection(n.Dir)) { + f.badAttribute(n, name, "Items", "Items places the children across a Row, Column, Stack or Flow; this element lays no children out that way") + } + if n.attrs&attrJustify != 0 && (!layouts || !justifyDirection(n.Dir)) { + f.badAttribute(n, name, "Justify", "Justify places the children along a Row, Column or Flow; this element lays no children out that way") + } + if n.attrs&attrLineGap != 0 && n.Dir != flow { + f.badAttribute(n, name, "LineGap", "LineGap is the space between the lines of a Flow; it has no effect on any other container") + } + if n.Ext != 0 { + if extra := &f.Exts[n.Ext]; extra.States != 0 && n.ID.IsZero() { + if looks := &f.States[extra.States-1]; looks.follow == 0 { + f.badAttribute(n, name, "Hover/Pressed/Focus", "a state look needs an identity to report the state; give the element an ID or a StateFrom") + } + } + } + if n.Flags&FlagMixed != 0 && n.Kind != kindCheckbox { + f.badAttribute(n, name, "Mixed", "Mixed is a Checkbox's neither-on-nor-off state") + } + extra := (*Extra)(nil) + if n.Ext != 0 { + extra = &f.Exts[n.Ext] + } + if n.attrs&attrScroll != 0 && (extra == nil || extra.scrollState == nil) { + f.badAttribute(n, name, "Scroll*", "Follow, Sideways, Scrollbars and Scrollbar* are a ScrollArea's (Scroll, List, Tree); on any other element they do nothing") + } + if extra != nil { + extra := extra + if extra.hitExact && n.Kind != kindCheckbox && n.Kind != kindSwitch { + f.badAttribute(n, name, "HitExact", "only a Checkbox and a Switch target their laid-out rectangle exactly") + } + if extra.hitOut != [4]float32{} && !engineHitKind(n.Kind) { + f.badAttribute(n, name, "HitOutset", "the pointer region grows beyond the rectangle only for the engine's own hits; this element declares its hit itself") + } + if extra.hit != (gfx.HitOptions{}) && !engineHitKind(n.Kind) && n.Kind != kindSplitter { + f.badAttribute(n, name, "HitWith", "this element declares its own hit; HitWith's options do not replace it") + } + } + if n.attrs&attrHit != 0 { + switch n.Kind { + case kindSelect, kindTabs, kindInput, kindTextarea: + f.badAttribute(n, name, "Hit", "this control declares its own hit under its own identity (the select's scope, the field's snapshot ID); Hit's ID does not replace it. Name it with Label") + } + } + if n.Flags&flagLabelFor != 0 && !engineHitKind(n.Kind) { + f.badAttribute(n, name, "LabelFor", "this element declares no hit of its own to be a label of; put LabelFor on an engine element that has one") + } + if n.Place != placeNone && n.Parent != -1 { + f.badAttribute(n, name, "At/Below/Above/Beside/Within", "only a Popup is placed against an anchor or kept inside the viewport") + } + if (n.ColSpan > 1 || n.RowSpan > 1) && !f.parentIsGrid(n) { + f.badAttribute(n, name, "ColSpan/RowSpan", "spanning cells only means something in a Grid") + } + if n.Ext != 0 { + if extra := &f.Exts[n.Ext]; extra.States != 0 { + if looks := &f.States[extra.States-1]; looks.follow != 0 && f.Nodes[looks.follow-1].ID.IsZero() { + f.badAttribute(n, name, "StateFrom", "the element it follows has no identity, so it reports no state; give that element an ID or a Hit") + } + } + } + switch n.Kind { + case kindIcon, kindImage, kindSpacer: + if n.Flags&flagSetPad != 0 || n.PadSet != 0 { + f.badAttribute(n, name, "Pad", "this element's measurement is its own; Pad does not move what it paints") + } + } + switch n.Kind { + case kindImage: + if n.Flags&flagHasRadius != 0 { + f.badAttribute(n, name, "Radius", "an Image paints its bitmap over the whole rectangle; Radius does not clip it") + } + if n.Ext != 0 && f.Exts[n.Ext].fade != 0 { + f.badAttribute(n, name, "Opacity", "an Image paints its bitmap at full opacity; the element's Opacity does not fade it") + } + if n.Flags&flagHasColor != 0 { + f.badAttribute(n, name, "Color", "an Image paints its own colors") + } + case kindText: + // A Text is where the element-level type lives: every text attribute is its own. + case kindSlot: + // A Slot's Label is its DrawContext's; element-level type styles nothing. + f.checkTextAttributes(n, name, false, false, false, false, false) + case kindContainer: + f.checkTextAttributes(n, name, false, false, false, false, false) + } + if f.attributeWidget(n) { + f.checkWidgetAttributes(n, name) + } + if n.Flags&FlagThemed != 0 { + f.checkThemedAttributes(n, name) + } +} + +// attributeWidget reports whether n is a widget that paints its whole surface +// itself: the engine draws the element's box first and the widget covers it, so +// most generic attributes never reach what the page sees. +func (f *Frame) attributeWidget(n *Node) bool { + switch n.Kind { + case kindSlider, kindSegmented, kindTable, kindInputGroup, kindProgress, + kindSpinner, kindSplitter, kindSplitButton, kindPagination: + return true + } + return false +} + +// hasIcon reports whether the element carries an icon of its own. +func hasIcon(f *Frame, n *Node) bool { + if n.Ext == 0 { + return false + } + icon := f.Exts[n.Ext].icon + return len(icon.Commands) > 0 || len(icon.Layers) > 0 +} + +func gapDirection(dir direction) bool { + return dir == row || dir == column || dir == flow || dir == grid +} + +func itemsDirection(dir direction) bool { + return dir == row || dir == column || dir == StackDir || dir == flow +} + +func justifyDirection(dir direction) bool { + return dir == row || dir == column || dir == flow +} + +// attributeChildContainer reports whether an element takes Children that the +// layout places: a container, or a themed control whose content slot makes it a +// container. A Slot is where a caller puts the content it hands a host, and its +// Children are painted in its rectangle. +func (f *Frame) attributeChildContainer(n *Node) bool { + return n.isContainer() || n.Kind == kindSlot +} + +// checkTextAttributes reports the element-level type attributes n ignores. +func (f *Frame) checkTextAttributes(n *Node, name string, mono, face, line, align bool, wrap bool) { + if !mono && n.Flags&flagMono != 0 { + f.badAttribute(n, name, "Mono", "Mono styles a Text or a single-line text field; this element paints no monospace text") + } + if !face && n.Face != 0 { + f.badAttribute(n, name, "MonoFace", "MonoFace styles a Text or a single-line text field; this element paints no monospace text") + } + if !line && n.LineH > 0 { + f.badAttribute(n, name, "LineHeight", "LineHeight styles the text this element lays out; this element lays out no text") + } + if !align { + if n.Flags&FlagTextCenter != 0 { + f.badAttribute(n, name, "TextCenter", "TextCenter aligns a Text or a text field's value; this element aligns no text") + } + if n.TextEnd { + f.badAttribute(n, name, "TextEnd", "TextEnd aligns a Text or a text field's value to its direction's end") + } + if n.TextDirection != 0 { + f.badAttribute(n, name, "TextDirection", "TextDirection sets the paragraph direction of a Text or a text field's value") + } + } + if !wrap && n.MaxLines > 0 { + f.badAttribute(n, name, "MaxLines", "MaxLines wraps a Text or autoresizes a Textarea; this element does not wrap") + } +} + +// checkThemedAttributes reports the attributes a themed control does not use. +func (f *Frame) checkThemedAttributes(n *Node, name string) { + switch n.Kind { + case kindButton: + f.checkTextAttributes(n, name, false, false, true, false, false) + f.checkButtonSize(n, name, true) + case kindBadge: + f.checkTextAttributes(n, name, false, false, true, false, false) + f.checkButtonSize(n, name, false) + case kindToggle: + f.checkTextAttributes(n, name, false, false, true, false, false) + f.checkButtonSize(n, name, true) + case kindTabs: + f.checkTextAttributes(n, name, false, false, false, false, false) + f.checkButtonSize(n, name, false) + if n.Variant != 0 { + f.badAttribute(n, name, "Variant", "a Tabs strip has its own variants: use Line() or Vertical()") + } + // The strip's padding is its inner padding: only a uniform Pad (or the top + // side) reaches the triggers. + if n.Flags&flagSetPad != 0 { + if (n.PadSet&padRight != 0 && n.Pad[1] != n.Pad[0]) || + (n.PadSet&padBottom != 0 && n.Pad[2] != n.Pad[0]) || + (n.PadSet&padLeft != 0 && n.Pad[3] != n.Pad[0]) { + f.badAttribute(n, name, "Pad sides", "a Tabs strip keeps one inner padding; PadX, PadY or different sides do not reach the triggers") + } + } + case kindSelect: + f.checkTextAttributes(n, name, false, false, false, false, false) + f.checkButtonSize(n, name, true) + if n.ButtonSize == style.SizeLarge || n.ButtonSize == style.SizeIcon { + f.badAttribute(n, name, "Size", "a Select trigger has the default, Small and XSmall sizes") + } + if n.Variant != 0 { + f.badAttribute(n, name, "Variant", "a Select trigger has no variants") + } + case kindInput: + f.checkTextAttributes(n, name, true, true, true, true, false) + f.checkButtonSize(n, name, false) + if n.Flags&flagSetPad != 0 || n.PadSet != 0 { + // A field's Pad is the room inside its border: it works. + } + if n.Variant != 0 { + f.badAttribute(n, name, "Variant", "an Input has no variants") + } + case kindTextarea: + f.checkTextAttributes(n, name, false, false, true, false, true) + f.checkButtonSize(n, name, false) + if n.Variant != 0 { + f.badAttribute(n, name, "Variant", "a Textarea has no variants") + } + case kindCheckbox: + if n.Flags&flagSetPad != 0 || n.PadSet != 0 { + f.badAttribute(n, name, "Pad", "a checkbox is its box and caption; Pad moves nothing") + } + if n.attrs&attrGap != 0 { + f.badAttribute(n, name, "Gap", "a checkbox is its box and caption; Gap spaces no children") + } + f.checkTextAttributes(n, name, false, false, false, false, false) + f.checkButtonSize(n, name, false) + if n.Variant != 0 { + f.badAttribute(n, name, "Variant", "a Checkbox has no variants") + } + f.checkCaptionType(n, name) + case kindSwitch: + if n.Flags&flagSetPad != 0 || n.PadSet != 0 { + f.badAttribute(n, name, "Pad", "a switch is its track and caption; Pad moves nothing") + } + if n.attrs&attrGap != 0 { + f.badAttribute(n, name, "Gap", "a switch is its track and caption; Gap spaces no children") + } + f.checkTextAttributes(n, name, false, false, false, false, false) + f.checkButtonSize(n, name, true) + if n.ButtonSize != 0 && n.ButtonSize != style.SizeSmall { + f.badAttribute(n, name, "Size", "a Switch has the default and Small sizes") + } + if n.Variant != 0 { + f.badAttribute(n, name, "Variant", "a Switch has no variants") + } + f.checkCaptionType(n, name) + } +} + +// checkButtonSize reports a size method the control does not read; some controls +// take no Size call at all, and some take only a subset (checkThemedAttributes +// adds the subsets). +func (f *Frame) checkButtonSize(n *Node, name string, any bool) { + if !any && n.ButtonSize != 0 { + f.badAttribute(n, name, "Size", "this control does not read the size methods (XSmall, Small, Large, IconOnly)") + } +} + +// checkCaptionType reports type styling on a Checkbox or Switch with no caption, +// where there is no text it could style. +func (f *Frame) checkCaptionType(n *Node, name string) { + if n.Text != "" { + return + } + if n.FontSet || n.WeightSet || n.Flags&flagHasColor != 0 { + f.badAttribute(n, name, "FontSize/Weight/Color", "this control's type styles its Caption; give it one with Caption(text)") + } +} + +func (f *Frame) badAttributeIfChildren(n *Node, name string) { + if n.Flags&FlagChildren != 0 { + f.badAttribute(n, name, "Children", "this control has no content slot: its default content is its label") + } +} + +// engineHitKind reports whether the engine declares the element's own hit, the +// kinds Hit and LabelFor reach. +func engineHitKind(k Kind) bool { + switch k { + case kindButton, kindBadge, kindToggle, kindContainer, kindText, kindIcon, kindSlot: + return true + } + return false +} + +// parentIsGrid reports whether the element sits in a Grid. +func (f *Frame) parentIsGrid(n *Node) bool { + return n.Parent >= 0 && f.Nodes[n.Parent].Kind == kindContainer && f.Nodes[n.Parent].Dir == grid +} + +// checkWidgetAttributes reports the generic attributes a widget that paints its +// own surface does not use. +func (f *Frame) checkWidgetAttributes(n *Node, name string) { + extra := &Extra{} + if n.Ext != 0 { + extra = &f.Exts[n.Ext] + } + rejectPad := func() { + if n.Flags&flagSetPad != 0 || n.PadSet != 0 { + f.badAttribute(n, name, "Pad", "this widget paints its whole surface; Pad moves nothing it paints") + } + if n.attrs&attrGap != 0 || n.attrs&attrItems != 0 || n.attrs&attrJustify != 0 { + f.badAttribute(n, name, "Gap/Items/Justify", "this widget lays out its own parts, not children") + } + } + rejectSurface := func() { + if n.Flags&flagSetBackground != 0 { + f.badAttribute(n, name, "Background", "this widget paints its own surface over the element's background") + } + if n.Flags&flagSetBorder != 0 { + f.badAttribute(n, name, "Border", "this widget paints its own border") + } + if n.Flags&flagHasRadius != 0 { + f.badAttribute(n, name, "Radius", "this widget paints its own corners") + } + if n.Flags&flagSetShadow != 0 { + f.badAttribute(n, name, "Shadow", "this widget paints its own elevation") + } + if extra.gradient != 0 { + f.badAttribute(n, name, "Gradient", "this widget paints its own surface over the element's gradient") + } + } + rejectType := func() { + f.checkTextAttributes(n, name, false, false, false, false, false) + if n.FontSet { + f.badAttribute(n, name, "FontSize", "this widget measures and styles its own text") + } + if n.WeightSet { + f.badAttribute(n, name, "Weight", "this widget styles its own text") + } + if n.Flags&flagHasColor != 0 { + f.badAttribute(n, name, "Color", "this widget paints its own colors") + } + } + rejectChildren := func() { + if n.Flags&FlagChildren != 0 { + f.badAttribute(n, name, "Children", "this widget paints its own parts and has no content slot") + } + } + rejectVariant := func() { + if n.Variant != 0 { + f.badAttribute(n, name, "Variant", "this widget has no theme variants") + } + } + rejectSize := func() { + if n.ButtonSize != 0 { + f.badAttribute(n, name, "Size", "this widget does not read the size methods (XSmall, Small, Large, IconOnly)") + } + } + rejectLabel := func() { + if n.Label != "" { + f.badAttribute(n, name, "Label", "this widget does not name a hit with Label; give the name where it declares its hit") + } + } + rejectDisabled := func() { + if n.Flags&FlagDisabled != 0 { + f.badAttribute(n, name, "Disabled", "this widget does not check the disabled state; disable its own state or leave it out") + } + } + switch n.Kind { + case kindSlider: + rejectPad() + rejectSurface() + rejectType() + rejectChildren() + rejectVariant() + rejectSize() + case kindSegmented: + rejectPad() + rejectSurface() + rejectType() + rejectChildren() + rejectVariant() + rejectSize() + rejectLabel() + case kindTable: + rejectPad() + rejectSurface() + rejectType() + rejectChildren() + rejectVariant() + rejectSize() + rejectLabel() + rejectDisabled() + case kindInputGroup: + rejectPad() + rejectSurface() + rejectType() + rejectChildren() + rejectVariant() + rejectSize() + rejectLabel() + rejectDisabled() + case kindProgress: + rejectPad() + rejectSurface() + rejectType() + rejectChildren() + rejectVariant() + rejectSize() + rejectLabel() + rejectDisabled() + case kindSpinner: + rejectPad() + rejectSurface() + rejectType() + rejectChildren() + rejectVariant() + rejectSize() + rejectLabel() + rejectDisabled() + case kindSplitter: + rejectPad() + rejectType() + rejectChildren() + rejectVariant() + rejectSize() + case kindSplitButton: + rejectPad() + rejectSurface() + rejectType() + rejectChildren() + case kindPagination: + rejectPad() + rejectSurface() + rejectType() + rejectChildren() + rejectVariant() + rejectSize() + rejectLabel() + rejectDisabled() + } +} + +// badAttribute panics with the element's name, the attribute and what to do +// instead. It is the dev build's report: a page that set an attribute the +// element cannot use is a declaration error, not something to ignore. +func (f *Frame) badAttribute(n *Node, kind, attribute, hint string) { + message := "ui: " + kind + " does not support " + attribute + ": " + hint + if attrCheckWarn { + println("VIVA_ATTR_CHECK: " + message) + return + } + panic(message) +} + +// kindAttributeName is the element's name in an attribute message: a container +// keeps the name its layout gives it. +func kindAttributeName(n *Node) string { + if n.Kind == kindContainer { + switch n.Dir { + case row: + return "Row" + case column: + return "Column" + case StackDir: + return "Stack" + case flow: + return "Flow" + case grid: + return "Grid" + } + } + if n.Kind == kindSplitButton { + return "SplitButton" + } + return controlName(n.Kind) +} diff --git a/base/attrcheck_dev_test.go b/base/attrcheck_dev_test.go new file mode 100644 index 000000000..775153c44 --- /dev/null +++ b/base/attrcheck_dev_test.go @@ -0,0 +1,188 @@ +//go:build dev || vivadev + +package base + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +var ( + attrTabsScope = tree.Sub(page, tree.Name("attr-tabs")) + attrSelectScope = tree.Sub(page, tree.Name("attr-select")) +) + +// drawBase declares one page through the engine under the dev attribute rules. +func drawBase(declare func(f *Frame)) { + var view View + view.Draw(styleCanvas(gfx.ID{}, gfx.ID{}, gfx.ID{}, false), gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, declare) +} + +// expectAttributePanic runs a declaration that sets an attribute the element +// cannot use, and checks the dev build reports the element and the attribute. +func expectAttributePanic(t *testing.T, run func(f *Frame), want ...string) { + t.Helper() + defer func() { + recovered := recover() + if recovered == nil { + t.Fatalf("declaration did not report; want a message containing %q", want) + } + message, _ := recovered.(string) + for _, part := range want { + if !strings.Contains(message, part) { + t.Fatalf("diagnostic %q does not name %q", message, part) + } + } + }() + drawBase(run) +} + +func TestBareConstructorsDoNotTripTheAttributeRules(t *testing.T) { + var state SelectState + drawBase(func(f *Frame) { + f.Column().Children(func() { + f.Button(gfx.Item(1), "Save") + f.Badge("New") + f.Toggle(gfx.Item(3), "Bold", true) + f.Tabs(attrTabsScope, []string{"A", "B"}, 0) + f.Select(attrSelectScope, &state, []string{"A", "B"}, 0).Label("Size") + f.Input(InputSnapshot{ID: gfx.Item(4), Label: "Name", Value: "x"}) + f.Textarea(TextareaSnapshot{ID: gfx.Item(5), Label: "Notes", Value: "x"}) + f.Checkbox(gfx.Item(6), true).Caption("Sync") + f.Switch(gfx.Item(7), false).Caption("Run") + f.Slot() + }) + }) +} + +func TestContainerAttributesAreChecked(t *testing.T) { + drawBase(func(f *Frame) { + f.Row().Gap(4).Items(Center).Justify(End).Children(func() { f.Text("x") }) + f.Column().Gap(4).Items(Start).Children(func() { f.Text("x") }) + f.Flow().Gap(4).LineGap(2).Children(func() { f.Text("x") }) + f.Stack() + f.Slot().Children(func() { f.Text("x") }) + }) +} + +// StateFrom follows an element that reports no state, and a span outside a Grid, +// and a placement outside a Popup are declaration errors. +func TestStructuralAttributesAreChecked(t *testing.T) { + expectAttributePanic(t, func(f *Frame) { + row := f.Row() + f.Text("x").StateFrom(row) + }, "Text", "StateFrom") + expectAttributePanic(t, func(f *Frame) { + f.Column().Children(func() { f.Text("x").ColSpan(2) }) + }, "Text", "ColSpan/RowSpan") + expectAttributePanic(t, func(f *Frame) { + f.Text("x").At(4, 4) + }, "Text", "At/Below/Above/Beside/Within") + expectAttributePanic(t, func(f *Frame) { + f.Splitter(gfx.Item(1), &SplitterState{}).LabelFor(gfx.Item(2)) + }, "Splitter", "LabelFor") +} + +// The type attributes of a Text are its own: they are the element-level type. +func TestTextTypeAttributesAreItsOwn(t *testing.T) { + drawBase(func(f *Frame) { + f.Text("x").Mono().TextCenter().LineHeight(20).MaxLines(3).FontSize(18).Bold() + }) +} + +func TestAttributesThatDoNothingReport(t *testing.T) { + cases := []struct { + name string + want []string + run func(f *Frame) + }{ + {"Stack Gap", []string{"Stack", "Gap"}, func(f *Frame) { f.Stack().Gap(4) }}, + {"Grid Items", []string{"Grid", "Items"}, func(f *Frame) { f.Grid(40).Items(Center) }}, + {"Stack Justify", []string{"Stack", "Justify"}, func(f *Frame) { f.Stack().Justify(End) }}, + {"Column LineGap", []string{"Column", "LineGap"}, func(f *Frame) { f.Column().LineGap(2) }}, + {"Input Children", []string{"Input", "Children"}, func(f *Frame) { + f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name"}).Children(func() { f.Text("x") }) + }}, + {"Textarea Children", []string{"Textarea", "Children"}, func(f *Frame) { + f.Textarea(TextareaSnapshot{ID: gfx.Item(1), Label: "Notes"}).Children(func() { f.Text("x") }) + }}, + {"Tabs Children", []string{"Tabs", "Children"}, func(f *Frame) { + f.Tabs(attrTabsScope, []string{"A"}, 0).Children(func() { f.Text("x") }) + }}, + {"Checkbox Pad", []string{"Checkbox", "Pad"}, func(f *Frame) { f.Checkbox(gfx.Item(1), true).Pad(4) }}, + {"Checkbox Children", []string{"Checkbox", "Children"}, func(f *Frame) { + f.Checkbox(gfx.Item(1), true).Children(func() { f.Text("x") }) + }}, + {"Switch Gap", []string{"Switch", "Gap"}, func(f *Frame) { f.Switch(gfx.Item(1), false).Gap(4) }}, + {"Switch Children", []string{"Switch", "Children"}, func(f *Frame) { + f.Switch(gfx.Item(1), false).Children(func() { f.Text("x") }) + }}, + {"Slider Pad", []string{"Slider", "Pad"}, func(f *Frame) { + f.SliderBase(gfx.Item(1), &SliderState{}).Pad(4) + }}, + {"Slider HitWith", []string{"Slider", "HitWith"}, func(f *Frame) { + f.SliderBase(gfx.Item(1), &SliderState{}).HitWith(gfx.Item(1), "Volume", gfx.HitOptions{Role: gfx.RoleButton}) + }}, + {"Segmented Background", []string{"Segmented", "Background"}, func(f *Frame) { + f.Segmented([]style.SegmentOption{{ID: gfx.Item(1), Label: "A"}}, gfx.Item(1)).Background(gfx.Color{Red: 1, Alpha: 1}) + }}, + {"Segmented Children", []string{"Segmented", "Children"}, func(f *Frame) { + f.Segmented(nil, gfx.ID{}).Children(func() { f.Text("x") }) + }}, + {"Progress Pad", []string{"Progress", "Pad"}, func(f *Frame) { f.Progress(0.5).Pad(4) }}, + {"Progress FontSize", []string{"Progress", "FontSize"}, func(f *Frame) { f.Progress(0.5).FontSize(18) }}, + {"Pagination Color", []string{"Pagination", "Color"}, func(f *Frame) { + f.Pagination(nil).Color(gfx.Color{Red: 1, Alpha: 1}) + }}, + {"Progress Disabled", []string{"Progress", "Disabled"}, func(f *Frame) { f.Progress(0.5).Disabled(true) }}, + {"Spinner Disabled", []string{"Spinner", "Disabled"}, func(f *Frame) { f.Spinner().Disabled(true) }}, + {"Pagination Disabled", []string{"Pagination", "Disabled"}, func(f *Frame) { + f.Pagination(nil).Disabled(true) + }}, + {"Splitter LabelFor", []string{"Splitter", "LabelFor"}, func(f *Frame) { + f.Splitter(gfx.Item(1), &SplitterState{}).LabelFor(gfx.Item(2)) + }}, + {"Select Hit", []string{"Select", "Hit"}, func(f *Frame) { + f.Select(attrSelectScope, &SelectState{}, []string{"A"}, 0).Hit(gfx.Item(9), "Size") + }}, + {"Input Hit", []string{"Input", "Hit"}, func(f *Frame) { + f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name"}).Hit(gfx.Item(9), "Name") + }}, + {"Scroll on a Text", []string{"Text", "Scroll*"}, func(f *Frame) { + f.Text("x").Scrollbars() + }}, + {"HitExact on an Input", []string{"Input", "HitExact"}, func(f *Frame) { + f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name"}).HitExact() + }}, + {"HitOutset on an Input", []string{"Input", "HitOutset"}, func(f *Frame) { + f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name"}).HitOutset(2, 2, 2, 2) + }}, + {"HitWith on a Slider", []string{"Slider", "HitWith"}, func(f *Frame) { + f.SliderBase(gfx.Item(1), &SliderState{}).HitWith(gfx.Item(1), "Volume", gfx.HitOptions{Role: gfx.RoleButton}) + }}, + {"Type without caption", []string{"Checkbox", "FontSize/Weight/Color"}, func(f *Frame) { + f.Checkbox(gfx.Item(1), true).Color(gfx.Color{Red: 1, Alpha: 1}) + }}, + {"Badge size method", []string{"Badge", "Size"}, func(f *Frame) { f.Badge("New").Small() }}, + {"Tabs asymmetric Pad", []string{"Tabs", "Pad sides"}, func(f *Frame) { + f.Tabs(attrTabsScope, []string{"A"}, 0).PadSides(2, 8, 2, 8) + }}, + {"Image Radius", []string{"Image", "Radius"}, func(f *Frame) { + f.Image(gfx.Bitmap{}).Radius(4) + }}, + {"Checkbox type without caption", []string{"Checkbox", "FontSize/Weight/Color"}, func(f *Frame) { + f.Checkbox(gfx.Item(1), true).FontSize(18) + }}, + {"Select Variant", []string{"Select", "Variant"}, func(f *Frame) { + f.Select(attrSelectScope, &SelectState{}, []string{"A"}, 0).Secondary() + }}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + expectAttributePanic(t, test.run, test.want...) + }) + } +} diff --git a/base/attrcheck_release.go b/base/attrcheck_release.go new file mode 100644 index 000000000..7cfa6ea3d --- /dev/null +++ b/base/attrcheck_release.go @@ -0,0 +1,10 @@ +//go:build !dev && !vivadev + +package base + +// checkAttributes is empty in release builds: the attribute rules and their +// messages exist only in the dev build (attrcheck_dev.go). +func (f *Frame) checkAttributes() {} + +// markAttr is empty in release builds: no attribute set is recorded. +func (n *Node) markAttr(uint8) {} diff --git a/base/attrcheck_release_test.go b/base/attrcheck_release_test.go new file mode 100644 index 000000000..fd8fe1dcc --- /dev/null +++ b/base/attrcheck_release_test.go @@ -0,0 +1,21 @@ +//go:build !dev && !vivadev + +package base + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// Release builds do not run the attribute rules: a declaration that the dev +// build reports is declared as before (the attribute has no effect), so tests +// and applications that rely on that keep building and running. +func TestAttributesThatDoNothingAreNotCheckedInRelease(t *testing.T) { + var view View + view.Draw(styleCanvas(gfx.ID{}, gfx.ID{}, gfx.ID{}, false), gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Stack().Gap(4) + f.Row().Hover(Look{}.Background(colorHover)) + f.Checkbox(gfx.Item(1), true).Pad(4) + }) +} diff --git a/base/attrs.go b/base/attrs.go new file mode 100644 index 000000000..3642773c5 --- /dev/null +++ b/base/attrs.go @@ -0,0 +1,21 @@ +package base + +// attrSet records the generic attributes a caller set explicitly where the +// element's value cannot say so: a control's constructor writes its row defaults +// (Gap, Items, Justify) before the caller's calls, and LineGap outside a Flow is +// dropped by the builder itself. The set lives beside PadSet and stays in the +// node's existing header padding, so a Node does not grow. Only dev builds read +// it; marking one is an empty call that inlines away in release builds. +const ( + attrGap uint8 = 1 << iota + attrItems + attrJustify + attrLineGap + attrScroll + attrHit +) + +// SwitchCheckedSlot is the animation slot that holds a switch thumb's travel +// toward on, 0 (off) to 1 (on): the engine animates it to dress the track, and +// the control's painter reads the same slot to place the thumb. +const SwitchCheckedSlot uint8 = 0 diff --git a/base/badge.go b/base/badge.go index a3bad31e0..4d68d34bd 100644 --- a/base/badge.go +++ b/base/badge.go @@ -12,6 +12,10 @@ func (f *Frame) Badge(Label string) Box { b := f.Box(kindBadge) n := &f.Nodes[b.i] n.Text, n.Label = Label, Label + n.Flags |= flagThemed + // The chip's content is centered: the default label, or what Children + // declares; the recipe gives its padding, pill radius and label size. + n.Dir, n.Items, n.Justify = row, Center, Center return b } diff --git a/base/badge_node_test.go b/base/badge_node_test.go new file mode 100644 index 000000000..3257d31b7 --- /dev/null +++ b/base/badge_node_test.go @@ -0,0 +1,248 @@ +package base_test + +import ( + "reflect" + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +type badgeProbe struct { + box Rect + rects []gfx.Rectangle + texts []gfx.Text + hits []gfx.Hit +} + +func probeBadge(t *testing.T, state func(*gfx.Canvas), declare func(f *Frame) Box) badgeProbe { + t.Helper() + canvas := testCanvas() + if state != nil { + state(canvas) + } + var view View + var box Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 120}, func(f *Frame) { + f.Row().Items(Start).Children(func() { box = declare(f) }) + }) + return badgeProbe{box: box.Rect(), rects: canvas.Rectangles(), texts: canvas.Texts(), hits: canvas.Hits()} +} + +// fontOf returns the style of the first painted text, which a badge's default +// content is. +func fontOf(t *testing.T, p badgeProbe) gfx.TextStyle { + t.Helper() + if len(p.texts) != 1 { + t.Fatalf("texts = %+v, want the one label", p.texts) + } + return p.texts[0].Style +} + +// A badge with no calls of its own is the chip the theme's recipe gives it: a +// pill the height of a badge, filled with the primary color, its label painted +// with the small font and the primary foreground. +func TestBadgeDefaultsAreTheRecipeChip(t *testing.T) { + theme := gfx.LightTheme() + look := components.BadgeRecipe(theme, components.BadgeDefault, gfx.State{}) + height, _, radius, fontSize := style.BadgeGeometry(theme.Metrics) + p := probeBadge(t, nil, func(f *Frame) Box { return f.Badge("beta") }) + if len(p.rects) != 1 { + t.Fatalf("rectangles = %+v, want the chip", p.rects) + } + if p.box.Height != height || p.rects[0].Bounds.Height != height { + t.Errorf("chip height = %v/%v, want %v", p.box.Height, p.rects[0].Bounds.Height, height) + } + if p.rects[0].Radius != radius { + t.Errorf("chip radius = %v, want the pill's %v", p.rects[0].Radius, radius) + } + if p.rects[0].Color != look.Background { + t.Errorf("chip fill = %v, want %v", p.rects[0].Color, look.Background) + } + text := fontOf(t, p) + if text.Size != fontSize || text.Weight != gfx.WeightMedium || text.Color != look.Foreground { + t.Errorf("label style = %+v, want size %v, medium, %v", text, fontSize, look.Foreground) + } + if len(p.hits) != 0 { + t.Errorf("a presentational badge declared hits: %+v", p.hits) + } +} + +// The calls every element takes reach the chip: FontSize and Weight the label, +// Color its ink, Pad the room inside the chip, Radius and Height the surface. +func TestBadgePropertiesReachTheChip(t *testing.T) { + ink := gfx.Color{Red: 1, Alpha: 1} + p := probeBadge(t, nil, func(f *Frame) Box { + return f.Badge("beta").FontSize(20).Weight(gfx.WeightBold).Color(ink).Height(40).Radius(3) + }) + if p.box.Height != 40 { + t.Errorf("chip height = %v, want the explicit 40", p.box.Height) + } + text := fontOf(t, p) + if text.Size != 20 || text.Weight != gfx.WeightBold || text.Color != ink { + t.Errorf("label style = %+v, want size 20, bold, red", text) + } + if len(p.rects) == 0 || p.rects[0].Radius != 3 { + t.Errorf("chip radius was not the explicit 3: %+v", p.rects) + } + + _, padding, _, _ := style.BadgeGeometry(gfx.LightTheme().Metrics) + plain := probeBadge(t, nil, func(f *Frame) Box { return f.Badge("beta") }) + padded := probeBadge(t, nil, func(f *Frame) Box { return f.Badge("beta").PadSides(1, 30, 1, 30) }) + if got, want := padded.box.Width, plain.box.Width-2*padding+60; got != want { + t.Errorf("padded badge width = %v, want %v (pad replaces the recipe's)", got, want) + } +} + +// Explicit Height gives the chip a new height; the look keeps the recipe's +// radius unless the caller gives one, as a Button's corners do. +func TestBadgeExplicitHeightKeepsTheRecipeRadius(t *testing.T) { + _, _, radius, _ := style.BadgeGeometry(gfx.LightTheme().Metrics) + p := probeBadge(t, nil, func(f *Frame) Box { return f.Badge("beta").Height(48) }) + if p.box.Height != 48 { + t.Fatalf("chip height = %v, want 48", p.box.Height) + } + if len(p.rects) == 0 || p.rects[0].Radius != radius { + t.Errorf("chip radius = %+v, want the recipe's %v", p.rects, radius) + } +} + +// Children replace the label and are laid out inside the content rect; the +// badge is still one button to the pointer when it is given an identity. +func TestBadgeChildrenReplaceTheLabel(t *testing.T) { + p := probeBadge(t, nil, func(f *Frame) Box { + return f.Badge("beta").Hit(gfx.Item(7), "beta").Children(func() { + f.Text("one") + f.Text("two") + }) + }) + if len(p.texts) != 2 { + t.Fatalf("texts = %+v, want the two children", p.texts) + } + for _, text := range p.texts { + if text.Value == "beta" { + t.Errorf("the default label was painted over the children: %+v", p.texts) + } + } + if len(p.hits) != 1 || p.hits[0].Role != gfx.RoleButton || p.hits[0].Label != "beta" || !p.hits[0].Focusable { + t.Errorf("hits = %+v, want one focusable button named by the label", p.hits) + } + for _, text := range p.texts { + if text.Bounds.X < p.box.X || text.Bounds.X+text.Bounds.Width > p.box.X+p.box.Width { + t.Errorf("child %q at %v is outside the chip %v", text.Value, text.Bounds, p.box) + } + } +} + +// A variant dresses the chip by the recipe: a secondary badge is the secondary +// colors, a ghost one paints no fill. +func TestBadgeVariantsFollowTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + secondary := components.BadgeRecipe(theme, components.BadgeSecondary, gfx.State{}) + p := probeBadge(t, nil, func(f *Frame) Box { return f.Badge("beta").Secondary() }) + if len(p.rects) != 1 || p.rects[0].Color != secondary.Background { + t.Errorf("secondary chip = %+v, want %v", p.rects, secondary.Background) + } + if text := fontOf(t, p); text.Color != secondary.Foreground { + t.Errorf("secondary label = %v, want %v", text.Color, secondary.Foreground) + } + + ghost := probeBadge(t, nil, func(f *Frame) Box { return f.Badge("beta").Ghost() }) + if len(ghost.rects) != 0 { + t.Errorf("ghost badge painted a fill: %+v", ghost.rects) + } +} + +// A disabled badge's content is inert, as a disabled button's is: its nested +// controls take no focus and no click. +func TestDisabledBadgeContentsAreInert(t *testing.T) { + ctl := gfx.Item(9) + p := probeBadge(t, nil, func(f *Frame) Box { + return f.Badge("outer").Disabled(true).Children(func() { + f.Button(ctl, "inner") + }) + }) + if len(p.hits) != 1 || !p.hits[0].Disabled || p.hits[0].Focusable { + t.Errorf("hits = %+v, want the nested button inert under the disabled badge", p.hits) + } +} + +// A row that lines elements up by their baseline uses the badge's label size, +// so a badge and a text sit on the same row. +func TestBadgeBaselineMatchesItsText(t *testing.T) { + var view View + canvas := testCanvas() + var sibling, badge Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 80}, func(f *Frame) { + f.Row().Height(80).Items(Baseline).Children(func() { + sibling = f.Text("Text").FontSize(20) + badge = f.Badge("badge") + }) + }) + _, _, _, fontSize := style.BadgeGeometry(gfx.LightTheme().Metrics) + got := canvas.LabelBaseline(badge.Rect(), gfx.TextStyle{Size: fontSize}) + want := canvas.LabelBaseline(sibling.Rect(), gfx.TextStyle{Size: 20}) + if d := got - want; d > 0.01 || d < -0.01 { + t.Fatalf("badge baseline %v, text baseline %v", got, want) + } +} + +// shapesOf normalizes painted shapes for comparison: two independent paints +// number their primitives differently. +func shapesOf(in []gfx.Rectangle) []gfx.Rectangle { + out := append([]gfx.Rectangle(nil), in...) + for i := 1; i < len(out); i++ { + for j := i; j > 0; j-- { + a, b := out[j-1], out[j] + if a.Bounds.X < b.Bounds.X || a.Bounds.X == b.Bounds.X && (a.Bounds.Y < b.Bounds.Y || a.Bounds.Y == b.Bounds.Y && a.Radius < b.Radius) { + break + } + out[j-1], out[j] = out[j], out[j-1] + } + } + return out +} + +// A node badge paints what components.PaintBadge painted before it: for every +// variant the same chip shapes and the same label, at the same place. +func TestBadgeNodePaintsWhatTheComponentDid(t *testing.T) { + theme := gfx.LightTheme() + cases := []struct { + name string + variant components.BadgeVariant + declare func(f *Frame) Box + }{ + {"default", components.BadgeDefault, func(f *Frame) Box { return f.Badge("beta") }}, + {"secondary", components.BadgeSecondary, func(f *Frame) Box { return f.Badge("beta").Secondary() }}, + {"outline", components.BadgeOutline, func(f *Frame) Box { return f.Badge("beta").Outline() }}, + {"ghost", components.BadgeGhost, func(f *Frame) Box { return f.Badge("beta").Ghost() }}, + {"link", components.BadgeLink, func(f *Frame) Box { return f.Badge("beta").Link() }}, + {"destructive", components.BadgeDestructive, func(f *Frame) Box { return f.Badge("beta").Destructive() }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + canvas := testCanvas() + var view View + var box Box + view.Draw(canvas, theme, gfx.Rect{Width: 200, Height: 80}, func(f *Frame) { + f.Row().Items(Start).Children(func() { box = tc.declare(f) }) + }) + wantCanvas := testCanvas() + components.PaintBadge(wantCanvas, theme, gfx.Rect{X: box.Rect().X, Y: box.Rect().Y}, "beta", tc.variant) + if !reflect.DeepEqual(shapesOf(wantCanvas.Rectangles()), shapesOf(canvas.Rectangles())) { + t.Errorf("chip differs from the component:\nwant %+v\n got %+v", wantCanvas.Rectangles(), canvas.Rectangles()) + } + wantTexts, gotTexts := wantCanvas.Texts(), canvas.Texts() + if len(wantTexts) != len(gotTexts) { + t.Fatalf("texts = %+v, want the component's %+v", gotTexts, wantTexts) + } + for i := range wantTexts { + if wantTexts[i] != gotTexts[i] { + t.Errorf("text %d differs: want %+v got %+v", i, wantTexts[i], gotTexts[i]) + } + } + }) + } +} diff --git a/base/box.go b/base/box.go index e92d88d9e..f5a4e0bcc 100644 --- a/base/box.go +++ b/base/box.go @@ -76,6 +76,7 @@ func (b Box) Hit(ID gfx.ID, Label string) Box { n := b.N() n.ID, n.Label = ID, Label n.Flags = n.Flags&^flagLabelFor | flagHasHit + n.markAttr(attrHit) return b } @@ -113,6 +114,7 @@ func (b Box) LabelFor(ID gfx.ID) Box { n := b.N() n.ID = ID n.Flags |= flagHasHit | flagLabelFor + n.markAttr(attrHit) return b } @@ -247,12 +249,19 @@ func (b Box) MarginSides(top, right, bottom, left float32) Box { // Gap is the space between the children of a Row, a Column or a Flow, and between // the lines of a Flow unless LineGap sets them apart. -func (b Box) Gap(v float32) Box { b.N().Gap = v; return b } +func (b Box) Gap(v float32) Box { + n := b.N() + n.Gap = v + n.markAttr(attrGap) + return b +} // LineGap is the space between the lines of a Flow, when it is not its Gap. It has // no effect on any other container. func (b Box) LineGap(v float32) Box { - if n := b.N(); n.Dir == flow { + n := b.N() + n.markAttr(attrLineGap) + if n.Dir == flow { n.GridMin = max(v, 0) } return b @@ -261,9 +270,19 @@ func (b Box) LineGap(v float32) Box { // Items places the children across the container (Start, Center, End or // Stretch, the default); Self does it for this element alone; Justify places // them along it when none grows (Start, Center, End or Between). -func (b Box) Items(a Align) Box { b.N().Items = a; return b } -func (b Box) Self(a Align) Box { b.N().Self = a; return b } -func (b Box) Justify(a Align) Box { b.N().Justify = a; return b } +func (b Box) Items(a Align) Box { + n := b.N() + n.Items = a + n.markAttr(attrItems) + return b +} +func (b Box) Self(a Align) Box { b.N().Self = a; return b } +func (b Box) Justify(a Align) Box { + n := b.N() + n.Justify = a + n.markAttr(attrJustify) + return b +} // Center centers the children both ways. func (b Box) Center() Box { return b.Items(Center).Justify(Center) } diff --git a/base/caption.go b/base/caption.go index c6a664dee..210e2b9b9 100644 --- a/base/caption.go +++ b/base/caption.go @@ -70,7 +70,11 @@ func (f *Frame) PaintCaptionView(v ControlView, control Rect) { if v.Disabled { color.Alpha *= 0.5 } - f.Surface.Label(v.Text, r, gfx.TextStyle{Size: size, Weight: gfx.WeightMedium, Color: color}) + weight := gfx.WeightMedium + if v.Weight > 0 { + weight = v.Weight + } + f.Surface.Label(v.Text, r, gfx.TextStyle{Size: size, Weight: weight, Color: color}) f.Surface.HitLabel(v.ID, r, v.Text, v.Disabled) } @@ -80,6 +84,11 @@ func (f *Frame) paintCaption(n *Node, control Rect) { x := control.X + control.Width + CaptionGap r := Rect{X: x, Y: n.Rect.Y + (n.Rect.Height-line)/2, Width: max(n.Rect.X+n.Rect.Width-x, 0), Height: line} disabled := n.Flags&flagDisabled != 0 + if n.Flags&flagThemed != 0 { + // A themed control is disabled by a disabled ancestor too, and its label + // dims with the rest of it. + disabled = f.Disabled(n) + } color := fade(f.Palette.Foreground, f.Opacity) if n.Flags&flagHasColor != 0 { color = n.Color // faded with the element already @@ -87,6 +96,10 @@ func (f *Frame) paintCaption(n *Node, control Rect) { if disabled { color.Alpha *= 0.5 } - f.Surface.Label(n.Text, r, gfx.TextStyle{Size: size, Weight: gfx.WeightMedium, Color: color}) + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + f.Surface.Label(n.Text, r, gfx.TextStyle{Size: size, Weight: weight, Color: color}) f.Surface.HitLabel(n.ID, r, n.Text, disabled) } diff --git a/base/checkbox_switch_node_test.go b/base/checkbox_switch_node_test.go new file mode 100644 index 000000000..d1a14d0e2 --- /dev/null +++ b/base/checkbox_switch_node_test.go @@ -0,0 +1,205 @@ +package base_test + +import ( + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +type choiceProbe struct { + box Rect + rects []gfx.Rectangle + texts []gfx.Text + hits []gfx.Hit + marked bool +} + +func probeChoice(t *testing.T, declare func(f *Frame) Box) choiceProbe { + t.Helper() + canvas := testCanvas() + var view View + var box Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 200}, func(f *Frame) { + f.Column().Pad(6).Children(func() { box = declare(f) }) + }) + return choiceProbe{ + box: box.Rect(), rects: canvas.Rectangles(), texts: canvas.Texts(), hits: canvas.Hits(), + marked: len(canvas.Triangles()) > 0, + } +} + +func checkboxBoxRect(t *testing.T, p choiceProbe) gfx.Rect { + t.Helper() + side := components.CheckboxExtent(gfx.LightTheme()) + for _, rect := range p.rects { + // The box's surface is the square of the checkbox's extent at the start of + // the element when it has a caption. + if rect.Bounds.Width == side && rect.Bounds.Height == side { + return rect.Bounds + } + } + t.Fatalf("no %v checkbox box in %+v", side, p.rects) + return gfx.Rect{} +} + +// A themed Checkbox's box, caption and mark come from the recipe and the +// element: the box surface from CheckboxRecipe, the caption text in the +// element's style, and the mark still the control's graphic. +func TestCheckboxDefaultsAreTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + look := components.CheckboxRecipe(theme, gfx.State{Checked: true}) + p := probeChoice(t, func(f *Frame) Box { return f.Checkbox(gfx.Item(1), true).Caption("Sync") }) + box := checkboxBoxRect(t, p) + if !p.marked { + t.Error("the checkbox painted no mark") + } + found := false + for _, rect := range p.rects { + if rect.Bounds == box { + found = true + if rect.Color != look.Fill || rect.Radius != look.Radius { + t.Errorf("box = %v radius %v, want %v radius %v", rect.Color, rect.Radius, look.Fill, look.Radius) + } + } + } + if !found { + t.Errorf("no box surface at %v: %+v", box, p.rects) + } + if len(p.texts) != 1 || p.texts[0].Value != "Sync" { + t.Fatalf("texts = %+v, want the caption", p.texts) + } + if p.texts[0].Style.Size != theme.Metrics.FontSizeM || p.texts[0].Style.Weight != gfx.WeightMedium { + t.Errorf("caption style = %+v, want body size and medium", p.texts[0].Style) + } + if p.texts[0].Bounds.X < box.X+box.Width { + t.Errorf("caption %v overlaps the box %v", p.texts[0].Bounds, box) + } + hit := hitByIDWithRole(p.hits, gfx.RoleCheckbox) + if hit.ID != gfx.Item(1) || !hit.Checked || hit.Role != gfx.RoleCheckbox { + t.Errorf("hit = %+v, want a checked checkbox", hit) + } +} + +func hitByIDWithRole(hits []gfx.Hit, role gfx.Role) gfx.Hit { + for _, hit := range hits { + if hit.Role == role { + return hit + } + } + return gfx.Hit{} +} + +// FontSize, Weight and Color style the caption; the box's own surface takes +// Background and Radius. +func TestCheckboxPropertiesReachTheCaptionAndBox(t *testing.T) { + ink := gfx.Color{Red: 1, Alpha: 1} + fill := gfx.Color{Blue: 1, Alpha: 1} + p := probeChoice(t, func(f *Frame) Box { + return f.Checkbox(gfx.Item(1), false).Caption("Sync").FontSize(18).Weight(gfx.WeightBold).Color(ink).Background(fill).Radius(3) + }) + if len(p.texts) != 1 { + t.Fatalf("texts = %+v", p.texts) + } + if got := p.texts[0].Style; got.Size != 18 || got.Weight != gfx.WeightBold || got.Color != ink { + t.Errorf("caption style = %+v, want 18, bold, red", got) + } + found := false + for _, rect := range p.rects { + if rect.Color == fill { + found = true + } + } + if !found { + t.Errorf("no box fill %v: %+v", fill, p.rects) + } + outer := float32(0) + for _, rect := range p.rects { + if rect.Radius > outer { + outer = rect.Radius + } + } + if outer != 3 { + t.Errorf("box radius = %v, want the explicit 3", outer) + } +} + +// A mixed box reports mixed, an invalid one paints the recipe's danger ring. +func TestCheckboxMixedAndInvalid(t *testing.T) { + theme := gfx.LightTheme() + p := probeChoice(t, func(f *Frame) Box { return f.Checkbox(gfx.Item(1), false).Mixed(true) }) + hit := hitByIDWithRole(p.hits, gfx.RoleCheckbox) + if !hit.Mixed || hit.Checked { + t.Errorf("mixed hit = %+v, want mixed and not checked", hit) + } + look := components.CheckboxRecipe(theme, gfx.State{Invalid: true}) + invalid := probeChoice(t, func(f *Frame) Box { + return f.Checkbox(gfx.Item(1), false).Invalid(true) + }) + // The ring is the recipe's invalid ring: a translucent, red-dominant halo + // around the box. + ring := false + for _, rect := range invalid.rects { + if rect.Color.Red > rect.Color.Green && rect.Color.Alpha > 0 && rect.Color.Alpha < 1 { + ring = true + } + } + _ = look + if !ring { + t.Errorf("invalid checkbox paints no danger ring: %+v", invalid.rects) + } + if hit := hitByIDWithRole(invalid.hits, gfx.RoleCheckbox); !hit.Invalid { + t.Errorf("invalid checkbox hit = %+v, want Invalid", hit) + } +} + +// A themed Switch's track is the recipe's surface (sized by explicit Width and +// Height), its thumb stays the control's graphic, and its caption is the +// element's label. +func TestSwitchDefaultsAreTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + look := components.SwitchRecipe(theme, gfx.State{}, 1) + p := probeChoice(t, func(f *Frame) Box { return f.Switch(gfx.Item(2), true).Caption("Running") }) + if len(p.texts) != 1 || p.texts[0].Value != "Running" { + t.Fatalf("texts = %+v, want the caption", p.texts) + } + var track gfx.Rectangle + for _, rect := range p.rects { + if rect.Color == look.Track { + track = rect + } + } + if track.Bounds.Width == 0 { + t.Fatalf("no track with %v: %+v", look.Track, p.rects) + } + if track.Radius != track.Bounds.Height/2 { + t.Errorf("track %v radius %v, want a pill of its own half height", track.Bounds, track.Radius) + } + thumb := false + for _, rect := range p.rects { + if rect.Color == look.Thumb && rect.Bounds.Width < track.Bounds.Height { + thumb = true + } + } + if !thumb { + t.Errorf("no thumb %v inside the track: %+v", look.Thumb, p.rects) + } + hit := hitByIDWithRole(p.hits, gfx.RoleSwitch) + if !hit.Checked || hit.Role != gfx.RoleSwitch { + t.Errorf("hit = %+v, want a checked switch", hit) + } + + wide := probeChoice(t, func(f *Frame) Box { + return f.Switch(gfx.Item(3), false).Caption("Running").Width(80).Height(40) + }) + var wideTrack gfx.Rectangle + for _, rect := range wide.rects { + if rect.Color == components.SwitchRecipe(theme, gfx.State{}, 0).Track { + wideTrack = rect + } + } + if wideTrack.Bounds.Width != 80 || wideTrack.Bounds.Height != 40 { + t.Errorf("explicit switch track = %v, want 80x40", wideTrack.Bounds) + } +} diff --git a/base/elements.go b/base/elements.go index 4578f044b..518abf165 100644 --- a/base/elements.go +++ b/base/elements.go @@ -495,7 +495,7 @@ func (f *Frame) FirstControl(i int32) gfx.ID { } if !n.ID.IsZero() { switch n.Kind { - case kindButton, kindSplitButton, kindCheckbox, kindSwitch, kindInput, kindTextarea, kindSlider: + case kindButton, kindToggle, kindSplitButton, kindCheckbox, kindSwitch, kindInput, kindTextarea, kindSlider: return n.ID case kindContainer: if n.Flags&flagHasHit != 0 && n.Flags&flagLabelFor == 0 { diff --git a/base/frame.go b/base/frame.go index e60a624e2..3b1607a34 100644 --- a/base/frame.go +++ b/base/frame.go @@ -97,6 +97,7 @@ type Node struct { Kind Kind Dir direction PadSet uint8 // bit i records Pad[i] explicitly set; fits existing header alignment + attrs uint8 // the generic attributes set where their value cannot tell; padding Flags uint32 Parent, First, Last, Next int32 @@ -228,30 +229,36 @@ type Frame struct { styles *Styles // the page's recipe overrides; nil keeps the theme's // buttonPainted is the look the recipe gave the themed button being painted, for the // painter of its content; inherited is the color the content of a themed button takes - // unless it has one, while hasInherited says there is one. - buttonPainted style.ButtonLook - inherited Color - hasInherited bool - Nodes []Node - addons []FieldAddons // the icons and buttons inside fields, by 1 + extra.addons - Images []gfx.Bitmap // what each Image element draws, indexed by its aux - Exts []Extra // exts[0] is never written: an element without extras points at it - Floats []int32 // the Popups, which belong to no container - States []stateLooks // what Hover, Pressed and Focus declared, by element - Draws []drawHooks // what Draw and DrawOver declared, by element - memoDepth int // how many Memos of a page are recording what is declared now - page *Page // the page declaring this frame; nil for a frame of the application's - tooltips bool // an element was given a Tooltip: End paints the one the pointer rests on - tooltip any // the tooltip state the layer above owns: see tooltipOf - drawContext DrawContext // what a Draw callback is handed, reused for the frame - pickerCtx Ctx // the declaration context a ColorPicker's painter is handed, reused for the frame - Gradients []gradient // the gradients of the elements that have one - Stops []gfx.GradientStop // their stops, in the order declared - paintStops []gfx.GradientStop // the stops of the gradient being painted, faded - Opacity float32 // the product of the opacities of the elements being painted - popupLayer uint16 // the canvas layer the Popups are painted on - nativeMark int // how many native views the canvas had when the page began - Binds []bindDecl // the bound controls, see bind.go + // unless it has one, while hasInherited says there is one. selectForeground and + // selectChevron are the recipe's colors for a Select trigger's painter, and + // checkboxPainted and switchPainted are the looks for a checkbox's mark and a + // switch's thumb. + buttonPainted style.ButtonLook + selectForeground, selectChevron Color + checkboxPainted style.CheckboxLook + switchPainted style.SwitchLook + inherited Color + hasInherited bool + Nodes []Node + addons []FieldAddons // the icons and buttons inside fields, by 1 + extra.addons + Images []gfx.Bitmap // what each Image element draws, indexed by its aux + Exts []Extra // exts[0] is never written: an element without extras points at it + Floats []int32 // the Popups, which belong to no container + States []stateLooks // what Hover, Pressed and Focus declared, by element + Draws []drawHooks // what Draw and DrawOver declared, by element + memoDepth int // how many Memos of a page are recording what is declared now + page *Page // the page declaring this frame; nil for a frame of the application's + tooltips bool // an element was given a Tooltip: End paints the one the pointer rests on + tooltip any // the tooltip state the layer above owns: see tooltipOf + drawContext DrawContext // what a Draw callback is handed, reused for the frame + pickerCtx Ctx // the declaration context a ColorPicker's painter is handed, reused for the frame + Gradients []gradient // the gradients of the elements that have one + Stops []gfx.GradientStop // their stops, in the order declared + paintStops []gfx.GradientStop // the stops of the gradient being painted, faded + Opacity float32 // the product of the opacities of the elements being painted + popupLayer uint16 // the canvas layer the Popups are painted on + nativeMark int // how many native views the canvas had when the page began + Binds []bindDecl // the bound controls, see bind.go // The paint of a Popover, the settling of bound values and the paint of a Caption // are reached through these, set by the call that declares one, so an application // that declares none does not link them. @@ -359,6 +366,7 @@ func (f *Frame) End() { } f.done = true f.checkHits() + f.checkAttributes() f.applyRecipes() root := &f.Nodes[0] f.measure(AxisX) @@ -634,6 +642,8 @@ func (f *Frame) Button(ID gfx.ID, Label string) Box { } // Checkbox adds a checkbox in the given state; Clicked reports a click on it. +// Its caption is Caption; it has no Children slot, as shadcn's checkbox is +// self-closing. func (f *Frame) Checkbox(ID gfx.ID, checked bool) Box { b := f.Box(kindCheckbox) n := &f.Nodes[b.i] @@ -641,11 +651,13 @@ func (f *Frame) Checkbox(ID gfx.ID, checked bool) Box { if checked { n.Flags |= flagChecked } - n.Flags |= flagHasHit + n.Flags |= flagHasHit | flagThemed return b } // Switch adds a two-state switch in the given state; Clicked reports a click. +// Its caption is Caption; it has no Children slot, as shadcn's switch is +// self-closing. func (f *Frame) Switch(ID gfx.ID, on bool) Box { b := f.Box(kindSwitch) n := &f.Nodes[b.i] @@ -653,11 +665,13 @@ func (f *Frame) Switch(ID gfx.ID, on bool) Box { if on { n.Flags |= flagChecked } - n.Flags |= flagHasHit + n.Flags |= flagHasHit | flagThemed return b } // Toggle adds a two-state button in the given state; Clicked reports a click. +// Its default look and measurements come from the theme's toggle recipe; what +// Children declares replaces its label and is laid out as a centered row. func (f *Frame) Toggle(ID gfx.ID, Label string, pressed bool) Box { b := f.Box(kindToggle) n := &f.Nodes[b.i] @@ -665,7 +679,8 @@ func (f *Frame) Toggle(ID gfx.ID, Label string, pressed bool) Box { if pressed { n.Flags |= flagChecked | flagSelected } - n.Flags |= flagHasHit + n.Flags |= flagHasHit | flagThemed + n.Dir, n.Items, n.Justify, n.Gap = row, Center, Center, style.ButtonIconGap return b } diff --git a/base/hooks.go b/base/hooks.go index 4aa391d2c..3b3b4a440 100644 --- a/base/hooks.go +++ b/base/hooks.go @@ -32,10 +32,21 @@ var ( TreeDraw func(s *TreeState, d *DrawContext) EntryLook func(f *Frame, palette *Theme, state gfx.State) style.TextEntryLook ButtonLookFn func(f *Frame, n *Node, palette *Theme, state gfx.State) style.ButtonLook - SliderPointer func(f *Frame, n *Node, s *SliderState) - BuildDialog func(f *Frame, spec DialogSpec) Box - BuildPopover func(f *Frame, anchor Box, spec PopoverSpec) Box - DrawerBoxes func(spec DrawerDeclaration, surface *gfx.Canvas, palette Theme, bounds Rect, layer uint16) DrawerRects + BadgeLookFn func(f *Frame, n *Node, palette *Theme, state gfx.State) style.ButtonLook + ToggleLookFn func(f *Frame, n *Node, palette *Theme, state gfx.State) style.ButtonLook + // TabsLookFn shares the badge look's signature: a tab strip has no state of its own. + TabsLookFn func(f *Frame, n *Node, palette *Theme, state gfx.State) style.ButtonLook + SelectLookFn func(f *Frame, n *Node, palette *Theme, state gfx.State, placeholder bool) (style.TextEntryLook, gfx.Color, gfx.Color) + CheckboxLookFn func(f *Frame, n *Node, palette *Theme, state gfx.State) style.CheckboxLook + SwitchLookFn func(f *Frame, n *Node, palette *Theme, state gfx.State, progress float32) style.SwitchLook + // ControlSurfaceRect gives where a themed control's own surface paints when that + // is smaller than the element, as a checkbox's box or a switch's track are when + // the element has a caption; nil uses the element's rectangle. + ControlSurfaceRect func(f *Frame, n *Node) Rect + SliderPointer func(f *Frame, n *Node, s *SliderState) + BuildDialog func(f *Frame, spec DialogSpec) Box + BuildPopover func(f *Frame, anchor Box, spec PopoverSpec) Box + DrawerBoxes func(spec DrawerDeclaration, surface *gfx.Canvas, palette Theme, bounds Rect, layer uint16) DrawerRects ) // DrawerRects is where a drawer's parts go. @@ -156,6 +167,30 @@ func (f *Frame) buttonLook(n *Node, palette *Theme, state gfx.State) style.Butto return style.ButtonLook{} } +// tabsLook is the look of the strip behind a tab list: its fill and radius. +func (f *Frame) tabsLook(n *Node, palette *Theme) style.ButtonLook { + if TabsLookFn != nil { + return TabsLookFn(f, n, palette, gfx.State{}) + } + return style.ButtonLook{} +} + +// toggleLook is the look the theme's recipe gives the toggle element n in a state. +func (f *Frame) toggleLook(n *Node, palette *Theme, state gfx.State) style.ButtonLook { + if ToggleLookFn != nil { + return ToggleLookFn(f, n, palette, state) + } + return style.ButtonLook{} +} + +// badgeLook is the look the theme's recipe gives the badge element n in a state. +func (f *Frame) badgeLook(n *Node, palette *Theme, state gfx.State) style.ButtonLook { + if BadgeLookFn != nil { + return BadgeLookFn(f, n, palette, state) + } + return style.ButtonLook{} +} + func (f *Frame) TextEntryLook(palette *Theme, state gfx.State) style.TextEntryLook { if EntryLook != nil { return EntryLook(f, palette, state) diff --git a/base/layout.go b/base/layout.go index bc03d8b30..059de141b 100644 --- a/base/layout.go +++ b/base/layout.go @@ -52,9 +52,10 @@ func (n *Node) marginOn(axis int) (start, end float32) { } // isContainer describes layout, independently of the control's semantic kind. -// A Button keeps its button identity when it holds caller-owned children. +// A Button or a Badge keeps its identity when it holds caller-owned children. func (n *Node) isContainer() bool { - return n.Kind == kindContainer || n.Kind == kindButton && n.Flags&flagChildren != 0 + return n.Kind == kindContainer || + (n.Kind == kindButton || n.Kind == kindBadge || n.Kind == kindToggle || n.Kind == kindSelect) && n.Flags&flagChildren != 0 } // flows reports whether a container lays its children out along axis. A Flow does @@ -551,7 +552,7 @@ func (f *Frame) measureBaseline(n *Node) { } } n.Baseline = top + row - case kindButton: + case kindButton, kindBadge, kindToggle, kindSelect: if n.Flags&flagChildren == 0 { if ControlBaseline != nil { n.Baseline = ControlBaseline(f, n) diff --git a/base/paint.go b/base/paint.go index fa9b133cd..b3eaf1ff0 100644 --- a/base/paint.go +++ b/base/paint.go @@ -43,13 +43,23 @@ func (f *Frame) PaintChild(i int32) { defer f.memoFn(f, i, false) } r := n.Rect + // A themed control whose own surface is smaller than the element (a checkbox + // with a caption, a switch's track) paints it at SurfaceRect. Its caption, an + // element label in every state, paints before the surface as the control's + // painter used to paint it. + surface := r + if n.Flags&flagThemed != 0 && ControlSurfaceRect != nil { + if own := ControlSurfaceRect(f, n); own.Width > 0 && own.Height > 0 { + surface = own + } + } canvas := f.Surface extra := &f.Exts[n.Ext] if s := extra.scrollState; s != nil && canvas != nil { s.scope = canvas.FocusScope() } style := f.resolve(n, extra) - if n.Kind == kindButton && n.Flags&flagChildren != 0 { + if (n.Kind == kindButton || n.Kind == kindBadge || n.Kind == kindToggle || n.Kind == kindSelect) && n.Flags&flagChildren != 0 { defer func(color Color, has bool) { f.inherited, f.hasInherited = color, has }(f.inherited, f.hasInherited) f.inherited, f.hasInherited = style.Color, true } @@ -61,7 +71,10 @@ func (f *Frame) PaintChild(i int32) { parentTheme = f.Palette // a theme is large: copied only for what is faded f.Palette = f.Palette.WithOpacity(style.Opacity) } - f.paintRing(r, n.Radius, &style) // outside the rectangle: before a Clip of the element's own + if n.Flags&flagThemed != 0 && (n.Kind == kindCheckbox || n.Kind == kindSwitch) && n.Text != "" && f.captionFn != nil { + f.captionFn(f, n, surface) + } + f.paintRing(surface, n.Radius, &style) // outside the rectangle: before a Clip of the element's own if n.Flags&flagClip != 0 { canvas.Clip(r) defer canvas.Unclip() @@ -70,11 +83,11 @@ func (f *Frame) PaintChild(i int32) { hasHit := n.Flags&flagHasHit != 0 && !n.ID.IsZero() background, border := fade(style.Background, f.Opacity), fade(style.border, f.Opacity) if style.shadow != gfx.ShadowNone { - canvas.ElevateFaded(r, n.Radius, style.shadow, f.Opacity) + canvas.ElevateFaded(surface, n.Radius, style.shadow, f.Opacity) } switch { case style.borderWidth > 0 && !style.dashed && !style.splitBorder && extra.gradient == 0 && f.Opacity >= 1 && background.Alpha >= 1: - canvas.RoundedBorder(r, n.Radius, style.borderWidth, border, background) + canvas.RoundedBorder(surface, n.Radius, style.borderWidth, border, background) default: // RoundedBorder paints the border color as a solid backing under the fill, which a // gradient or a faded fill would show through. For those the fill, then the @@ -83,7 +96,7 @@ func (f *Frame) PaintChild(i int32) { // so what an application painted before looks as it did. if background.Alpha > 0 { if n.Radius > 0 { - canvas.Rounded(r, n.Radius, background) + canvas.Rounded(surface, n.Radius, background) } else { canvas.Fill(r, background) } @@ -93,9 +106,9 @@ func (f *Frame) PaintChild(i int32) { } if style.borderWidth > 0 { if style.dashed { - canvas.DashedRoundedOutline(n.Rect, n.Radius, style.borderWidth, border) + canvas.DashedRoundedOutline(surface, n.Radius, style.borderWidth, border) } else { - canvas.RoundedOutline(r, n.Radius, style.borderWidth, border) + canvas.RoundedOutline(surface, n.Radius, style.borderWidth, border) } } } @@ -114,7 +127,7 @@ func (f *Frame) PaintChild(i int32) { group = canvas.Mark() } // A ColorSwatch declares its own hit, as a radio, under whatever id Hit gave it. - if hasHit && !extra.swatch && (n.Kind == kindButton || n.Kind == kindContainer || n.Kind == kindText || n.Kind == kindIcon || n.Kind == kindSlot) { + if hasHit && !extra.swatch && (n.Kind == kindButton || n.Kind == kindBadge || n.Kind == kindToggle || n.Kind == kindContainer || n.Kind == kindText || n.Kind == kindIcon || n.Kind == kindSlot) { h := extra.hitOut hit := Rect{X: r.X - h[3], Y: r.Y - h[0], Width: r.Width + h[1] + h[3], Height: r.Height + h[0] + h[2]} if n.Flags&flagLabelFor != 0 { @@ -125,13 +138,19 @@ func (f *Frame) PaintChild(i int32) { canvas.HitLabel(n.ID, hit, text, n.Flags&flagDisabled != 0) } else { options := extra.hit - if n.Kind == kindButton { + if n.Kind == kindButton || n.Kind == kindBadge || n.Kind == kindToggle { if options.Role == 0 { options.Role = gfx.RoleButton } - if options.Hint == "" && n.ButtonSize >= controlstyle.SizeIcon { + if n.Kind == kindButton && options.Hint == "" && n.ButtonSize >= controlstyle.SizeIcon { options.Hint = n.Label } + if n.Kind == kindToggle { + if n.Flags&flagChecked != 0 { + options.Checked, options.Selected = true, true + } + options.Invalid = options.Invalid || n.Flags&FlagInvalid != 0 + } } // Disabled on the element is the control's own: a Base that was told it is // unavailable says so to assistive technology and leaves the Tab order, @@ -154,12 +173,12 @@ func (f *Frame) PaintChild(i int32) { } n.Color = color - disableContents := n.Kind == kindButton && n.Flags&flagChildren != 0 && f.Disabled(n) + disableContents := (n.Kind == kindButton || n.Kind == kindBadge || n.Kind == kindToggle || n.Kind == kindSelect) && n.Flags&flagChildren != 0 && f.Disabled(n) var contentsMark gfx.Mark if disableContents { contentsMark = canvas.Mark() } - clipContents := n.Kind == kindButton && n.Flags&flagChildren != 0 + clipContents := (n.Kind == kindButton || n.Kind == kindBadge || n.Kind == kindToggle || n.Kind == kindSelect) && n.Flags&flagChildren != 0 if clipContents { canvas.Clip(f.ContentRect(n)) } diff --git a/base/recipe.go b/base/recipe.go index 2e6b592dc..e145ff656 100644 --- a/base/recipe.go +++ b/base/recipe.go @@ -56,6 +56,155 @@ func (f *Frame) applyRecipes() { } case kindButton: f.applyButtonRecipe(n) + case kindBadge: + theme := f.RecipeTheme(n, &f.scratch.theme) + height, padding, _, fontSize := style.BadgeGeometry(theme.Metrics) + if d := n.Size[AxisY]; d.Kind == dimPx { + height = d.Value + } + if n.FontSize > 0 { + fontSize = n.FontSize + } + if n.Flags&flagHasRadius == 0 { + n.Radius = f.badgeLook(n, theme, gfx.State{}).Radius + } + if n.PadSet&padRight == 0 { + n.Pad[1] = padding + } + if n.PadSet&padLeft == 0 { + n.Pad[3] = padding + } + if n.Flags&flagChildren != 0 { + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + f.buttonTextDefaults(n, fontSize, weight, n.LineH) + } + if n.Size[AxisY].Kind == dimAuto && n.MinS[AxisY] == 0 { + n.MinS[AxisY] = height + } + case kindToggle: + theme := f.RecipeTheme(n, &f.scratch.theme) + height, padding, fontSize := style.ToggleGeometry(theme.Metrics, n.ButtonSize) + if n.FontSize > 0 { + fontSize = n.FontSize + } + if n.Flags&flagHasRadius == 0 { + n.Radius = f.toggleLook(n, theme, gfx.State{}).Radius + } + if n.PadSet&padRight == 0 { + n.Pad[1] = padding + } + if n.PadSet&padLeft == 0 { + n.Pad[3] = padding + } + if n.Flags&flagChildren != 0 { + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + f.buttonTextDefaults(n, fontSize, weight, n.LineH) + } + // shadcn's min-w: a toggle is at least as wide as it is tall. + if n.Size[AxisX].Kind == dimAuto && n.MinS[AxisX] == 0 { + n.MinS[AxisX] = height + } + if n.Size[AxisY].Kind == dimAuto && n.MinS[AxisY] == 0 { + n.MinS[AxisY] = height + } + case kindTabs: + theme := f.RecipeTheme(n, &f.scratch.theme) + listHeight, listPadding, _, _, lineGap, _, _ := style.TabsGeometry(theme.Metrics) + t := &WidgetsOf(f).tabs[n.Aux] + gap := float32(0) + if t.line { + gap = lineGap + } + if n.Gap != 0 { + gap = n.Gap + } + n.Gap = gap + if n.PadSet&padTop == 0 { + n.Pad[0] = listPadding + } + if n.PadSet&padRight == 0 { + n.Pad[1] = listPadding + } + if n.PadSet&padBottom == 0 { + n.Pad[2] = listPadding + } + if n.PadSet&padLeft == 0 { + n.Pad[3] = listPadding + } + if n.Flags&flagHasRadius == 0 { + n.Radius = f.tabsLook(n, theme).Radius + } + if n.Size[AxisY].Kind == dimAuto && n.MinS[AxisY] == 0 { + n.MinS[AxisY] = listHeight + } + case kindSelect: + theme := f.RecipeTheme(n, &f.scratch.theme) + d := &WidgetsOf(f).selects[n.Aux] + placeholder := d.selected < 0 || d.selected >= len(d.labels) + surface := style.TextEntryLook{} + if SelectLookFn != nil { + surface, _, _ = SelectLookFn(f, n, theme, gfx.State{}, placeholder) + } + if n.Flags&flagHasRadius == 0 { + n.Radius = surface.Radius + } + if n.Flags&flagSetBorder == 0 { + n.BorderWidth = surface.BorderWidth + } + height, _ := style.SelectGeometry(theme.Metrics, n.ButtonSize) + if d := n.Size[AxisY]; d.Kind == dimPx { + height = d.Value + } + if n.Size[AxisY].Kind == dimAuto && n.MinS[AxisY] == 0 { + n.MinS[AxisY] = height + } + if n.Flags&flagChildren != 0 { + _, textSize := style.SelectGeometry(theme.Metrics, n.ButtonSize) + if n.FontSize > 0 { + textSize = n.FontSize + } + weight := gfx.WeightRegular + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + f.buttonTextDefaults(n, textSize, weight, n.LineH) + } + case kindCheckbox: + theme := f.RecipeTheme(n, &f.scratch.theme) + look := style.CheckboxLook{} + if CheckboxLookFn != nil { + look = CheckboxLookFn(f, n, theme, gfx.State{}) + } + if n.Flags&flagHasRadius == 0 { + n.Radius = look.Radius + } + if n.Flags&flagSetBorder == 0 { + n.BorderWidth = 1 + } + case kindSwitch: + theme := f.RecipeTheme(n, &f.scratch.theme) + _, height := SwitchExtent(*theme, n.Flags&flagSmall != 0) + if d := n.Size[AxisY]; d.Kind == dimPx { + height = d.Value + } + if n.Flags&flagHasRadius == 0 { + n.Radius = height / 2 + } + if n.Flags&flagSetBorder == 0 { + bordered := n.Flags&FlagInvalid != 0 + if c := f.Surface; c != nil && !n.ID.IsZero() { + bordered = bordered || c.FocusVisible() == n.ID + } + if bordered { + n.BorderWidth = 1 + } + } } } } @@ -131,6 +280,178 @@ func (f *Frame) themedDefaults(n *Node, Extra *Extra, s *resolved) { case kindButton: f.themedButtonDefaults(n, Extra, s) return + case kindBadge, kindToggle: + // A badge and a toggle are dressed by one ButtonLook the same way; the + // toggle's state also carries its pressed and invalid marks. + theme := f.RecipeTheme(n, &f.scratch.theme) + if c := f.Surface; c != nil && !n.ID.IsZero() { + state.Hovered = c.Hovered() == n.ID + state.Pressed = c.Pressed() == n.ID + state.FocusVisible = c.FocusVisible() == n.ID + } + if n.Kind == kindToggle { + state.Invalid = n.Flags&FlagInvalid != 0 + state.Checked = n.Flags&flagChecked != 0 + } + state.Disabled = f.Disabled(n) + var look style.ButtonLook + if n.Kind == kindBadge { + look = f.badgeLook(n, theme, state) + } else { + look = f.toggleLook(n, theme, state) + } + if n.Flags&flagSetBackground == 0 { + s.Background = gfx.Color{} + if look.Filled { + s.Background = look.Background + } + } + bordered := look.Bordered && look.Filled + if bordered && theme.Background.Alpha >= 1 { + if n.Flags&flagSetBackground == 0 { + s.Background = s.Background.Over(theme.Background) + } + look.Border = look.Border.Over(theme.Background) + } + if n.Flags&flagSetBorder == 0 { + s.border = look.Border + if bordered { + s.borderWidth = 1 + s.splitBorder = theme.Background.Alpha < 1 + } + } + if n.Flags&flagSetShadow == 0 { + s.shadow = look.Shadow + } + if Extra.ringWidth <= 0 && look.RingWidth > 0 { + s.ring, s.ringWidth = look.Ring, look.RingWidth + s.ringFilled, s.ringLine = !look.RingOutline, 0 + if look.RingOutline { + s.ringLine = 2 + } + } + if n.Flags&flagHasColor == 0 { + s.Color = look.Foreground + } + return + case kindTabs: + theme := f.RecipeTheme(n, &f.scratch.theme) + look := f.tabsLook(n, theme) + if n.Flags&flagSetBackground == 0 { + s.Background = gfx.Color{} + if look.Filled { + s.Background = look.Background + } + } + if n.Flags&flagSetBorder == 0 && look.Bordered { + s.border = look.Border + s.borderWidth = 1 + s.splitBorder = theme.Background.Alpha < 1 + } + if n.Flags&flagSetShadow == 0 { + s.shadow = look.Shadow + } + return + case kindSelect: + theme := f.RecipeTheme(n, &f.scratch.theme) + d := &WidgetsOf(f).selects[n.Aux] + placeholder := d.selected < 0 || d.selected >= len(d.labels) + if c := f.Surface; c != nil { + id := d.TriggerID(len(d.labels)) + state.Hovered = !id.IsZero() && c.Hovered() == id + state.Pressed = !id.IsZero() && c.Pressed() == id + state.Focused = !id.IsZero() && c.FocusVisible() == id + } + state.Invalid = n.Flags&FlagInvalid != 0 + state.Disabled = f.Disabled(n) + surface, foreground, chevron := style.TextEntryLook{}, gfx.Color{}, gfx.Color{} + if SelectLookFn != nil { + surface, foreground, chevron = SelectLookFn(f, n, theme, state, placeholder) + } + f.selectForeground, f.selectChevron = foreground, chevron + if n.Flags&flagSetBackground == 0 { + s.Background = surface.Fill + } + if n.Flags&flagSetBorder == 0 { + s.border = surface.Border + s.borderWidth = surface.BorderWidth + s.splitBorder = theme.Background.Alpha < 1 + } + if n.Flags&flagSetShadow == 0 { + s.shadow = surface.Shadow + } + if n.Flags&flagHasColor == 0 { + s.Color = foreground + } + return + case kindCheckbox: + theme := f.RecipeTheme(n, &f.scratch.theme) + state := gfx.State{Checked: n.Flags&flagChecked != 0, Mixed: n.Flags&flagMixed != 0, Invalid: n.Flags&FlagInvalid != 0} + if c := f.Surface; c != nil && !n.ID.IsZero() { + state.Hovered = c.Hovered() == n.ID + state.Pressed = c.Pressed() == n.ID + state.FocusVisible = c.FocusVisible() == n.ID + } + state.Disabled = f.Disabled(n) + look := style.CheckboxLook{} + if CheckboxLookFn != nil { + look = CheckboxLookFn(f, n, theme, state) + } + f.checkboxPainted = look + if n.Flags&flagSetBackground == 0 { + s.Background = look.Fill + } + if n.Flags&flagSetBorder == 0 { + s.border = look.Border + s.borderWidth = 1 + } + if n.Flags&flagSetShadow == 0 { + s.shadow = look.Shadow + } + if Extra.ringWidth <= 0 && look.RingWidth > 0 { + s.ring, s.ringWidth = look.Ring, look.RingWidth + s.ringFilled = true + } + return + case kindSwitch: + theme := f.RecipeTheme(n, &f.scratch.theme) + state := gfx.State{Checked: n.Flags&flagChecked != 0, Invalid: n.Flags&FlagInvalid != 0} + if c := f.Surface; c != nil && !n.ID.IsZero() { + state.Hovered = c.Hovered() == n.ID + state.Pressed = c.Pressed() == n.ID + state.FocusVisible = c.FocusVisible() == n.ID + } + state.Disabled = f.Disabled(n) + progress := float32(0) + if state.Checked { + progress = 1 + } + if c := f.Surface; c != nil && !n.ID.IsZero() { + progress = c.Animate(n.ID, SwitchCheckedSlot, progress, theme.Transition) + } + bordered := state.FocusVisible || state.Invalid + look := style.SwitchLook{} + if own := f.Exts[n.Ext].GetSwitchRecipe(); own != nil { + look = own(*theme, state, progress) + } else if SwitchLookFn != nil { + look = SwitchLookFn(f, n, theme, state, progress) + } + f.switchPainted = look + if n.Flags&flagSetBackground == 0 { + s.Background = look.Track + } + if n.Flags&flagSetBorder == 0 && bordered { + s.border = look.Border + s.borderWidth = 1 + } + if n.Flags&flagSetShadow == 0 { + s.shadow = look.Shadow + } + if Extra.ringWidth <= 0 && look.RingWidth > 0 { + s.ring, s.ringWidth = look.Ring, look.RingWidth + s.ringFilled = true + } + return case kindInput: snapshot := &WidgetsOf(f).inputs[n.Aux] state = gfx.State{Focused: snapshot.Focused || f.Focused(n), Invalid: snapshot.Invalid, Disabled: snapshot.Disabled} @@ -163,9 +484,15 @@ func (f *Frame) Focused(n *Node) bool { // control's edge, not taken out of the area the text is centered in. func (f *Frame) ContentRect(n *Node) Rect { r := n.Rect - if n.Flags&flagThemed != 0 && n.Flags&flagSetPad == 0 && (n.Kind == kindInput || n.Kind == kindTextarea) { - x, y := textEntryInsets(f.RecipeTheme(n, &f.scratch.theme), n.Kind) - return Rect{X: r.X + x, Y: r.Y + y, Width: max(r.Width-2*x, 0), Height: max(r.Height-2*y, 0)} + if n.Flags&flagThemed != 0 && n.Flags&flagSetPad == 0 { + switch n.Kind { + case kindInput, kindTextarea: + x, y := textEntryInsets(f.RecipeTheme(n, &f.scratch.theme), n.Kind) + return Rect{X: r.X + x, Y: r.Y + y, Width: max(r.Width-2*x, 0), Height: max(r.Height-2*y, 0)} + case kindSelect: + left, right := style.SelectContentInsets(f.RecipeTheme(n, &f.scratch.theme).Metrics) + return Rect{X: r.X + left, Y: r.Y, Width: max(r.Width-left-right, 0), Height: r.Height} + } } left, right := n.Inset(AxisX) top, bottom := n.Inset(AxisY) diff --git a/base/scroll.go b/base/scroll.go index 57991db81..c5dcfbc8a 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -384,6 +384,7 @@ func (f *Frame) ScrollArea(ID gfx.ID) Box { // scrolls up, and again once they scroll back down to it: a log, a chat. It starts at // the end. Follow(false), the default, leaves the offset to the user and to ScrollTo. func (b Box) Follow(on bool) Box { + b.N().markAttr(attrScroll) if n := b.N(); n.Ext != 0 { if s := b.f.Exts[n.Ext].scrollState; s != nil { s.Follow(on) @@ -403,6 +404,7 @@ func (b Box) Follow(on bool) Box { // wheel with Shift held; ScrollState().OffsetX says how far it is scrolled. It has no // effect on a box that is not a ScrollArea. func (b Box) Sideways() Box { + b.N().markAttr(attrScroll) if s := b.areaState(); s != nil { s.sideways = true } @@ -418,6 +420,7 @@ func (b Box) Sideways() Box { // the pointer leaves and then fade. A view drawn without a Page has no pointer, and // keeps them revealed. func (b Box) Scrollbars() Box { + b.N().markAttr(attrScroll) if s := b.areaState(); s != nil { s.bars = true b.f.paintBarsFn = (*Frame).paintScrollbars @@ -429,6 +432,7 @@ func (b Box) Scrollbars() Box { // area, as a gutter a list keeps while its content overflows, instead of revealing // them on hover. It implies Scrollbars; give ScrollbarSize to set their thickness. func (b Box) AlwaysScrollbars() Box { + b.N().markAttr(attrScroll) if s := b.areaState(); s != nil { s.bars, s.barsAlways = true, true b.f.paintBarsFn = (*Frame).paintScrollbars @@ -441,6 +445,7 @@ func (b Box) AlwaysScrollbars() Box { // under its name. Zero keeps the derived name. Like Scrollbars, it has no effect on // a box that is not a ScrollArea. func (b Box) ScrollbarIDs(vertical, horizontal gfx.ID) Box { + b.N().markAttr(attrScroll) if s := b.areaState(); s != nil { s.verticalID, s.horizontalID = vertical, horizontal } @@ -452,6 +457,7 @@ func (b Box) ScrollbarIDs(vertical, horizontal gfx.ID) Box { // given another name. Like Scrollbars, it has no effect on a box that is not a // ScrollArea. func (b Box) ScrollbarLabels(vertical, horizontal string) Box { + b.N().markAttr(attrScroll) if s := b.areaState(); s != nil { s.verticalLabel, s.horizontalLabel = vertical, horizontal } @@ -462,6 +468,7 @@ func (b Box) ScrollbarLabels(vertical, horizontal string) Box { // bar's width or a horizontal bar's height. Zero keeps the thin hover default. // Like Scrollbars, it has no effect on a box that is not a ScrollArea. func (b Box) ScrollbarSize(Size float32) Box { + b.N().markAttr(attrScroll) if s := b.areaState(); s != nil { s.barSize = Size } @@ -473,6 +480,7 @@ func (b Box) ScrollbarSize(Size float32) Box { // percentage, a row's name, or what the bar means. Empty keeps the default, which // has no value. Like Scrollbars, it has no effect on a box that is not a ScrollArea. func (b Box) ScrollbarValues(vertical, horizontal string) Box { + b.N().markAttr(attrScroll) if s := b.areaState(); s != nil { s.verticalValue, s.horizontalValue = vertical, horizontal } diff --git a/base/select.go b/base/select.go index f7602c571..9e5744000 100644 --- a/base/select.go +++ b/base/select.go @@ -6,6 +6,7 @@ import ( "unicode/utf8" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) // clock is the time type-ahead measures its pause by; tests replace it. @@ -399,7 +400,11 @@ const ( // slice is kept until End. func (f *Frame) Select(scope gfx.Scope, state *SelectState, labels []string, selected int) Box { b := f.SelectBase(scope, state, labels, selected) - f.Nodes[b.i].Flags |= flagThemed + n := &f.Nodes[b.i] + n.Flags |= flagThemed + // The trigger's value (or the caller's Children) is a start-aligned row with + // the gap an icon keeps from its label. + n.Dir, n.Items, n.Justify, n.Gap = row, Center, Start, style.ButtonIconGap return b } diff --git a/base/select_node_test.go b/base/select_node_test.go new file mode 100644 index 000000000..0ac70ad1b --- /dev/null +++ b/base/select_node_test.go @@ -0,0 +1,172 @@ +package base_test + +import ( + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +type selectProbe struct { + box Rect + rects []gfx.Rectangle + texts []gfx.Text + hits []gfx.Hit +} + +func probeSelect(t *testing.T, interaction func(*gfx.Canvas), declare func(f *Frame) Box) selectProbe { + t.Helper() + canvas := testCanvas() + if interaction != nil { + interaction(canvas) + } + var view View + var box Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { + f.Column().Pad(10).Children(func() { box = declare(f) }) + }) + return selectProbe{box: box.Rect(), rects: canvas.Rectangles(), texts: canvas.Texts(), hits: canvas.Hits()} +} + +func selectValue(t *testing.T, p selectProbe) gfx.Text { + t.Helper() + if len(p.texts) == 0 { + t.Fatalf("no value painted") + } + return p.texts[0] +} + +// A Select trigger with no calls of its own is the theme's text-entry surface: +// the chosen value, the arrow, and one combobox hit named by the trigger. +func TestSelectDefaultsAreTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + look := components.SelectRecipe(theme, gfx.State{}, false) + var state SelectState + p := probeSelect(t, nil, func(f *Frame) Box { + return f.Select(selScope, &state, selLabels, 1).Label("Size").Placeholder("Size").Width(200) + }) + if p.box.Width != 200 { + t.Errorf("trigger width = %v, want 200", p.box.Width) + } + if len(p.hits) != 1 || p.hits[0].Role != gfx.RoleCombobox || p.hits[0].Label != "Size" || p.hits[0].Value != selLabels[1] { + t.Fatalf("hit = %+v, want one combobox named Size with the chosen value", p.hits) + } + value := selectValue(t, p) + if value.Value != selLabels[1] || value.Style.Size != theme.Metrics.FontSizeM { + t.Errorf("value = %+v, want %q at the body size", value, selLabels[1]) + } + if value.Style.Color != look.Foreground { + t.Errorf("value color = %v, want %v", value.Style.Color, look.Foreground) + } + found := false + for _, rect := range p.rects { + if rect.Bounds == p.box { + found = true + if rect.Radius != look.Surface.Radius { + t.Errorf("trigger radius = %v, want %v", rect.Radius, look.Surface.Radius) + } + } + } + if !found { + t.Errorf("no trigger surface for %v: %+v", p.box, p.rects) + } +} + +// The calls every element takes reach the trigger: FontSize and Weight the +// value, Color its ink, Pad the content, Height the trigger, Radius its corners, +// Background its fill. +func TestSelectPropertiesReachTheTrigger(t *testing.T) { + ink := gfx.Color{Red: 1, Alpha: 1} + fill := gfx.Color{Blue: 1, Alpha: 1} + var state SelectState + p := probeSelect(t, nil, func(f *Frame) Box { + return f.Select(selScope, &state, selLabels, 0).Label("Size").Width(200).Height(48). + FontSize(18).Weight(gfx.WeightBold).Color(ink).Radius(5).Background(fill) + }) + if p.box.Height != 48 { + t.Errorf("trigger height = %v, want 48", p.box.Height) + } + value := selectValue(t, p) + if value.Style.Size != 18 || value.Style.Weight != gfx.WeightBold || value.Style.Color != ink { + t.Errorf("value style = %+v, want 18, bold, red", value.Style) + } + found, radius := false, float32(0) + for _, rect := range p.rects { + if rect.Color == fill { + found = true + } + if rect.Bounds == p.box && rect.Radius > radius { + radius = rect.Radius + } + } + if found && radius != 5 { + t.Errorf("trigger radius = %v, want 5", radius) + } + if !found { + t.Errorf("no trigger fill %v for %v: %+v", fill, p.box, p.rects) + } +} + +// A focused or invalid trigger draws the recipe's ring and line, and hover +// lightens the fill, exactly as the component does. +func TestSelectStatesFollowTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + var state SelectState + trigger := selScope.At(len(selLabels)) + focused := probeSelect(t, func(c *gfx.Canvas) { c.SetInteraction(gfx.ID{}, gfx.ID{}, trigger, true) }, + func(f *Frame) Box { return f.Select(selScope, &state, selLabels, 0).Label("Size").Width(200) }) + focusLook := components.SelectRecipe(theme, gfx.State{Focused: true}, false) + ring := false + for _, rect := range focused.rects { + ring = ring || rect.Color == focusLook.Surface.Border + } + if !ring { + t.Errorf("focused select paints no focus line %v: %+v", focusLook.Surface.Border, focused.rects) + } + invalid := probeSelect(t, nil, func(f *Frame) Box { + return f.Select(selScope, &state, selLabels, 0).Label("Size").Width(200).Invalid(true) + }) + invalidLook := components.SelectRecipe(theme, gfx.State{Invalid: true}, false) + danger := false + for _, rect := range invalid.rects { + danger = danger || rect.Color == invalidLook.Surface.Border + } + if !danger { + t.Errorf("invalid select paints no dangerous line: %+v", invalid.rects) + } + if len(invalid.hits) != 1 || !invalid.hits[0].Invalid { + t.Errorf("invalid select hit = %+v, want Invalid", invalid.hits) + } +} + +// Children replace the value and icon while the arrow and the trigger's hit +// stay the control's; a disabled select's content is inert. +func TestSelectChildrenReplaceTheValue(t *testing.T) { + var state SelectState + p := probeSelect(t, nil, func(f *Frame) Box { + return f.Select(selScope, &state, selLabels, 0).Label("Size").Width(200).Children(func() { + f.Text("own") + }) + }) + for _, text := range p.texts { + if text.Value == selLabels[0] { + t.Errorf("the value was painted over the children: %+v", p.texts) + } + } + if len(p.hits) != 1 || p.hits[0].Role != gfx.RoleCombobox { + t.Errorf("hits = %+v, want the trigger's one combobox", p.hits) + } + + var disabled SelectState + d := probeSelect(t, nil, func(f *Frame) Box { + return f.Select(selScope, &disabled, selLabels, 0).Label("Size").Width(200).Disabled(true).Children(func() { + f.Button(gfx.Item(9), "inner") + }) + }) + for _, hit := range d.hits { + if !hit.Disabled || hit.Focusable { + t.Errorf("hit %+v is not inert under the disabled select", hit) + } + } +} diff --git a/base/splitter.go b/base/splitter.go index 80606b27c..66273f87a 100644 --- a/base/splitter.go +++ b/base/splitter.go @@ -258,7 +258,8 @@ func (f *Frame) PaintSplitter(n *Node) { row := f.splitsRow(n) r := n.Rect - if event, ok := canvas.PointerOn(n.ID); ok { + disabled := f.Disabled(n) + if event, ok := canvas.PointerOn(n.ID); ok && !disabled { pointer := event.X if !row { pointer = event.Y @@ -279,8 +280,8 @@ func (f *Frame) PaintSplitter(n *Node) { } theme := f.Palette - pressed := canvas.Pressed() == n.ID - hovered := canvas.Hovered() == n.ID + pressed := !disabled && canvas.Pressed() == n.ID + hovered := !disabled && canvas.Hovered() == n.ID line, thickness := theme.Border, float32(1) switch { case pressed: @@ -288,6 +289,9 @@ func (f *Frame) PaintSplitter(n *Node) { case hovered: line, thickness = theme.Ring, 3 } + if disabled { + line.Alpha *= 0.50 + } var bar Rect cursor := gfx.PointerCursorResizeVertical if row { @@ -296,7 +300,7 @@ func (f *Frame) PaintSplitter(n *Node) { } else { bar = Rect{X: r.X, Y: r.Y + (r.Height-thickness)/2, Width: r.Width, Height: thickness} } - if canvas.FocusVisible() == n.ID { + if !disabled && canvas.FocusVisible() == n.ID { ring := theme.Ring ring.Alpha *= 0.5 canvas.Rounded(Rect{X: bar.X - 1, Y: bar.Y - 1, Width: bar.Width + 2, Height: bar.Height + 2}, 2, ring) @@ -332,5 +336,9 @@ func (f *Frame) PaintSplitter(n *Node) { if options.Cursor == 0 { options.Cursor = cursor } + if disabled { + options.Disabled = true + options.Cursor = 0 + } canvas.HitWithOptions(n.ID, hit, label, options) } diff --git a/base/style_look_identity_dev_test.go b/base/style_look_identity_dev_test.go new file mode 100644 index 000000000..10e456587 --- /dev/null +++ b/base/style_look_identity_dev_test.go @@ -0,0 +1,28 @@ +//go:build dev || vivadev + +package base + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A look on an element with no identity changes nothing in release builds; the +// dev build says so when the page is declared, since no state can ever report. +func TestAnElementWithoutIdentityIgnoresItsLooks(t *testing.T) { + defer func() { + recovered := recover() + if recovered == nil { + t.Fatal("a look on an element without an identity did not report in the dev build") + } + if message, _ := recovered.(string); !strings.Contains(message, "Hover/Pressed/Focus") || !strings.Contains(message, "Row") { + t.Fatalf("unhelpful diagnostic: %v", recovered) + } + }() + var view View + view.Draw(styleCanvas(gfx.ID{}, gfx.ID{}, gfx.ID{}, false), gfx.LightTheme(), gfx.Rect{Width: 100, Height: 100}, func(f *Frame) { + f.Row().Size(50, 50).Hover(Look{}.Background(colorHover)) + }) +} diff --git a/base/style_look_identity_release_test.go b/base/style_look_identity_release_test.go new file mode 100644 index 000000000..9e9f52ebd --- /dev/null +++ b/base/style_look_identity_release_test.go @@ -0,0 +1,26 @@ +//go:build !dev && !vivadev + +package base + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A look on an element with no identity changes nothing: no state can be +// reported for it, and release builds ignore the look instead of failing. +func TestAnElementWithoutIdentityIgnoresItsLooks(t *testing.T) { + canvas := styleCanvas(styleRow, styleRow, styleRow, true) + var view View + var box Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 100, Height: 100}, func(f *Frame) { + box = f.Row().Size(50, 50).Background(colorRest).Hover(Look{}.Background(colorHover)).Focus(Look{}.Ring(3, colorRing)) + }) + if got := fillOf(t, canvas, box); got != colorRest { + t.Errorf("fill is %+v, want the resting one", got) + } + if count, _, _ := ringTriangles(canvas); count != 0 { + t.Error("a ring was painted") + } +} diff --git a/base/style_test.go b/base/style_test.go index ea2f2d86b..cdc8cb121 100644 --- a/base/style_test.go +++ b/base/style_test.go @@ -99,21 +99,6 @@ func TestLooksApplyWhileTheirStateHolds(t *testing.T) { } } -func TestAnElementWithoutIdentityIgnoresItsLooks(t *testing.T) { - canvas := styleCanvas(styleRow, styleRow, styleRow, true) - var view View - var box Box - view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 100, Height: 100}, func(f *Frame) { - box = f.Row().Size(50, 50).Background(colorRest).Hover(Look{}.Background(colorHover)).Focus(Look{}.Ring(3, colorRing)) - }) - if got := fillOf(t, canvas, box); got != colorRest { - t.Errorf("fill is %+v, want the resting one", got) - } - if count, _, _ := ringTriangles(canvas); count != 0 { - t.Error("a ring was painted") - } -} - func TestStateFromMakesWhatIsInsideFollowTheContainer(t *testing.T) { text := gfx.Color{Red: 0.5, Alpha: 1} for _, hovered := range []bool{false, true} { diff --git a/base/styles.go b/base/styles.go index 5a3dabd82..1ec643fe8 100644 --- a/base/styles.go +++ b/base/styles.go @@ -23,6 +23,15 @@ import ( type Styles struct { // Button dresses Button, and the buttons a component paints. Button func(Palette gfx.Theme, Variant style.ButtonVariant, state gfx.State) style.ButtonLook + // Badge dresses Badge, and the badges a component paints. + Badge func(Palette gfx.Theme, Variant style.ButtonVariant, state gfx.State) style.ButtonLook + // Toggle dresses Toggle: its fill, line, focus ring and label for each state. + Toggle func(Palette gfx.Theme, Variant style.ButtonVariant, state gfx.State) style.ButtonLook + // Tabs dresses the strip behind a Tabs list: its fill and radius. Line is the + // line variant, which has no strip. + Tabs func(Palette gfx.Theme, Line bool) style.ButtonLook + // Select dresses a Select's trigger: its surface, value and chevron. + Select func(Palette gfx.Theme, state gfx.State, placeholder bool) (style.TextEntryLook, gfx.Color, gfx.Color) // Checkbox dresses Checkbox. Checkbox func(Palette gfx.Theme, state gfx.State) style.CheckboxLook // Switch dresses Switch, progress being how far the thumb has travelled. diff --git a/base/table_test.go b/base/table_test.go index 6e5c90d39..fd497ca8d 100644 --- a/base/table_test.go +++ b/base/table_test.go @@ -23,7 +23,18 @@ var ( func sameCanvas(t *testing.T, Name string, flexed, direct *gfx.Canvas) { t.Helper() - if a, b := flexed.Rectangles(), direct.Rectangles(); len(a) != len(b) { + // A fully transparent rectangle is a paint record, not a pixel: the engine + // skips one where a component records it (a line strip's empty fill, say). + visible := func(in []gfx.Rectangle) []gfx.Rectangle { + out := make([]gfx.Rectangle, 0, len(in)) + for _, rect := range in { + if rect.Color.Alpha > 0 { + out = append(out, rect) + } + } + return out + } + if a, b := visible(flexed.Rectangles()), visible(direct.Rectangles()); len(a) != len(b) { t.Fatalf("%s: ui painted %d rectangles, the component %d", Name, len(a), len(b)) } else { for i := range a { diff --git a/base/tabs.go b/base/tabs.go index 73ac94d78..0d8bdd9e7 100644 --- a/base/tabs.go +++ b/base/tabs.go @@ -2,6 +2,7 @@ package base import ( "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) type TabsDecl struct { @@ -35,6 +36,7 @@ const ( func (f *Frame) Tabs(scope gfx.Scope, labels []string, selected int) Box { b := f.Box(kindTabs) n := &f.Nodes[b.i] + n.Flags |= flagThemed n.Aux = int32(len(WidgetsOf(f).tabs)) WidgetsOf(f).tabs = append(WidgetsOf(f).tabs, TabsDecl{scope: scope, labels: labels, selected: selected}) return b @@ -98,36 +100,47 @@ func (b Box) TabClicked() (int, bool) { func (f *Frame) measureTabs(n *Node) { t := &WidgetsOf(f).tabs[n.Aux] + listHeight, listPadding, triggerHeight, triggerPad, lineGap, fontSize, weight := style.TabsGeometry(f.Palette.Metrics) + if n.FontSize > 0 { + fontSize = n.FontSize + } + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + if n.Pad[0] != 0 || n.PadSet&padTop != 0 { + listPadding = n.Pad[0] + } var widest float32 for index, label := range t.labels { - width := f.Surface.TextWidthWeight(label, f.Palette.Metrics.FontSizeM, gfx.WeightMedium) + width := f.Surface.TextWidthWeight(label, fontSize, weight) if t.icon != nil { icon := t.icon(index) if len(icon.Commands) > 0 || len(icon.Layers) > 0 { if t.iconOnly { - // The label is the tab's accessible name, not its face. - width = f.Palette.Metrics.FontSizeM + width = fontSize } else { - width += f.Palette.Metrics.FontSizeM + 6 + width += fontSize + 6 } } } widest = max(widest, width) } count := float32(len(t.labels)) - var gap float32 - if t.line { - gap = 4 + gap := float32(0) + if n.Gap != 0 { + gap = n.Gap + } else if t.line { + gap = lineGap } between := gap * max(count-1, 0) switch { case t.vertical && t.line: - n.Pref = [2]float32{widest + 16 + TabIndicator + 1, tabHeight*count + between} + n.Pref = [2]float32{widest + 2*triggerPad + 2*listPadding - 8 + TabIndicator + 1, triggerHeight*count + between} case t.vertical: - n.Pref = [2]float32{widest + 16, tabHeight*count + between} + n.Pref = [2]float32{widest + 2*triggerPad + 2*listPadding - 8, triggerHeight*count + between} case t.line: - n.Pref = [2]float32{(widest+24)*count + between, tabHeight + TabIndicator} + n.Pref = [2]float32{(widest+2*triggerPad+2*listPadding)*count + between, listHeight + TabIndicator} default: - n.Pref = [2]float32{(widest + 24) * count, tabHeight} + n.Pref = [2]float32{(widest+2*triggerPad+2*listPadding)*count + between, listHeight} } } diff --git a/base/tabs_node_test.go b/base/tabs_node_test.go new file mode 100644 index 000000000..e84893120 --- /dev/null +++ b/base/tabs_node_test.go @@ -0,0 +1,120 @@ +package base_test + +import ( + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +type tabsProbe struct { + box Rect + rects []gfx.Rectangle + texts []gfx.Text + hits []gfx.Hit +} + +func probeTabs(t *testing.T, declare func(f *Frame) Box) tabsProbe { + t.Helper() + canvas := testCanvas() + var view View + var box Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 160}, func(f *Frame) { + f.Column().Children(func() { box = declare(f) }) + }) + return tabsProbe{box: box.Rect(), rects: canvas.Rectangles(), texts: canvas.Texts(), hits: canvas.Hits()} +} + +var tabsNodeLabels = tabLabels + +// A Tabs strip with no calls of its own is the theme's: the muted strip behind +// the triggers, one tab role per label, the selected one filled. +func TestTabsDefaultsAreTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + p := probeTabs(t, func(f *Frame) Box { return f.Tabs(tabsScope, tabsNodeLabels, 1) }) + if len(p.hits) != len(tabsNodeLabels) { + t.Fatalf("hits = %d, want one tab per label", len(p.hits)) + } + for index, hit := range p.hits { + if hit.Role != gfx.RoleTab || hit.Label != tabsNodeLabels[index] { + t.Errorf("hit %d = %+v, want a tab named %q", index, hit, tabsNodeLabels[index]) + } + if hit.Selected != (index == 1) { + t.Errorf("hit %d selected=%v, want %v", index, hit.Selected, index == 1) + } + } + list := gfx.Rectangle{} + found := false + for _, rect := range p.rects { + if rect.Bounds == p.box { + list, found = rect, true + } + } + if !found { + t.Fatalf("no strip rectangle for %v: %+v", p.box, p.rects) + } + look := components.TabsListRecipe(theme, components.TabsDefault) + if list.Color != look.Background || list.Radius != look.Radius { + t.Errorf("strip = %v radius %v, want %v radius %v", list.Color, list.Radius, look.Background, look.Radius) + } +} + +// The calls every element takes reach the strip and its triggers: Pad insets the +// triggers, Gap separates line triggers, FontSize and Weight style the labels, +// Color their ink, Radius the strip, Background its fill, Height its height. +func TestTabsPropertiesReachTheStrip(t *testing.T) { + theme := gfx.LightTheme() + ink := gfx.Color{Red: 1, Alpha: 1} + fill := gfx.Color{Blue: 1, Alpha: 1} + _, defPadding, _, _, _, _, _ := style.TabsGeometry(theme.Metrics) + p := probeTabs(t, func(f *Frame) Box { + return f.Tabs(tabsScope, tabsNodeLabels, 0).FontSize(18).Weight(gfx.WeightBold).Color(ink). + Pad(7).Radius(4).Background(fill).Height(44) + }) + if p.box.Height != 44 { + t.Errorf("strip height = %v, want 44", p.box.Height) + } + if len(p.texts) != len(tabsNodeLabels) { + t.Fatalf("texts = %d, want one per label", len(p.texts)) + } + dimmed := ink + dimmed.Alpha *= 0.60 + for index, text := range p.texts { + if text.Style.Size != 18 || text.Style.Weight != gfx.WeightBold { + t.Errorf("label %d style = %+v, want 18, bold", index, text.Style) + } + want := dimmed + if index == 0 { + want = ink // the selected tab keeps the ink whole + } + if text.Style.Color != want { + t.Errorf("label %d color = %v, want %v", index, text.Style.Color, want) + } + } + list := gfx.Rectangle{} + for _, rect := range p.rects { + if rect.Bounds == p.box { + list = rect + } + } + if list.Color != fill || list.Radius != 4 { + t.Errorf("strip = %v radius %v, want %v radius 4", list.Color, list.Radius, fill) + } + // Pad 7 puts the first trigger's left edge seven pixels inside the strip. + first := p.hits[0].Bounds + if first.X != p.box.X+7 { + t.Errorf("first trigger x = %v, want the strip's x+7 = %v (default padding %v)", first.X, p.box.X+7, defPadding) + } + + line := probeTabs(t, func(f *Frame) Box { + return f.Tabs(tabsScope, tabsNodeLabels, 0).Line().Gap(10) + }) + if len(line.hits) < 2 { + t.Fatalf("line strip hits = %d", len(line.hits)) + } + if gap := line.hits[1].Bounds.X - (line.hits[0].Bounds.X + line.hits[0].Bounds.Width); gap < 9.99 || gap > 10.01 { + t.Errorf("line trigger gap = %v, want the explicit 10", gap) + } +} diff --git a/base/text_entry_node_test.go b/base/text_entry_node_test.go new file mode 100644 index 000000000..c25d968c4 --- /dev/null +++ b/base/text_entry_node_test.go @@ -0,0 +1,146 @@ +package base_test + +import ( + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +type fieldProbe struct { + box Rect + rects []gfx.Rectangle + texts []gfx.Text + hits []gfx.Hit +} + +func probeField(t *testing.T, declare func(f *Frame) Box) fieldProbe { + t.Helper() + canvas := testCanvas() + var view View + var box Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 240}, func(f *Frame) { + f.Column().Pad(6).Children(func() { box = declare(f) }) + }) + return fieldProbe{box: box.Rect(), rects: canvas.Rectangles(), texts: canvas.Texts(), hits: canvas.Hits()} +} + +// A themed Input is the text-entry recipe's control: the fill and line of the +// recipe, the value at the element's text style, and no width of its own. +func TestInputDefaultsAreTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + look := components.TextEntryRecipe(theme, gfx.State{}) + p := probeField(t, func(f *Frame) Box { + return f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name", Value: "Gopher"}).Width(200) + }) + if p.box.Height != theme.Metrics.ControlHeight { + t.Errorf("input height = %v, want the control height %v", p.box.Height, theme.Metrics.ControlHeight) + } + if len(p.texts) == 0 || p.texts[0].Value != "Gopher" { + t.Fatalf("texts = %+v, want the value", p.texts) + } + if p.texts[0].Style.Size != theme.Metrics.FontSizeM || p.texts[0].Style.Color != look.Fill.Over(theme.Background) && p.texts[0].Style.Color != theme.Foreground { + // The recipe's foreground is the page's; only the size is worth pinning here. + if p.texts[0].Style.Size != theme.Metrics.FontSizeM { + t.Errorf("value size = %v, want %v", p.texts[0].Style.Size, theme.Metrics.FontSizeM) + } + } + found := false + for _, rect := range p.rects { + if rect.Bounds == p.box { + found = true + if rect.Radius != look.Radius { + t.Errorf("input radius = %v, want %v", rect.Radius, look.Radius) + } + } + } + if !found { + t.Errorf("no input surface for %v: %+v", p.box, p.rects) + } +} + +// FontSize and Weight style the value; a larger size makes the field taller +// rather than clipping the text, and explicit Pad moves the text inside. +func TestInputTextStyleAndPaddingReachTheValue(t *testing.T) { + theme := gfx.LightTheme() + baseLine := probeField(t, func(f *Frame) Box { + return f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name", Value: "Gopher"}).Width(200) + }) + big := probeField(t, func(f *Frame) Box { + return f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name", Value: "Gopher"}). + Width(200).FontSize(30).Weight(gfx.WeightBold) + }) + if big.box.Height <= baseLine.box.Height { + t.Errorf("FontSize 30 input height = %v, want taller than %v", big.box.Height, baseLine.box.Height) + } + if len(big.texts) == 0 { + t.Fatal("the larger input painted no value") + } + if got := big.texts[0].Style; got.Size != 30 || got.Weight != gfx.WeightBold { + t.Errorf("value style = %+v, want size 30, bold", got) + } + + padded := probeField(t, func(f *Frame) Box { + return f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name", Value: "Gopher"}).Width(200).PadSides(9, 24, 9, 24) + }) + if len(padded.texts) == 0 { + t.Fatal("the padded input painted no value") + } + if padded.texts[0].Bounds.X < padded.box.X+24-0.01 { + t.Errorf("value x = %v, want at least %v (explicit left padding)", padded.texts[0].Bounds.X, padded.box.X+24) + } + _ = theme +} + +// A focused or invalid field draws the recipe's focus or danger line. +func TestInputStatesFollowTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + focused := probeField(t, func(f *Frame) Box { + return f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name", Value: "Gopher", Focused: true}).Width(200) + }) + want := components.TextEntryRecipe(theme, gfx.State{Focused: true}) + ok := false + for _, rect := range focused.rects { + ok = ok || rect.Color == want.Border.Over(theme.Background) + } + if !ok { + t.Errorf("focused input paints no focus line %v: %+v", want.Border, focused.rects) + } + invalid := probeField(t, func(f *Frame) Box { + return f.Input(InputSnapshot{ID: gfx.Item(1), Label: "Name", Value: "Gopher", Invalid: true}).Width(200) + }) + wantInvalid := components.TextEntryRecipe(theme, gfx.State{Invalid: true}) + danger := false + for _, rect := range invalid.rects { + danger = danger || rect.Color == wantInvalid.Border.Over(theme.Background) + } + if !danger { + t.Errorf("invalid input paints no dangerous line: %+v", invalid.rects) + } +} + +// A themed Textarea is at least 64 tall, grows with its text size, and its +// value takes the element's FontSize and Weight. +func TestTextareaTextStyleAndHeight(t *testing.T) { + theme := gfx.LightTheme() + p := probeField(t, func(f *Frame) Box { + return f.Textarea(TextareaSnapshot{ID: gfx.Item(2), Label: "Notes", Value: "line one"}).FontSize(24).Weight(gfx.WeightBold) + }) + if p.box.Height < 64 { + t.Errorf("textarea height = %v, want at least 64", p.box.Height) + } + if len(p.texts) == 0 { + t.Fatal("the textarea painted no row") + } + if got := p.texts[0].Style; got.Size != 24 || got.Weight != gfx.WeightBold { + t.Errorf("row style = %+v, want size 24, bold", got) + } + tall := probeField(t, func(f *Frame) Box { + return f.Textarea(TextareaSnapshot{ID: gfx.Item(2), Label: "Notes", Value: "line one"}).Height(140) + }) + if tall.box.Height != 140 { + t.Errorf("explicit textarea height = %v, want 140", tall.box.Height) + } + _ = theme +} diff --git a/base/textarea.go b/base/textarea.go index 72a9d910d..0c9bdfb5f 100644 --- a/base/textarea.go +++ b/base/textarea.go @@ -61,6 +61,10 @@ type TextareaSnapshot struct { // NoWrap keeps every line on one row, clipped at the edge of the box, as // `white-space: pre` does. The default wraps. NoWrap bool + // TextSize and TextWeight style the rows' text; zero keeps the theme's body + // size and the regular weight. A page's element passes its own FontSize and + // Weight here, so the rows, the caret and the native editor agree. + TextSize, TextWeight float32 // InsetTop reserves room above the editor for caller-owned controls. The // native text bounds and caret placement use the same inset as the paint. InsetTop float32 diff --git a/base/toggle_node_test.go b/base/toggle_node_test.go new file mode 100644 index 000000000..1ac9005a9 --- /dev/null +++ b/base/toggle_node_test.go @@ -0,0 +1,257 @@ +package base_test + +import ( + "reflect" + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +type toggleProbe struct { + box Rect + rects []gfx.Rectangle + texts []gfx.Text + hits []gfx.Hit +} + +func probeToggle(t *testing.T, state func(*gfx.Canvas), declare func(f *Frame) Box) toggleProbe { + t.Helper() + canvas := testCanvas() + if state != nil { + state(canvas) + } + var view View + var box Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 120}, func(f *Frame) { + f.Row().Items(Start).Children(func() { box = declare(f) }) + }) + return toggleProbe{box: box.Rect(), rects: canvas.Rectangles(), texts: canvas.Texts(), hits: canvas.Hits()} +} + +func toggleLabel(t *testing.T, p toggleProbe) gfx.Text { + t.Helper() + if len(p.texts) != 1 { + t.Fatalf("texts = %+v, want the one label", p.texts) + } + return p.texts[0] +} + +// A toggle with no calls of its own is the recipe's chip: no fill while off, +// the muted fill while on, the medium label in the foreground color, and one +// button hit that reports its pressed state. +func TestToggleDefaultsAreTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + _, _, fontSize := style.ToggleGeometry(theme.Metrics, style.SizeDefault) + for _, tc := range []struct { + name string + pressed bool + fill gfx.Color + }{ + {"off", false, gfx.Color{}}, + {"on", true, theme.Muted}, + } { + t.Run(tc.name, func(t *testing.T) { + p := probeToggle(t, nil, func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", tc.pressed) }) + if len(p.hits) != 1 || p.hits[0].Role != gfx.RoleButton || p.hits[0].Checked != tc.pressed || p.hits[0].Selected != tc.pressed { + t.Errorf("hits = %+v, want one button with checked=%v", p.hits, tc.pressed) + } + if p.hits[0].Bounds != p.box { + t.Errorf("hit %v is not the box %v", p.hits[0].Bounds, p.box) + } + label := toggleLabel(t, p) + if label.Style.Size != fontSize || label.Style.Weight != gfx.WeightMedium || label.Style.Color != theme.Foreground { + t.Errorf("label style = %+v, want size %v, medium, %v", label.Style, fontSize, theme.Foreground) + } + _ = tc.fill // checked by the recipe parity test; the engine paints the look + }) + } +} + +// The calls every element takes reach the toggle: FontSize, Weight and Color +// the label, Pad the room inside, Radius and Height the surface, and the size's +// min-w keeps the toggle at least as wide as it is tall. +func TestTogglePropertiesReachTheSurface(t *testing.T) { + ink := gfx.Color{Red: 1, Alpha: 1} + p := probeToggle(t, nil, func(f *Frame) Box { + return f.Toggle(gfx.Item(1), "Bold", true).FontSize(20).Weight(gfx.WeightBold).Color(ink).Height(40).Radius(3) + }) + if p.box.Height != 40 { + t.Errorf("toggle height = %v, want 40", p.box.Height) + } + label := toggleLabel(t, p) + if label.Style.Size != 20 || label.Style.Weight != gfx.WeightBold || label.Style.Color != ink { + t.Errorf("label style = %+v, want 20, bold, red", label.Style) + } + if len(p.rects) == 0 || p.rects[len(p.rects)-1].Radius != 3 { + t.Errorf("surface radius was not the explicit 3: %+v", p.rects) + } + // The size's min-w: a short label still fills a square. + _, padding, _ := style.ToggleGeometry(gfx.LightTheme().Metrics, style.SizeDefault) + short := probeToggle(t, nil, func(f *Frame) Box { return f.Toggle(gfx.Item(1), "x", false) }) + if short.box.Width < short.box.Height { + t.Errorf("toggle %v is narrower than it is tall", short.box) + } + _ = padding +} + +// Sizes: Small and Large move the height by the metrics' four pixels. +func TestToggleSizesChangeTheHeight(t *testing.T) { + theme := gfx.LightTheme() + for name, tc := range map[string]struct { + declare func(f *Frame) Box + want float32 + }{ + "small": {func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false).Small() }, theme.Metrics.ControlHeight - 4}, + "large": {func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false).Large() }, theme.Metrics.ControlHeight + 4}, + } { + p := probeToggle(t, nil, tc.declare) + if p.box.Height != tc.want { + t.Errorf("%s toggle height = %v, want %v", name, p.box.Height, tc.want) + } + } +} + +// A focused or invalid toggle draws the recipe's ring and border; hover fills +// the muted surface the component does. +func TestToggleStatesFollowTheRecipe(t *testing.T) { + theme := gfx.LightTheme() + focused := probeToggle(t, func(c *gfx.Canvas) { c.SetInteraction(gfx.ID{}, gfx.ID{}, gfx.Item(1), true) }, + func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false) }) + if len(focused.rects) < 2 { // the ring disc and the surface + t.Errorf("focused toggle has no ring: %+v", focused.rects) + } + invalid := probeToggle(t, nil, func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false).Invalid(true) }) + danger := false + for _, rect := range invalid.rects { + danger = danger || rect.Color == theme.Danger || rect.Color == theme.Ring + } + if !danger { + t.Errorf("invalid toggle paints no dangerous edge: %+v", invalid.rects) + } + if len(invalid.hits) != 1 || !invalid.hits[0].Invalid { + t.Errorf("invalid toggle hit = %+v, want Invalid", invalid.hits) + } + hovered := probeToggle(t, func(c *gfx.Canvas) { c.SetInteraction(gfx.Item(1), gfx.ID{}, gfx.ID{}, false) }, + func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false) }) + fill := false + for _, rect := range hovered.rects { + fill = fill || rect.Color == theme.Muted + } + if !fill { + t.Errorf("hovered toggle paints no muted fill: %+v", hovered.rects) + } +} + +// Children replace the label and stay inside the content rect; a disabled +// toggle makes its nested content inert. +func TestToggleChildrenReplaceTheLabel(t *testing.T) { + p := probeToggle(t, nil, func(f *Frame) Box { + return f.Toggle(gfx.Item(2), "Bold", true).Children(func() { + f.Text("one") + f.Text("two") + }) + }) + if len(p.texts) != 2 { + t.Fatalf("texts = %+v, want the two children", p.texts) + } + for _, text := range p.texts { + if text.Value == "Bold" { + t.Errorf("the label was painted over the children: %+v", p.texts) + } + if text.Bounds.X < p.box.X || text.Bounds.X+text.Bounds.Width > p.box.X+p.box.Width { + t.Errorf("child %q at %v is outside the toggle %v", text.Value, text.Bounds, p.box) + } + } + if len(p.hits) != 1 || p.hits[0].Checked != true || p.hits[0].Label != "Bold" { + t.Errorf("hits = %+v, want one checked button named by the label", p.hits) + } + + disabled := probeToggle(t, nil, func(f *Frame) Box { + return f.Toggle(gfx.Item(3), "Outer", false).Disabled(true).Children(func() { + f.Button(gfx.Item(4), "inner") + }) + }) + if len(disabled.hits) != 2 { + t.Fatalf("hits = %+v, want the toggle and its nested button", disabled.hits) + } + for _, hit := range disabled.hits { + if !hit.Disabled || hit.Focusable { + t.Errorf("hit %+v is not inert under the disabled toggle", hit) + } + } +} + +// The node toggle paints what components.BeginToggle painted: same shapes and +// same label for each treatment. A zero-alpha fill is drawn as a record by the +// component and skipped by the engine, so it is filtered before comparing. +func TestToggleNodePaintsWhatTheComponentDid(t *testing.T) { + theme := gfx.LightTheme() + cases := []struct { + name string + pressed bool + variant components.ToggleVariant + box func(f *Frame) Box + }{ + {"default off", false, components.ToggleDefault, func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false) }}, + {"default on", true, components.ToggleDefault, func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", true) }}, + {"outline", false, components.ToggleOutline, func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false).Outline() }}, + {"small", false, components.ToggleDefault, func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false).Small() }}, + {"large", false, components.ToggleDefault, func(f *Frame) Box { return f.Toggle(gfx.Item(1), "Bold", false).Large() }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + canvas := testCanvas() + var view View + var box Box + view.Draw(canvas, theme, gfx.Rect{Width: 200, Height: 80}, func(f *Frame) { + f.Row().Items(Start).Children(func() { box = tc.box(f) }) + }) + want := testCanvas() + toggle := components.BeginToggle(want, theme, gfx.Item(1), box.Rect(), tc.pressed) + if tc.variant == components.ToggleOutline { + toggle.Outline("Bold") + } else { + toggle.Default("Bold") + } + var drawn []gfx.Rectangle + for _, rect := range want.Rectangles() { + if rect.Color.Alpha > 0 { + drawn = append(drawn, rect) + } + } + if !reflect.DeepEqual(toggleShapes(drawn), toggleShapes(canvas.Rectangles())) { + t.Errorf("toggle differs from the component:\nwant %+v\n got %+v", drawn, canvas.Rectangles()) + } + wantTexts, gotTexts := want.Texts(), canvas.Texts() + if len(wantTexts) != len(gotTexts) { + t.Fatalf("texts = %+v, want %+v", gotTexts, wantTexts) + } + for i := range wantTexts { + wantText, gotText := wantTexts[i], gotTexts[i] + // The paint order numbers primitives; a skipped zero-alpha fill + // moves the label's number without moving the label. + wantText.Order, gotText.Order = 0, 0 + if wantText != gotText { + t.Errorf("text %d differs: want %+v got %+v", i, wantTexts[i], gotTexts[i]) + } + } + }) + } +} + +func toggleShapes(in []gfx.Rectangle) []gfx.Rectangle { + out := append([]gfx.Rectangle(nil), in...) + for i := 1; i < len(out); i++ { + for j := i; j > 0; j-- { + a, b := out[j-1], out[j] + if a.Bounds.X < b.Bounds.X || a.Bounds.X == b.Bounds.X && (a.Bounds.Y < b.Bounds.Y || a.Bounds.Y == b.Bounds.Y && a.Radius < b.Radius) { + break + } + out[j-1], out[j] = out[j], out[j-1] + } + } + return out +} diff --git a/cmd/viva/templates/badge.go.txt b/cmd/viva/templates/badge.go.txt index 49bb289bc..dca48a99b 100644 --- a/cmd/viva/templates/badge.go.txt +++ b/cmd/viva/templates/badge.go.txt @@ -1,6 +1,9 @@ package {{PACKAGE}} -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) // BadgeVariant selects one of the shadcn Vega badge treatments. Destructive is // Vega's: a danger-tinted pill with a danger label, not a solid red one. @@ -73,3 +76,43 @@ func PaintBadge(canvas *gfx.Canvas, theme gfx.Theme, origin gfx.Rect, label stri }) return bounds } + +// BadgeRecipe resolves the look of a badge variant: the chip's fill, label, +// line and pill radius. A badge is presentational, so hover, press, focus and +// disabled do not change its treatment, as PaintBadge does not; a page that +// wants those states gives the element a Hover, Pressed or Focus look itself. +func BadgeRecipe(theme gfx.Theme, variant BadgeVariant, _ gfx.State) style.ButtonLook { + _, _, radius, _ := style.BadgeGeometry(theme.Metrics) + background, foreground := theme.Primary, theme.PrimaryForeground + border := gfx.Color{} + filled, bordered := true, false + switch variant { + case BadgeSecondary: + background, foreground = theme.Secondary, theme.SecondaryForeground + case BadgeDestructive: + background = withAlpha(theme.Danger, 0.10) + if isDark(&theme) { + background.Alpha = 0.20 + } + foreground = theme.Danger + case BadgeOutline: + // The chip's fill is the page's own color at zero alpha: over an opaque + // page that flattens to the page, over a translucent one only the line + // stays, exactly as paintBordered does for the component. + background = theme.Background + background.Alpha = 0 + foreground = theme.Foreground + border = theme.Border + bordered = true + case BadgeGhost: + filled = false + foreground = theme.Foreground + case BadgeLink: + filled = false + foreground = theme.Primary + } + return style.ButtonLook{ + Background: background, Foreground: foreground, Border: border, + Filled: filled, Bordered: bordered, Radius: radius, + } +} diff --git a/cmd/viva/templates/checkbox.go.txt b/cmd/viva/templates/checkbox.go.txt index 30bbb79ee..70743af3f 100644 --- a/cmd/viva/templates/checkbox.go.txt +++ b/cmd/viva/templates/checkbox.go.txt @@ -17,7 +17,13 @@ type Checkbox struct { bounds gfx.Rect hitBounds gfx.Rect label string - checked bool + // unpaintedSurface is set when the caller's engine paints the box's fill, + // border, shadow and ring; Paint then draws only the mark and the hit. + unpaintedSurface bool + // markColor overrides the recipe's mark when hasMarkColor is set. + markColor gfx.Color + hasMarkColor bool + checked bool // indeterminate is Base UI's mixed state: the box shows a dash and the // accessibility value is "mixed", whatever checked says. indeterminate bool @@ -64,6 +70,20 @@ func (checkbox Checkbox) Label(label string) Checkbox { // way to make an enclosing region activate a control; it keeps the control's // own bounds and exposes the region as that control's label, so prefer it when // the semantic target should stay the square. +// UnpaintedSurface declares that the caller paints the box's own fill, border, +// shadow and ring, as the page's engine does; Paint then draws the mark, as the +// control's own graphic, and its hit. +func (checkbox Checkbox) UnpaintedSurface() Checkbox { + checkbox.unpaintedSurface = true + return checkbox +} + +// MarkColor paints the check or dash in color instead of the recipe's mark. +func (checkbox Checkbox) MarkColor(color gfx.Color) Checkbox { + checkbox.markColor, checkbox.hasMarkColor = color, true + return checkbox +} + func (checkbox Checkbox) HitBounds(bounds gfx.Rect) Checkbox { checkbox.hitBounds = bounds return checkbox @@ -130,11 +150,16 @@ func (checkbox Checkbox) Paint() CheckboxResult { if checkbox.recipe != nil { look = checkbox.recipe(checkbox.theme, state) } - checkbox.canvas.Elevate(checkbox.bounds, look.Radius, look.Shadow) // shadow-xs - if look.RingWidth > 0 { - checkbox.canvas.Rounded(expand(checkbox.bounds, look.RingWidth), look.RingRadius, look.Ring) + if checkbox.hasMarkColor { + look.Mark = checkbox.markColor + } + if !checkbox.unpaintedSurface { + checkbox.canvas.Elevate(checkbox.bounds, look.Radius, look.Shadow) // shadow-xs + if look.RingWidth > 0 { + checkbox.canvas.Rounded(expand(checkbox.bounds, look.RingWidth), look.RingRadius, look.Ring) + } + paintBordered(checkbox.canvas, checkbox.theme, checkbox.bounds, look.Radius, look.Border, look.Fill) } - paintBordered(checkbox.canvas, checkbox.theme, checkbox.bounds, look.Radius, look.Border, look.Fill) PaintCheckboxMark(checkbox.canvas, checkbox.bounds, state, look.Mark) if !checkbox.id.IsZero() { hitBounds := gfx.Rect{ diff --git a/cmd/viva/templates/select.go.txt b/cmd/viva/templates/select.go.txt index 231af10c8..87ece9c33 100644 --- a/cmd/viva/templates/select.go.txt +++ b/cmd/viva/templates/select.go.txt @@ -64,6 +64,23 @@ type SelectOptions struct { // MenuItemRecipe or from its own look. It is the same code path as the painted select, so // a select of the application's own cannot behave differently. Unpainted bool + // UnpaintedSurface lets the caller's engine paint the trigger's surface, so the + // trigger painter draws only the value (unless UnpaintedValue) and the chevron. + UnpaintedSurface bool + // UnpaintedValue keeps the painter from drawing the trigger's value and icon: + // caller-owned content declared with Children replaces them, while the chevron + // and the trigger's hit stay the control's. + UnpaintedValue bool + // TriggerContent is where the value and icon are laid out, in window + // coordinates: the element's content rect, which keeps the room for the chevron. + TriggerContent gfx.Rect + // TextSize and Weight override the type of the value (Weight is the label's + // weight when non-zero). + TextSize, Weight float32 + // Foreground paints the value (and a single-color icon) instead of the recipe's, + // when HasForeground is set; Chevron paints the arrow when HasChevron is set. + Foreground, Chevron gfx.Color + HasForeground, HasChevron bool } // SelectItem describes one stable value in the open popup. @@ -100,13 +117,18 @@ const SelectIconSpan = selectIconSize + selectIconGap // Only the extra-small step changes the type, as in Button: a compact control // keeps the body size and just gets shorter. func selectTriggerSize(metrics gfx.Metrics, size SelectSize) (height, textSize float32) { + return style.SelectGeometry(metrics, selectStyleSize(size)) +} + +// selectStyleSize is the element size a component select size maps to. +func selectStyleSize(size SelectSize) style.Size { switch size { case SelectSizeSmall: - return metrics.ControlHeight - 4, metrics.FontSizeM + return style.SizeSmall case SelectSizeXSmall: - return metrics.ControlHeight - 8, metrics.FontSizeS + return style.SizeXSmall } - return metrics.ControlHeight, metrics.FontSizeM + return style.SizeDefault } // Select paints a typed native select trigger and, when open, its source-owned @@ -286,32 +308,58 @@ func (selectControl Select) paintTrigger() { bounds := selectControl.triggerBounds options := selectControl.options enabled := !options.TriggerID.IsZero() && !options.Disabled + textSize := selectControl.textSize + if options.TextSize > 0 { + textSize = options.TextSize + } + foreground, chevron := selectControl.theme.Foreground, selectControl.theme.MutedForeground if !options.Unpainted { - state := gfx.State{ - Focused: enabled && canvas.FocusVisible() == options.TriggerID, - Invalid: options.Invalid, - Disabled: options.Disabled, - Hovered: enabled && (canvas.Hovered() == options.TriggerID || canvas.Pressed() == options.TriggerID), + if !options.UnpaintedSurface { + state := gfx.State{ + Focused: enabled && canvas.FocusVisible() == options.TriggerID, + Invalid: options.Invalid, + Disabled: options.Disabled, + Hovered: enabled && (canvas.Hovered() == options.TriggerID || canvas.Pressed() == options.TriggerID), + } + look := selectRecipe(&selectControl.theme, state, options.Value == "") + paintTextEntryLook(canvas, selectControl.theme.Background.Alpha, bounds, look.Surface) + foreground, chevron = look.Foreground, look.Chevron + } + if options.HasForeground { + foreground = options.Foreground + } + if options.HasChevron { + chevron = options.Chevron } - look := selectRecipe(&selectControl.theme, state, options.Value == "") - paintTextEntryLook(canvas, selectControl.theme.Background.Alpha, bounds, look.Surface) - foreground := look.Foreground value := options.Value if value == "" { value = options.Placeholder } // Vega: pl-2.5 and pr-2 inside the border, gap-1.5 before the 16px chevron. const chevronSpan = 1 + 8 + selectIconSize - inset := selectControl.theme.Metrics.TextInsetX() - textX, textWidth := bounds.X+inset, bounds.Width-inset-chevronSpan-6 - if paintSelectIcon(canvas, options.Icon, options.IconImage, options.IconText, gfx.Rect{X: textX, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, foreground, selectControl.textSize) { - textX += SelectIconSpan - textWidth -= SelectIconSpan + inset, _ := style.SelectContentInsets(selectControl.theme.Metrics) + content := options.TriggerContent + if content.Width <= 0 { + content = gfx.Rect{ + X: bounds.X + inset, Y: bounds.Y, + Width: selectMax(0, bounds.Width-inset-chevronSpan-6), Height: bounds.Height, + } } - canvas.Label(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ - Size: selectControl.textSize, Weight: gfx.WeightRegular, Color: foreground, - }) - paintChevron(canvas, &chevronDownIcon, gfx.Rect{X: bounds.X + bounds.Width - chevronSpan, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, look.Chevron) + if !options.UnpaintedValue { + textX, textWidth := content.X, content.Width + if paintSelectIcon(canvas, options.Icon, options.IconImage, options.IconText, gfx.Rect{X: textX, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, foreground, textSize) { + textX += SelectIconSpan + textWidth -= SelectIconSpan + } + weight := gfx.WeightRegular + if options.Weight > 0 { + weight = options.Weight + } + canvas.Label(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + Size: textSize, Weight: weight, Color: foreground, + }) + } + paintChevron(canvas, &chevronDownIcon, gfx.Rect{X: bounds.X + bounds.Width - chevronSpan, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, chevron) } if !options.TriggerID.IsZero() { canvas.HitWithOptions(options.TriggerID, bounds, options.Label, gfx.HitOptions{ diff --git a/cmd/viva/templates/switch.go.txt b/cmd/viva/templates/switch.go.txt index 01d822015..29c2a332c 100644 --- a/cmd/viva/templates/switch.go.txt +++ b/cmd/viva/templates/switch.go.txt @@ -16,6 +16,10 @@ const ( SwitchSizeSmall ) +// SwitchCheckedSlot is the animation slot holding a switch thumb's travel toward +// on; a caller painting the track from the same look asks Canvas.Animate for it. +const SwitchCheckedSlot uint8 = base.SwitchCheckedSlot + // switchSlotChecked is the animation slot holding thumb travel, 0 (off) to 1 (on). const switchSlotChecked uint8 = 0 @@ -30,11 +34,17 @@ type Switch struct { bounds gfx.Rect label string hitBounds gfx.Rect - checked bool - focused bool - invalid bool - size SwitchSize - disabled bool + // unpaintedSurface is set when the caller's engine paints the track's fill, + // border, shadow and ring; Paint then draws only the thumb and the hit. + unpaintedSurface bool + // thumbColor overrides the recipe's thumb when hasThumbColor is set. + thumbColor gfx.Color + hasThumbColor bool + checked bool + focused bool + invalid bool + size SwitchSize + disabled bool // recipe, when set, replaces SwitchRecipe; see Button.Recipe. recipe func(gfx.Theme, gfx.State, float32) SwitchLook } @@ -102,6 +112,21 @@ func (result SwitchResult) Clicked() bool { // The visual track keeps its normal position and size; zero bounds use the // default enlarged target. The rect replaces the track's target rather than // adding to it and must contain the track. +// UnpaintedSurface declares that the caller paints the track's fill, border, +// shadow and ring, as the page's engine does; Paint then draws the thumb, the +// control's own graphic, and its hit. +func (switchControl Switch) UnpaintedSurface() Switch { + switchControl.unpaintedSurface = true + return switchControl +} + +// ThumbColor paints the thumb in color instead of the recipe's, so a caller +// that painted the track from the same look keeps them in step. +func (switchControl Switch) ThumbColor(color gfx.Color) Switch { + switchControl.thumbColor, switchControl.hasThumbColor = color, true + return switchControl +} + func (switchControl Switch) HitBounds(bounds gfx.Rect) Switch { switchControl.hitBounds = bounds return switchControl @@ -156,14 +181,19 @@ func (switchControl Switch) Paint() SwitchResult { FocusVisible: switchControl.focused, Invalid: switchControl.invalid, Disabled: switchControl.disabled, }, progress) } - switchControl.canvas.Elevate(switchControl.bounds, switchControl.bounds.Height/2, look.Shadow) // shadow-xs - if look.Bordered { - switchControl.canvas.Rounded(expand(switchControl.bounds, look.RingWidth), switchControl.bounds.Height/2+look.RingWidth, look.Ring) - paintBordered(switchControl.canvas, switchControl.theme, switchControl.bounds, switchControl.bounds.Height/2, look.Border, look.Track) - } else { - switchControl.canvas.Rounded(switchControl.bounds, switchControl.bounds.Height/2, look.Track) + if !switchControl.unpaintedSurface { + switchControl.canvas.Elevate(switchControl.bounds, switchControl.bounds.Height/2, look.Shadow) // shadow-xs + if look.Bordered { + switchControl.canvas.Rounded(expand(switchControl.bounds, look.RingWidth), switchControl.bounds.Height/2+look.RingWidth, look.Ring) + paintBordered(switchControl.canvas, switchControl.theme, switchControl.bounds, switchControl.bounds.Height/2, look.Border, look.Track) + } else { + switchControl.canvas.Rounded(switchControl.bounds, switchControl.bounds.Height/2, look.Track) + } } thumb := look.Thumb + if switchControl.hasThumbColor { + thumb = switchControl.thumbColor + } // The thumb sits inside the track's 1px border: one pixel from the left edge // when off and one from the right when on (translate-x-[calc(100%-2px)]). diff --git a/cmd/viva/templates/tabs.go.txt b/cmd/viva/templates/tabs.go.txt index 208d1bffd..adcbf9442 100644 --- a/cmd/viva/templates/tabs.go.txt +++ b/cmd/viva/templates/tabs.go.txt @@ -3,6 +3,7 @@ package {{PACKAGE}} import ( "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) // Tabs paints a compact Base UI-style tab list. The active tab and associated @@ -21,9 +22,60 @@ type Tabs struct { direction TabsOrientation disabled bool fit bool + style TabsStyle + // unpaintedSurface is set when the caller's engine paints the strip itself, + // as a page's does; BeginTabs users leave it off and get the strip painted. + unpaintedSurface bool // tabStop is the one tab Tab reaches; the arrow helper moves focus among the // rest, which are SkipTab. tabStop gfx.ID + // The strip's effective style, filled from TabStyle's zero fields at Paint. + paint tabsPaint +} + +// TabsStyle overrides what a tab strip paints and how its triggers are laid +// out. Every field is optional: a zero value keeps the size's default, so this +// is how the page passes Pad, Gap, Radius, FontSize, Weight, Color, Background +// and Border of the element down to the component. +type TabsStyle struct { + // ListHeight and ListPadding size the strip; TriggerHeight and TriggerPadding + // size one trigger inside it. LineGap is the gap between line-variant triggers; + // Gap is used for both variants when set. + ListHeight, ListPadding, TriggerHeight, TriggerPadding, LineGap, Gap float32 + // TriggerRadius is a trigger's corner radius; the strip's own radius is the + // element's Radius, painted by the engine. + TriggerRadius float32 + // FontSize and Weight style a trigger's label and icon. + FontSize, Weight float32 + // Fill paints the list's surface when HasFill is set; Border draws its line + // when HasBorder is set. Foreground replaces the label color when HasForeground + // is set, keeping the selected, hovered and disabled dimming. + Fill, Border, Foreground gfx.Color + HasFill, HasBorder bool + HasForeground bool +} + +// tabsPaint is TabsStyle resolved against the theme at Paint. +type tabsPaint struct { + listHeight, listPadding, triggerHeight, triggerPadding, lineGap, gap float32 + listRadius, triggerRadius, fontSize, weight float32 + foreground gfx.Color + hasForeground bool +} + +// WithStyle overrides the strip's measurements, colors and label style; zero +// fields keep the size's defaults. +func (tabs Tabs) WithStyle(style TabsStyle) Tabs { + tabs.style = style + return tabs +} + +// UnpaintedSurface declares that the caller paints the strip's own surface +// behind the triggers, as the page's engine does; Paint then draws only the +// triggers and their indicator. +func (tabs Tabs) UnpaintedSurface() Tabs { + tabs.unpaintedSurface = true + return tabs } // Line selects the transparent list with a two-pixel active indicator. @@ -150,27 +202,73 @@ const ( tabsTriggerHeight = 30 // list height less its padding ) +// resolvedPaint is the strip's style with the theme defaults filled in and the +// caller's overrides applied. +func (tabs Tabs) resolvedPaint() tabsPaint { + metrics := tabs.theme.Metrics + defHeight, defPadding, defTriggerHeight, defTriggerPad, defLineGap, defFont, defWeight := style.TabsGeometry(metrics) + p := tabsPaint{ + listHeight: defHeight, listPadding: defPadding, + triggerHeight: defTriggerHeight, triggerPadding: defTriggerPad, + lineGap: defLineGap, gap: 0, + listRadius: style.TabsListRadius(metrics), triggerRadius: style.TabsTriggerRadius(metrics), + fontSize: defFont, weight: defWeight, + } + override := tabs.style + if override.ListHeight > 0 { + p.listHeight = override.ListHeight + } + if override.ListPadding > 0 { + p.listPadding = override.ListPadding + } + if override.TriggerHeight > 0 { + p.triggerHeight = override.TriggerHeight + } + if override.TriggerPadding > 0 { + p.triggerPadding = override.TriggerPadding + } + if override.LineGap > 0 { + p.lineGap = override.LineGap + } + if override.Gap > 0 { + p.gap = override.Gap + } + if override.TriggerRadius > 0 { + p.triggerRadius = override.TriggerRadius + } + if override.FontSize > 0 { + p.fontSize = override.FontSize + } + if override.Weight > 0 { + p.weight = override.Weight + } + if override.HasForeground { + p.foreground, p.hasForeground = override.Foreground, true + } + return p +} + // Paint draws the list and independently focusable tab triggers. func (tabs Tabs) Paint() TabsResult { result := TabsResult{canvas: tabs.canvas, list: tabs.list} if tabs.canvas == nil || tabs.count() == 0 { return result } - metrics := tabs.theme.Metrics - weight := gfx.WeightMedium + tabs.paint = tabs.resolvedPaint() + weight := tabs.paint.weight gap := tabs.itemGap() count := float32(tabs.count()) if tabs.fit { var widest, total float32 for index := range tabs.count() { - width := tabs.contentWidth(tabs.option(index)) + tabsTriggerPad*2 + width := tabs.contentWidth(tabs.option(index)) + tabs.paint.triggerPadding*2 widest = max(widest, width) total += width } if tabs.direction == TabsVertical { - tabs.bounds.Width = widest + tabsPadding*2 + tabs.bounds.Width = widest + tabs.paint.listPadding*2 } else { - tabs.bounds.Width = total + gap*(count-1) + tabsPadding*2 + tabs.bounds.Width = total + gap*(count-1) + tabs.paint.listPadding*2 } } if tabs.bounds.Width <= 0 { @@ -178,24 +276,26 @@ func (tabs Tabs) Paint() TabsResult { } if tabs.bounds.Height <= 0 { if tabs.direction == TabsVertical { - tabs.bounds.Height = tabsTriggerHeight*count + gap*(count-1) + tabsPadding*2 + tabs.bounds.Height = tabs.paint.triggerHeight*count + gap*(count-1) + tabs.paint.listPadding*2 } else { - tabs.bounds.Height = tabsListHeight + tabs.bounds.Height = tabs.paint.listHeight } } result.bounds = tabs.bounds - radius := metrics.RadiusControl - listFill := tabs.theme.Muted - listRadius := radius + 2 - if tabs.variant == TabsLine { - listFill = tabs.theme.Background - listFill.Alpha = 0 - listRadius = 0 + triggerRadius := tabs.paint.triggerRadius + if !tabs.unpaintedSurface { + listFill := tabs.theme.Muted + listRadius := tabs.paint.listRadius + if tabs.variant == TabsLine { + listFill = tabs.theme.Background + listFill.Alpha = 0 + listRadius = 0 + } + tabs.canvas.Rounded(tabs.bounds, listRadius, listFill) } - tabs.canvas.Rounded(tabs.bounds, listRadius, listFill) inner := gfx.Rect{ - X: tabs.bounds.X + tabsPadding, Y: tabs.bounds.Y + tabsPadding, - Width: tabs.bounds.Width - tabsPadding*2, Height: tabs.bounds.Height - tabsPadding*2, + X: tabs.bounds.X + tabs.paint.listPadding, Y: tabs.bounds.Y + tabs.paint.listPadding, + Width: tabs.bounds.Width - tabs.paint.listPadding*2, Height: tabs.bounds.Height - tabs.paint.listPadding*2, } cursor := float32(0) for index := range tabs.count() { @@ -211,14 +311,32 @@ func (tabs Tabs) Paint() TabsResult { state.FocusVisible = tabs.canvas.FocusVisible() == option.ID } look := tabTriggerRecipe(&tabs.theme, tabs.variant, state) + if tabs.paint.hasForeground { + foreground := tabs.paint.foreground + hovered := !state.Disabled && state.Hovered + if !state.Selected && !hovered { + foreground.Alpha *= 0.60 + } + if state.Disabled { + foreground.Alpha *= 0.50 + } + look.Foreground = foreground + if look.Indicator.Alpha > 0 { + indicator := tabs.paint.foreground + if state.Disabled { + indicator.Alpha *= 0.50 + } + look.Indicator = indicator + } + } if look.RingWidth > 0 { tabs.canvas.Rounded(expand(trigger, look.RingWidth), look.RingRadius, look.Ring) } if look.Bordered { - tabs.canvas.Elevate(trigger, radius, look.Shadow) // the selected trigger's shadow-sm - tabs.canvas.RoundedBorder(trigger, radius, 1, look.Border, look.Fill) + tabs.canvas.Elevate(trigger, triggerRadius, look.Shadow) // the selected trigger's shadow-sm + tabs.canvas.RoundedBorder(trigger, triggerRadius, 1, look.Border, look.Fill) } else { - tabs.canvas.Rounded(trigger, radius, look.Fill) + tabs.canvas.Rounded(trigger, triggerRadius, look.Fill) } indicator := look.Indicator @@ -228,8 +346,8 @@ func (tabs Tabs) Paint() TabsResult { } tabs.canvas.Rounded(indicatorBounds, 1, indicator) - style := gfx.TextStyle{Size: metrics.FontSizeM, Weight: weight, Color: look.Foreground} - tabs.paintContent(option, trigger, style) + textStyle := gfx.TextStyle{Size: tabs.paint.fontSize, Weight: weight, Color: look.Foreground} + tabs.paintContent(option, trigger, textStyle) if !option.ID.IsZero() { hint := "" if option.IconOnly { @@ -249,13 +367,16 @@ func (tabs Tabs) Paint() TabsResult { // triggerBounds returns the index-th trigger inside the list's padded interior. // cursor is the distance already used along the row in Fit mode. func (tabs Tabs) triggerBounds(inner gfx.Rect, index int, count, cursor float32) gfx.Rect { + if tabs.paint.fontSize == 0 { + tabs.paint = tabs.resolvedPaint() + } gap := tabs.itemGap() if tabs.direction == TabsVertical { height := (inner.Height - gap*(count-1)) / count return gfx.Rect{X: inner.X, Y: inner.Y + float32(index)*(height+gap), Width: inner.Width, Height: height} } if tabs.fit { - width := tabs.contentWidth(tabs.option(index)) + tabsTriggerPad*2 + width := tabs.contentWidth(tabs.option(index)) + tabs.paint.triggerPadding*2 return gfx.Rect{X: inner.X + cursor, Y: inner.Y, Width: width, Height: inner.Height} } width := (inner.Width - gap*(count-1)) / count @@ -263,19 +384,28 @@ func (tabs Tabs) triggerBounds(inner gfx.Rect, index int, count, cursor float32) } func (tabs Tabs) itemGap() float32 { + if tabs.paint.fontSize == 0 { + tabs.paint = tabs.resolvedPaint() + } + if tabs.paint.gap > 0 { + return tabs.paint.gap + } if tabs.variant == TabsLine { - return tabsLineGap + return tabs.paint.lineGap } return 0 } func (tabs Tabs) contentWidth(option TabOption) float32 { + if tabs.paint.fontSize == 0 { + tabs.paint = tabs.resolvedPaint() + } width := float32(0) if !option.IconOnly { - width = tabs.canvas.TextWidthWeight(option.Label, tabs.theme.Metrics.FontSizeM, gfx.WeightMedium) + width = tabs.canvas.TextWidthWeight(option.Label, tabs.paint.fontSize, tabs.paint.weight) } if len(option.Icon.Commands) > 0 || len(option.Icon.Layers) > 0 { - width += tabs.theme.Metrics.FontSizeM + width += tabs.paint.fontSize if option.Label != "" && !option.IconOnly { width += 6 } @@ -284,7 +414,10 @@ func (tabs Tabs) contentWidth(option TabOption) float32 { } func (tabs Tabs) paintContent(option TabOption, trigger gfx.Rect, style gfx.TextStyle) { - b := gfx.Rect{X: trigger.X + tabsTriggerPad, Y: trigger.Y, Width: max(0, trigger.Width-tabsTriggerPad*2), Height: trigger.Height} + if tabs.paint.fontSize == 0 { + tabs.paint = tabs.resolvedPaint() + } + b := gfx.Rect{X: trigger.X + tabs.paint.triggerPadding, Y: trigger.Y, Width: max(0, trigger.Width-tabs.paint.triggerPadding*2), Height: trigger.Height} tabs.canvas.Clip(trigger) defer tabs.canvas.Unclip() if len(option.Icon.Commands) == 0 && len(option.Icon.Layers) == 0 { @@ -295,7 +428,7 @@ func (tabs Tabs) paintContent(option TabOption, trigger gfx.Rect, style gfx.Text } return } - size := min(tabs.theme.Metrics.FontSizeM, max(0, b.Height)) + size := min(tabs.paint.fontSize, max(0, b.Height)) gap := float32(0) if option.Label != "" && !option.IconOnly { gap = 6 @@ -317,6 +450,18 @@ func (tabs Tabs) paintContent(option TabOption, trigger gfx.Rect, style gfx.Text tabs.canvas.Label(text, b, style) } +// TabsListRecipe resolves the look of the strip behind a tab list: its fill and +// its corner radius. The line variant draws no strip, so it is not filled. +func TabsListRecipe(theme gfx.Theme, variant TabsVariant) style.ButtonLook { + if variant == TabsLine { + return style.ButtonLook{} + } + return style.ButtonLook{ + Background: theme.Muted, Filled: true, + Radius: style.TabsListRadius(theme.Metrics), + } +} + // TabTriggerLook is the look of one tab of a strip in one state. type TabTriggerLook struct { // Fill is the trigger's background, transparent unless the tab is the selected one of diff --git a/cmd/viva/templates/textarea.go.txt b/cmd/viva/templates/textarea.go.txt index b9a84c0b9..b3ebc979f 100644 --- a/cmd/viva/templates/textarea.go.txt +++ b/cmd/viva/templates/textarea.go.txt @@ -72,7 +72,7 @@ func paintTextareaContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, area gfx. options := gfx.HitOptions{ Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, Disabled: snapshot.Disabled, ReadOnly: snapshot.ReadOnly, Multiline: true, Invalid: snapshot.Invalid, - TextBounds: content, TextSize: theme.Metrics.FontSizeM, TextColor: theme.Foreground, + TextBounds: content, TextSize: textareaHitSize(theme, snapshot), TextColor: theme.Foreground, } if snapshot.HideEditorText { options.TextColor = gfx.Color{} @@ -121,8 +121,27 @@ func (rows *textareaRows) next() (row gfx.TextRow, after int, ok bool) { return row, rows.from, true } +// textareaHitSize is the text size a textarea reports to the platform. +func textareaHitSize(theme gfx.Theme, snapshot TextareaSnapshot) float32 { + size, _ := textareaTextStyle(theme, snapshot) + return size +} + +// textareaTextStyle is the size and weight of a textarea's rows: the +// snapshot's own when set, else the theme's body size at the regular weight. +func textareaTextStyle(theme gfx.Theme, snapshot TextareaSnapshot) (size, weight float32) { + size, weight = theme.Metrics.FontSizeM, gfx.WeightRegular + if snapshot.TextSize > 0 { + size = snapshot.TextSize + } + if snapshot.TextWeight > 0 { + weight = snapshot.TextWeight + } + return size, weight +} + func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot TextareaSnapshot, focused bool) { - fontSize := theme.Metrics.FontSizeM + fontSize, weight := textareaTextStyle(theme, snapshot) lineHeight := fontSize + 7 placeholderShown := value == "" if placeholderShown { @@ -187,7 +206,7 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val line = trimTrailingSpaces(line) } lineEnd := row.Start + len(line) - style := gfx.TextStyle{Size: fontSize, Weight: gfx.WeightRegular, Color: color} + style := gfx.TextStyle{Size: fontSize, Weight: weight, Color: color} origin := canvas.LabelOrigin(line, lineBounds, style, gfx.AlignStart) labelBounds := lineBounds if origin == lineBounds.X { @@ -255,7 +274,7 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val if snapshot.Disabled { selectedColor.Alpha *= 0.50 } - canvas.Label(line, labelBounds, gfx.TextStyle{Size: fontSize, Weight: gfx.WeightRegular, Color: selectedColor}) + canvas.Label(line, labelBounds, gfx.TextStyle{Size: fontSize, Weight: weight, Color: selectedColor}) canvas.Unclip() } } diff --git a/cmd/viva/templates/toggle.go.txt b/cmd/viva/templates/toggle.go.txt index 4264c2264..392c70e61 100644 --- a/cmd/viva/templates/toggle.go.txt +++ b/cmd/viva/templates/toggle.go.txt @@ -1,6 +1,9 @@ package {{PACKAGE}} -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) // ToggleVariant selects the neutral or bordered treatment. type ToggleVariant uint8 @@ -19,6 +22,52 @@ const ( ToggleSizeLarge ) +// ToggleRecipe resolves the look of a toggle of one variant in one state: the +// fill, the label, the line, the focus ring and the shadow. Checked is the +// active state; hover, press, focus and invalid are read only while the toggle +// is not disabled, and Disabled dims the fill, the label and the line by half. +func ToggleRecipe(theme gfx.Theme, variant ToggleVariant, state gfx.State) style.ButtonLook { + radius := theme.Metrics.RadiusControl + fill := theme.Background + fill.Alpha = 0 + foreground := theme.Foreground + border := theme.Input + bordered := variant == ToggleOutline + if state.Checked { + fill = theme.Muted + } + if state.Hovered && !state.Disabled { + fill = theme.Muted + foreground = theme.Foreground + } + if state.Pressed && !state.Disabled { + fill = blend(fill, theme.Foreground, 0.05) + } + look := style.ButtonLook{ + Background: fill, Foreground: foreground, Border: border, + Filled: true, Bordered: bordered, Radius: radius, + } + if variant == ToggleOutline { + look.Shadow = gfx.ShadowXS + } + // The component draws an invalid ring even on a disabled toggle; focus is + // the keyboard's, so it stops when the toggle is unavailable. + if state.Invalid || state.FocusVisible && !state.Disabled { + ring, edge := scaledAlpha(theme.Ring, 0.50), theme.Ring + if state.Invalid { + ring, edge = invalidRing(&theme), invalidBorder(&theme) + } + look.Ring, look.RingWidth, look.RingRadius = ring, 3, radius+3 + look.Border, look.Bordered = edge, true + } + if state.Disabled { + look.Background.Alpha *= 0.50 + look.Foreground.Alpha *= 0.50 + look.Border.Alpha *= 0.50 + } + return look +} + // Toggle paints one two-state compact action. The application owns active // state and responds to the stable Canvas hit ID. type Toggle struct { @@ -64,8 +113,9 @@ func (toggle Toggle) Disabled() Toggle { // SizeToFit widens the toggle to its label plus Vega's px-2.5, never narrower // than it is tall (min-w). func (toggle Toggle) SizeToFit(label string) Toggle { - toggle.bounds.Height = toggle.controlHeight() - toggle.bounds.Width = toggleFittedWidth(toggle.canvas, toggle.theme, label, toggle.bounds.Height, 10) + height, padding, _ := style.ToggleGeometry(toggle.theme.Metrics, toggleStyleSize(toggle.size)) + toggle.bounds.Height = height + toggle.bounds.Width = toggleFittedWidth(toggle.canvas, toggle.theme, label, height, padding) return toggle } @@ -112,51 +162,26 @@ func (toggle Toggle) paint(label string, variant ToggleVariant) ToggleResult { if toggle.bounds.Width <= 0 { toggle.bounds.Width = toggle.bounds.Height } - enabled := !toggle.disabled && !toggle.id.IsZero() - hovered := enabled && toggle.canvas.Hovered() == toggle.id - pressed := enabled && toggle.canvas.Pressed() == toggle.id - focused := enabled && toggle.canvas.FocusVisible() == toggle.id - radius := toggle.theme.Metrics.RadiusControl - border := toggle.theme.Input - if focused || toggle.invalid { - focus := scaledAlpha(toggle.theme.Ring, 0.50) - border = toggle.theme.Ring - if toggle.invalid { - focus, border = invalidRing(&toggle.theme), invalidBorder(&toggle.theme) - } - toggle.canvas.Rounded(expand(toggle.bounds, 3), radius+3, focus) - } - - fill := toggle.theme.Background - fill.Alpha = 0 - foreground := toggle.theme.Foreground - if toggle.active { - fill = toggle.theme.Muted - } - if hovered { - fill = toggle.theme.Muted - foreground = toggle.theme.Foreground + state := gfx.State{Checked: toggle.active, Invalid: toggle.invalid, Disabled: toggle.disabled} + if !toggle.disabled && !toggle.id.IsZero() { + state.Hovered = toggle.canvas.Hovered() == toggle.id + state.Pressed = toggle.canvas.Pressed() == toggle.id + state.FocusVisible = toggle.canvas.FocusVisible() == toggle.id } - if pressed { - fill = blend(fill, toggle.theme.Foreground, 0.05) + look := ToggleRecipe(toggle.theme, variant, state) + if look.Shadow != gfx.ShadowNone { + toggle.canvas.Elevate(toggle.bounds, look.Radius, look.Shadow) // shadow-xs } - if toggle.disabled { - fill.Alpha *= 0.50 - foreground.Alpha *= 0.50 + if look.RingWidth > 0 { + toggle.canvas.Rounded(expand(toggle.bounds, look.RingWidth), look.RingRadius, look.Ring) } - if variant == ToggleOutline || toggle.invalid || focused { - if variant == ToggleOutline { - toggle.canvas.Elevate(toggle.bounds, radius, gfx.ShadowXS) // shadow-xs - } - if toggle.disabled { - border.Alpha *= 0.50 - } - paintBordered(toggle.canvas, toggle.theme, toggle.bounds, radius, border, fill) - } else { - toggle.canvas.Rounded(toggle.bounds, radius, fill) + if look.Bordered && look.Filled { + paintBordered(toggle.canvas, toggle.theme, toggle.bounds, look.Radius, look.Border, look.Background) + } else if look.Filled { + toggle.canvas.Rounded(toggle.bounds, look.Radius, look.Background) } toggle.canvas.LabelCenter(label, toggle.bounds, gfx.TextStyle{ - Size: toggle.theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: foreground, + Size: toggle.theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: look.Foreground, }) if !toggle.id.IsZero() { toggle.canvas.HitWithOptions(toggle.id, toggle.bounds, label, gfx.HitOptions{ @@ -172,15 +197,19 @@ func (toggle Toggle) controlHeight() float32 { } func toggleControlHeight(theme gfx.Theme, size ToggleSize) float32 { - height := theme.Metrics.ControlHeight + height, _, _ := style.ToggleGeometry(theme.Metrics, toggleStyleSize(size)) + return height +} + +// toggleStyleSize is the element size a component toggle size maps to; both +// the node measurement and the component's SizeToFit take their metrics from +// style.ToggleGeometry. +func toggleStyleSize(size ToggleSize) style.Size { switch size { case ToggleSizeSmall: - height -= 4 + return style.SizeSmall case ToggleSizeLarge: - height += 4 - } - if height < 20 { - height = 20 + return style.SizeLarge } - return height + return style.SizeDefault } diff --git a/components/badge.go b/components/badge.go index 54b66f860..5138942ed 100644 --- a/components/badge.go +++ b/components/badge.go @@ -1,6 +1,9 @@ package components -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) // BadgeVariant selects one of the shadcn Vega badge treatments. Destructive is // Vega's: a danger-tinted pill with a danger label, not a solid red one. @@ -73,3 +76,43 @@ func PaintBadge(canvas *gfx.Canvas, theme gfx.Theme, origin gfx.Rect, label stri }) return bounds } + +// BadgeRecipe resolves the look of a badge variant: the chip's fill, label, +// line and pill radius. A badge is presentational, so hover, press, focus and +// disabled do not change its treatment, as PaintBadge does not; a page that +// wants those states gives the element a Hover, Pressed or Focus look itself. +func BadgeRecipe(theme gfx.Theme, variant BadgeVariant, _ gfx.State) style.ButtonLook { + _, _, radius, _ := style.BadgeGeometry(theme.Metrics) + background, foreground := theme.Primary, theme.PrimaryForeground + border := gfx.Color{} + filled, bordered := true, false + switch variant { + case BadgeSecondary: + background, foreground = theme.Secondary, theme.SecondaryForeground + case BadgeDestructive: + background = withAlpha(theme.Danger, 0.10) + if isDark(&theme) { + background.Alpha = 0.20 + } + foreground = theme.Danger + case BadgeOutline: + // The chip's fill is the page's own color at zero alpha: over an opaque + // page that flattens to the page, over a translucent one only the line + // stays, exactly as paintBordered does for the component. + background = theme.Background + background.Alpha = 0 + foreground = theme.Foreground + border = theme.Border + bordered = true + case BadgeGhost: + filled = false + foreground = theme.Foreground + case BadgeLink: + filled = false + foreground = theme.Primary + } + return style.ButtonLook{ + Background: background, Foreground: foreground, Border: border, + Filled: filled, Bordered: bordered, Radius: radius, + } +} diff --git a/components/badge_recipe_test.go b/components/badge_recipe_test.go new file mode 100644 index 000000000..4774415bb --- /dev/null +++ b/components/badge_recipe_test.go @@ -0,0 +1,76 @@ +package components + +import ( + "reflect" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +// measured returns a canvas that measures text the way the test pages do. +func measured() *gfx.Canvas { + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 { return float32(len(Value)) * Size / 2 }) + return canvas +} + +// A badge of the page's own, dressed from BadgeRecipe with the canvas calls the +// engine makes, is the chip PaintBadge paints: for every theme and variant the +// surface is the same shapes in the same colors. This is what the node-based +// Badge relies on. +func TestBadgeRecipePaintsTheSurfaceAsTheComponentDoes(t *testing.T) { + variants := map[string]BadgeVariant{ + "default": BadgeDefault, "secondary": BadgeSecondary, "destructive": BadgeDestructive, + "outline": BadgeOutline, "ghost": BadgeGhost, "link": BadgeLink, + } + for themeName, theme := range recipeThemes() { + for variantName, variant := range variants { + t.Run(themeName+"/"+variantName, func(t *testing.T) { + label := "beta" + width, height := BadgeExtent(measured(), theme, label) + bounds := gfx.Rect{X: 4, Y: 4, Width: width, Height: height} + want := measured() + PaintBadge(want, theme, gfx.Rect{X: bounds.X, Y: bounds.Y}, label, variant) + + var got gfx.Canvas + look := BadgeRecipe(theme, variant, gfx.State{}) + background := gfx.Color{} + if look.Filled { + background = look.Background + } + bordered := look.Bordered && look.Filled + if bordered && theme.Background.Alpha >= 1 { + background = background.Over(theme.Background) + look.Border = look.Border.Over(theme.Background) + } + switch { + case bordered: + paintBordered(&got, theme, bounds, look.Radius, look.Border, background) + case look.Filled: + got.Rounded(bounds, look.Radius, background) + } + if !reflect.DeepEqual(noOrders(want.Rectangles()), noOrders(got.Rectangles())) { + t.Errorf("recipe and component differ:\nwant %+v\n got %+v", want.Rectangles(), got.Rectangles()) + } + }) + } + } +} + +// The recipe's pill radius is the geometry's: half the chip height, which is +// what makes a badge a pill rather than a rounded rectangle. +func TestBadgeRecipeRadiusIsHalfTheChip(t *testing.T) { + theme := gfx.LightTheme() + height, padding, radius, fontSize := style.BadgeGeometry(theme.Metrics) + if radius != height/2 { + t.Errorf("radius %v, want half of height %v", radius, height) + } + look := BadgeRecipe(theme, BadgeDefault, gfx.State{}) + if look.Radius != radius { + t.Errorf("recipe radius %v, want %v", look.Radius, radius) + } + if padding <= 0 || fontSize <= 0 { + t.Errorf("geometry padding %v, fontSize %v, want both positive", padding, fontSize) + } +} diff --git a/components/checkbox.go b/components/checkbox.go index 19102563b..726e67b4d 100644 --- a/components/checkbox.go +++ b/components/checkbox.go @@ -17,7 +17,13 @@ type Checkbox struct { bounds gfx.Rect hitBounds gfx.Rect label string - checked bool + // unpaintedSurface is set when the caller's engine paints the box's fill, + // border, shadow and ring; Paint then draws only the mark and the hit. + unpaintedSurface bool + // markColor overrides the recipe's mark when hasMarkColor is set. + markColor gfx.Color + hasMarkColor bool + checked bool // indeterminate is Base UI's mixed state: the box shows a dash and the // accessibility value is "mixed", whatever checked says. indeterminate bool @@ -64,6 +70,20 @@ func (checkbox Checkbox) Label(label string) Checkbox { // way to make an enclosing region activate a control; it keeps the control's // own bounds and exposes the region as that control's label, so prefer it when // the semantic target should stay the square. +// UnpaintedSurface declares that the caller paints the box's own fill, border, +// shadow and ring, as the page's engine does; Paint then draws the mark, as the +// control's own graphic, and its hit. +func (checkbox Checkbox) UnpaintedSurface() Checkbox { + checkbox.unpaintedSurface = true + return checkbox +} + +// MarkColor paints the check or dash in color instead of the recipe's mark. +func (checkbox Checkbox) MarkColor(color gfx.Color) Checkbox { + checkbox.markColor, checkbox.hasMarkColor = color, true + return checkbox +} + func (checkbox Checkbox) HitBounds(bounds gfx.Rect) Checkbox { checkbox.hitBounds = bounds return checkbox @@ -130,11 +150,16 @@ func (checkbox Checkbox) Paint() CheckboxResult { if checkbox.recipe != nil { look = checkbox.recipe(checkbox.theme, state) } - checkbox.canvas.Elevate(checkbox.bounds, look.Radius, look.Shadow) // shadow-xs - if look.RingWidth > 0 { - checkbox.canvas.Rounded(expand(checkbox.bounds, look.RingWidth), look.RingRadius, look.Ring) + if checkbox.hasMarkColor { + look.Mark = checkbox.markColor + } + if !checkbox.unpaintedSurface { + checkbox.canvas.Elevate(checkbox.bounds, look.Radius, look.Shadow) // shadow-xs + if look.RingWidth > 0 { + checkbox.canvas.Rounded(expand(checkbox.bounds, look.RingWidth), look.RingRadius, look.Ring) + } + paintBordered(checkbox.canvas, checkbox.theme, checkbox.bounds, look.Radius, look.Border, look.Fill) } - paintBordered(checkbox.canvas, checkbox.theme, checkbox.bounds, look.Radius, look.Border, look.Fill) PaintCheckboxMark(checkbox.canvas, checkbox.bounds, state, look.Mark) if !checkbox.id.IsZero() { hitBounds := gfx.Rect{ diff --git a/components/select.go b/components/select.go index 3c19a791d..f64c5b583 100644 --- a/components/select.go +++ b/components/select.go @@ -64,6 +64,23 @@ type SelectOptions struct { // MenuItemRecipe or from its own look. It is the same code path as the painted select, so // a select of the application's own cannot behave differently. Unpainted bool + // UnpaintedSurface lets the caller's engine paint the trigger's surface, so the + // trigger painter draws only the value (unless UnpaintedValue) and the chevron. + UnpaintedSurface bool + // UnpaintedValue keeps the painter from drawing the trigger's value and icon: + // caller-owned content declared with Children replaces them, while the chevron + // and the trigger's hit stay the control's. + UnpaintedValue bool + // TriggerContent is where the value and icon are laid out, in window + // coordinates: the element's content rect, which keeps the room for the chevron. + TriggerContent gfx.Rect + // TextSize and Weight override the type of the value (Weight is the label's + // weight when non-zero). + TextSize, Weight float32 + // Foreground paints the value (and a single-color icon) instead of the recipe's, + // when HasForeground is set; Chevron paints the arrow when HasChevron is set. + Foreground, Chevron gfx.Color + HasForeground, HasChevron bool } // SelectItem describes one stable value in the open popup. @@ -100,13 +117,18 @@ const SelectIconSpan = selectIconSize + selectIconGap // Only the extra-small step changes the type, as in Button: a compact control // keeps the body size and just gets shorter. func selectTriggerSize(metrics gfx.Metrics, size SelectSize) (height, textSize float32) { + return style.SelectGeometry(metrics, selectStyleSize(size)) +} + +// selectStyleSize is the element size a component select size maps to. +func selectStyleSize(size SelectSize) style.Size { switch size { case SelectSizeSmall: - return metrics.ControlHeight - 4, metrics.FontSizeM + return style.SizeSmall case SelectSizeXSmall: - return metrics.ControlHeight - 8, metrics.FontSizeS + return style.SizeXSmall } - return metrics.ControlHeight, metrics.FontSizeM + return style.SizeDefault } // Select paints a typed native select trigger and, when open, its source-owned @@ -286,32 +308,58 @@ func (selectControl Select) paintTrigger() { bounds := selectControl.triggerBounds options := selectControl.options enabled := !options.TriggerID.IsZero() && !options.Disabled + textSize := selectControl.textSize + if options.TextSize > 0 { + textSize = options.TextSize + } + foreground, chevron := selectControl.theme.Foreground, selectControl.theme.MutedForeground if !options.Unpainted { - state := gfx.State{ - Focused: enabled && canvas.FocusVisible() == options.TriggerID, - Invalid: options.Invalid, - Disabled: options.Disabled, - Hovered: enabled && (canvas.Hovered() == options.TriggerID || canvas.Pressed() == options.TriggerID), + if !options.UnpaintedSurface { + state := gfx.State{ + Focused: enabled && canvas.FocusVisible() == options.TriggerID, + Invalid: options.Invalid, + Disabled: options.Disabled, + Hovered: enabled && (canvas.Hovered() == options.TriggerID || canvas.Pressed() == options.TriggerID), + } + look := selectRecipe(&selectControl.theme, state, options.Value == "") + paintTextEntryLook(canvas, selectControl.theme.Background.Alpha, bounds, look.Surface) + foreground, chevron = look.Foreground, look.Chevron + } + if options.HasForeground { + foreground = options.Foreground + } + if options.HasChevron { + chevron = options.Chevron } - look := selectRecipe(&selectControl.theme, state, options.Value == "") - paintTextEntryLook(canvas, selectControl.theme.Background.Alpha, bounds, look.Surface) - foreground := look.Foreground value := options.Value if value == "" { value = options.Placeholder } // Vega: pl-2.5 and pr-2 inside the border, gap-1.5 before the 16px chevron. const chevronSpan = 1 + 8 + selectIconSize - inset := selectControl.theme.Metrics.TextInsetX() - textX, textWidth := bounds.X+inset, bounds.Width-inset-chevronSpan-6 - if paintSelectIcon(canvas, options.Icon, options.IconImage, options.IconText, gfx.Rect{X: textX, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, foreground, selectControl.textSize) { - textX += SelectIconSpan - textWidth -= SelectIconSpan + inset, _ := style.SelectContentInsets(selectControl.theme.Metrics) + content := options.TriggerContent + if content.Width <= 0 { + content = gfx.Rect{ + X: bounds.X + inset, Y: bounds.Y, + Width: selectMax(0, bounds.Width-inset-chevronSpan-6), Height: bounds.Height, + } } - canvas.Label(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ - Size: selectControl.textSize, Weight: gfx.WeightRegular, Color: foreground, - }) - paintChevron(canvas, &chevronDownIcon, gfx.Rect{X: bounds.X + bounds.Width - chevronSpan, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, look.Chevron) + if !options.UnpaintedValue { + textX, textWidth := content.X, content.Width + if paintSelectIcon(canvas, options.Icon, options.IconImage, options.IconText, gfx.Rect{X: textX, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, foreground, textSize) { + textX += SelectIconSpan + textWidth -= SelectIconSpan + } + weight := gfx.WeightRegular + if options.Weight > 0 { + weight = options.Weight + } + canvas.Label(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + Size: textSize, Weight: weight, Color: foreground, + }) + } + paintChevron(canvas, &chevronDownIcon, gfx.Rect{X: bounds.X + bounds.Width - chevronSpan, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, chevron) } if !options.TriggerID.IsZero() { canvas.HitWithOptions(options.TriggerID, bounds, options.Label, gfx.HitOptions{ diff --git a/components/switch.go b/components/switch.go index 5b5ead4bd..73c7e6dde 100644 --- a/components/switch.go +++ b/components/switch.go @@ -16,6 +16,10 @@ const ( SwitchSizeSmall ) +// SwitchCheckedSlot is the animation slot holding a switch thumb's travel toward +// on; a caller painting the track from the same look asks Canvas.Animate for it. +const SwitchCheckedSlot uint8 = base.SwitchCheckedSlot + // switchSlotChecked is the animation slot holding thumb travel, 0 (off) to 1 (on). const switchSlotChecked uint8 = 0 @@ -30,11 +34,17 @@ type Switch struct { bounds gfx.Rect label string hitBounds gfx.Rect - checked bool - focused bool - invalid bool - size SwitchSize - disabled bool + // unpaintedSurface is set when the caller's engine paints the track's fill, + // border, shadow and ring; Paint then draws only the thumb and the hit. + unpaintedSurface bool + // thumbColor overrides the recipe's thumb when hasThumbColor is set. + thumbColor gfx.Color + hasThumbColor bool + checked bool + focused bool + invalid bool + size SwitchSize + disabled bool // recipe, when set, replaces SwitchRecipe; see Button.Recipe. recipe func(gfx.Theme, gfx.State, float32) SwitchLook } @@ -102,6 +112,21 @@ func (result SwitchResult) Clicked() bool { // The visual track keeps its normal position and size; zero bounds use the // default enlarged target. The rect replaces the track's target rather than // adding to it and must contain the track. +// UnpaintedSurface declares that the caller paints the track's fill, border, +// shadow and ring, as the page's engine does; Paint then draws the thumb, the +// control's own graphic, and its hit. +func (switchControl Switch) UnpaintedSurface() Switch { + switchControl.unpaintedSurface = true + return switchControl +} + +// ThumbColor paints the thumb in color instead of the recipe's, so a caller +// that painted the track from the same look keeps them in step. +func (switchControl Switch) ThumbColor(color gfx.Color) Switch { + switchControl.thumbColor, switchControl.hasThumbColor = color, true + return switchControl +} + func (switchControl Switch) HitBounds(bounds gfx.Rect) Switch { switchControl.hitBounds = bounds return switchControl @@ -156,14 +181,19 @@ func (switchControl Switch) Paint() SwitchResult { FocusVisible: switchControl.focused, Invalid: switchControl.invalid, Disabled: switchControl.disabled, }, progress) } - switchControl.canvas.Elevate(switchControl.bounds, switchControl.bounds.Height/2, look.Shadow) // shadow-xs - if look.Bordered { - switchControl.canvas.Rounded(expand(switchControl.bounds, look.RingWidth), switchControl.bounds.Height/2+look.RingWidth, look.Ring) - paintBordered(switchControl.canvas, switchControl.theme, switchControl.bounds, switchControl.bounds.Height/2, look.Border, look.Track) - } else { - switchControl.canvas.Rounded(switchControl.bounds, switchControl.bounds.Height/2, look.Track) + if !switchControl.unpaintedSurface { + switchControl.canvas.Elevate(switchControl.bounds, switchControl.bounds.Height/2, look.Shadow) // shadow-xs + if look.Bordered { + switchControl.canvas.Rounded(expand(switchControl.bounds, look.RingWidth), switchControl.bounds.Height/2+look.RingWidth, look.Ring) + paintBordered(switchControl.canvas, switchControl.theme, switchControl.bounds, switchControl.bounds.Height/2, look.Border, look.Track) + } else { + switchControl.canvas.Rounded(switchControl.bounds, switchControl.bounds.Height/2, look.Track) + } } thumb := look.Thumb + if switchControl.hasThumbColor { + thumb = switchControl.thumbColor + } // The thumb sits inside the track's 1px border: one pixel from the left edge // when off and one from the right when on (translate-x-[calc(100%-2px)]). diff --git a/components/tabs.go b/components/tabs.go index d6484711d..ca3e5e6c5 100644 --- a/components/tabs.go +++ b/components/tabs.go @@ -3,6 +3,7 @@ package components import ( "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) // Tabs paints a compact Base UI-style tab list. The active tab and associated @@ -21,9 +22,60 @@ type Tabs struct { direction TabsOrientation disabled bool fit bool + style TabsStyle + // unpaintedSurface is set when the caller's engine paints the strip itself, + // as a page's does; BeginTabs users leave it off and get the strip painted. + unpaintedSurface bool // tabStop is the one tab Tab reaches; the arrow helper moves focus among the // rest, which are SkipTab. tabStop gfx.ID + // The strip's effective style, filled from TabStyle's zero fields at Paint. + paint tabsPaint +} + +// TabsStyle overrides what a tab strip paints and how its triggers are laid +// out. Every field is optional: a zero value keeps the size's default, so this +// is how the page passes Pad, Gap, Radius, FontSize, Weight, Color, Background +// and Border of the element down to the component. +type TabsStyle struct { + // ListHeight and ListPadding size the strip; TriggerHeight and TriggerPadding + // size one trigger inside it. LineGap is the gap between line-variant triggers; + // Gap is used for both variants when set. + ListHeight, ListPadding, TriggerHeight, TriggerPadding, LineGap, Gap float32 + // TriggerRadius is a trigger's corner radius; the strip's own radius is the + // element's Radius, painted by the engine. + TriggerRadius float32 + // FontSize and Weight style a trigger's label and icon. + FontSize, Weight float32 + // Fill paints the list's surface when HasFill is set; Border draws its line + // when HasBorder is set. Foreground replaces the label color when HasForeground + // is set, keeping the selected, hovered and disabled dimming. + Fill, Border, Foreground gfx.Color + HasFill, HasBorder bool + HasForeground bool +} + +// tabsPaint is TabsStyle resolved against the theme at Paint. +type tabsPaint struct { + listHeight, listPadding, triggerHeight, triggerPadding, lineGap, gap float32 + listRadius, triggerRadius, fontSize, weight float32 + foreground gfx.Color + hasForeground bool +} + +// WithStyle overrides the strip's measurements, colors and label style; zero +// fields keep the size's defaults. +func (tabs Tabs) WithStyle(style TabsStyle) Tabs { + tabs.style = style + return tabs +} + +// UnpaintedSurface declares that the caller paints the strip's own surface +// behind the triggers, as the page's engine does; Paint then draws only the +// triggers and their indicator. +func (tabs Tabs) UnpaintedSurface() Tabs { + tabs.unpaintedSurface = true + return tabs } // Line selects the transparent list with a two-pixel active indicator. @@ -150,27 +202,73 @@ const ( tabsTriggerHeight = 30 // list height less its padding ) +// resolvedPaint is the strip's style with the theme defaults filled in and the +// caller's overrides applied. +func (tabs Tabs) resolvedPaint() tabsPaint { + metrics := tabs.theme.Metrics + defHeight, defPadding, defTriggerHeight, defTriggerPad, defLineGap, defFont, defWeight := style.TabsGeometry(metrics) + p := tabsPaint{ + listHeight: defHeight, listPadding: defPadding, + triggerHeight: defTriggerHeight, triggerPadding: defTriggerPad, + lineGap: defLineGap, gap: 0, + listRadius: style.TabsListRadius(metrics), triggerRadius: style.TabsTriggerRadius(metrics), + fontSize: defFont, weight: defWeight, + } + override := tabs.style + if override.ListHeight > 0 { + p.listHeight = override.ListHeight + } + if override.ListPadding > 0 { + p.listPadding = override.ListPadding + } + if override.TriggerHeight > 0 { + p.triggerHeight = override.TriggerHeight + } + if override.TriggerPadding > 0 { + p.triggerPadding = override.TriggerPadding + } + if override.LineGap > 0 { + p.lineGap = override.LineGap + } + if override.Gap > 0 { + p.gap = override.Gap + } + if override.TriggerRadius > 0 { + p.triggerRadius = override.TriggerRadius + } + if override.FontSize > 0 { + p.fontSize = override.FontSize + } + if override.Weight > 0 { + p.weight = override.Weight + } + if override.HasForeground { + p.foreground, p.hasForeground = override.Foreground, true + } + return p +} + // Paint draws the list and independently focusable tab triggers. func (tabs Tabs) Paint() TabsResult { result := TabsResult{canvas: tabs.canvas, list: tabs.list} if tabs.canvas == nil || tabs.count() == 0 { return result } - metrics := tabs.theme.Metrics - weight := gfx.WeightMedium + tabs.paint = tabs.resolvedPaint() + weight := tabs.paint.weight gap := tabs.itemGap() count := float32(tabs.count()) if tabs.fit { var widest, total float32 for index := range tabs.count() { - width := tabs.contentWidth(tabs.option(index)) + tabsTriggerPad*2 + width := tabs.contentWidth(tabs.option(index)) + tabs.paint.triggerPadding*2 widest = max(widest, width) total += width } if tabs.direction == TabsVertical { - tabs.bounds.Width = widest + tabsPadding*2 + tabs.bounds.Width = widest + tabs.paint.listPadding*2 } else { - tabs.bounds.Width = total + gap*(count-1) + tabsPadding*2 + tabs.bounds.Width = total + gap*(count-1) + tabs.paint.listPadding*2 } } if tabs.bounds.Width <= 0 { @@ -178,24 +276,26 @@ func (tabs Tabs) Paint() TabsResult { } if tabs.bounds.Height <= 0 { if tabs.direction == TabsVertical { - tabs.bounds.Height = tabsTriggerHeight*count + gap*(count-1) + tabsPadding*2 + tabs.bounds.Height = tabs.paint.triggerHeight*count + gap*(count-1) + tabs.paint.listPadding*2 } else { - tabs.bounds.Height = tabsListHeight + tabs.bounds.Height = tabs.paint.listHeight } } result.bounds = tabs.bounds - radius := metrics.RadiusControl - listFill := tabs.theme.Muted - listRadius := radius + 2 - if tabs.variant == TabsLine { - listFill = tabs.theme.Background - listFill.Alpha = 0 - listRadius = 0 + triggerRadius := tabs.paint.triggerRadius + if !tabs.unpaintedSurface { + listFill := tabs.theme.Muted + listRadius := tabs.paint.listRadius + if tabs.variant == TabsLine { + listFill = tabs.theme.Background + listFill.Alpha = 0 + listRadius = 0 + } + tabs.canvas.Rounded(tabs.bounds, listRadius, listFill) } - tabs.canvas.Rounded(tabs.bounds, listRadius, listFill) inner := gfx.Rect{ - X: tabs.bounds.X + tabsPadding, Y: tabs.bounds.Y + tabsPadding, - Width: tabs.bounds.Width - tabsPadding*2, Height: tabs.bounds.Height - tabsPadding*2, + X: tabs.bounds.X + tabs.paint.listPadding, Y: tabs.bounds.Y + tabs.paint.listPadding, + Width: tabs.bounds.Width - tabs.paint.listPadding*2, Height: tabs.bounds.Height - tabs.paint.listPadding*2, } cursor := float32(0) for index := range tabs.count() { @@ -211,14 +311,32 @@ func (tabs Tabs) Paint() TabsResult { state.FocusVisible = tabs.canvas.FocusVisible() == option.ID } look := tabTriggerRecipe(&tabs.theme, tabs.variant, state) + if tabs.paint.hasForeground { + foreground := tabs.paint.foreground + hovered := !state.Disabled && state.Hovered + if !state.Selected && !hovered { + foreground.Alpha *= 0.60 + } + if state.Disabled { + foreground.Alpha *= 0.50 + } + look.Foreground = foreground + if look.Indicator.Alpha > 0 { + indicator := tabs.paint.foreground + if state.Disabled { + indicator.Alpha *= 0.50 + } + look.Indicator = indicator + } + } if look.RingWidth > 0 { tabs.canvas.Rounded(expand(trigger, look.RingWidth), look.RingRadius, look.Ring) } if look.Bordered { - tabs.canvas.Elevate(trigger, radius, look.Shadow) // the selected trigger's shadow-sm - tabs.canvas.RoundedBorder(trigger, radius, 1, look.Border, look.Fill) + tabs.canvas.Elevate(trigger, triggerRadius, look.Shadow) // the selected trigger's shadow-sm + tabs.canvas.RoundedBorder(trigger, triggerRadius, 1, look.Border, look.Fill) } else { - tabs.canvas.Rounded(trigger, radius, look.Fill) + tabs.canvas.Rounded(trigger, triggerRadius, look.Fill) } indicator := look.Indicator @@ -228,8 +346,8 @@ func (tabs Tabs) Paint() TabsResult { } tabs.canvas.Rounded(indicatorBounds, 1, indicator) - style := gfx.TextStyle{Size: metrics.FontSizeM, Weight: weight, Color: look.Foreground} - tabs.paintContent(option, trigger, style) + textStyle := gfx.TextStyle{Size: tabs.paint.fontSize, Weight: weight, Color: look.Foreground} + tabs.paintContent(option, trigger, textStyle) if !option.ID.IsZero() { hint := "" if option.IconOnly { @@ -249,13 +367,16 @@ func (tabs Tabs) Paint() TabsResult { // triggerBounds returns the index-th trigger inside the list's padded interior. // cursor is the distance already used along the row in Fit mode. func (tabs Tabs) triggerBounds(inner gfx.Rect, index int, count, cursor float32) gfx.Rect { + if tabs.paint.fontSize == 0 { + tabs.paint = tabs.resolvedPaint() + } gap := tabs.itemGap() if tabs.direction == TabsVertical { height := (inner.Height - gap*(count-1)) / count return gfx.Rect{X: inner.X, Y: inner.Y + float32(index)*(height+gap), Width: inner.Width, Height: height} } if tabs.fit { - width := tabs.contentWidth(tabs.option(index)) + tabsTriggerPad*2 + width := tabs.contentWidth(tabs.option(index)) + tabs.paint.triggerPadding*2 return gfx.Rect{X: inner.X + cursor, Y: inner.Y, Width: width, Height: inner.Height} } width := (inner.Width - gap*(count-1)) / count @@ -263,19 +384,28 @@ func (tabs Tabs) triggerBounds(inner gfx.Rect, index int, count, cursor float32) } func (tabs Tabs) itemGap() float32 { + if tabs.paint.fontSize == 0 { + tabs.paint = tabs.resolvedPaint() + } + if tabs.paint.gap > 0 { + return tabs.paint.gap + } if tabs.variant == TabsLine { - return tabsLineGap + return tabs.paint.lineGap } return 0 } func (tabs Tabs) contentWidth(option TabOption) float32 { + if tabs.paint.fontSize == 0 { + tabs.paint = tabs.resolvedPaint() + } width := float32(0) if !option.IconOnly { - width = tabs.canvas.TextWidthWeight(option.Label, tabs.theme.Metrics.FontSizeM, gfx.WeightMedium) + width = tabs.canvas.TextWidthWeight(option.Label, tabs.paint.fontSize, tabs.paint.weight) } if len(option.Icon.Commands) > 0 || len(option.Icon.Layers) > 0 { - width += tabs.theme.Metrics.FontSizeM + width += tabs.paint.fontSize if option.Label != "" && !option.IconOnly { width += 6 } @@ -284,7 +414,10 @@ func (tabs Tabs) contentWidth(option TabOption) float32 { } func (tabs Tabs) paintContent(option TabOption, trigger gfx.Rect, style gfx.TextStyle) { - b := gfx.Rect{X: trigger.X + tabsTriggerPad, Y: trigger.Y, Width: max(0, trigger.Width-tabsTriggerPad*2), Height: trigger.Height} + if tabs.paint.fontSize == 0 { + tabs.paint = tabs.resolvedPaint() + } + b := gfx.Rect{X: trigger.X + tabs.paint.triggerPadding, Y: trigger.Y, Width: max(0, trigger.Width-tabs.paint.triggerPadding*2), Height: trigger.Height} tabs.canvas.Clip(trigger) defer tabs.canvas.Unclip() if len(option.Icon.Commands) == 0 && len(option.Icon.Layers) == 0 { @@ -295,7 +428,7 @@ func (tabs Tabs) paintContent(option TabOption, trigger gfx.Rect, style gfx.Text } return } - size := min(tabs.theme.Metrics.FontSizeM, max(0, b.Height)) + size := min(tabs.paint.fontSize, max(0, b.Height)) gap := float32(0) if option.Label != "" && !option.IconOnly { gap = 6 @@ -317,6 +450,18 @@ func (tabs Tabs) paintContent(option TabOption, trigger gfx.Rect, style gfx.Text tabs.canvas.Label(text, b, style) } +// TabsListRecipe resolves the look of the strip behind a tab list: its fill and +// its corner radius. The line variant draws no strip, so it is not filled. +func TabsListRecipe(theme gfx.Theme, variant TabsVariant) style.ButtonLook { + if variant == TabsLine { + return style.ButtonLook{} + } + return style.ButtonLook{ + Background: theme.Muted, Filled: true, + Radius: style.TabsListRadius(theme.Metrics), + } +} + // TabTriggerLook is the look of one tab of a strip in one state. type TabTriggerLook struct { // Fill is the trigger's background, transparent unless the tab is the selected one of diff --git a/components/textarea.go b/components/textarea.go index 6e4515c0c..8fdff6d3c 100644 --- a/components/textarea.go +++ b/components/textarea.go @@ -72,7 +72,7 @@ func paintTextareaContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, area gfx. options := gfx.HitOptions{ Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, Disabled: snapshot.Disabled, ReadOnly: snapshot.ReadOnly, Multiline: true, Invalid: snapshot.Invalid, - TextBounds: content, TextSize: theme.Metrics.FontSizeM, TextColor: theme.Foreground, + TextBounds: content, TextSize: textareaHitSize(theme, snapshot), TextColor: theme.Foreground, } if snapshot.HideEditorText { options.TextColor = gfx.Color{} @@ -121,8 +121,27 @@ func (rows *textareaRows) next() (row gfx.TextRow, after int, ok bool) { return row, rows.from, true } +// textareaHitSize is the text size a textarea reports to the platform. +func textareaHitSize(theme gfx.Theme, snapshot TextareaSnapshot) float32 { + size, _ := textareaTextStyle(theme, snapshot) + return size +} + +// textareaTextStyle is the size and weight of a textarea's rows: the +// snapshot's own when set, else the theme's body size at the regular weight. +func textareaTextStyle(theme gfx.Theme, snapshot TextareaSnapshot) (size, weight float32) { + size, weight = theme.Metrics.FontSizeM, gfx.WeightRegular + if snapshot.TextSize > 0 { + size = snapshot.TextSize + } + if snapshot.TextWeight > 0 { + weight = snapshot.TextWeight + } + return size, weight +} + func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot TextareaSnapshot, focused bool) { - fontSize := theme.Metrics.FontSizeM + fontSize, weight := textareaTextStyle(theme, snapshot) lineHeight := fontSize + 7 placeholderShown := value == "" if placeholderShown { @@ -187,7 +206,7 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val line = trimTrailingSpaces(line) } lineEnd := row.Start + len(line) - style := gfx.TextStyle{Size: fontSize, Weight: gfx.WeightRegular, Color: color} + style := gfx.TextStyle{Size: fontSize, Weight: weight, Color: color} origin := canvas.LabelOrigin(line, lineBounds, style, gfx.AlignStart) labelBounds := lineBounds if origin == lineBounds.X { @@ -255,7 +274,7 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val if snapshot.Disabled { selectedColor.Alpha *= 0.50 } - canvas.Label(line, labelBounds, gfx.TextStyle{Size: fontSize, Weight: gfx.WeightRegular, Color: selectedColor}) + canvas.Label(line, labelBounds, gfx.TextStyle{Size: fontSize, Weight: weight, Color: selectedColor}) canvas.Unclip() } } diff --git a/components/toggle.go b/components/toggle.go index dffc591f1..1691e4820 100644 --- a/components/toggle.go +++ b/components/toggle.go @@ -1,6 +1,9 @@ package components -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) // ToggleVariant selects the neutral or bordered treatment. type ToggleVariant uint8 @@ -19,6 +22,52 @@ const ( ToggleSizeLarge ) +// ToggleRecipe resolves the look of a toggle of one variant in one state: the +// fill, the label, the line, the focus ring and the shadow. Checked is the +// active state; hover, press, focus and invalid are read only while the toggle +// is not disabled, and Disabled dims the fill, the label and the line by half. +func ToggleRecipe(theme gfx.Theme, variant ToggleVariant, state gfx.State) style.ButtonLook { + radius := theme.Metrics.RadiusControl + fill := theme.Background + fill.Alpha = 0 + foreground := theme.Foreground + border := theme.Input + bordered := variant == ToggleOutline + if state.Checked { + fill = theme.Muted + } + if state.Hovered && !state.Disabled { + fill = theme.Muted + foreground = theme.Foreground + } + if state.Pressed && !state.Disabled { + fill = blend(fill, theme.Foreground, 0.05) + } + look := style.ButtonLook{ + Background: fill, Foreground: foreground, Border: border, + Filled: true, Bordered: bordered, Radius: radius, + } + if variant == ToggleOutline { + look.Shadow = gfx.ShadowXS + } + // The component draws an invalid ring even on a disabled toggle; focus is + // the keyboard's, so it stops when the toggle is unavailable. + if state.Invalid || state.FocusVisible && !state.Disabled { + ring, edge := scaledAlpha(theme.Ring, 0.50), theme.Ring + if state.Invalid { + ring, edge = invalidRing(&theme), invalidBorder(&theme) + } + look.Ring, look.RingWidth, look.RingRadius = ring, 3, radius+3 + look.Border, look.Bordered = edge, true + } + if state.Disabled { + look.Background.Alpha *= 0.50 + look.Foreground.Alpha *= 0.50 + look.Border.Alpha *= 0.50 + } + return look +} + // Toggle paints one two-state compact action. The application owns active // state and responds to the stable Canvas hit ID. type Toggle struct { @@ -64,8 +113,9 @@ func (toggle Toggle) Disabled() Toggle { // SizeToFit widens the toggle to its label plus Vega's px-2.5, never narrower // than it is tall (min-w). func (toggle Toggle) SizeToFit(label string) Toggle { - toggle.bounds.Height = toggle.controlHeight() - toggle.bounds.Width = toggleFittedWidth(toggle.canvas, toggle.theme, label, toggle.bounds.Height, 10) + height, padding, _ := style.ToggleGeometry(toggle.theme.Metrics, toggleStyleSize(toggle.size)) + toggle.bounds.Height = height + toggle.bounds.Width = toggleFittedWidth(toggle.canvas, toggle.theme, label, height, padding) return toggle } @@ -112,51 +162,26 @@ func (toggle Toggle) paint(label string, variant ToggleVariant) ToggleResult { if toggle.bounds.Width <= 0 { toggle.bounds.Width = toggle.bounds.Height } - enabled := !toggle.disabled && !toggle.id.IsZero() - hovered := enabled && toggle.canvas.Hovered() == toggle.id - pressed := enabled && toggle.canvas.Pressed() == toggle.id - focused := enabled && toggle.canvas.FocusVisible() == toggle.id - radius := toggle.theme.Metrics.RadiusControl - border := toggle.theme.Input - if focused || toggle.invalid { - focus := scaledAlpha(toggle.theme.Ring, 0.50) - border = toggle.theme.Ring - if toggle.invalid { - focus, border = invalidRing(&toggle.theme), invalidBorder(&toggle.theme) - } - toggle.canvas.Rounded(expand(toggle.bounds, 3), radius+3, focus) - } - - fill := toggle.theme.Background - fill.Alpha = 0 - foreground := toggle.theme.Foreground - if toggle.active { - fill = toggle.theme.Muted - } - if hovered { - fill = toggle.theme.Muted - foreground = toggle.theme.Foreground + state := gfx.State{Checked: toggle.active, Invalid: toggle.invalid, Disabled: toggle.disabled} + if !toggle.disabled && !toggle.id.IsZero() { + state.Hovered = toggle.canvas.Hovered() == toggle.id + state.Pressed = toggle.canvas.Pressed() == toggle.id + state.FocusVisible = toggle.canvas.FocusVisible() == toggle.id } - if pressed { - fill = blend(fill, toggle.theme.Foreground, 0.05) + look := ToggleRecipe(toggle.theme, variant, state) + if look.Shadow != gfx.ShadowNone { + toggle.canvas.Elevate(toggle.bounds, look.Radius, look.Shadow) // shadow-xs } - if toggle.disabled { - fill.Alpha *= 0.50 - foreground.Alpha *= 0.50 + if look.RingWidth > 0 { + toggle.canvas.Rounded(expand(toggle.bounds, look.RingWidth), look.RingRadius, look.Ring) } - if variant == ToggleOutline || toggle.invalid || focused { - if variant == ToggleOutline { - toggle.canvas.Elevate(toggle.bounds, radius, gfx.ShadowXS) // shadow-xs - } - if toggle.disabled { - border.Alpha *= 0.50 - } - paintBordered(toggle.canvas, toggle.theme, toggle.bounds, radius, border, fill) - } else { - toggle.canvas.Rounded(toggle.bounds, radius, fill) + if look.Bordered && look.Filled { + paintBordered(toggle.canvas, toggle.theme, toggle.bounds, look.Radius, look.Border, look.Background) + } else if look.Filled { + toggle.canvas.Rounded(toggle.bounds, look.Radius, look.Background) } toggle.canvas.LabelCenter(label, toggle.bounds, gfx.TextStyle{ - Size: toggle.theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: foreground, + Size: toggle.theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: look.Foreground, }) if !toggle.id.IsZero() { toggle.canvas.HitWithOptions(toggle.id, toggle.bounds, label, gfx.HitOptions{ @@ -172,15 +197,19 @@ func (toggle Toggle) controlHeight() float32 { } func toggleControlHeight(theme gfx.Theme, size ToggleSize) float32 { - height := theme.Metrics.ControlHeight + height, _, _ := style.ToggleGeometry(theme.Metrics, toggleStyleSize(size)) + return height +} + +// toggleStyleSize is the element size a component toggle size maps to; both +// the node measurement and the component's SizeToFit take their metrics from +// style.ToggleGeometry. +func toggleStyleSize(size ToggleSize) style.Size { switch size { case ToggleSizeSmall: - height -= 4 + return style.SizeSmall case ToggleSizeLarge: - height += 4 - } - if height < 20 { - height = 20 + return style.SizeLarge } - return height + return style.SizeDefault } diff --git a/components/toggle_recipe_test.go b/components/toggle_recipe_test.go new file mode 100644 index 000000000..e17ed9588 --- /dev/null +++ b/components/toggle_recipe_test.go @@ -0,0 +1,119 @@ +package components + +import ( + "reflect" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +// A toggle of the page's own, dressed from ToggleRecipe with the canvas calls +// the engine makes, is the toggle the component paints: for every theme, +// variant, size and state the surface is the same shapes in the same colors. +func TestToggleRecipePaintsTheToggleAsTheComponentDoes(t *testing.T) { + variants := map[string]ToggleVariant{"default": ToggleDefault, "outline": ToggleOutline} + sizes := map[string]struct { + small, large bool + height float32 + }{"default": {height: 32}, "small": {small: true, height: 28}, "large": {large: true, height: 36}} + states := map[string]gfx.State{ + "rest": {}, "active": {Checked: true}, "hover": {Hovered: true}, + "pressed": {Hovered: true, Pressed: true}, "focus": {FocusVisible: true}, + "invalid": {Invalid: true}, "disabled": {Disabled: true}, + "disabled active": {Disabled: true, Checked: true}, "disabled invalid": {Disabled: true, Invalid: true}, + } + for themeName, theme := range recipeThemes() { + for variantName, variant := range variants { + for sizeName, size := range sizes { + for stateName, state := range states { + t.Run(themeName+"/"+variantName+"/"+sizeName+"/"+stateName, func(t *testing.T) { + id := gfx.Item(1) + bounds := gfx.Rect{X: 4, Y: 4, Width: 90, Height: size.height} + want := measured() + if !state.Disabled { + hovered, pressed, focused := gfx.ID{}, gfx.ID{}, gfx.ID{} + if state.Hovered { + hovered = id + } + if state.Pressed { + pressed = id + } + if state.FocusVisible { + focused = id + } + want.SetInteraction(hovered, pressed, focused, state.FocusVisible) + } + toggle := BeginToggle(want, theme, id, bounds, state.Checked) + if size.small { + toggle = toggle.Small() + } + if size.large { + toggle = toggle.Large() + } + if state.Disabled { + toggle = toggle.Disabled() + } + if state.Invalid { + toggle = toggle.Invalid() + } + if variant == ToggleOutline { + toggle.Outline("Bold") + } else { + toggle.Default("Bold") + } + + got := measured() + look := ToggleRecipe(theme, variant, state) + if look.Shadow != gfx.ShadowNone { + got.Elevate(bounds, look.Radius, look.Shadow) + } + if look.RingWidth > 0 { + got.Rounded(expand(bounds, look.RingWidth), look.RingRadius, look.Ring) + } + background := gfx.Color{} + if look.Filled { + background = look.Background + } + bordered := look.Bordered && look.Filled + if bordered && theme.Background.Alpha >= 1 { + background = background.Over(theme.Background) + look.Border = look.Border.Over(theme.Background) + } + switch { + case bordered: + paintBordered(got, theme, bounds, look.Radius, look.Border, background) + case look.Filled: + got.Rounded(bounds, look.Radius, background) + } + if !reflect.DeepEqual(noOrders(want.Rectangles()), noOrders(got.Rectangles())) { + t.Errorf("recipe and component differ:\nwant %+v\n got %+v", want.Rectangles(), got.Rectangles()) + } + }) + } + } + } + } +} + +// The recipe gives the same geometry the component fits: the size's height, +// 10px either side and the medium font, never shorter than 20. +func TestToggleGeometryMatchesTheComponent(t *testing.T) { + for name, theme := range recipeThemes() { + for sizeName, size := range map[string]ToggleSize{"default": ToggleSizeDefault, "small": ToggleSizeSmall, "large": ToggleSizeLarge} { + height, padding, fontSize := style.ToggleGeometry(theme.Metrics, toggleStyleSize(size)) + if got := toggleControlHeight(theme, size); got != height { + t.Errorf("%s/%s: component height %v, geometry %v", name, sizeName, got, height) + } + if padding != 10 { + t.Errorf("%s/%s: padding %v, want 10", name, sizeName, padding) + } + if fontSize != theme.Metrics.FontSizeM { + t.Errorf("%s/%s: font size %v, want %v", name, sizeName, fontSize, theme.Metrics.FontSizeM) + } + if height < 20 { + t.Errorf("%s/%s: height %v below 20", name, sizeName, height) + } + } + } +} diff --git a/style/badge.go b/style/badge.go new file mode 100644 index 000000000..05e90bb21 --- /dev/null +++ b/style/badge.go @@ -0,0 +1,12 @@ +package style + +import "github.com/vivaui/viva/gfx" + +// BadgeGeometry is what a theme's metrics give a badge: the height of its chip, +// the padding either side of its content, the radius that makes it a pill (half +// the height) and the size of its label. Vega scales the chip at 20/32 of the +// control height and pads it by 9/32 either side. +func BadgeGeometry(m gfx.Metrics) (height, padding, radius, fontSize float32) { + scale := m.ControlHeight / 32 + return 20 * scale, 9 * scale, 10 * scale, m.FontSizeS +} diff --git a/style/select.go b/style/select.go new file mode 100644 index 000000000..6d499887e --- /dev/null +++ b/style/select.go @@ -0,0 +1,40 @@ +package style + +import "github.com/vivaui/viva/gfx" + +// The select trigger's parts: the arrow's square, the gap before it, and the +// slack the value keeps before that gap. They are Vega's px-2, gap-1.5 and the +// 16px chevron. +const ( + SelectChevronSize = 16 + SelectChevronGap = 6 + SelectValueSlack = 6 +) + +// SelectGeometry is what a theme's metrics give a select trigger at a size: its +// height and the size of its value. Only the extra-small step changes the type. +func SelectGeometry(m gfx.Metrics, size Size) (height, textSize float32) { + switch size { + case SizeSmall: + return m.ControlHeight - 4, m.FontSizeM + case SizeXSmall: + return m.ControlHeight - 8, m.FontSizeS + } + return m.ControlHeight, m.FontSizeM +} + +// SelectContentInsets is the room the trigger leaves inside its edge for the +// value: the text inset on the left, and on the right the inset less its border +// plus the gap, the chevron and the slack. +func SelectContentInsets(m gfx.Metrics) (left, right float32) { + left = m.TextInsetX() + right = left - 2 + SelectValueSlack + SelectChevronSize + return left, right +} + +// SelectDefaultWidth is what a trigger with the widest value needs beyond that +// value: its content insets and the slack before the chevron. +func SelectDefaultWidth(m gfx.Metrics) float32 { + left, right := SelectContentInsets(m) + return left + right + SelectValueSlack +} diff --git a/style/tabs.go b/style/tabs.go new file mode 100644 index 000000000..e596f4eae --- /dev/null +++ b/style/tabs.go @@ -0,0 +1,29 @@ +package style + +import "github.com/vivaui/viva/gfx" + +// A tab strip's metrics: the list's height and padding, its triggers' height and +// padding, the gap between line-variant triggers, and the line indicator that the +// line variant draws just past the active trigger. They are Vega's numbers. +const ( + TabsListHeight = 36 + TabsListPadding = 3 + TabsTriggerHeight = 30 + TabsTriggerPadding = 9 + TabsLineGap = 4 + TabsIndicator = 2 + TabsLineDrop = 3 +) + +// TabsGeometry is what a theme's metrics give a tab strip: its height, the +// padding inside the list, a trigger's height and padding either side of its +// content, the gap between line-variant triggers, and the size and weight of a +// trigger's label. +func TabsGeometry(m gfx.Metrics) (listHeight, listPadding, triggerHeight, triggerPadding, lineGap, fontSize, weight float32) { + return TabsListHeight, TabsListPadding, TabsTriggerHeight, TabsTriggerPadding, TabsLineGap, m.FontSizeM, gfx.WeightMedium +} + +// TabsListRadius is the corner radius of the strip behind its triggers, and +// TabsTriggerRadius the radius of one trigger's surface. +func TabsListRadius(m gfx.Metrics) float32 { return m.RadiusControl + 2 } +func TabsTriggerRadius(m gfx.Metrics) float32 { return m.RadiusControl } diff --git a/style/toggle.go b/style/toggle.go new file mode 100644 index 000000000..7b91745ce --- /dev/null +++ b/style/toggle.go @@ -0,0 +1,21 @@ +package style + +import "github.com/vivaui/viva/gfx" + +// ToggleGeometry is what a toggle's size gives it at a theme's metrics: its +// height, the padding either side of its content and the size of its label. +// The width is at least the height (shadcn's min-w), which the layout applies +// as the element's MinS. +func ToggleGeometry(m gfx.Metrics, size Size) (height, padding, fontSize float32) { + height, padding, fontSize = m.ControlHeight, 10, m.FontSizeM + switch size { + case SizeSmall: + height = m.ControlHeight - 4 + case SizeLarge: + height = m.ControlHeight + 4 + } + if height < 20 { + height = 20 + } + return height, padding, fontSize +} diff --git a/ui/badge_page_test.go b/ui/badge_page_test.go new file mode 100644 index 000000000..0d8c3327d --- /dev/null +++ b/ui/badge_page_test.go @@ -0,0 +1,190 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" + "github.com/vivaui/viva/ui" +) + +// The calls a page makes on a Badge reach its chip and label: FontSize, Weight +// and Color the text, Width and Height the chip, Radius its corners. +func TestBadgePagePropertiesReachTheChip(t *testing.T) { + ink := gfx.Color{Red: 1, Alpha: 1} + var target gfx.Hit + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Badge(c, "beta").FontSize(18).Weight(gfx.WeightBold).Color(ink). + Width(120).Height(40).Radius(7).Hit(gfx.Item(3), "beta") + }) + }) + snapshot := d.driver.Snapshot() + for _, hit := range snapshot.Hits { + if hit.ID == gfx.Item(3) { + target = hit + } + } + if target.ID != gfx.Item(3) { + t.Fatalf("the badge declared no hit: %+v", snapshot.Hits) + } + if target.Bounds.Width != 120 || target.Bounds.Height != 40 { + t.Errorf("chip = %v, want 120x40", target.Bounds) + } + var text gfx.Text + for _, painted := range snapshot.Texts { + if painted.Value == "beta" { + text = painted + } + } + if text.Value != "beta" { + t.Fatalf("the badge label was not painted: %+v", snapshot.Texts) + } + if text.Style.Size != 18 || text.Style.Weight != gfx.WeightBold || text.Style.Color != ink { + t.Errorf("label style = %+v, want size 18, bold, red", text.Style) + } + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Bounds == target.Bounds { + found = true + if primitive.Radius != 7 { + t.Errorf("chip radius = %v, want the explicit 7", primitive.Radius) + } + } + } + if !found { + t.Errorf("no chip rectangle for %v", target.Bounds) + } +} + +// Children replace the label; the badge stays one button for the pointer. +func TestBadgePageChildrenReplaceTheLabel(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Badge(c, "beta").Hit(gfx.Item(4), "beta").Children(func() { + ui.Text(c, "one") + ui.Text(c, "two") + }) + }) + }) + snapshot := d.driver.Snapshot() + for _, text := range snapshot.Texts { + if text.Value == "beta" { + t.Errorf("the label was painted over the children: %+v", snapshot.Texts) + } + } + var target gfx.Hit + for _, hit := range snapshot.Hits { + if hit.ID == gfx.Item(4) { + target = hit + } + } + if target.Role != gfx.RoleButton || target.Label != "beta" { + t.Errorf("hit = %+v, want one button named beta", target) + } + for _, text := range snapshot.Texts { + if text.Value != "one" && text.Value != "two" { + continue + } + if text.Bounds.X < target.Bounds.X || text.Bounds.X+text.Bounds.Width > target.Bounds.X+target.Bounds.Width { + t.Errorf("child %q at %v is outside the chip %v", text.Value, text.Bounds, target.Bounds) + } + } +} + +// A page's Styles.Badge dresses every badge of the page: the chip takes the +// page's fill, radius and label color. +func TestPageStylesDressBadges(t *testing.T) { + fill := gfx.Color{Red: 0.1, Green: 0.4, Blue: 0.2, Alpha: 1} + ink := gfx.Color{Red: 0.9, Green: 0.9, Blue: 0.1, Alpha: 1} + styles := &ui.Styles{Badge: func(gfx.Theme, style.Variant, gfx.State) style.ButtonLook { + return style.ButtonLook{Background: fill, Foreground: ink, Filled: true, Radius: 4} + }} + d := openPageWith(t, ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { ui.Badge(c, "beta").Hit(gfx.Item(5), "beta") }) + }, + Styles: styles, + }, app.Config{}) + snapshot := d.driver.Snapshot() + var target gfx.Hit + for _, hit := range snapshot.Hits { + if hit.ID == gfx.Item(5) { + target = hit + } + } + chip := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Bounds == target.Bounds { + chip = true + if primitive.Color != fill || primitive.Radius != 4 { + t.Errorf("chip = %v radius %v, want the page recipe's %v radius 4", primitive.Color, primitive.Radius, fill) + } + } + } + if !chip { + t.Fatalf("no chip authored by the page recipe for %v", target.Bounds) + } + label := false + for _, text := range snapshot.Texts { + if text.Value == "beta" { + label = true + if text.Style.Color != ink { + t.Errorf("label color = %v, want the page recipe's %v", text.Style.Color, ink) + } + } + } + if !label { + t.Error("the badge label was not painted") + } +} + +// A steady page of badges allocates nothing: the recipe defaults and the node +// layout reuse the frame's arena. +func TestPageOfBadgesAllocatesNothing(t *testing.T) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + for range 3 { + drawPage(page, canvas, denseBadges) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, denseBadges) }); allocs != 0 { + t.Fatalf("a steady page of badges allocates %v times", allocs) + } +} + +// BenchmarkPageBadges is the page-level cost of themed badges, for the stage-2 +// regression budget. +func BenchmarkPageBadges(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, denseBadges) + } +} + +var badgeLabels = [...]string{"beta", "new", "deprecated", "stable", "linked"} + +var badgeVariants = [...]func(ui.Box) ui.Box{ + func(b ui.Box) ui.Box { return b }, + func(b ui.Box) ui.Box { return b.Secondary() }, + func(b ui.Box) ui.Box { return b.Outline() }, + func(b ui.Box) ui.Box { return b.Ghost() }, + func(b ui.Box) ui.Box { return b.Link() }, +} + +// denseBadges is a page made of badges, as a status-heavy workbench row is: +// every variant, with and without Hit, in several rows. +func denseBadges(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(6).Children(func() { + for row := 0; row < 20; row++ { + ui.Row(c).FillWidth().Gap(6).Children(func() { + for i, label := range badgeLabels { + badge := badgeVariants[(row+i)%len(badgeVariants)](ui.Badge(c, label)) + if (row+i)%2 == 0 { + badge.Hit(gfx.Item(row*len(badgeLabels)+i), label) + } + } + }) + } + }) +} diff --git a/ui/badge_paint.go b/ui/badge_paint.go index d5ae47ef6..60620e713 100644 --- a/ui/badge_paint.go +++ b/ui/badge_paint.go @@ -3,6 +3,7 @@ package ui import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) // badgeVariant is the chip's look, from the variant the Button methods chose: @@ -24,16 +25,38 @@ func badgeVariant(Variant components.ButtonVariant) components.BadgeVariant { return components.BadgeDefault } -// paintBadge paints the chip the view measured, and its hit when one was -// declared. -func paintBadge(f *Frame, v ControlView) { - rect := v.Rect - components.PaintBadge(f.Surface, f.Palette, Rect{X: rect.X, Y: rect.Y}, v.Text, badgeVariant(v.Variant)) - if v.HasHit && !v.ID.IsZero() { - options := v.Hit - if options.Role == 0 { - options.Role = gfx.RoleButton - } - f.Surface.HitWithOptions(v.ID, rect, v.Label, options) +// frameBadgeLook is the recipe a badge is dressed with: the page's Styles.Badge +// when it set one, else the theme's. A badge is presentational, so the state +// only reaches a page recipe that asks for it. +func frameBadgeLook(f *Frame, n *Node, Palette *Theme, state gfx.State) components.ButtonLook { + if f.GetStyles() != nil && f.GetStyles().Badge != nil { + return f.GetStyles().Badge(*Palette, n.Variant, state) } + return components.BadgeRecipe(*Palette, badgeVariant(n.Variant), state) +} + +// paintBadge paints the default label of a badge; the engine paints the chip's +// surface around it and clips it to the content area. Content of the caller's +// own is declared with Children and laid out by the engine instead. +func paintBadge(f *Frame, n *Node) { + if n.Flags&FlagChildren != 0 { + return + } + _, _, _, fontSize := style.BadgeGeometry(f.Palette.Metrics) + if n.FontSize > 0 { + fontSize = n.FontSize + } + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + area := buttonContentArea(f, n) + room := f.ContentRect(n) + if room.Width > 0 && f.Surface.TextWidthWeight(n.Label, fontSize, weight) > room.Width { + f.Surface.Clip(room) + defer f.Surface.Unclip() + } + components.PaintButtonContent(f.Surface, area, components.ButtonContent{ + Label: n.Label, FontSize: fontSize, Weight: weight, Color: n.Color, + }) } diff --git a/ui/choice_page_test.go b/ui/choice_page_test.go new file mode 100644 index 000000000..5c1bce6df --- /dev/null +++ b/ui/choice_page_test.go @@ -0,0 +1,187 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" + "github.com/vivaui/viva/ui" +) + +var checkValue, switchValue bool + +// The calls a page makes on a Checkbox style its caption and box. +func TestCheckboxPagePropertiesReachTheCaptionAndBox(t *testing.T) { + checkValue = true + ink, fill := gfx.Color{Red: 1, Alpha: 1}, gfx.Color{Blue: 1, Alpha: 1} + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Checkbox(c, &checkValue, "Sync").FontSize(18).Weight(gfx.WeightBold).Color(ink).Background(fill) + }) + }) + snapshot := d.driver.Snapshot() + var caption gfx.Text + for _, text := range snapshot.Texts { + if text.Value == "Sync" { + caption = text + } + } + if caption.Value != "Sync" { + t.Fatalf("the caption was not painted: %+v", snapshot.Texts) + } + if caption.Style.Size != 18 || caption.Style.Weight != gfx.WeightBold || caption.Style.Color != ink { + t.Errorf("caption style = %+v, want 18, bold, red", caption.Style) + } + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Color == fill { + found = true + } + } + if !found { + t.Errorf("no checkbox fill %v in %+v", fill, snapshot.Primitives) + } + marked := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.TrianglePrimitive { + marked = true + } + } + if !marked { + t.Error("the checkbox painted no mark") + } + checkHit := false + for _, hit := range snapshot.Hits { + if hit.Role == gfx.RoleCheckbox { + checkHit = true + if hit.Label != "Sync" { + t.Errorf("checkbox hit label = %q, want the caption", hit.Label) + } + } + } + if !checkHit { + t.Errorf("no checkbox hit: %+v", snapshot.Hits) + } +} + +// A Switch's track takes an explicit height and its caption the element's style. +func TestSwitchPagePropertiesReachTheTrackAndCaption(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Switch(c, &switchValue, "Running").Height(40).FontSize(18).Weight(gfx.WeightBold) + }) + }) + snapshot := d.driver.Snapshot() + var caption gfx.Text + for _, text := range snapshot.Texts { + if text.Value == "Running" { + caption = text + } + } + if caption.Value != "Running" { + t.Fatalf("the caption was not painted: %+v", snapshot.Texts) + } + if caption.Style.Size != 18 || caption.Style.Weight != gfx.WeightBold { + t.Errorf("caption style = %+v, want 18, bold", caption.Style) + } + track := gfx.Rect{} + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Bounds.Height == 40 && primitive.Radius == 20 { + track, found = primitive.Bounds, true + } + } + if !found { + t.Fatalf("no 40-tall pill track: %+v", snapshot.Primitives) + } + var hit gfx.Hit + for _, h := range snapshot.Hits { + if h.Role == gfx.RoleSwitch { + hit = h + } + } + if hit.Role != gfx.RoleSwitch { + t.Fatalf("no switch hit: %+v", snapshot.Hits) + } + if hit.Bounds.X > track.X || hit.Bounds.Y > track.Y { + t.Errorf("switch hit %v does not reach the track %v", hit.Bounds, track) + } +} + +// A page's Styles.Checkbox and Styles.Switch dress the controls. +func TestPageStylesDressCheckboxesAndSwitches(t *testing.T) { + fill := gfx.Color{Red: 0.2, Green: 0.6, Blue: 0.3, Alpha: 1} + track := gfx.Color{Red: 0.7, Green: 0.1, Blue: 0.1, Alpha: 1} + styles := &ui.Styles{ + Checkbox: func(gfx.Theme, gfx.State) style.CheckboxLook { + return style.CheckboxLook{Fill: fill, Radius: 3} + }, + Switch: func(gfx.Theme, gfx.State, float32) style.SwitchLook { + return style.SwitchLook{Track: track} + }, + } + d := openPageWith(t, ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Checkbox(c, &checkValue, "Sync") + ui.Switch(c, &switchValue, "Run") + }) + }, + Styles: styles, + }, app.Config{}) + snapshot := d.driver.Snapshot() + checkboxFill, switchTrack := false, false + for _, primitive := range snapshot.Primitives { + if primitive.Kind != app.RectanglePrimitive { + continue + } + if primitive.Color == fill { + checkboxFill = true + } + if primitive.Color == track { + switchTrack = true + } + } + if !checkboxFill { + t.Errorf("no checkbox fill %v from the page recipe", fill) + } + if !switchTrack { + t.Errorf("no switch track %v from the page recipe", track) + } +} + +// A steady page of checkboxes and switches allocates nothing. +func TestPageOfChoicesAllocatesNothing(t *testing.T) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + for range 3 { + drawPage(page, canvas, denseChoices) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, denseChoices) }); allocs != 0 { + t.Fatalf("a steady page of choices allocates %v times", allocs) + } +} + +// BenchmarkPageChoices is the page-level cost of checkboxes and switches, for +// the stage-2 regression budget. +func BenchmarkPageChoices(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, denseChoices) + } +} + +var choiceValues [16]bool + +// denseChoices is a settings page of checkboxes and switches with captions. +func denseChoices(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(6).Children(func() { + for row := 0; row < 8; row++ { + ui.Row(c).FillWidth().Gap(12).Children(func() { + ui.Checkbox(c, &choiceValues[row*2], "Sync over SSH") + ui.Switch(c, &choiceValues[row*2+1], "Running") + }) + } + }) +} diff --git a/ui/controls_baseline.go b/ui/controls_baseline.go index 6ddfed724..177014168 100644 --- a/ui/controls_baseline.go +++ b/ui/controls_baseline.go @@ -5,16 +5,24 @@ import ( "github.com/vivaui/viva/style" ) -// controlBaseline is the label's baseline of a button, for a row that lines -// elements up by it. The engine asks the hook; the control layer answers with -// the label size the button's size gives, which is the size both its -// measurement and its painting use. +// controlBaseline is the label's baseline of a button or a badge, for a row +// that lines elements up by it. The engine asks the hook; the control layer +// answers with the label size the control's size gives, which is the size both +// its measurement and its painting use. var controlBaseline = func(f *Frame, n *Node) float32 { theme := f.Palette if n.HasOwnTheme() { theme = f.OwnTheme(n) } - _, _, fontSize, _ := style.ButtonGeometry(theme.Metrics, n.ButtonSize) + var fontSize float32 + switch n.Kind { + case KindBadge: + _, _, _, fontSize = style.BadgeGeometry(theme.Metrics) + case KindToggle: + _, _, fontSize = style.ToggleGeometry(theme.Metrics, n.ButtonSize) + default: + _, _, fontSize, _ = style.ButtonGeometry(theme.Metrics, n.ButtonSize) + } if n.FontSize > 0 { fontSize = n.FontSize } diff --git a/ui/controls_paint.go b/ui/controls_paint.go index 463cf626d..552114998 100644 --- a/ui/controls_paint.go +++ b/ui/controls_paint.go @@ -8,12 +8,71 @@ import ( "github.com/vivaui/viva/style" ) -func paintCheckbox(f *Frame, v ControlView) { - canvas := f.Surface +// checkboxSurfaceRect is the box a Checkbox paints inside its element: beside +// its caption at the element's start, centered in the element when it has none. +func checkboxSurfaceRect(f *Frame, r Rect, caption bool) Rect { side := components.CheckboxExtent(f.Palette) - bounds := Rect{X: v.Rect.X + (v.Rect.Width-side)/2, Y: v.Rect.Y + (v.Rect.Height-side)/2, Width: side, Height: side} - if v.Text != "" { - bounds.X = v.Rect.X + x := r.X + (r.Width-side)/2 + if caption { + x = r.X + } + return Rect{X: x, Y: r.Y + (r.Height-side)/2, Width: side, Height: side} +} + +// switchSurfaceRect is the track a Switch paints inside its element; an explicit +// Width or Height sizes the track, as it does every other control's surface. +func switchSurfaceRect(f *Frame, n *Node) Rect { + small := n.Flags&FlagSmall != 0 + width, height := components.SwitchExtent(f.Palette, small) + if d := n.Size[AxisX]; d.Kind == DimPx { + width = d.Value + } + if d := n.Size[AxisY]; d.Kind == DimPx { + height = d.Value + } + r := n.Rect + x := r.X + (r.Width-width)/2 + if n.Text != "" { + x = r.X + } + return Rect{X: x, Y: r.Y + (r.Height-height)/2, Width: width, Height: height} +} + +// controlSurfaceRect is where a themed control's own surface paints when it is +// smaller than the element: a Checkbox's box, a Switch's track. +func controlSurfaceRect(f *Frame, n *Node) Rect { + switch n.Kind { + case KindCheckbox: + return checkboxSurfaceRect(f, n.Rect, n.Text != "") + case KindSwitch: + return switchSurfaceRect(f, n) + } + return n.Rect +} + +// frameCheckboxLook is the look a Checkbox's box is dressed with: the page's +// Styles.Checkbox when it set one, else the theme's. +func frameCheckboxLook(f *Frame, n *Node, Palette *Theme, state gfx.State) style.CheckboxLook { + if f.GetStyles() != nil && f.GetStyles().Checkbox != nil { + return f.GetStyles().Checkbox(*Palette, state) + } + return components.CheckboxRecipe(*Palette, state) +} + +// frameSwitchLook is the look a Switch's track and thumb are dressed with: the +// page's Styles.Switch when it set one, else the theme's. +func frameSwitchLook(f *Frame, n *Node, Palette *Theme, state gfx.State, progress float32) style.SwitchLook { + if f.GetStyles() != nil && f.GetStyles().Switch != nil { + return f.GetStyles().Switch(*Palette, state, progress) + } + return components.SwitchRecipe(*Palette, state, progress) +} + +func paintCheckbox(f *Frame, v ControlView, n *Node) { + canvas := f.Surface + bounds := checkboxSurfaceRect(f, v.Rect, v.Text != "") + themed := v.Flags&FlagThemed != 0 + if v.Text != "" && !themed { f.PaintCaptionView(v, bounds) } checkbox := components.BeginCheckbox(canvas, f.Palette, v.ID, bounds, v.Flags&FlagChecked != 0) @@ -26,37 +85,45 @@ func paintCheckbox(f *Frame, v ControlView) { if v.Flags&FlagInvalid != 0 { checkbox = checkbox.Invalid() } - if f.GetStyles() != nil && f.GetStyles().Checkbox != nil { + if themed { + // The engine painted the box from the recipe; the mark is the control's. + checkbox = checkbox.UnpaintedSurface().MarkColor(f.GetCheckboxLook().Mark) + } else if f.GetStyles() != nil && f.GetStyles().Checkbox != nil { checkbox = checkbox.Recipe(f.GetStyles().Checkbox) } if v.Label != "" { checkbox = checkbox.Label(v.Label) } - if v.Disabled { + disabled := v.Disabled + if themed { + // The visual above already dims under a disabled ancestor; the hit must too. + disabled = f.Disabled(n) + } + if disabled { checkbox = checkbox.Disabled() } checkbox.Paint() } -func paintSwitch(f *Frame, v ControlView) { +func paintSwitch(f *Frame, v ControlView, n *Node) { canvas := f.Surface - small := v.Flags&FlagSmall != 0 - width, height := components.SwitchExtent(f.Palette, small) - bounds := Rect{X: v.Rect.X + (v.Rect.Width-width)/2, Y: v.Rect.Y + (v.Rect.Height-height)/2, Width: width, Height: height} - if v.Text != "" { - bounds.X = v.Rect.X + bounds := switchSurfaceRect(f, n) + themed := v.Flags&FlagThemed != 0 + if v.Text != "" && !themed { f.PaintCaptionView(v, bounds) } control := components.BeginSwitch(canvas, f.Palette, v.ID, bounds, v.Flags&FlagChecked != 0) if v.Exact { control = control.HitBounds(v.Rect) } - if recipe := v.SwitchRecipe; recipe != nil { + if themed { + control = control.UnpaintedSurface().ThumbColor(f.GetSwitchLook().Thumb) + } else if recipe := v.SwitchRecipe; recipe != nil { control = control.Recipe(recipe) } else if f.GetStyles() != nil && f.GetStyles().Switch != nil { control = control.Recipe(f.GetStyles().Switch) } - if small { + if v.Flags&FlagSmall != 0 { control = control.Small() } if v.Flags&FlagInvalid != 0 { @@ -65,36 +132,16 @@ func paintSwitch(f *Frame, v ControlView) { if v.Label != "" { control = control.Label(v.Label) } - if v.Disabled { + disabled := v.Disabled + if themed { + disabled = f.Disabled(n) + } + if disabled { control = control.Disabled() } control.Paint() } -func paintToggle(f *Frame, v ControlView) { - toggle := components.BeginToggle(f.Surface, f.Palette, v.ID, v.Rect, v.Flags&FlagChecked != 0) - if v.Size == style.SizeSmall { - toggle = toggle.Small() - } else if v.Size == style.SizeLarge { - toggle = toggle.Large() - } - if v.Flags&FlagDisabled != 0 { - toggle = toggle.Disabled() - } - if v.Flags&FlagInvalid != 0 { - toggle = toggle.Invalid() - } - label := v.Text - if label == "" { - label = v.Label - } - if v.Variant == style.VariantOutline { - toggle.Outline(label) - } else { - toggle.Default(label) - } -} - func paintInputGroup(f *Frame, v ControlView) { components.PaintInputGroup(f.Surface, f.Palette, v.Rect, base.WidgetsOf(f).GetGroups()[v.Aux]) } @@ -111,10 +158,32 @@ func paintSegmented(f *Frame, v ControlView) { // measureButtonNode sizes a button that paints its own label and icon. func measureButtonNode(f *Frame, n *Node) { n.Pref = measureButton(f, n) } -// measureBadgeNode gives a Badge the extent its component wants. +// measureBadgeNode gives a badge its chip's height and its label's width inside +// the element's Pad, which the recipe set to the chip's padding unless the +// caller said otherwise. An explicit Height or FontSize replaces the size's. func measureBadgeNode(f *Frame, n *Node) { - w, h := components.BadgeExtent(f.Surface, f.Palette, n.Text) - n.Pref = [2]float32{w, h} + height, _, _, fontSize := style.BadgeGeometry(f.Palette.Metrics) + if n.FontSize > 0 { + fontSize = n.FontSize + } + if d := n.Size[AxisY]; d.Kind == DimPx { + height = d.Value + } + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + label := n.Text + if label == "" { + label = n.Label + } + width := n.PadX() + f.Surface.TextWidthWeight(label, fontSize, weight) + leading := fontSize + 7 + if n.LineH > 0 { + leading = n.LineH + } + height = max(height, leading+n.PadY()) + n.Pref = [2]float32{width, height} } // measurePaginationNode gives a Pagination the extent its items want. @@ -137,7 +206,11 @@ func measureCheckboxNode(f *Frame, n *Node) { w, h := components.CheckboxHitExtent(f.Palette) n.Pref = [2]float32{w, h} if n.Text != "" { - n.Pref[AxisX] = components.CheckboxExtent(f.Palette) + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), gfx.WeightMedium) + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + n.Pref[AxisX] = components.CheckboxExtent(f.Palette) + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), weight) } } @@ -146,29 +219,40 @@ func measureSwitchNode(f *Frame, n *Node) { n.Pref = [2]float32{w, h} if n.Text != "" { control, _ := components.SwitchExtent(f.Palette, n.Flags&FlagSmall != 0) - n.Pref[AxisX] = control + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), gfx.WeightMedium) + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + n.Pref[AxisX] = control + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), weight) } } +// measureToggleNode gives a toggle its size's height (or the caller's) and its +// label's width inside the element's Pad; the recipe's MinS keeps it at least +// as wide as it is tall. func measureToggleNode(f *Frame, n *Node) { - toggle := components.BeginToggle(f.Surface, f.Palette, gfx.ID{}, Rect{}, false) - if n.ButtonSize == style.SizeSmall { - toggle = toggle.Small() - } else if n.ButtonSize == style.SizeLarge { - toggle = toggle.Large() + height, _, fontSize := style.ToggleGeometry(f.Palette.Metrics, n.ButtonSize) + if n.FontSize > 0 { + fontSize = n.FontSize + } + if d := n.Size[AxisY]; d.Kind == DimPx { + height = d.Value + } + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight } label := n.Text if label == "" { label = n.Label } - toggle = toggle.SizeToFit(label) - height := f.Palette.Metrics.ControlHeight - if n.ButtonSize == style.SizeSmall { - height -= 4 - } else if n.ButtonSize == style.SizeLarge { - height += 4 + width := n.PadX() + f.Surface.TextWidthWeight(label, fontSize, weight) + leading := fontSize + 7 + if n.LineH > 0 { + leading = n.LineH } - n.Pref = [2]float32{toggle.BoundsWidth(), height} + height = max(height, leading+n.PadY()) + n.Pref = [2]float32{width, height} } func measureSegmentedNode(f *Frame, n *Node) { @@ -182,7 +266,10 @@ func measureSegmentedNode(f *Frame, n *Node) { func measureInputNode(f *Frame, n *Node) { n.Pref = [2]float32{n.PadX(), f.InputLine(n) + n.PadY()} if n.Flags&FlagThemed != 0 { - n.Pref = [2]float32{0, f.Palette.Metrics.ControlHeight} + // A themed field is a control tall, or taller when its text needs more + // room (a larger FontSize); it has no width of its own, it fills its row. + height := max(f.Palette.Metrics.ControlHeight, f.InputLine(n)+n.PadY()) + n.Pref = [2]float32{0, height} } } @@ -194,20 +281,32 @@ func measureInputGroupNode(f *Frame, n *Node) { } func measureTextareaNode(f *Frame, n *Node) { - n.Pref = [2]float32{n.PadX(), f.Palette.Metrics.FontSizeM + 7 + n.PadY()} + snapshot := &base.WidgetsOf(f).GetTextareas()[n.Aux] + textSize := snapshot.TextSize + if textSize <= 0 { + textSize = f.Palette.Metrics.FontSizeM + } + line := textSize + 7 + if n.LineH > 0 { + line = n.LineH + } + n.Pref = [2]float32{n.PadX(), line + n.PadY()} + insets := snapshot.InsetTop + snapshot.InsetBottom if n.Flags&FlagThemed != 0 { - n.Pref = [2]float32{0, 64} + n.Pref = [2]float32{0, max(64, line+n.PadY()+insets)} + if n.MaxLines == 0 { + return + } } if n.MaxLines > 0 { // AutoGrow: the rows measured by the same layout the paint will use, // capped at n.MaxLines rows and never below the control's minimum. // The width is the one the last layout gave the box, which the first // paint records and then asks for before it is shown. - snapshot := &base.WidgetsOf(f).GetTextareas()[n.Aux] if layout := snapshot.Layout; layout != nil { if width := layout.BoxWidth(); width > 0 { height := layout.ContentHeight(f.Surface, f.Palette, snapshot.LayoutText(), width, snapshot.NoWrap) - maxHeight := float32(n.MaxLines)*(f.Palette.Metrics.FontSizeM+7) + 2*base.TextareaPadY + maxHeight := float32(n.MaxLines)*line + 2*base.TextareaPadY n.Pref[AxisY] = max(64, min(height, maxHeight)) } } @@ -347,6 +446,12 @@ func paintInput(f *Frame, n *Node) { // Border, as paintInput does for a line. func paintTextarea(f *Frame, n *Node) { snapshot := base.WidgetsOf(f).GetTextareas()[n.Aux] + if n.FontSize > 0 { + snapshot.TextSize = n.FontSize + } + if n.WeightSet || n.Weight != 0 { + snapshot.TextWeight = n.Weight + } if n.MaxLines > 0 { if layout := snapshot.Layout; layout != nil { // AutoGrow measured the last width the layout gave this box. The diff --git a/ui/controls_table.go b/ui/controls_table.go index be9b59267..1c284e543 100644 --- a/ui/controls_table.go +++ b/ui/controls_table.go @@ -11,10 +11,10 @@ func paintSplitterControl(f *Frame, n *Node, _ Rect) { f.PaintSplitter(n) } func paintSliderControl(f *Frame, n *Node, _ Rect) { paintSlider(f, n) } func paintWidgetControl(f *Frame, n *Node, _ Rect) { f.PaintWidget(n) } func paintSplitButtonControl(f *Frame, n *Node, _ Rect) { paintSplitButton(f, base.ViewOf(f, n)) } -func paintBadgeControl(f *Frame, n *Node, _ Rect) { paintBadge(f, base.ViewOf(f, n)) } +func paintBadgeControl(f *Frame, n *Node, _ Rect) { paintBadge(f, n) } func paintPaginationControl(f *Frame, n *Node, _ Rect) { paintPagination(f, base.ViewOf(f, n)) } -func paintCheckboxControl(f *Frame, n *Node, _ Rect) { paintCheckbox(f, base.ViewOf(f, n)) } -func paintSwitchControl(f *Frame, n *Node, _ Rect) { paintSwitch(f, base.ViewOf(f, n)) } -func paintToggleControl(f *Frame, n *Node, _ Rect) { paintToggle(f, base.ViewOf(f, n)) } +func paintCheckboxControl(f *Frame, n *Node, _ Rect) { paintCheckbox(f, base.ViewOf(f, n), n) } +func paintSwitchControl(f *Frame, n *Node, _ Rect) { paintSwitch(f, base.ViewOf(f, n), n) } +func paintToggleControl(f *Frame, n *Node, _ Rect) { paintToggle(f, n) } func paintInputGroupControl(f *Frame, n *Node, _ Rect) { paintInputGroup(f, base.ViewOf(f, n)) } func paintSegmentedControl(f *Frame, n *Node, _ Rect) { paintSegmented(f, base.ViewOf(f, n)) } diff --git a/ui/hooks_install.go b/ui/hooks_install.go index ee667a9d8..6836d6b4d 100644 --- a/ui/hooks_install.go +++ b/ui/hooks_install.go @@ -36,6 +36,8 @@ func useBadge() { installBadge.Do(func() { base.SetControlPainter(KindBadge, paintBadgeControl) base.SetControlMeasurer(KindBadge, measureBadgeNode) + base.BadgeLookFn = frameBadgeLook + base.ControlBaseline = controlBaseline }) } @@ -57,6 +59,8 @@ func useCheckbox() { installCheckbox.Do(func() { base.SetControlPainter(KindCheckbox, paintCheckboxControl) base.SetControlMeasurer(KindCheckbox, measureCheckboxNode) + base.CheckboxLookFn = frameCheckboxLook + base.ControlSurfaceRect = controlSurfaceRect }) } @@ -64,6 +68,8 @@ func useSwitch() { installSwitch.Do(func() { base.SetControlPainter(KindSwitch, paintSwitchControl) base.SetControlMeasurer(KindSwitch, measureSwitchNode) + base.SwitchLookFn = frameSwitchLook + base.ControlSurfaceRect = controlSurfaceRect }) } @@ -71,6 +77,8 @@ func useToggle() { installToggle.Do(func() { base.SetControlPainter(KindToggle, paintToggleControl) base.SetControlMeasurer(KindToggle, measureToggleNode) + base.ToggleLookFn = frameToggleLook + base.ControlBaseline = controlBaseline }) } @@ -126,6 +134,7 @@ func useSelect() { installSelect.Do(func() { base.SetControlPainter(KindSelect, paintWidgetControl) base.SetControlMeasurer(KindSelect, measureWidgetNode) + base.SelectLookFn = frameSelectLook base.PaintSelect = paintSelect base.MeasureSelect = measureSelect }) @@ -134,6 +143,7 @@ func useTabs() { installTabs.Do(func() { base.SetControlPainter(KindTabs, paintWidgetControl) base.SetControlMeasurer(KindTabs, measureWidgetNode) + base.TabsLookFn = frameTabsLook base.PaintTabs = paintTabs }) } diff --git a/ui/message/message.go b/ui/message/message.go index 0b1b6b0e5..a09cf5998 100644 --- a/ui/message/message.go +++ b/ui/message/message.go @@ -241,7 +241,7 @@ func avatar(c ui.C, message Row, side float32) { stack := ui.Stack(c).Size(side, side).Shrink(0) stack.Children(func() { if message.image.Width > 0 && message.image.Height > 0 { - ui.Image(c, message.image).Fill().Radius(side / 2) + ui.Image(c, message.image).Fill() return } face := ui.Column(c).Fill().Radius(side / 2).Background(look.Muted).Center() diff --git a/ui/select_page_test.go b/ui/select_page_test.go new file mode 100644 index 000000000..b462585ec --- /dev/null +++ b/ui/select_page_test.go @@ -0,0 +1,166 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" + "github.com/vivaui/viva/ui" +) + +var selectChoices = []int{0, 1, 2} + +func selectName(index int) string { return [...]string{"Small", "Medium", "Large"}[index] } + +// The calls a page makes on a Select reach its trigger and value. +func TestSelectPagePropertiesReachTheTrigger(t *testing.T) { + choice, ink, fill := 1, gfx.Color{Red: 1, Alpha: 1}, gfx.Color{Blue: 1, Alpha: 1} + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Select(c, &choice, selectChoices, selectName).Placeholder("Size"). + FontSize(18).Weight(gfx.WeightBold).Color(ink).Height(48).Radius(5).Background(fill) + }) + }) + snapshot := d.driver.Snapshot() + var trigger gfx.Hit + for _, hit := range snapshot.Hits { + if hit.Role == gfx.RoleCombobox { + trigger = hit + } + } + if trigger.Role != gfx.RoleCombobox || trigger.Value != "Medium" { + t.Fatalf("trigger = %+v, want a combobox showing Medium", trigger) + } + if trigger.Bounds.Height != 48 { + t.Errorf("trigger height = %v, want 48", trigger.Bounds.Height) + } + var value gfx.Text + for _, text := range snapshot.Texts { + if text.Value == "Medium" { + value = text + } + } + if value.Value != "Medium" { + t.Fatalf("the value was not painted: %+v", snapshot.Texts) + } + if value.Style.Size != 18 || value.Style.Weight != gfx.WeightBold || value.Style.Color != ink { + t.Errorf("value style = %+v, want 18, bold, red", value.Style) + } + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Color == fill { + found = true + } + } + if !found { + t.Errorf("no trigger fill %v in %+v", fill, snapshot.Primitives) + } + // The chevron stays the control's: triangles are painted at the trigger's end. + triangles := 0 + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.TrianglePrimitive { + triangles++ + } + } + if triangles == 0 { + t.Error("the trigger painted no chevron") + } +} + +// Children replace the chosen value while the combobox hit and the chevron stay. +func TestSelectPageChildrenReplaceTheValue(t *testing.T) { + choice := 0 + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Select(c, &choice, selectChoices, selectName).Placeholder("Size").Children(func() { + ui.Text(c, "own") + }) + }) + }) + snapshot := d.driver.Snapshot() + for _, text := range snapshot.Texts { + if text.Value == "Small" || text.Value == "Size" { + t.Errorf("the value or placeholder was painted over the children: %+v", snapshot.Texts) + } + } + var trigger gfx.Hit + for _, hit := range snapshot.Hits { + if hit.Role == gfx.RoleCombobox { + trigger = hit + } + } + if trigger.Role != gfx.RoleCombobox { + t.Fatalf("children dropped the trigger's combobox hit: %+v", snapshot.Hits) + } + triangles := 0 + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.TrianglePrimitive { + triangles++ + } + } + if triangles == 0 { + t.Error("children dropped the trigger's chevron") + } +} + +// A page's Styles.Select dresses the trigger: its surface fill and radius. +func TestPageStylesDressSelects(t *testing.T) { + choice := 0 + fill := gfx.Color{Red: 0.2, Green: 0.6, Blue: 0.3, Alpha: 1} + styles := &ui.Styles{Select: func(gfx.Theme, gfx.State, bool) (style.TextEntryLook, gfx.Color, gfx.Color) { + surface := style.TextEntryLook{Fill: fill, Radius: 9, BorderWidth: 1, Border: gfx.Color{Alpha: 1}} + return surface, gfx.Color{Alpha: 1}, gfx.Color{Alpha: 1} + }} + d := openPageWith(t, ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { ui.Select(c, &choice, selectChoices, selectName).Placeholder("Size") }) + }, + Styles: styles, + }, app.Config{}) + snapshot := d.driver.Snapshot() + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Color == fill { + found = true + } + } + if !found { + t.Errorf("no trigger authored by the page recipe with fill %v", fill) + } +} + +var selectState = 0 + +// A steady page of selects allocates nothing. +func TestPageOfSelectsAllocatesNothing(t *testing.T) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + for range 3 { + drawPage(page, canvas, denseSelects) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, denseSelects) }); allocs != 0 { + t.Fatalf("a steady page of selects allocates %v times", allocs) + } +} + +// BenchmarkPageSelects is the page-level cost of select triggers, for the +// stage-2 regression budget. +func BenchmarkPageSelects(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, denseSelects) + } +} + +// denseSelects is a page of closed select triggers, as a settings form is. +func denseSelects(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(6).Children(func() { + for row := 0; row < 20; row++ { + ui.Row(c).FillWidth().Gap(6).Children(func() { + ui.Select(c, &selectState, selectChoices, selectName).Placeholder("Size").Width(120) + ui.Select(c, &selectState, selectChoices, selectName).Placeholder("Size").Width(160).Small() + }) + } + }) +} diff --git a/ui/select_paint.go b/ui/select_paint.go index c05761642..24dd36876 100644 --- a/ui/select_paint.go +++ b/ui/select_paint.go @@ -3,31 +3,67 @@ package ui import ( "github.com/vivaui/viva/base" "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) +// selectSize maps the element's size calls to the component size whose +// geometry the trigger takes. +func selectSize(n *Node) style.Size { + switch { + case n.ButtonSize == components.ButtonSizeXSmall: + return style.SizeXSmall + case n.Flags&FlagSmall != 0: + return style.SizeSmall + } + return style.SizeDefault +} + +// frameSelectLook is the look a Select trigger is dressed with: the page's +// Styles.Select when it set one, else the theme's. +func frameSelectLook(f *Frame, n *Node, Palette *Theme, state gfx.State, placeholder bool) (style.TextEntryLook, gfx.Color, gfx.Color) { + if f.GetStyles() != nil && f.GetStyles().Select != nil { + return f.GetStyles().Select(*Palette, state, placeholder) + } + look := components.SelectRecipe(*Palette, state, placeholder) + return look.Surface, look.Foreground, look.Chevron +} + func measureSelect(f *Frame, n *Node) { d := &base.WidgetsOf(f).GetSelects()[n.Aux] - widest := d.GetState().WidestOption(f.Surface, d.GetLabels(), f.Palette.Metrics.FontSizeM) + height, textSize := style.SelectGeometry(f.Palette.Metrics, selectSize(n)) + if n.FontSize > 0 { + textSize = n.FontSize + } + weight := gfx.WeightRegular + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + var widest float32 + if weight == gfx.WeightRegular && textSize == f.Palette.Metrics.FontSizeM { + widest = d.GetState().WidestOption(f.Surface, d.GetLabels(), textSize) + } else { + for _, label := range d.GetLabels() { + widest = max(widest, f.Surface.TextWidthWeight(label, textSize, weight)) + } + } if len(d.GetIcons()) > 0 { widest += components.SelectIconSpan } - height := f.Palette.Metrics.ControlHeight - switch { - case n.ButtonSize == components.ButtonSizeXSmall: - height -= 8 - case n.Flags&FlagSmall != 0: - height -= 4 + if d := n.Size[AxisY]; d.Kind == DimPx { + height = d.Value } - n.Pref = [2]float32{widest + f.Palette.Metrics.PadControlX + 36, height} + n.Pref = [2]float32{widest + style.SelectDefaultWidth(f.Palette.Metrics), height} } func paintSelect(f *Frame, n *Node) { d := &base.WidgetsOf(f).GetSelects()[n.Aux] count := len(d.GetLabels()) // A Select is as tall as it measures unless the application gave it a height, - // which then sizes the trigger itself. + // which then sizes the trigger itself. A themed trigger's surface is the + // element's rectangle, so its hit is too. height := n.Pref[AxisY] - if n.Size[AxisY].Kind != DimAuto { + if n.Size[AxisY].Kind != DimAuto || n.Flags&FlagThemed != 0 { height = n.Rect.Height } trigger := Rect{X: n.Rect.X, Y: n.Rect.Y, Width: n.Rect.Width, Height: height} @@ -43,6 +79,24 @@ func paintSelect(f *Frame, n *Node) { options.Size = components.SelectSizeSmall } options.Unpainted = n.Flags&FlagThemed == 0 + if n.Flags&FlagThemed != 0 { + foreground, chevron := f.GetSelectColors() + options.UnpaintedSurface = true + options.UnpaintedValue = n.Flags&FlagChildren != 0 + options.TriggerContent = f.ContentRect(n) + options.Foreground, options.HasForeground = foreground, true + if n.Flags&FlagHasColor != 0 { + options.Foreground = n.Color + } + if n.WeightSet || n.Weight != 0 { + options.Weight = n.Weight + } + options.Chevron, options.HasChevron = chevron, true + if n.FontSize > 0 { + options.TextSize = n.FontSize + } + options.Disabled = f.Disabled(n) + } if d.GetSelected() >= 0 && d.GetSelected() < count { options.Value = d.GetLabels()[d.GetSelected()] if d.GetSelected() < len(d.GetIcons()) { diff --git a/ui/tabs_page_test.go b/ui/tabs_page_test.go new file mode 100644 index 000000000..12d38abb8 --- /dev/null +++ b/ui/tabs_page_test.go @@ -0,0 +1,141 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" + "github.com/vivaui/viva/ui" +) + +var tabsChoices = []int{0, 1, 2} + +func tabsLabel(index int) string { return [...]string{"General", "Keys", "Advanced"}[index] } + +// The calls a page makes on a Tabs strip reach the strip and its labels. +func TestTabsPagePropertiesReachTheStrip(t *testing.T) { + current, ink, fill := 1, gfx.Color{Red: 1, Alpha: 1}, gfx.Color{Blue: 1, Alpha: 1} + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Tabs(c, ¤t, tabsChoices, tabsLabel).FontSize(18).Weight(gfx.WeightBold). + Color(ink).Pad(7).Radius(4).Background(fill).Height(44) + }) + }) + snapshot := d.driver.Snapshot() + // The strip holds three tab-role hits; its own rectangle is the painted fill. + tabHits := 0 + for _, hit := range snapshot.Hits { + if hit.Role == gfx.RoleTab { + tabHits++ + } + } + if tabHits != 3 { + t.Fatalf("%d tab hits, want 3", tabHits) + } + // Find the strip's surface: it spans all triggers and has the explicit fill. + list := gfx.Rect{} + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Color == fill && primitive.Radius == 4 { + list, found = primitive.Bounds, true + } + } + if !found { + t.Fatalf("no strip painted with the explicit fill %v radius 4", fill) + } + if list.Height != 44 { + t.Errorf("strip height = %v, want 44", list.Height) + } + dimmed := ink + dimmed.Alpha *= 0.60 + seen := 0 + for _, text := range snapshot.Texts { + label := text.Value + if label != "General" && label != "Keys" && label != "Advanced" { + continue + } + seen++ + if text.Style.Size != 18 || text.Style.Weight != gfx.WeightBold { + t.Errorf("%s style = %+v, want 18, bold", label, text.Style) + } + want := dimmed + if label == "Keys" { + want = ink // the selected tab keeps the ink whole + } + if text.Style.Color != want { + t.Errorf("%s color = %v, want %v", label, text.Style.Color, want) + } + } + if seen != 3 { + t.Errorf("%d labels painted, want 3", seen) + } +} + +// A page's Styles.Tabs dresses the strip: its fill and radius. +func TestPageStylesDressTabs(t *testing.T) { + current := 0 + fill := gfx.Color{Red: 0.1, Green: 0.5, Blue: 0.2, Alpha: 1} + styles := &ui.Styles{Tabs: func(gfx.Theme, bool) style.ButtonLook { + return style.ButtonLook{Background: fill, Filled: true, Radius: 8} + }} + d := openPageWith(t, ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { ui.Tabs(c, ¤t, tabsChoices, tabsLabel) }) + }, + Styles: styles, + }, app.Config{}) + snapshot := d.driver.Snapshot() + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Color == fill && primitive.Radius == 8 { + found = true + } + } + if !found { + t.Errorf("no strip authored by the page recipe with fill %v radius 8", fill) + } +} + +var tabsState = 0 + +// A steady page of tab strips allocates nothing. +func TestPageOfTabsAllocatesNothing(t *testing.T) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + for range 3 { + drawPage(page, canvas, denseTabs) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, denseTabs) }); allocs != 0 { + t.Fatalf("a steady page of tabs allocates %v times", allocs) + } +} + +// BenchmarkPageTabs is the page-level cost of tab strips, for the stage-2 +// regression budget. +func BenchmarkPageTabs(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, denseTabs) + } +} + +// denseTabs is a page of tab strips: the default and line variants, horizontal +// and vertical, at the sizes a settings page uses. +func denseTabs(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(8).Children(func() { + for row := 0; row < 12; row++ { + ui.Row(c).FillWidth().Gap(8).Children(func() { + tabs := ui.Tabs(c, &tabsState, tabsChoices, tabsLabel) + switch row % 4 { + case 1: + tabs.Line() + case 2: + tabs.Vertical().Height(108) + case 3: + tabs.Line().Vertical().Height(108) + } + }) + } + }) +} diff --git a/ui/tabs_paint.go b/ui/tabs_paint.go index d29a9aac9..0e5dba7e4 100644 --- a/ui/tabs_paint.go +++ b/ui/tabs_paint.go @@ -6,6 +6,19 @@ import ( "github.com/vivaui/viva/gfx" ) +// frameTabsLook is the look of the strip behind a tab list: the page's +// Styles.Tabs when it set one, else the theme's. +func frameTabsLook(f *Frame, n *Node, Palette *Theme, _ gfx.State) components.ButtonLook { + line := base.WidgetsOf(f).GetTabs()[n.Aux].GetLine() + if f.GetStyles() != nil && f.GetStyles().Tabs != nil { + return f.GetStyles().Tabs(*Palette, line) + } + if line { + return components.TabsListRecipe(*Palette, components.TabsLine) + } + return components.TabsListRecipe(*Palette, components.TabsDefault) +} + func paintTabs(f *Frame, n *Node) { t := &base.WidgetsOf(f).GetTabs()[n.Aux] // The strip is as tall as the element: an explicit height is the trigger's, @@ -50,7 +63,24 @@ func paintTabs(f *Frame, n *Node) { if t.GetVertical() { tabs = tabs.Vertical() } - if n.Flags&FlagDisabled != 0 { + tabStyle := components.TabsStyle{ + ListPadding: n.Pad[0], + Gap: n.Gap, + FontSize: n.FontSize, + } + if n.WeightSet { + tabStyle.Weight = n.Weight + } + if n.Flags&base.FlagHasColor != 0 { + tabStyle.Foreground, tabStyle.HasForeground = n.Color, true + } + tabs = tabs.WithStyle(tabStyle) + if !t.GetLine() { + // The engine paints the muted strip; the line variant has no strip to + // paint, so the component keeps its transparent record exactly as before. + tabs = tabs.UnpaintedSurface() + } + if f.Disabled(n) { tabs = tabs.Disabled() } tabs.Paint() diff --git a/ui/text_entry_page_test.go b/ui/text_entry_page_test.go new file mode 100644 index 000000000..15e5b15f7 --- /dev/null +++ b/ui/text_entry_page_test.go @@ -0,0 +1,122 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var textValue = "Gopher" +var textAreaValue = "line one" + +// The calls a page makes on a text field reach its value and surface. +func TestTextFieldPagePropertiesReachTheField(t *testing.T) { + ink, fill := gfx.Color{Red: 1, Alpha: 1}, gfx.Color{Blue: 1, Alpha: 1} + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.TextField(c, &textValue, "Name", "Type here").Width(220).Height(48). + FontSize(20).Weight(gfx.WeightBold).Color(ink).Background(fill).Radius(6) + }) + }) + snapshot := d.driver.Snapshot() + var field gfx.Hit + for _, hit := range snapshot.Hits { + if hit.Role == gfx.RoleTextField { + field = hit + } + } + if field.Role != gfx.RoleTextField { + t.Fatalf("no text-field hit: %+v", snapshot.Hits) + } + if field.Bounds.Height != 48 { + t.Errorf("field height = %v, want 48", field.Bounds.Height) + } + var value gfx.Text + for _, text := range snapshot.Texts { + if text.Value == "Gopher" { + value = text + } + } + if value.Value != "Gopher" { + t.Fatalf("the value was not painted: %+v", snapshot.Texts) + } + if value.Style.Size != 20 || value.Style.Weight != gfx.WeightBold || value.Style.Color != ink { + t.Errorf("value style = %+v, want 20, bold, red", value.Style) + } + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Color == fill { + found = true + } + } + if !found { + t.Errorf("no field fill %v in %+v", fill, snapshot.Primitives) + } +} + +// A text area takes the element's FontSize for its rows and its Height. +func TestTextAreaPagePropertiesReachTheRows(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.TextArea(c, &textAreaValue, "Notes", "Type here").Width(240).Height(120).FontSize(22).Weight(gfx.WeightBold) + }) + }) + snapshot := d.driver.Snapshot() + var field gfx.Hit + for _, hit := range snapshot.Hits { + if hit.Role == gfx.RoleTextField { + field = hit + } + } + if field.Bounds.Height != 120 { + t.Errorf("textarea height = %v, want 120", field.Bounds.Height) + } + var row gfx.Text + for _, text := range snapshot.Texts { + if text.Value == "line one" { + row = text + } + } + if row.Value != "line one" { + t.Fatalf("the row was not painted: %+v", snapshot.Texts) + } + if row.Style.Size != 22 || row.Style.Weight != gfx.WeightBold { + t.Errorf("row style = %+v, want 22, bold", row.Style) + } +} + +// A steady page of text fields allocates nothing. +func TestPageOfTextFieldsAllocatesNothing(t *testing.T) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + for range 3 { + drawPage(page, canvas, denseTextFields) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, denseTextFields) }); allocs != 0 { + t.Fatalf("a steady page of text fields allocates %v times", allocs) + } +} + +// BenchmarkPageTextFields is the page-level cost of themed text fields, for the +// stage-2 regression budget. +func BenchmarkPageTextFields(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, denseTextFields) + } +} + +var fieldValue = "value" +var areaValue = "two\nrows" + +// denseTextFields is a settings form of text fields and text areas. +func denseTextFields(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(6).Children(func() { + for row := 0; row < 8; row++ { + ui.TextField(c, &fieldValue, "Name", "Type here").FillWidth() + ui.TextArea(c, &areaValue, "Notes", "Type here").FillWidth().Height(96) + } + }) +} diff --git a/ui/toggle_page_test.go b/ui/toggle_page_test.go new file mode 100644 index 000000000..e6eb97363 --- /dev/null +++ b/ui/toggle_page_test.go @@ -0,0 +1,196 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" + "github.com/vivaui/viva/ui" +) + +// The calls a page makes on a Toggle reach its surface and label: FontSize, +// Weight and Color the text, Height and Radius the surface. +func TestTogglePagePropertiesReachTheSurface(t *testing.T) { + ink := gfx.Color{Red: 1, Alpha: 1} + on := true + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Toggle(c, &on, "Bold").FontSize(18).Weight(gfx.WeightBold).Color(ink).Height(40).Radius(5) + }) + }) + snapshot := d.driver.Snapshot() + var target gfx.Hit + for _, hit := range snapshot.Hits { + if hit.Label == "Bold" { + target = hit + } + } + if target.Label != "Bold" { + t.Fatalf("the toggle declared no hit: %+v", snapshot.Hits) + } + if target.Bounds.Height != 40 { + t.Errorf("toggle height = %v, want 40", target.Bounds.Height) + } + if !target.Checked || !target.Selected { + t.Errorf("toggle hit = %+v, want checked and selected", target) + } + var label gfx.Text + for _, painted := range snapshot.Texts { + if painted.Value == "Bold" { + label = painted + } + } + if label.Value != "Bold" { + t.Fatalf("the toggle label was not painted: %+v", snapshot.Texts) + } + if label.Style.Size != 18 || label.Style.Weight != gfx.WeightBold || label.Style.Color != ink { + t.Errorf("label style = %+v, want 18, bold, red", label.Style) + } + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Bounds == target.Bounds { + found = true + if primitive.Radius != 5 { + t.Errorf("surface radius = %v, want the explicit 5", primitive.Radius) + } + } + } + if !found { + t.Errorf("no surface for %v", target.Bounds) + } +} + +// Children replace the label; the toggle keeps its pressed state and hit. +func TestTogglePageChildrenReplaceTheLabel(t *testing.T) { + on := false + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { + ui.Toggle(c, &on, "Bold").Children(func() { + ui.Text(c, "one") + ui.Text(c, "two") + }) + }) + }) + snapshot := d.driver.Snapshot() + for _, text := range snapshot.Texts { + if text.Value == "Bold" { + t.Errorf("the label was painted over the children: %+v", snapshot.Texts) + } + } + var target gfx.Hit + for _, hit := range snapshot.Hits { + if hit.Label == "Bold" { + target = hit + } + } + if target.Role != gfx.RoleButton || target.Checked { + t.Errorf("hit = %+v, want one unpressed button named Bold", target) + } + children := 0 + for _, text := range snapshot.Texts { + if text.Value == "one" || text.Value == "two" { + children++ + if text.Bounds.X < target.Bounds.X || text.Bounds.X+text.Bounds.Width > target.Bounds.X+target.Bounds.Width { + t.Errorf("child %q at %v is outside the toggle %v", text.Value, text.Bounds, target.Bounds) + } + } + } + if children != 2 { + t.Errorf("painted %d children, want 2: %+v", children, snapshot.Texts) + } +} + +// A page's Styles.Toggle dresses every toggle of the page; the state the page +// recipe asks about includes Checked. +func TestPageStylesDressToggles(t *testing.T) { + fill := gfx.Color{Red: 0.2, Green: 0.6, Blue: 0.3, Alpha: 1} + checked := false + styles := &ui.Styles{Toggle: func(_ gfx.Theme, _ style.Variant, state gfx.State) style.ButtonLook { + if state.Checked { + checked = true + } + return style.ButtonLook{Background: fill, Foreground: fill, Filled: true, Radius: 2} + }} + on := true + d := openPageWith(t, ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c).Pad(20).Children(func() { ui.Toggle(c, &on, "Bold") }) + }, + Styles: styles, + }, app.Config{}) + if !checked { + t.Error("the page recipe did not see the checked state") + } + snapshot := d.driver.Snapshot() + var target gfx.Hit + for _, hit := range snapshot.Hits { + if hit.Label == "Bold" { + target = hit + } + } + found := false + for _, primitive := range snapshot.Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Bounds == target.Bounds { + found = true + if primitive.Color != fill || primitive.Radius != 2 { + t.Errorf("surface = %v radius %v, want the page recipe's %v radius 2", primitive.Color, primitive.Radius, fill) + } + } + } + if !found { + t.Errorf("no surface authored by the page recipe for %v", target.Bounds) + } +} + +// A steady page of toggles allocates nothing. +func TestPageOfTogglesAllocatesNothing(t *testing.T) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + for range 3 { + drawPage(page, canvas, denseToggles) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, denseToggles) }); allocs != 0 { + t.Fatalf("a steady page of toggles allocates %v times", allocs) + } +} + +// BenchmarkPageToggles is the page-level cost of themed toggles, for the +// stage-2 regression budget. +func BenchmarkPageToggles(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, denseToggles) + } +} + +var toggleLabels = [...]string{"Bold", "Italic", "Underline", "Code", "Link"} + +// toggleState is the model of denseToggles, kept out of the declaration so a +// steady paint allocates nothing. +var toggleState [20 * len(toggleLabels)]bool + +// denseToggles is a page made of toggles, as a formatting toolbar is: every +// label, the outline treatment and the sizes, in a few rows. +func denseToggles(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(6).Children(func() { + for row := 0; row < 20; row++ { + ui.Row(c).FillWidth().Gap(6).Children(func() { + for i, label := range toggleLabels { + index := row*len(toggleLabels) + i + value := &toggleState[index] + *value = index%2 == 0 + toggle := ui.Toggle(c, value, label) + switch index % 4 { + case 1: + toggle.Outline() + case 2: + toggle.Small() + case 3: + toggle.Large() + } + } + }) + } + }) +} diff --git a/ui/toggle_paint.go b/ui/toggle_paint.go new file mode 100644 index 000000000..6b1d56418 --- /dev/null +++ b/ui/toggle_paint.go @@ -0,0 +1,51 @@ +package ui + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +// toggleVariant is the component's treatment for the variant the Button +// methods chose: an outline toggle is the bordered one, anything else the +// borderless default. +func toggleVariant(Variant style.Variant) components.ToggleVariant { + if Variant == style.VariantOutline { + return components.ToggleOutline + } + return components.ToggleDefault +} + +// frameToggleLook is the recipe a toggle is dressed with: the page's +// Styles.Toggle when it set one, else the theme's. +func frameToggleLook(f *Frame, n *Node, Palette *Theme, state gfx.State) components.ButtonLook { + if f.GetStyles() != nil && f.GetStyles().Toggle != nil { + return f.GetStyles().Toggle(*Palette, n.Variant, state) + } + return components.ToggleRecipe(*Palette, toggleVariant(n.Variant), state) +} + +// paintToggle paints the default label of a toggle; the engine paints the +// surface, the ring and the hit around it, and clips the content area. +func paintToggle(f *Frame, n *Node) { + if n.Flags&FlagChildren != 0 { + return + } + _, _, fontSize := style.ToggleGeometry(f.Palette.Metrics, n.ButtonSize) + if n.FontSize > 0 { + fontSize = n.FontSize + } + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + area := buttonContentArea(f, n) + room := f.ContentRect(n) + if room.Width > 0 && f.Surface.TextWidthWeight(n.Label, fontSize, weight) > room.Width { + f.Surface.Clip(room) + defer f.Surface.Unclip() + } + components.PaintButtonContent(f.Surface, area, components.ButtonContent{ + Label: n.Label, FontSize: fontSize, Weight: weight, Color: n.Color, + }) +} From 2b8c415c9b42261be2e9bf8e9ba3c14ec0d1da38 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 21 Nov 2026 12:43:15 +0800 Subject: [PATCH 05/16] feat(ui): size Tabs padding, Table type and Checkbox boxes from the element Four attributes that used to be silently ignored now reach what they name: - Tabs: Pad applies to all four sides instead of only the top, so PadX, PadY and uneven sides inset the triggers and the strip's own thickness; a strip without a height is exactly its triggers plus PadY, so PadY(0) no longer falls back to the theme's 36. - Table: the element's FontSize and Color style the header and the cells, replacing the spec's size and the theme's foreground; FitHeadings then fits at the element's size. Weight stays with the table's recipe. - Checkbox: an explicit Size sizes the box, not only its element; a non-square box draws its mark for the shorter side. - Switch: FillWidth, FillHeight and percent sizes size the track from the layout, keeping the caption's room out of it, and the pill radius follows the height. A pixel size still sizes it directly. The dev attribute rules are relaxed for the attributes that now work. The component defaults are untouched, so nothing changes for callers that set none of these. --- base/accessors.go | 10 ++++ base/attrcheck_dev.go | 16 +++---- base/attrcheck_dev_test.go | 19 ++++++-- base/checkbox_switch_node_test.go | 53 +++++++++++++++++++++ base/frame.go | 1 + base/paint.go | 5 ++ base/recipe.go | 4 +- base/table.go | 44 +++++++++++++---- base/table_element_style_test.go | 76 ++++++++++++++++++++++++++++++ base/tabs.go | 27 ++++++++--- base/tabs_node_test.go | 52 ++++++++++++++++++++ cmd/viva/templates/checkbox.go.txt | 25 +++++++--- cmd/viva/templates/table.go.txt | 24 +++++++++- cmd/viva/templates/tabs.go.txt | 41 ++++++++++------ components/checkbox.go | 25 +++++++--- components/table.go | 24 +++++++++- components/tabs.go | 41 ++++++++++------ ui/controls_paint.go | 48 ++++++++++++++++--- ui/table_paint.go | 12 +++-- ui/tabs_paint.go | 7 +-- 20 files changed, 465 insertions(+), 89 deletions(-) create mode 100644 base/table_element_style_test.go diff --git a/base/accessors.go b/base/accessors.go index 226b818c5..9a63d4948 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -1181,6 +1181,16 @@ func (x *TableDecl) GetRows() int { return x.rows } // GetSpec reads the spec of TableDecl for the styled painting layer. func (x *TableDecl) GetSpec() TableSpec { return x.spec } +// GetFontSize reads the element's font size for the table being painted: the +// explicit size when it has one, else the spec's. +func (x *TableDecl) GetFontSize() float32 { return x.fontSize } + +// GetForeground reads the element's text color for the table being painted. +func (x *TableDecl) GetForeground() gfx.Color { return x.foreground } + +// GetForegroundSet reports whether the element set a text color of its own. +func (x *TableDecl) GetForegroundSet() bool { return x.hasForeground } + // GetState reads the state of TableDecl for the styled painting layer. func (x *TableDecl) GetState() *TableState { return x.state } diff --git a/base/attrcheck_dev.go b/base/attrcheck_dev.go index 4d454bea0..a4f5b6d79 100644 --- a/base/attrcheck_dev.go +++ b/base/attrcheck_dev.go @@ -230,15 +230,6 @@ func (f *Frame) checkThemedAttributes(n *Node, name string) { if n.Variant != 0 { f.badAttribute(n, name, "Variant", "a Tabs strip has its own variants: use Line() or Vertical()") } - // The strip's padding is its inner padding: only a uniform Pad (or the top - // side) reaches the triggers. - if n.Flags&flagSetPad != 0 { - if (n.PadSet&padRight != 0 && n.Pad[1] != n.Pad[0]) || - (n.PadSet&padBottom != 0 && n.Pad[2] != n.Pad[0]) || - (n.PadSet&padLeft != 0 && n.Pad[3] != n.Pad[0]) { - f.badAttribute(n, name, "Pad sides", "a Tabs strip keeps one inner padding; PadX, PadY or different sides do not reach the triggers") - } - } case kindSelect: f.checkTextAttributes(n, name, false, false, false, false, false) f.checkButtonSize(n, name, true) @@ -424,7 +415,12 @@ func (f *Frame) checkWidgetAttributes(n *Node, name string) { case kindTable: rejectPad() rejectSurface() - rejectType() + // FontSize and Color style the table's text; its own weight rules keep + // headers medium and rows regular. + f.checkTextAttributes(n, name, false, false, false, false, false) + if n.WeightSet { + f.badAttribute(n, name, "Weight", "a Table's header is medium and its rows regular; change the font size or color instead") + } rejectChildren() rejectVariant() rejectSize() diff --git a/base/attrcheck_dev_test.go b/base/attrcheck_dev_test.go index 775153c44..03a4e7dc3 100644 --- a/base/attrcheck_dev_test.go +++ b/base/attrcheck_dev_test.go @@ -15,6 +15,17 @@ var ( attrSelectScope = tree.Sub(page, tree.Name("attr-select")) ) +type devTableRows struct{ n int } + +func (r *devTableRows) Len() int { return r.n } +func (r *devTableRows) Cell(row, column int) string { return "r" } + +var devTableSpec = TableSpec{ + Columns: []style.TableColumn{{Width: 80}}, + Headers: []string{"Name"}, + Source: &devTableRows{n: 1}, +} + // drawBase declares one page through the engine under the dev attribute rules. func drawBase(declare func(f *Frame)) { var view View @@ -47,7 +58,7 @@ func TestBareConstructorsDoNotTripTheAttributeRules(t *testing.T) { f.Button(gfx.Item(1), "Save") f.Badge("New") f.Toggle(gfx.Item(3), "Bold", true) - f.Tabs(attrTabsScope, []string{"A", "B"}, 0) + f.Tabs(attrTabsScope, []string{"A", "B"}, 0).PadSides(2, 8, 4, 12) f.Select(attrSelectScope, &state, []string{"A", "B"}, 0).Label("Size") f.Input(InputSnapshot{ID: gfx.Item(4), Label: "Name", Value: "x"}) f.Textarea(TextareaSnapshot{ID: gfx.Item(5), Label: "Notes", Value: "x"}) @@ -145,6 +156,9 @@ func TestAttributesThatDoNothingReport(t *testing.T) { {"Splitter LabelFor", []string{"Splitter", "LabelFor"}, func(f *Frame) { f.Splitter(gfx.Item(1), &SplitterState{}).LabelFor(gfx.Item(2)) }}, + {"Table Weight", []string{"Table", "Weight"}, func(f *Frame) { + f.Table(&TableState{}, devTableSpec).Bold() + }}, {"Select Hit", []string{"Select", "Hit"}, func(f *Frame) { f.Select(attrSelectScope, &SelectState{}, []string{"A"}, 0).Hit(gfx.Item(9), "Size") }}, @@ -167,9 +181,6 @@ func TestAttributesThatDoNothingReport(t *testing.T) { f.Checkbox(gfx.Item(1), true).Color(gfx.Color{Red: 1, Alpha: 1}) }}, {"Badge size method", []string{"Badge", "Size"}, func(f *Frame) { f.Badge("New").Small() }}, - {"Tabs asymmetric Pad", []string{"Tabs", "Pad sides"}, func(f *Frame) { - f.Tabs(attrTabsScope, []string{"A"}, 0).PadSides(2, 8, 2, 8) - }}, {"Image Radius", []string{"Image", "Radius"}, func(f *Frame) { f.Image(gfx.Bitmap{}).Radius(4) }}, diff --git a/base/checkbox_switch_node_test.go b/base/checkbox_switch_node_test.go index d1a14d0e2..f0e2defb6 100644 --- a/base/checkbox_switch_node_test.go +++ b/base/checkbox_switch_node_test.go @@ -203,3 +203,56 @@ func TestSwitchDefaultsAreTheRecipe(t *testing.T) { t.Errorf("explicit switch track = %v, want 80x40", wideTrack.Bounds) } } + +// An explicit pixel Size sizes a Checkbox's box itself, not only its element, +// and a non-square box draws a mark sized for its shorter side. +func TestCheckboxExplicitSizeSizesTheBox(t *testing.T) { + p := probeChoice(t, func(f *Frame) Box { return f.Checkbox(gfx.Item(1), true).Size(22, 24) }) + var box gfx.Rectangle + for _, rect := range p.rects { + if rect.Bounds.Width == 22 && rect.Bounds.Height == 24 { + box = rect + } + } + if box.Bounds.Width == 0 { + t.Fatalf("no 22x24 box in %+v", p.rects) + } + if !p.marked { + t.Error("the explicit box painted no mark") + } +} + +// FillWidth and Percent sizes size a Switch's track from what the layout gave +// the element, keeping the caption's room out of the track. +func TestSwitchStretchedTrack(t *testing.T) { + theme := gfx.LightTheme() + off := components.SwitchRecipe(theme, gfx.State{}, 0) + caption := "Running" + canvas := testCanvas() + var view View + var box Box + view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 120}, func(f *Frame) { + f.Column().Width(400).Children(func() { + f.Column().Width(400).Children(func() { + box = f.Switch(gfx.Item(1), false).Caption(caption).FillWidth() + }) + }) + }) + width := canvas.TextWidthWeight(caption, theme.Metrics.FontSizeM, gfx.WeightMedium) + want := box.Rect().Width - width - CaptionGap + track := gfx.Rectangle{} + for _, rect := range canvas.Rectangles() { + if rect.Color == off.Track && rect.Bounds.Height > 0 { + track = rect + } + } + if track.Bounds.Width == 0 { + t.Fatalf("no track with %v in %+v", off.Track, canvas.Rectangles()) + } + if diff := track.Bounds.Width - want; diff > 0.01 || diff < -0.01 { + t.Errorf("track width = %v, want the element width less the caption and gap (%v)", track.Bounds.Width, want) + } + if track.Radius != track.Bounds.Height/2 { + t.Errorf("track radius = %v, want half its height %v", track.Radius, track.Bounds.Height/2) + } +} diff --git a/base/frame.go b/base/frame.go index 3b1607a34..c8d0a5808 100644 --- a/base/frame.go +++ b/base/frame.go @@ -368,6 +368,7 @@ func (f *Frame) End() { f.checkHits() f.checkAttributes() f.applyRecipes() + f.resolveTables() root := &f.Nodes[0] f.measure(AxisX) root.Rect.X, root.Rect.Width = f.bounds.X, f.bounds.Width diff --git a/base/paint.go b/base/paint.go index b3eaf1ff0..793f16ca4 100644 --- a/base/paint.go +++ b/base/paint.go @@ -53,6 +53,11 @@ func (f *Frame) PaintChild(i int32) { surface = own } } + // A stacked or stretched switch's track is a pill of its own height, which + // the layout only knows once it has sized the element. + if n.Flags&flagThemed != 0 && n.Kind == kindSwitch && n.Flags&flagHasRadius == 0 && surface.Height > 0 { + n.Radius = surface.Height / 2 + } canvas := f.Surface extra := &f.Exts[n.Ext] if s := extra.scrollState; s != nil && canvas != nil { diff --git a/base/recipe.go b/base/recipe.go index e145ff656..81799eb1a 100644 --- a/base/recipe.go +++ b/base/recipe.go @@ -115,7 +115,7 @@ func (f *Frame) applyRecipes() { } case kindTabs: theme := f.RecipeTheme(n, &f.scratch.theme) - listHeight, listPadding, _, _, lineGap, _, _ := style.TabsGeometry(theme.Metrics) + _, listPadding, triggerHeight, _, lineGap, _, _ := style.TabsGeometry(theme.Metrics) t := &WidgetsOf(f).tabs[n.Aux] gap := float32(0) if t.line { @@ -141,7 +141,7 @@ func (f *Frame) applyRecipes() { n.Radius = f.tabsLook(n, theme).Radius } if n.Size[AxisY].Kind == dimAuto && n.MinS[AxisY] == 0 { - n.MinS[AxisY] = listHeight + n.MinS[AxisY] = triggerHeight + n.Pad[0] + n.Pad[2] } case kindSelect: theme := f.RecipeTheme(n, &f.scratch.theme) diff --git a/base/table.go b/base/table.go index 5bb4e3795..845bcba62 100644 --- a/base/table.go +++ b/base/table.go @@ -208,6 +208,11 @@ type TableDecl struct { // and paints from. It keeps its capacity across frames, so a warm table // fits no heading into a new allocation. columns []style.TableColumn + // fontSize and foreground are the element's explicit text style: what the + // recipe's spec default is replaced with when the element set one. + fontSize float32 + foreground gfx.Color + hasForeground bool } // Table adds a table painted by components.Table, with a header row of sortable @@ -244,20 +249,41 @@ func (f *Frame) Table(state *TableState, spec TableSpec) Box { rows = max(spec.Source.Len(), 0) } decl := TableDecl{spec: spec, state: state, rows: rows} - if spec.FitHeadings && f.Surface != nil && len(spec.Columns) > 0 { - // Reuse the fitted columns of this table from the last paint. The slice - // is at the same index every frame, so its capacity survives the reset. - if index < cap(*decls) { - decl.columns = (*decls)[:cap(*decls)][index].columns - } - decl.columns = append(decl.columns[:0], spec.Columns...) - fitTableHeadings(f.Surface, f.Palette, decl.columns, spec.Headers, spec.FontSize, spec.CellPadding) - decl.spec.Columns = decl.columns + if spec.FitHeadings && index < cap(*decls) { + // Reuse the fitted columns of this table from the last paint even though + // the fit itself waits for the element's FontSize in resolveTables. + decl.columns = (*decls)[:cap(*decls)][index].columns } *decls = append(*decls, decl) return b } +// resolveTables reads the element-level text style into each table's declaration +// and fits the headings once the element's FontSize is known, before measurement. +func (f *Frame) resolveTables() { + decls := &WidgetsOf(f).tables + for i := range f.Nodes { + n := &f.Nodes[i] + if n.Kind != kindTable || int(n.Aux) >= len(*decls) { + continue + } + decl := &(*decls)[n.Aux] + decl.fontSize = decl.spec.FontSize + if n.FontSet { + decl.fontSize = n.FontSize + } + if n.Flags&flagHasColor != 0 { + decl.foreground, decl.hasForeground = n.Color, true + } + if !decl.spec.FitHeadings || f.Surface == nil || len(decl.spec.Columns) == 0 { + continue + } + decl.columns = append(decl.columns[:0], decl.spec.Columns...) + fitTableHeadings(f.Surface, f.Palette, decl.columns, decl.spec.Headers, decl.fontSize, decl.spec.CellPadding) + decl.spec.Columns = decl.columns + } +} + // fitTableHeadings widens each fixed-width column of columns that is narrower // than its heading to the width the heading needs, so no heading is cut or ends // in an ellipsis. A column that takes the remaining space (Width <= 0) and a diff --git a/base/table_element_style_test.go b/base/table_element_style_test.go new file mode 100644 index 000000000..5f1e4c3a0 --- /dev/null +++ b/base/table_element_style_test.go @@ -0,0 +1,76 @@ +package base_test + +import ( + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" +) + +// A Table's element-level FontSize and Color style its header and its cells, +// replacing the spec's font size and the theme's foreground. +func TestTableElementTextStyleReachesHeaderAndCells(t *testing.T) { + theme := gfx.LightTheme() + ink := gfx.Color{Red: 1, Alpha: 1} + spec := TableSpec{ + Columns: []style.TableColumn{{Width: 120}}, + Headers: []string{"Name"}, + Source: &countingRows{n: 2}, + } + paint := func(declare func(f *Frame) Box) ([]gfx.Text, Rect) { + canvas := testCanvas() + var view View + var box Box + view.Draw(canvas, theme, gfx.Rect{Width: 300, Height: 200}, func(f *Frame) { + f.Column().Pad(10).Children(func() { box = declare(f) }) + }) + return canvas.Texts(), box.Rect() + } + + plain, _ := paint(func(f *Frame) Box { return f.Table(&TableState{}, spec) }) + styled, _ := paint(func(f *Frame) Box { + return f.Table(&TableState{}, spec).FontSize(18).Color(ink) + }) + if len(plain) == 0 || len(styled) == 0 { + t.Fatalf("painted %d and %d texts, want the header and cells", len(plain), len(styled)) + } + if len(plain) != len(styled) { + t.Fatalf("text count changed with the element's style: %d vs %d", len(plain), len(styled)) + } + for _, text := range styled { + if text.Style.Size != 18 { + t.Errorf("text %q size = %v, want the element's 18", text.Value, text.Style.Size) + } + if text.Style.Color != ink { + t.Errorf("text %q color = %v, want the element's %v", text.Value, text.Style.Color, ink) + } + } + if plain[0].Style.Size == 18 { + t.Error("the unstyled table already painted at 18; the test cannot tell the override apart") + } +} + +// The element's FontSize replaces the spec's, rather than adding to it. +func TestTableElementFontSizeWinsOverTheSpec(t *testing.T) { + spec := TableSpec{ + Columns: []style.TableColumn{{Width: 120}}, + Headers: []string{"Name"}, + Source: &countingRows{n: 1}, + FontSize: 12, + } + canvas := testCanvas() + var view View + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 300, Height: 200}, func(f *Frame) { + f.Column().Pad(10).Children(func() { f.Table(&TableState{}, spec).FontSize(16) }) + }) + texts := canvas.Texts() + if len(texts) == 0 { + t.Fatal("no table text painted") + } + for _, text := range texts { + if text.Style.Size != 16 { + t.Errorf("text %q size = %v, want the element's 16, not the spec's 12", text.Value, text.Style.Size) + } + } +} diff --git a/base/tabs.go b/base/tabs.go index 0d8bdd9e7..66d591b98 100644 --- a/base/tabs.go +++ b/base/tabs.go @@ -100,15 +100,27 @@ func (b Box) TabClicked() (int, bool) { func (f *Frame) measureTabs(n *Node) { t := &WidgetsOf(f).tabs[n.Aux] - listHeight, listPadding, triggerHeight, triggerPad, lineGap, fontSize, weight := style.TabsGeometry(f.Palette.Metrics) + _, listPadding, triggerHeight, triggerPad, lineGap, fontSize, weight := style.TabsGeometry(f.Palette.Metrics) if n.FontSize > 0 { fontSize = n.FontSize } if n.WeightSet || n.Weight != 0 { weight = n.Weight } - if n.Pad[0] != 0 || n.PadSet&padTop != 0 { - listPadding = n.Pad[0] + // The recipe filled every side the caller did not set with the same theme + // padding, so the element's Pad is the strip's four inner edges here. + top, right, bottom, left := n.Pad[0], n.Pad[1], n.Pad[2], n.Pad[3] + if n.PadSet&padTop == 0 { + top = listPadding + } + if n.PadSet&padRight == 0 { + right = listPadding + } + if n.PadSet&padBottom == 0 { + bottom = listPadding + } + if n.PadSet&padLeft == 0 { + left = listPadding } var widest float32 for index, label := range t.labels { @@ -133,14 +145,15 @@ func (f *Frame) measureTabs(n *Node) { gap = lineGap } between := gap * max(count-1, 0) + triggerWidth := widest + 2*triggerPad switch { case t.vertical && t.line: - n.Pref = [2]float32{widest + 2*triggerPad + 2*listPadding - 8 + TabIndicator + 1, triggerHeight*count + between} + n.Pref = [2]float32{triggerWidth + left + right + TabIndicator + 1, triggerHeight*count + between + top + bottom} case t.vertical: - n.Pref = [2]float32{widest + 2*triggerPad + 2*listPadding - 8, triggerHeight*count + between} + n.Pref = [2]float32{triggerWidth + left + right, triggerHeight*count + between + top + bottom} case t.line: - n.Pref = [2]float32{(widest+2*triggerPad+2*listPadding)*count + between, listHeight + TabIndicator} + n.Pref = [2]float32{triggerWidth*count + between + left + right, top + triggerHeight + bottom + TabIndicator} default: - n.Pref = [2]float32{(widest+2*triggerPad+2*listPadding)*count + between, listHeight} + n.Pref = [2]float32{triggerWidth*count + between + left + right, top + triggerHeight + bottom} } } diff --git a/base/tabs_node_test.go b/base/tabs_node_test.go index e84893120..f0adcd6c2 100644 --- a/base/tabs_node_test.go +++ b/base/tabs_node_test.go @@ -1,6 +1,7 @@ package base_test import ( + "math" "testing" . "github.com/vivaui/viva/base" @@ -118,3 +119,54 @@ func TestTabsPropertiesReachTheStrip(t *testing.T) { t.Errorf("line trigger gap = %v, want the explicit 10", gap) } } + +// Pad reaches the strip on every side: it insets the triggers and the strip's +// thickness, rather than only the top. +func TestTabsPadOnEverySide(t *testing.T) { + horizontal := probeTabs(t, func(f *Frame) Box { + return f.Tabs(tabsScope, tabsNodeLabels, 0).PadSides(2, 8, 4, 12).Height(44) + }) + first, last := horizontal.hits[0].Bounds, horizontal.hits[len(horizontal.hits)-1].Bounds + if math.Abs(float64(first.X-(horizontal.box.X+12))) > 0.01 || math.Abs(float64(first.Y-(horizontal.box.Y+2))) > 0.01 { + t.Errorf("first trigger at %v, want the strip's left 12 and top 2", first) + } + if math.Abs(float64(first.Height-(44-2-4))) > 0.01 { + t.Errorf("trigger height = %v, want the strip height less top and bottom", first.Height) + } + if math.Abs(float64(last.X+last.Width-(horizontal.box.X+horizontal.box.Width-8))) > 0.01 { + t.Errorf("last trigger ends at %v, want 8 from the right edge %v", last.X+last.Width, horizontal.box.X+horizontal.box.Width) + } + + vertical := probeTabs(t, func(f *Frame) Box { + return f.Tabs(tabsScope, tabsNodeLabels, 0).Vertical().PadSides(2, 8, 4, 12).Height(140) + }) + first, last = vertical.hits[0].Bounds, vertical.hits[len(vertical.hits)-1].Bounds + if math.Abs(float64(first.X-(vertical.box.X+12))) > 0.01 || math.Abs(float64(first.Width-(vertical.box.Width-12-8))) > 0.01 { + t.Errorf("vertical trigger at %v width %v, want 12 in and the width less both sides", first, first.Width) + } + if math.Abs(float64(first.Y-(vertical.box.Y+2))) > 0.01 || math.Abs(float64(last.Y+last.Height-(vertical.box.Y+vertical.box.Height-4))) > 0.01 { + t.Errorf("vertical triggers from %v to %v, want 2 from top and 4 from bottom", first.Y, last.Y+last.Height) + } +} + +// Without an explicit height a strip is exactly its triggers and its Pad: PadY(0) +// no longer falls back to the theme's 36. +func TestTabsPadYShrinksTheAutomaticHeight(t *testing.T) { + theme := gfx.LightTheme() + _, _, triggerHeight, _, _, _, _ := style.TabsGeometry(theme.Metrics) + for _, tc := range []struct { + name string + declare func(f *Frame) Box + want float32 + }{ + {"padY 0", func(f *Frame) Box { return f.Tabs(tabsScope, tabsNodeLabels, 0).PadY(0) }, triggerHeight}, + {"padY 2", func(f *Frame) Box { return f.Tabs(tabsScope, tabsNodeLabels, 0).PadY(2) }, triggerHeight + 4}, + {"line padY 2", func(f *Frame) Box { return f.Tabs(tabsScope, tabsNodeLabels, 0).Line().PadY(2) }, triggerHeight + 4 + TabIndicator}, + } { + p := probeTabs(t, tc.declare) + if p.box.Height != tc.want { + t.Errorf("%s: strip height = %v, want %v", tc.name, p.box.Height, tc.want) + } + } + _ = theme +} diff --git a/cmd/viva/templates/checkbox.go.txt b/cmd/viva/templates/checkbox.go.txt index 70743af3f..2a5b74c1c 100644 --- a/cmd/viva/templates/checkbox.go.txt +++ b/cmd/viva/templates/checkbox.go.txt @@ -23,7 +23,10 @@ type Checkbox struct { // markColor overrides the recipe's mark when hasMarkColor is set. markColor gfx.Color hasMarkColor bool - checked bool + // explicitBounds keeps the caller's bounds for the box instead of the + // control's 16px extent, for an element that set a width or height. + explicitBounds bool + checked bool // indeterminate is Base UI's mixed state: the box shows a dash and the // accessibility value is "mixed", whatever checked says. indeterminate bool @@ -78,6 +81,13 @@ func (checkbox Checkbox) UnpaintedSurface() Checkbox { return checkbox } +// ExplicitBounds keeps the bounds BeginCheckbox was given as the box instead +// of the control's extent; the element sizes the box then. +func (checkbox Checkbox) ExplicitBounds() Checkbox { + checkbox.explicitBounds = true + return checkbox +} + // MarkColor paints the check or dash in color instead of the recipe's mark. func (checkbox Checkbox) MarkColor(color gfx.Color) Checkbox { checkbox.markColor, checkbox.hasMarkColor = color, true @@ -139,8 +149,10 @@ func (checkbox Checkbox) Paint() CheckboxResult { return result } scale := checkbox.theme.Metrics.ControlHeight / 32 - checkbox.bounds.Width = CheckboxExtent(checkbox.theme) - checkbox.bounds.Height = checkbox.bounds.Width + if !checkbox.explicitBounds || checkbox.bounds.Width <= 0 || checkbox.bounds.Height <= 0 { + checkbox.bounds.Width = CheckboxExtent(checkbox.theme) + checkbox.bounds.Height = checkbox.bounds.Width + } state := gfx.State{ Checked: checkbox.checked, Mixed: checkbox.indeterminate, FocusVisible: checkbox.focused, @@ -246,17 +258,18 @@ func checkboxRecipe(theme *gfx.Theme, state gfx.State) CheckboxLook { // a check when checked, nothing otherwise. The check is the vector the shadcn checkbox // draws, so a box of the application's own shows the same mark. func PaintCheckboxMark(canvas *gfx.Canvas, bounds gfx.Rect, state gfx.State, color gfx.Color) { + side := min(bounds.Width, bounds.Height) switch { case state.Mixed: - dash := bounds.Width * 0.5 - thickness := max(bounds.Height/8, 1) + dash := side * 0.5 + thickness := max(side/8, 1) canvas.Fill(gfx.Rect{ X: bounds.X + (bounds.Width-dash)/2, Y: bounds.Y + (bounds.Height-thickness)/2, Width: dash, Height: thickness, }, color) case state.Checked: - paintCheck(canvas, bounds, bounds.Height*0.875, color) + paintCheck(canvas, bounds, side*0.875, color) } } func CheckboxExtent(theme gfx.Theme) float32 { return base.CheckboxExtent(theme) } diff --git a/cmd/viva/templates/table.go.txt b/cmd/viva/templates/table.go.txt index 0251908a1..40e93143f 100644 --- a/cmd/viva/templates/table.go.txt +++ b/cmd/viva/templates/table.go.txt @@ -55,6 +55,10 @@ type Table struct { headerSet bool Selection TableSelection text *tableTextState + // foreground is the element's text color when hasForeground is set; the rows + // and headers paint in it instead of the theme's. + foreground gfx.Color + hasForeground bool } type tableTextState struct { @@ -335,7 +339,7 @@ func (table *Table) paintRow(id gfx.ID, cells []string, state TableRowState, kin collect := cellsOut != nil cellsOut = cellsOut[:0] background := table.theme.Background - foreground := table.theme.Foreground + foreground := table.textColor() weight := gfx.WeightRegular paintBackground := false if kind == tableRowHeader { @@ -713,6 +717,22 @@ func nearestTableTextCell(cells []tableTextCell, x float32) int { // tableSelectionColors keeps the table recipe self-contained while preserving // the Primary fallback used by hand-built themes from before Selection existed. +// Foreground paints the rows and headers in color instead of the theme's; +// selection colors keep their own foreground. +func (table Table) Foreground(color gfx.Color) Table { + table.foreground, table.hasForeground = color, true + return table +} + +// textColor is the color of row and header text: the element's own when it set +// one, else the theme's foreground. +func (table Table) textColor() gfx.Color { + if table.hasForeground { + return table.foreground + } + return table.theme.Foreground +} + func tableSelectionColors(theme gfx.Theme) (background, foreground gfx.Color) { background, foreground = theme.Selection, theme.SelectionForeground if background.Alpha == 0 { @@ -897,7 +917,7 @@ func (table *Table) paintSortableHeaderCell( ) tableTextCell { canvas, theme := table.canvas, table.theme interactive := !cell.ID.IsZero() - color := theme.Foreground + color := table.textColor() if cell.Disabled { color.Alpha *= 0.5 } diff --git a/cmd/viva/templates/tabs.go.txt b/cmd/viva/templates/tabs.go.txt index adcbf9442..0be4373af 100644 --- a/cmd/viva/templates/tabs.go.txt +++ b/cmd/viva/templates/tabs.go.txt @@ -40,8 +40,15 @@ type Tabs struct { type TabsStyle struct { // ListHeight and ListPadding size the strip; TriggerHeight and TriggerPadding // size one trigger inside it. LineGap is the gap between line-variant triggers; - // Gap is used for both variants when set. - ListHeight, ListPadding, TriggerHeight, TriggerPadding, LineGap, Gap float32 + // Gap is used for both variants when set. ListPadding is the room on each of the + // strip's four sides; HasListPadding distinguishes an explicit zero from the + // theme default. + ListHeight float32 + ListPadding gfx.Insets + HasListPadding bool + TriggerHeight float32 + TriggerPadding float32 + LineGap, Gap float32 // TriggerRadius is a trigger's corner radius; the strip's own radius is the // element's Radius, painted by the engine. TriggerRadius float32 @@ -57,10 +64,11 @@ type TabsStyle struct { // tabsPaint is TabsStyle resolved against the theme at Paint. type tabsPaint struct { - listHeight, listPadding, triggerHeight, triggerPadding, lineGap, gap float32 - listRadius, triggerRadius, fontSize, weight float32 - foreground gfx.Color - hasForeground bool + listHeight, triggerHeight, triggerPadding, lineGap, gap float32 + listPadding gfx.Insets + listRadius, triggerRadius, fontSize, weight float32 + foreground gfx.Color + hasForeground bool } // WithStyle overrides the strip's measurements, colors and label style; zero @@ -208,7 +216,7 @@ func (tabs Tabs) resolvedPaint() tabsPaint { metrics := tabs.theme.Metrics defHeight, defPadding, defTriggerHeight, defTriggerPad, defLineGap, defFont, defWeight := style.TabsGeometry(metrics) p := tabsPaint{ - listHeight: defHeight, listPadding: defPadding, + listHeight: defHeight, listPadding: gfx.All(defPadding), triggerHeight: defTriggerHeight, triggerPadding: defTriggerPad, lineGap: defLineGap, gap: 0, listRadius: style.TabsListRadius(metrics), triggerRadius: style.TabsTriggerRadius(metrics), @@ -218,7 +226,7 @@ func (tabs Tabs) resolvedPaint() tabsPaint { if override.ListHeight > 0 { p.listHeight = override.ListHeight } - if override.ListPadding > 0 { + if override.HasListPadding { p.listPadding = override.ListPadding } if override.TriggerHeight > 0 { @@ -265,20 +273,24 @@ func (tabs Tabs) Paint() TabsResult { widest = max(widest, width) total += width } + pad := tabs.paint.listPadding if tabs.direction == TabsVertical { - tabs.bounds.Width = widest + tabs.paint.listPadding*2 + tabs.bounds.Width = widest + pad.Left + pad.Right } else { - tabs.bounds.Width = total + gap*(count-1) + tabs.paint.listPadding*2 + tabs.bounds.Width = total + gap*(count-1) + pad.Left + pad.Right } } if tabs.bounds.Width <= 0 { return result } if tabs.bounds.Height <= 0 { + pad := tabs.paint.listPadding if tabs.direction == TabsVertical { - tabs.bounds.Height = tabs.paint.triggerHeight*count + gap*(count-1) + tabs.paint.listPadding*2 - } else { + tabs.bounds.Height = tabs.paint.triggerHeight*count + gap*(count-1) + pad.Top + pad.Bottom + } else if tabs.paint.listHeight > 0 { tabs.bounds.Height = tabs.paint.listHeight + } else { + tabs.bounds.Height = tabs.paint.triggerHeight + pad.Top + pad.Bottom } } result.bounds = tabs.bounds @@ -293,9 +305,10 @@ func (tabs Tabs) Paint() TabsResult { } tabs.canvas.Rounded(tabs.bounds, listRadius, listFill) } + pad := tabs.paint.listPadding inner := gfx.Rect{ - X: tabs.bounds.X + tabs.paint.listPadding, Y: tabs.bounds.Y + tabs.paint.listPadding, - Width: tabs.bounds.Width - tabs.paint.listPadding*2, Height: tabs.bounds.Height - tabs.paint.listPadding*2, + X: tabs.bounds.X + pad.Left, Y: tabs.bounds.Y + pad.Top, + Width: max(tabs.bounds.Width-pad.Left-pad.Right, 0), Height: max(tabs.bounds.Height-pad.Top-pad.Bottom, 0), } cursor := float32(0) for index := range tabs.count() { diff --git a/components/checkbox.go b/components/checkbox.go index 726e67b4d..62e1d35e7 100644 --- a/components/checkbox.go +++ b/components/checkbox.go @@ -23,7 +23,10 @@ type Checkbox struct { // markColor overrides the recipe's mark when hasMarkColor is set. markColor gfx.Color hasMarkColor bool - checked bool + // explicitBounds keeps the caller's bounds for the box instead of the + // control's 16px extent, for an element that set a width or height. + explicitBounds bool + checked bool // indeterminate is Base UI's mixed state: the box shows a dash and the // accessibility value is "mixed", whatever checked says. indeterminate bool @@ -78,6 +81,13 @@ func (checkbox Checkbox) UnpaintedSurface() Checkbox { return checkbox } +// ExplicitBounds keeps the bounds BeginCheckbox was given as the box instead +// of the control's extent; the element sizes the box then. +func (checkbox Checkbox) ExplicitBounds() Checkbox { + checkbox.explicitBounds = true + return checkbox +} + // MarkColor paints the check or dash in color instead of the recipe's mark. func (checkbox Checkbox) MarkColor(color gfx.Color) Checkbox { checkbox.markColor, checkbox.hasMarkColor = color, true @@ -139,8 +149,10 @@ func (checkbox Checkbox) Paint() CheckboxResult { return result } scale := checkbox.theme.Metrics.ControlHeight / 32 - checkbox.bounds.Width = CheckboxExtent(checkbox.theme) - checkbox.bounds.Height = checkbox.bounds.Width + if !checkbox.explicitBounds || checkbox.bounds.Width <= 0 || checkbox.bounds.Height <= 0 { + checkbox.bounds.Width = CheckboxExtent(checkbox.theme) + checkbox.bounds.Height = checkbox.bounds.Width + } state := gfx.State{ Checked: checkbox.checked, Mixed: checkbox.indeterminate, FocusVisible: checkbox.focused, @@ -246,17 +258,18 @@ func checkboxRecipe(theme *gfx.Theme, state gfx.State) CheckboxLook { // a check when checked, nothing otherwise. The check is the vector the shadcn checkbox // draws, so a box of the application's own shows the same mark. func PaintCheckboxMark(canvas *gfx.Canvas, bounds gfx.Rect, state gfx.State, color gfx.Color) { + side := min(bounds.Width, bounds.Height) switch { case state.Mixed: - dash := bounds.Width * 0.5 - thickness := max(bounds.Height/8, 1) + dash := side * 0.5 + thickness := max(side/8, 1) canvas.Fill(gfx.Rect{ X: bounds.X + (bounds.Width-dash)/2, Y: bounds.Y + (bounds.Height-thickness)/2, Width: dash, Height: thickness, }, color) case state.Checked: - paintCheck(canvas, bounds, bounds.Height*0.875, color) + paintCheck(canvas, bounds, side*0.875, color) } } func CheckboxExtent(theme gfx.Theme) float32 { return base.CheckboxExtent(theme) } diff --git a/components/table.go b/components/table.go index baf233ccb..1e7a06d40 100644 --- a/components/table.go +++ b/components/table.go @@ -55,6 +55,10 @@ type Table struct { headerSet bool Selection TableSelection text *tableTextState + // foreground is the element's text color when hasForeground is set; the rows + // and headers paint in it instead of the theme's. + foreground gfx.Color + hasForeground bool } type tableTextState struct { @@ -335,7 +339,7 @@ func (table *Table) paintRow(id gfx.ID, cells []string, state TableRowState, kin collect := cellsOut != nil cellsOut = cellsOut[:0] background := table.theme.Background - foreground := table.theme.Foreground + foreground := table.textColor() weight := gfx.WeightRegular paintBackground := false if kind == tableRowHeader { @@ -713,6 +717,22 @@ func nearestTableTextCell(cells []tableTextCell, x float32) int { // tableSelectionColors keeps the table recipe self-contained while preserving // the Primary fallback used by hand-built themes from before Selection existed. +// Foreground paints the rows and headers in color instead of the theme's; +// selection colors keep their own foreground. +func (table Table) Foreground(color gfx.Color) Table { + table.foreground, table.hasForeground = color, true + return table +} + +// textColor is the color of row and header text: the element's own when it set +// one, else the theme's foreground. +func (table Table) textColor() gfx.Color { + if table.hasForeground { + return table.foreground + } + return table.theme.Foreground +} + func tableSelectionColors(theme gfx.Theme) (background, foreground gfx.Color) { background, foreground = theme.Selection, theme.SelectionForeground if background.Alpha == 0 { @@ -897,7 +917,7 @@ func (table *Table) paintSortableHeaderCell( ) tableTextCell { canvas, theme := table.canvas, table.theme interactive := !cell.ID.IsZero() - color := theme.Foreground + color := table.textColor() if cell.Disabled { color.Alpha *= 0.5 } diff --git a/components/tabs.go b/components/tabs.go index ca3e5e6c5..c1c821564 100644 --- a/components/tabs.go +++ b/components/tabs.go @@ -40,8 +40,15 @@ type Tabs struct { type TabsStyle struct { // ListHeight and ListPadding size the strip; TriggerHeight and TriggerPadding // size one trigger inside it. LineGap is the gap between line-variant triggers; - // Gap is used for both variants when set. - ListHeight, ListPadding, TriggerHeight, TriggerPadding, LineGap, Gap float32 + // Gap is used for both variants when set. ListPadding is the room on each of the + // strip's four sides; HasListPadding distinguishes an explicit zero from the + // theme default. + ListHeight float32 + ListPadding gfx.Insets + HasListPadding bool + TriggerHeight float32 + TriggerPadding float32 + LineGap, Gap float32 // TriggerRadius is a trigger's corner radius; the strip's own radius is the // element's Radius, painted by the engine. TriggerRadius float32 @@ -57,10 +64,11 @@ type TabsStyle struct { // tabsPaint is TabsStyle resolved against the theme at Paint. type tabsPaint struct { - listHeight, listPadding, triggerHeight, triggerPadding, lineGap, gap float32 - listRadius, triggerRadius, fontSize, weight float32 - foreground gfx.Color - hasForeground bool + listHeight, triggerHeight, triggerPadding, lineGap, gap float32 + listPadding gfx.Insets + listRadius, triggerRadius, fontSize, weight float32 + foreground gfx.Color + hasForeground bool } // WithStyle overrides the strip's measurements, colors and label style; zero @@ -208,7 +216,7 @@ func (tabs Tabs) resolvedPaint() tabsPaint { metrics := tabs.theme.Metrics defHeight, defPadding, defTriggerHeight, defTriggerPad, defLineGap, defFont, defWeight := style.TabsGeometry(metrics) p := tabsPaint{ - listHeight: defHeight, listPadding: defPadding, + listHeight: defHeight, listPadding: gfx.All(defPadding), triggerHeight: defTriggerHeight, triggerPadding: defTriggerPad, lineGap: defLineGap, gap: 0, listRadius: style.TabsListRadius(metrics), triggerRadius: style.TabsTriggerRadius(metrics), @@ -218,7 +226,7 @@ func (tabs Tabs) resolvedPaint() tabsPaint { if override.ListHeight > 0 { p.listHeight = override.ListHeight } - if override.ListPadding > 0 { + if override.HasListPadding { p.listPadding = override.ListPadding } if override.TriggerHeight > 0 { @@ -265,20 +273,24 @@ func (tabs Tabs) Paint() TabsResult { widest = max(widest, width) total += width } + pad := tabs.paint.listPadding if tabs.direction == TabsVertical { - tabs.bounds.Width = widest + tabs.paint.listPadding*2 + tabs.bounds.Width = widest + pad.Left + pad.Right } else { - tabs.bounds.Width = total + gap*(count-1) + tabs.paint.listPadding*2 + tabs.bounds.Width = total + gap*(count-1) + pad.Left + pad.Right } } if tabs.bounds.Width <= 0 { return result } if tabs.bounds.Height <= 0 { + pad := tabs.paint.listPadding if tabs.direction == TabsVertical { - tabs.bounds.Height = tabs.paint.triggerHeight*count + gap*(count-1) + tabs.paint.listPadding*2 - } else { + tabs.bounds.Height = tabs.paint.triggerHeight*count + gap*(count-1) + pad.Top + pad.Bottom + } else if tabs.paint.listHeight > 0 { tabs.bounds.Height = tabs.paint.listHeight + } else { + tabs.bounds.Height = tabs.paint.triggerHeight + pad.Top + pad.Bottom } } result.bounds = tabs.bounds @@ -293,9 +305,10 @@ func (tabs Tabs) Paint() TabsResult { } tabs.canvas.Rounded(tabs.bounds, listRadius, listFill) } + pad := tabs.paint.listPadding inner := gfx.Rect{ - X: tabs.bounds.X + tabs.paint.listPadding, Y: tabs.bounds.Y + tabs.paint.listPadding, - Width: tabs.bounds.Width - tabs.paint.listPadding*2, Height: tabs.bounds.Height - tabs.paint.listPadding*2, + X: tabs.bounds.X + pad.Left, Y: tabs.bounds.Y + pad.Top, + Width: max(tabs.bounds.Width-pad.Left-pad.Right, 0), Height: max(tabs.bounds.Height-pad.Top-pad.Bottom, 0), } cursor := float32(0) for index := range tabs.count() { diff --git a/ui/controls_paint.go b/ui/controls_paint.go index 552114998..4c917cf38 100644 --- a/ui/controls_paint.go +++ b/ui/controls_paint.go @@ -10,13 +10,23 @@ import ( // checkboxSurfaceRect is the box a Checkbox paints inside its element: beside // its caption at the element's start, centered in the element when it has none. -func checkboxSurfaceRect(f *Frame, r Rect, caption bool) Rect { +// An explicit pixel Size sizes the box itself; a non-square box is allowed and +// its mark is drawn for the shorter side. +func checkboxSurfaceRect(f *Frame, n *Node) Rect { side := components.CheckboxExtent(f.Palette) - x := r.X + (r.Width-side)/2 - if caption { + width, height := side, side + if d := n.Size[AxisX]; d.Kind == DimPx { + width = d.Value + } + if d := n.Size[AxisY]; d.Kind == DimPx { + height = d.Value + } + r := n.Rect + x := r.X + (r.Width-width)/2 + if n.Text != "" { x = r.X } - return Rect{X: x, Y: r.Y + (r.Height-side)/2, Width: side, Height: side} + return Rect{X: x, Y: r.Y + (r.Height-height)/2, Width: width, Height: height} } // switchSurfaceRect is the track a Switch paints inside its element; an explicit @@ -24,13 +34,21 @@ func checkboxSurfaceRect(f *Frame, r Rect, caption bool) Rect { func switchSurfaceRect(f *Frame, n *Node) Rect { small := n.Flags&FlagSmall != 0 width, height := components.SwitchExtent(f.Palette, small) + r := n.Rect + // An explicit pixel size, and a Fill or Percent size the layout resolved, + // both size the track. A track stretched across a row keeps its caption, so + // the caption's width and the gap after it come out of the element's width. + stretched := func(d Dimension) bool { return d.Kind == DimFill || d.Kind == DimPercent } if d := n.Size[AxisX]; d.Kind == DimPx { width = d.Value + } else if stretched(d) { + width = max(r.Width-captionWidth(f, n)-base.CaptionGap, 0) } if d := n.Size[AxisY]; d.Kind == DimPx { height = d.Value + } else if stretched(d) { + height = r.Height } - r := n.Rect x := r.X + (r.Width-width)/2 if n.Text != "" { x = r.X @@ -38,12 +56,25 @@ func switchSurfaceRect(f *Frame, n *Node) Rect { return Rect{X: x, Y: r.Y + (r.Height-height)/2, Width: width, Height: height} } +// captionWidth is the width a Switch's caption takes at the element's text +// style, the same measurement measureSwitchNode adds to the element. +func captionWidth(f *Frame, n *Node) float32 { + if n.Text == "" { + return 0 + } + weight := gfx.WeightMedium + if n.WeightSet || n.Weight != 0 { + weight = n.Weight + } + return f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), weight) +} + // controlSurfaceRect is where a themed control's own surface paints when it is // smaller than the element: a Checkbox's box, a Switch's track. func controlSurfaceRect(f *Frame, n *Node) Rect { switch n.Kind { case KindCheckbox: - return checkboxSurfaceRect(f, n.Rect, n.Text != "") + return checkboxSurfaceRect(f, n) case KindSwitch: return switchSurfaceRect(f, n) } @@ -70,7 +101,7 @@ func frameSwitchLook(f *Frame, n *Node, Palette *Theme, state gfx.State, progres func paintCheckbox(f *Frame, v ControlView, n *Node) { canvas := f.Surface - bounds := checkboxSurfaceRect(f, v.Rect, v.Text != "") + bounds := checkboxSurfaceRect(f, n) themed := v.Flags&FlagThemed != 0 if v.Text != "" && !themed { f.PaintCaptionView(v, bounds) @@ -79,6 +110,9 @@ func paintCheckbox(f *Frame, v ControlView, n *Node) { if v.Exact { checkbox = checkbox.HitBounds(v.Rect) } + if n.Size[AxisX].Kind != DimAuto || n.Size[AxisY].Kind != DimAuto { + checkbox = checkbox.ExplicitBounds() + } if v.Flags&FlagMixed != 0 { checkbox = checkbox.Indeterminate() } diff --git a/ui/table_paint.go b/ui/table_paint.go index 3898c929f..5b5606e20 100644 --- a/ui/table_paint.go +++ b/ui/table_paint.go @@ -13,7 +13,10 @@ import ( func paintTableRows(f *Frame, t *TableDecl, rows Rect, First, Last int, top, contentWidth, rowHeight float32) { canvas := f.Surface table := components.BeginTable(canvas, f.Palette, rows, t.GetSpec().Columns). - RowHeight(rowHeight).FontSize(t.GetSpec().FontSize).CellPadding(t.GetSpec().CellPadding) + RowHeight(rowHeight).FontSize(t.GetFontSize()).CellPadding(t.GetSpec().CellPadding) + if t.GetForegroundSet() { + table = table.Foreground(t.GetForeground()) + } w := base.WidgetsOf(f) if cap(w.GetCells()) < len(t.GetSpec().Columns) { w.SetCells(make([]string, len(t.GetSpec().Columns))) @@ -110,12 +113,15 @@ func paintTableHeaderRow(f *Frame, t *TableDecl, r Rect, headerHeight, rowHeight headerRow.Height = headerHeight } table := components.BeginTable(canvas, f.Palette, headerRow, t.GetSpec().Columns). - RowHeight(rowHeight).HeaderHeight(headerHeight).FontSize(t.GetSpec().FontSize).CellPadding(t.GetSpec().CellPadding) + RowHeight(rowHeight).HeaderHeight(headerHeight).FontSize(t.GetFontSize()).CellPadding(t.GetSpec().CellPadding) + if t.GetForegroundSet() { + table = table.Foreground(t.GetForeground()) + } table.Header(t.GetSpec().Headers) sorted, descending, isSorted := t.GetState().Sort() metrics := f.Palette.Metrics - fontSize := t.GetSpec().FontSize + fontSize := t.GetFontSize() if fontSize <= 0 { fontSize = metrics.FontSizeM } diff --git a/ui/tabs_paint.go b/ui/tabs_paint.go index 0e5dba7e4..d2956cb93 100644 --- a/ui/tabs_paint.go +++ b/ui/tabs_paint.go @@ -64,9 +64,10 @@ func paintTabs(f *Frame, n *Node) { tabs = tabs.Vertical() } tabStyle := components.TabsStyle{ - ListPadding: n.Pad[0], - Gap: n.Gap, - FontSize: n.FontSize, + ListPadding: gfx.Insets{Top: n.Pad[0], Right: n.Pad[1], Bottom: n.Pad[2], Left: n.Pad[3]}, + HasListPadding: true, + Gap: n.Gap, + FontSize: n.FontSize, } if n.WeightSet { tabStyle.Weight = n.Weight From 913e2dc6bbc651eb062ad5f8fba81738178a4b29 Mon Sep 17 00:00:00 2001 From: ma <110266605+403bug@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:01:32 +0800 Subject: [PATCH 06/16] fix(list): include row margins in scrollable content height --- base/list.go | 13 +++++++++-- base/list_margin_test.go | 50 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 base/list_margin_test.go diff --git a/base/list.go b/base/list.go index fca12a2f0..a6a999f94 100644 --- a/base/list.go +++ b/base/list.go @@ -1276,14 +1276,23 @@ func (p *Page) TypeKey(event gfx.KeyEvent) (gfx.EventResult, bool) { return p.ListType(event) } +// rowSlotHeight is the room a row takes in the list: its rectangle and the +// vertical margins the layout puts around it. A row that sets one carries it +// between itself and the next, so measuring only the rectangle would leave the +// content the list scrolls to shorter than the rows it places, and the last +// rows could never be scrolled into view. +func rowSlotHeight(node *Node) float32 { + return node.Rect.Height + node.Margin[0] + node.Margin[2] +} + // measureLists records the heights the layout gave the rows the Lists declared. func (p *Page) measureLists() { for _, list := range p.lists { for k, node := range p.listRows[list.rows:list.until] { - list.state.measured(list.First+k, p.ctx.f.Nodes[node].Rect.Height) + list.state.measured(list.First+k, rowSlotHeight(&p.ctx.f.Nodes[node])) } if list.pinned >= 0 { - list.state.measured(list.pinnedRow, p.ctx.f.Nodes[list.pinned].Rect.Height) + list.state.measured(list.pinnedRow, rowSlotHeight(&p.ctx.f.Nodes[list.pinned])) } list.state.afterLayout() // the offset is the layout's now, not the request's } diff --git a/base/list_margin_test.go b/base/list_margin_test.go new file mode 100644 index 000000000..8a11f8067 --- /dev/null +++ b/base/list_margin_test.go @@ -0,0 +1,50 @@ +package base_test + +import ( + "testing" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) + +// A margin below a row is room the row takes between itself and the next one, so +// the content a list scrolls to must hold it: measured by its rectangle alone, the +// wheel stops short of the end and the last rows never come into view. +func TestListReachesItsLastRowWhenEveryRowSetsAMargin(t *testing.T) { + const rows, rowHeight, rowGap, window = 17, 44, 4, 602 + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + var list ListState + var last Box + draw := func(c C) { + last = Box{} + Column(c).Fill().Children(func() { + List(c, &list, rows, func(row ListRow) { + box := row.Element.Height(rowHeight).MarginBottom(rowGap) + if row.Index == rows-1 { + last = box + } + }).Grow(1).MinHeight(0) + }) + } + bounds := gfx.Rect{Width: 300, Height: window} + page.Draw(canvas, bounds, draw) + // The wheel is how a reader reaches the end: 60 rows' worth is more than the + // content under a correct height, so the last paint shows the true end. + for range 60 { + page.Draw(canvas, bounds, draw) + page.Wheel(gfx.ScrollEvent{X: 150, Y: window / 2, DeltaY: 60, Precise: true}) + } + page.Draw(canvas, bounds, draw) + rect := last.Rect() + if rect.Height == 0 { + t.Fatalf("the last of %d rows was never placed", rows) + } + if rect.Y+rect.Height > window { + t.Fatalf("the wheel left the last row at %v, past the bottom of the list, %d", rect, window) + } + if !list.AtEnd() { + t.Fatalf("the list says it is not at its end while showing the last row") + } +} From bf2b2dd4f13f0888ed75d70682e0fadcb64e0bd0 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 13:01:48 +0800 Subject: [PATCH 07/16] fix(platform): draw long lines from windows of their texture --- internal/platform/grid_columns.go | 11 + internal/platform/grid_columns_test.go | 13 + internal/platform/label_pixels.go | 103 ++++++- internal/platform/label_pixels_test.go | 126 ++++++++- internal/platform/linux/cpu_lcd_linux_test.go | 2 +- .../platform/linux/cpu_offscreen_linux.go | 49 +++- internal/platform/linux/soft_scene_linux.go | 10 +- internal/platform/linux/text_engine_linux.go | 2 +- internal/platform/linux/text_linux.go | 44 ++- internal/platform/linux/vulkan_linux.go | 6 +- .../platform/linux/vulkan_refresh_linux.go | 2 +- internal/platform/linux/vulkan_text_linux.go | 109 +++++++- .../platform/linux/wide_label_linux_test.go | 254 ++++++++++++++++++ .../platform/windows/direct_grid_windows.go | 20 +- internal/platform/windows/direct_windows.go | 9 +- .../platform/windows/label_picture_windows.go | 4 +- internal/platform/windows/renderer_windows.go | 12 +- .../platform/windows/renderer_windows_test.go | 4 +- .../platform/windows/text_batch_windows.go | 23 +- .../windows/text_editing_windows_test.go | 4 +- internal/platform/windows/text_windows.go | 71 +++-- .../windows/wide_label_windows_test.go | 214 +++++++++++++++ 22 files changed, 994 insertions(+), 98 deletions(-) create mode 100644 internal/platform/linux/wide_label_linux_test.go create mode 100644 internal/platform/windows/wide_label_windows_test.go diff --git a/internal/platform/grid_columns.go b/internal/platform/grid_columns.go index 16a74bb50..efb85bd32 100644 --- a/internal/platform/grid_columns.go +++ b/internal/platform/grid_columns.go @@ -19,6 +19,17 @@ func GridColumns(left, span float64, width int) (from, to int) { return from, max(to, from) } +// ShiftGridSpans moves the columns the runs of a grid line own, planned in the line's +// own device columns, onto a texture width columns wide that starts skip columns into +// the line: a line wider than a texture holds is rasterized from a window of it. A +// run's columns are cut to the texture, and a run outside it owns none. +func ShiftGridSpans(spans []GridSpan, skip, width int) { + for index, span := range spans { + from := min(max(span.From-skip, 0), width) + spans[index] = GridSpan{From: from, To: min(max(span.To-skip, from), width)} + } +} + func roundColumn(edge float64) int { return int(math.Floor(edge + 0.5)) } diff --git a/internal/platform/grid_columns_test.go b/internal/platform/grid_columns_test.go index 9f54be5ba..131319d0e 100644 --- a/internal/platform/grid_columns_test.go +++ b/internal/platform/grid_columns_test.go @@ -45,3 +45,16 @@ func TestGridColumnsOfAnEmptyRunAreEmpty(t *testing.T) { t.Errorf("a run without cells = %d,%d", from, to) } } + +// Columns planned along a whole line land on the window of it a texture holds: a run that +// straddles the window's edge keeps the part inside, and a run outside owns nothing. +func TestShiftGridSpansMovesTheColumnsOntoTheWindow(t *testing.T) { + spans := []GridSpan{{From: 0, To: 100}, {From: 100, To: 300}, {From: 300, To: 500}, {From: 500, To: 520}, {From: 700, To: 700}} + ShiftGridSpans(spans, 200, 300) + want := []GridSpan{{From: 0, To: 0}, {From: 0, To: 100}, {From: 100, To: 300}, {From: 300, To: 300}, {From: 300, To: 300}} + for index := range want { + if spans[index] != want[index] { + t.Errorf("span %d = %+v, want %+v", index, spans[index], want[index]) + } + } +} diff --git a/internal/platform/label_pixels.go b/internal/platform/label_pixels.go index 9373de64d..723ee419a 100644 --- a/internal/platform/label_pixels.go +++ b/internal/platform/label_pixels.go @@ -19,13 +19,114 @@ func DeviceExtent(logical, length, scale float32) int { return DevicePosition(logical+length, 0, scale) - DevicePosition(logical, 0, scale) } +// LabelTextureLimit is the widest and tallest texture a label is rasterized into, in +// device pixels: the 2D texture limit of the Direct3D 11 and Vulkan devices Viva runs +// on, and the limit native.m keeps for Metal. LabelTexturePixels bounds the pixels of +// one such texture. +const ( + LabelTextureLimit = 16384 + LabelTexturePixels = 16 * 1024 * 1024 +) + +// LabelTextureWidth is the widest texture a label height device pixels high is +// rasterized into: LabelTextureLimit, narrowed for a tall label so that its texture +// stays within LabelTexturePixels. It is 0 for a label too tall for any texture, +// which is not drawn. +func LabelTextureWidth(height int) int { + if height <= 0 || height > LabelTextureLimit { + return 0 + } + return min(LabelTextureLimit, LabelTexturePixels/height) +} + +// LabelTextureFits reports whether a label texture width by height device pixels is +// one a backend allocates: width is at most LabelTextureWidth(height). It is tested +// without a division, as renderers ask it of every label every frame. +func LabelTextureFits(width, height int) bool { + return width > 0 && height > 0 && width <= LabelTextureLimit && height <= LabelTextureLimit && width*height <= LabelTexturePixels +} + +// LabelVisibleColumns is the part of a label full device pixels wide, drawn at device +// column origin, that the device columns from left to right show: the columns from +// first to last, counted from the label's left edge. ok is false when they show none. +func LabelVisibleColumns(origin, full, left, right int) (first, last int, ok bool) { + first = min(max(left-origin, 0), full) + last = min(max(right-origin, 0), full) + return first, last, last > first +} + +// WideLabelWindow chooses the device columns that the texture of a label full columns +// wide, more than one texture of limit columns holds, is rasterized from: the columns +// from skip to skip+width of the label. The columns from left to right, with left +// below right, are the ones that can be seen, and haveSkip and haveWidth the window of +// the texture the label has, or a width of 0 when it has none. +// +// A texture that still holds every column that can be seen is kept, so a scroll inside +// it does not rasterize the line again. Otherwise the visible columns are kept with as +// much margin on both sides as they are wide, so a scroll of up to their width keeps +// the new texture; at an end of the label the margin goes to the other side. This is +// the window viva_label_window in native.m chooses. Visible columns wider than limit +// keep their first limit columns: these backends draw one texture per label, and a +// viewport is wider than limit only for a label so tall that its limit is narrowed. +func WideLabelWindow(full, limit, left, right, haveSkip, haveWidth int) (skip, width int) { + if haveWidth > 0 && haveWidth <= limit && haveSkip <= left && right <= haveSkip+haveWidth && haveSkip+haveWidth <= full { + return haveSkip, haveWidth + } + span := right - left + if span >= limit { + return left, limit + } + margin := min(span, (limit-span)/2) + width = span + 2*margin + skip = max(left-margin, 0) + if skip+width > full { + skip = full - width + } + return skip, width +} + +// WideTextLabelWindow is the window a text label's texture is rasterized from when one +// texture cannot hold the whole label. The label is full device columns wide and height +// high, drawn at the device column DevicePosition puts it at, on a target viewport device +// columns wide, or 0 when the caller has none. The columns that can be seen are the +// viewport's, cut to the label's clip; haveSkip and haveWidth are the window of the +// texture the label has, a width of 0 when it has none (see WideLabelWindow). wide is +// false for a label one texture holds whole, which is left to the caller. A wide label +// is not drawn, ok false, when none of it can be seen or it is too tall for any texture: +// an error for it would stop the window drawing anything. +func WideTextLabelWindow(label TextLabel, scale float32, full, height, viewport, haveSkip, haveWidth int) (skip, width int, wide, ok bool) { + limit := LabelTextureWidth(height) + if full <= limit { + return 0, full, false, full > 0 + } + if limit <= 0 { + return 0, 0, true, false + } + origin := DevicePosition(label.X, label.OriginX, scale) + left, right := 0, origin+full + if viewport > 0 { + right = min(right, viewport) + } + if label.Clipped { + left = max(left, int(math.Floor(float64(label.Clip.X*scale)))) + right = min(right, int(math.Ceil(float64((label.Clip.X+label.Clip.Width)*scale)))) + } + first, last, visible := LabelVisibleColumns(origin, full, left, right) + if !visible { + return 0, 0, true, false + } + skip, width = WideLabelWindow(full, limit, first, last, haveSkip, haveWidth) + return skip, width, true, true +} + // LabelWindow is the part of a label's texture that a clip can show, in device // pixels: the columns from skip to skip+width of a texture drawn at origin, whose // whole width is full, when the clip covers left to right. A clip that starts left // of the label keeps the whole texture. One that starts inside it skips the columns // it cuts, so a long scrolled line costs its visible width, not its whole width, // without moving the text by a fraction of a device pixel. ok is false when the -// clip shows none of those columns. +// clip shows none of those columns. It is for a label no wider than its texture +// limit; a wider one takes the window WideLabelWindow chooses. func LabelWindow(origin, full, left, right int) (skip, width int, ok bool) { if full <= 0 || right <= left { return 0, 0, false diff --git a/internal/platform/label_pixels_test.go b/internal/platform/label_pixels_test.go index 86aaa28b0..c33616899 100644 --- a/internal/platform/label_pixels_test.go +++ b/internal/platform/label_pixels_test.go @@ -1,6 +1,10 @@ package platform -import "testing" +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) // A layout position half a device pixel either way snaps to the nearest pixel, and // the remainder the painter took off is part of it. @@ -97,3 +101,123 @@ func TestBitmapTextureFollowsTheDrawnSize(t *testing.T) { t.Errorf("an image drawn larger than stored is %dx%d, want the stored size", width, height) } } + +// A label texture is held to the device limit across and to the pixel budget overall, so a +// tall label gets a narrower texture, and one taller than the limit gets none. +func TestLabelTextureWidthKeepsTheTextureBounded(t *testing.T) { + cases := []struct{ height, width int }{ + {0, 0}, + {-3, 0}, + {24, LabelTextureLimit}, + {1024, LabelTextureLimit}, + {2048, LabelTexturePixels / 2048}, + {LabelTextureLimit, LabelTexturePixels / LabelTextureLimit}, + {LabelTextureLimit + 1, 0}, + } + for _, c := range cases { + if got := LabelTextureWidth(c.height); got != c.width { + t.Errorf("LabelTextureWidth(%d) = %d, want %d", c.height, got, c.width) + } + } + if !LabelTextureFits(LabelTextureLimit, 24) || LabelTextureFits(LabelTextureLimit+1, 24) || LabelTextureFits(0, 24) { + t.Error("a short label's texture is not bounded by the device limit") + } + if LabelTextureFits(LabelTexturePixels/2048+1, 2048) { + t.Error("a tall label's texture is not bounded by the pixel budget") + } + // LabelTextureFits tests without a division what LabelTextureWidth bounds, at each edge. + for _, height := range []int{-1, 0, 1, 24, 1023, 1024, 1025, 2047, 2048, 3000, LabelTextureLimit - 1, LabelTextureLimit, LabelTextureLimit + 1} { + limit := LabelTextureWidth(height) + for _, width := range []int{-1, 0, 1, limit - 1, limit, limit + 1, LabelTextureLimit, LabelTextureLimit + 1} { + if got, want := LabelTextureFits(width, height), width > 0 && width <= limit; got != want { + t.Errorf("LabelTextureFits(%d, %d) = %v; LabelTextureWidth is %d", width, height, got, limit) + } + } + } +} + +// The columns a clip shows are counted from the label's left edge and cut to the label. +func TestLabelVisibleColumnsCutsTheClipToTheLabel(t *testing.T) { + cases := []struct { + name string + origin, full, left, right int + first, last int + ok bool + }{ + {"label inside", 100, 200, 0, 1000, 0, 200, true}, + {"label starts left of the clip", -5000, 40000, 0, 1920, 5000, 6920, true}, + {"label ends inside the clip", -39000, 40000, 0, 1920, 39000, 40000, true}, + {"clip left of the label", 2000, 100, 0, 1920, 100, 100, false}, + {"clip right of the label", -500, 100, 0, 1920, 100, 100, false}, + } + for _, c := range cases { + first, last, ok := LabelVisibleColumns(c.origin, c.full, c.left, c.right) + if ok != c.ok || ok && (first != c.first || last != c.last) { + t.Errorf("%s: LabelVisibleColumns(%d, %d, %d, %d) = %d, %d, %v; want %d, %d, %v", + c.name, c.origin, c.full, c.left, c.right, first, last, ok, c.first, c.last, c.ok) + } + } +} + +// A line wider than a texture holds is rasterized around what can be seen, with a margin of +// the visible width on each side, shifted inward at the ends of the line; a texture that +// still holds what can be seen is kept, and one that does not is replaced. +func TestWideLabelWindowKeepsTheVisibleColumnsWithAMargin(t *testing.T) { + const full, limit = 60000, LabelTextureLimit + cases := []struct { + name string + left, right int + haveSkip, haveWidth int + skip, width int + }{ + {"start of the line", 0, 2000, 0, 0, 0, 6000}, + {"middle of the line", 20000, 22000, 0, 0, 18000, 6000}, + {"end of the line", 58000, 60000, 0, 0, 54000, 6000}, + {"wide span", 10000, 20000, 0, 0, 10000 - 3192, 10000 + 2*3192}, + {"span wider than a texture", 1000, 1000 + limit + 10, 0, 0, 1000, limit}, + {"scroll inside the texture", 19000, 21000, 18000, 6000, 18000, 6000}, + {"scroll past the texture", 23000, 25000, 18000, 6000, 21000, 6000}, + {"texture past the end of the line", 0, 2000, 59000, 6000, 0, 6000}, + {"texture wider than the limit", 0, 2000, 0, limit + 1, 0, 6000}, + } + for _, c := range cases { + skip, width := WideLabelWindow(full, limit, c.left, c.right, c.haveSkip, c.haveWidth) + if skip != c.skip || width != c.width { + t.Errorf("%s: WideLabelWindow(%d, %d, %d, %d, %d, %d) = %d, %d; want %d, %d", + c.name, full, limit, c.left, c.right, c.haveSkip, c.haveWidth, skip, width, c.skip, c.width) + continue + } + if width > limit || skip < 0 || skip+width > full || skip > c.left || skip+width < min(c.right, skip+limit) { + t.Errorf("%s: window %d+%d does not hold the visible columns %d..%d within the limit", c.name, skip, width, c.left, c.right) + } + } +} + +// A text label wider than a texture is windowed to the columns the viewport shows, cut to +// its clip; one the viewport does not show, or too tall for any texture, is not drawn, and +// one a texture holds whole is left to its backend. +func TestWideTextLabelWindowFollowsTheViewportAndTheClip(t *testing.T) { + const scale, full, height, viewport = 1.5, 49164, 27, 600 + label := TextLabel{X: -20000} // 30000 device columns off the left of the viewport + cases := []struct { + name string + label TextLabel + full, height int + haveSkip, haveWidth int + skip, width int + wide, ok bool + }{ + {"viewport", label, full, height, 0, 0, 29400, 1800, true, true}, + {"clip", TextLabel{X: -20000, Clipped: true, Clip: gfx.Rect{X: 100, Width: 200}}, full, height, 0, 0, 29850, 900, true, true}, + {"kept texture", label, full, height, 29000, 2000, 29000, 2000, true, true}, + {"scrolled out", TextLabel{X: -40000}, full, height, 0, 0, 0, 0, true, false}, + {"too tall", label, full, LabelTextureLimit + 1, 0, 0, 0, 0, true, false}, + {"one texture holds it", label, 2000, height, 0, 0, 0, 2000, false, true}, + } + for _, c := range cases { + skip, width, wide, ok := WideTextLabelWindow(c.label, scale, c.full, c.height, viewport, c.haveSkip, c.haveWidth) + if skip != c.skip || width != c.width || wide != c.wide || ok != c.ok { + t.Errorf("%s: window = %d, %d, %v, %v; want %d, %d, %v, %v", c.name, skip, width, wide, ok, c.skip, c.width, c.wide, c.ok) + } + } +} diff --git a/internal/platform/linux/cpu_lcd_linux_test.go b/internal/platform/linux/cpu_lcd_linux_test.go index 5c188b237..3ce2aa7fe 100644 --- a/internal/platform/linux/cpu_lcd_linux_test.go +++ b/internal/platform/linux/cpu_lcd_linux_test.go @@ -62,7 +62,7 @@ func TestCPUGridLCDLabelKeepsItsRunColors(t *testing.T) { {Column: 1, Bytes: 1, Cells: 1, Color: gfx.RGB(0, 0, 255)}, }, } - image, ok, err := rasterizeLabel(services, label, 1, true) + image, ok, err := rasterizeLabel(services, label, 1, 0, labelImage{}, true) if err != nil || !ok { t.Fatalf("rasterize: ok=%v err=%v", ok, err) } diff --git a/internal/platform/linux/cpu_offscreen_linux.go b/internal/platform/linux/cpu_offscreen_linux.go index 0dcd5ed1b..61b5b2d7d 100644 --- a/internal/platform/linux/cpu_offscreen_linux.go +++ b/internal/platform/linux/cpu_offscreen_linux.go @@ -100,7 +100,7 @@ func (offscreen *CPUOffscreen) Close() { // device pixel (platform.DevicePosition), a clip takes every device pixel it touches. ok is false // when the label draws nothing. func prepareLabel(services *textServices, l platform.TextLabel, scale float32, canvasWidth, canvasHeight int, allowLCD bool) (label raster.Label, ok bool, err error) { - image, ok, err := rasterizeLabel(services, l, scale, allowLCD) + image, ok, err := rasterizeLabel(services, l, scale, canvasWidth, labelImage{}, allowLCD) if err != nil || !ok { return raster.Label{}, false, err } @@ -114,16 +114,41 @@ func prepareLabel(services *textServices, l platform.TextLabel, scale float32, c type labelImage struct { pixels []byte width, height int - lcd bool - spans []raster.Span + // skip is the device column of a text label the picture starts at: a line wider than a + // texture holds, wide, is drawn from the window of it the canvas shows (textWindow). It + // is 0 for every other label. + skip int + wide bool + lcd bool + spans []raster.Span +} + +// textWindow is the part of a text label drawn into its picture at scale on a canvas +// canvasWidth device pixels wide: the device columns from skip to skip+width of the label, +// height high. A label one texture holds is drawn whole. A wider one, wide, is drawn from +// the columns of it the canvas and its clip show, keeping have, the picture it has, while +// that still holds them (platform.WideTextLabelWindow); the Vulkan backend draws the same +// window. ok is false when nothing is drawn: none of a wide line can be seen, or no +// texture holds the label. +func textWindow(l platform.TextLabel, scale float32, canvasWidth int, have labelImage) (skip, width, height int, wide, ok bool) { + full := int(math.Ceil(float64(l.Width * scale))) + height = int(math.Ceil(float64(l.Height * scale))) + haveSkip, haveWidth := 0, 0 + if have.wide { + haveSkip, haveWidth = have.skip, have.width + } + skip, width, wide, ok = platform.WideTextLabelWindow(l, scale, full, height, canvasWidth, haveSkip, haveWidth) + return skip, width, height, wide, ok && platform.LabelTextureFits(width, height) } // rasterizeLabel draws a label's text, or resamples its image to the device pixels it covers. ok is // false when it draws nothing. The picture does not depend on where the label is, except that an -// image smaller than its bitmap does, through the fraction of a pixel it starts at. With allowLCD, -// and the desktop asking for subpixel antialiasing, text comes back as per-channel coverage for the +// image smaller than its bitmap does, through the fraction of a pixel it starts at, and a line +// wider than a texture holds is drawn from the window of it a canvas canvasWidth device pixels +// wide shows, kept from have, the picture the label has (textWindow). With allowLCD, and the +// desktop asking for subpixel antialiasing, text comes back as per-channel coverage for the // rasterizer to tint, the same way the Vulkan LCD shader reads it. -func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, allowLCD bool) (image labelImage, ok bool, err error) { +func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, canvasWidth int, have labelImage, allowLCD bool) (image labelImage, ok bool, err error) { if l.Width <= 0 || l.Height <= 0 || (l.Value == "" && len(l.Bitmap) == 0) { return labelImage{}, false, nil } @@ -138,13 +163,15 @@ func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, } return labelImage{pixels: tightBitmap(l.Bitmap, width, height, l.BitmapStride), width: width, height: height}, true, nil } - width := int(math.Ceil(float64(l.Width * scale))) - height := int(math.Ceil(float64(l.Height * scale))) - pixels, lcd, err := services.rasterize(l, scale, width, height, allowLCD) + skip, width, height, wide, shown := textWindow(l, scale, canvasWidth, have) + if !shown { + return labelImage{}, false, nil + } + pixels, lcd, err := services.rasterizeWindow(l, scale, skip, width, height, allowLCD) if err != nil { return labelImage{}, false, err } - image = labelImage{pixels: pixels, width: width, height: height, lcd: lcd} + image = labelImage{pixels: pixels, width: width, height: height, skip: skip, wide: wide, lcd: lcd} if lcd && len(services.spans) > 0 { image.spans = make([]raster.Span, len(services.spans)) for index, span := range services.spans { @@ -161,7 +188,7 @@ func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, // clip, if a canvas clip cuts it, on the device pixels the clip touches. ok is false when the clip // leaves nothing. func placeLabel(l platform.TextLabel, scale float32, image labelImage, canvasWidth, canvasHeight int) (label raster.Label, ok bool) { - x, y := platform.DevicePosition(l.X, l.OriginX, scale), platform.DevicePosition(l.Y, l.OriginY, scale) + x, y := platform.DevicePosition(l.X, l.OriginX, scale)+image.skip, platform.DevicePosition(l.Y, l.OriginY, scale) if len(l.Bitmap) > 0 { x, y = platform.DevicePosition(l.X, 0, scale), platform.DevicePosition(l.Y, 0, scale) } diff --git a/internal/platform/linux/soft_scene_linux.go b/internal/platform/linux/soft_scene_linux.go index 651f57f1e..368c5c560 100644 --- a/internal/platform/linux/soft_scene_linux.go +++ b/internal/platform/linux/soft_scene_linux.go @@ -176,11 +176,19 @@ func (s *softScene) setLabel(slot *softLabel, next platform.TextLabel) error { previous := slot.placed wasVisible := slot.visible redraw := !slot.hasImage || slot.imageScale != s.scale || labelContentChanged(slot.label, next) || (len(next.Bitmap) > 0 && bitmapShownChanged(slot.label, next, s.scale)) + var have labelImage + if !redraw && slot.image.wide { + // A line wider than a texture holds is drawn again when its picture, a window of + // it, no longer holds the part of it the canvas shows. + have = slot.image + skip, width, _, _, ok := textWindow(next, s.scale, s.canvas.Width, have) + redraw = !ok || skip != have.skip || width != have.width + } slot.runs = append(slot.runs[:0], next.Runs...) slot.label = next slot.label.Runs = slot.runs if redraw { - image, ok, err := rasterizeLabel(s.services, slot.label, s.scale, s.clear.Alpha >= 1) + image, ok, err := rasterizeLabel(s.services, slot.label, s.scale, s.canvas.Width, have, s.clear.Alpha >= 1) if err != nil { return err } diff --git a/internal/platform/linux/text_engine_linux.go b/internal/platform/linux/text_engine_linux.go index aa33822a6..639915104 100644 --- a/internal/platform/linux/text_engine_linux.go +++ b/internal/platform/linux/text_engine_linux.go @@ -108,7 +108,7 @@ func (engine *textEngine) RasterizeText(value string, style gfx.TextStyle, scale Red: float64(style.Color.Red), Green: float64(style.Color.Green), Blue: float64(style.Color.Blue), Alpha: float64(style.Color.Alpha), }, - }, scale, width, height, false) + }, scale, 0, width, height, false) if err != nil { return gfx.Bitmap{}, err } diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go index 6be23c2bd..a1b481ac1 100644 --- a/internal/platform/linux/text_linux.go +++ b/internal/platform/linux/text_linux.go @@ -483,6 +483,15 @@ func NewTextMeasurer() (text.MeasureFunc, func(), error) { // the renderer to blend with the label's color, and lcd is true. Otherwise the pixels are // premultiplied BGRA in the label's color. func (services *textServices) rasterize(label platform.TextLabel, scale float32, width, height int, allowLCD bool) (pixels []byte, lcd bool, err error) { + return services.rasterizeWindow(label, scale, 0, width, height, allowLCD) +} + +// rasterizeWindow draws the device columns from skip to skip+width of the label, as +// rasterize draws the whole of it: a line wider than a texture holds is drawn from a +// window of it (platform.WideTextLabelWindow). skip is a whole number of device +// columns, so every glyph keeps the phase it has in the whole line, and the columns +// of services.spans are the window's. +func (services *textServices) rasterizeWindow(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) (pixels []byte, lcd bool, err error) { settings := systemFonts() services.spans = services.spans[:0] // A fixed-pitch label is LCD text too, unless it holds a color glyph, which has no @@ -493,12 +502,15 @@ func (services *textServices) rasterize(label platform.TextLabel, scale float32, settings = settings.grayscale() } services.useFonts(settings) - pixels, err = services.draw(label, scale, width, height, lcd) + pixels, err = services.draw(label, scale, skip, width, height, lcd) return pixels, lcd && err == nil, err } -func (services *textServices) draw(label platform.TextLabel, scale float32, width, height int, lcd bool) ([]byte, error) { - if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 { +// draw draws the device columns from skip to skip+width of the label into pixels width +// by height. The renderers do not ask for a texture larger than platform.LabelTextureFits +// allows: they window a wide line and leave a label no texture holds undrawn. +func (services *textServices) draw(label platform.TextLabel, scale float32, skip, width, height int, lcd bool) ([]byte, error) { + if !platform.LabelTextureFits(width, height) || skip < 0 { return nil, fmt.Errorf("linux: label texture exceeds bounded size") } if !validFontSize(label.FontSize) || scale <= 0 || math.IsNaN(float64(scale)) || math.IsInf(float64(scale), 0) { @@ -525,6 +537,10 @@ func (services *textServices) draw(label platform.TextLabel, scale float32, widt return nil, fmt.Errorf("linux: create Cairo text context") } defer services.cairoDestroy(context) + if skip > 0 { + // The line is drawn where it stands; the surface is the window of it. + services.cairoTranslate(context, -float64(skip), 0) + } if label.Value != "" { if len(label.Runs) == 0 { family := proportionalFamily @@ -553,7 +569,7 @@ func (services *textServices) draw(label platform.TextLabel, scale float32, widt return nil, err } } - } else if err := services.drawRuns(context, label, scale, width, height, lcd); err != nil { + } else if err := services.drawRuns(context, label, scale, skip, width, height, lcd); err != nil { return nil, err } } @@ -614,8 +630,10 @@ type colorSpan struct { } // drawRuns draws a fixed-pitch label's runs. With lcd they are drawn white, for their coverage, -// and the color of each run is recorded in services.spans instead. -func (services *textServices) drawRuns(context uintptr, label platform.TextLabel, scale float32, width, height int, lcd bool) error { +// and the color of each run is recorded in services.spans instead. The surface is the device +// columns from skip to skip+width of the line, translated onto them: a run outside them is not +// drawn, and the columns of its spans are the surface's. +func (services *textServices) drawRuns(context uintptr, label platform.TextLabel, scale float32, skip, width, height int, lcd bool) error { pitch := float64(label.CellWidth * scale) if pitch <= 0 || math.IsNaN(pitch) || math.IsInf(pitch, 0) { return fmt.Errorf("linux: invalid fixed-pitch cell width") @@ -626,7 +644,8 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel return err } baseline := float64(platform.TextBaseline(label, height, scale)) - columns := services.ownedColumns(label, family, scale, pitch, width) + columns := services.ownedColumns(label, family, scale, pitch, skip+width) + shownLeft, shownRight := float64(skip), float64(skip+width) offset := 0 for index, run := range label.Runs { end := offset + int(run.Bytes) @@ -643,6 +662,9 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel // The run draws in the columns it owns, which are its cells and the blank cells its // ink reaches into, and nowhere else. owned := columns[index] + if min(float64(owned.From), left) >= shownRight || max(float64(owned.To), left+span) <= shownLeft { + continue // the run is outside the window of the line + } services.cairoSave(context) services.cairoRectangle(context, float64(owned.From), 0, float64(owned.To-owned.From), float64(height)) services.cairoClip(context) @@ -654,8 +676,7 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel } } source() - if lcd && run.Cells > 0 && piece != "" && owned.To > owned.From { - from, to := owned.From, owned.To + if from, to := min(max(owned.From-skip, 0), width), min(max(owned.To-skip, 0), width); lcd && run.Cells > 0 && piece != "" && to > from { services.addSpan(from, to, [4]float32{run.Color.Red, run.Color.Green, run.Color.Blue, run.Color.Alpha}) } metrics := baseMetrics @@ -679,7 +700,10 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel services.cairoRestore(context) } } else if printableASCII(piece) { - for index := range len(piece) { + // ASCII ink stays inside its cell; a cell either side holds an italic's overhang. + first := max(int(math.Floor((shownLeft-left)/pitch))-1, 0) + last := min(int(math.Ceil((shownRight-left)/pitch))+1, len(piece)) + for index := first; index < last; index++ { metrics, err = services.configureLayout(piece[index:index+1], family, label.FontSize*scale, run.Weight, run.Italic) if err != nil { services.cairoRestore(context) diff --git a/internal/platform/linux/vulkan_linux.go b/internal/platform/linux/vulkan_linux.go index 4411b6a82..ee7be0dbe 100644 --- a/internal/platform/linux/vulkan_linux.go +++ b/internal/platform/linux/vulkan_linux.go @@ -964,7 +964,7 @@ func (renderer *vulkanRenderer) createScenePipelines(extent vkExtent2D) error { return err } } - if err := renderer.text.upload(renderer, renderer.pixelScale()); err != nil { + if err := renderer.text.upload(renderer, renderer.pixelScale(), renderer.textViewport(extent.Width, extent.Height)); err != nil { return err } return renderer.recordCommands(extent) @@ -1302,7 +1302,7 @@ func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { } } renderer.compositingBatches = groupCompositingLayers(renderer.rectangleBatches, renderer.text.labels, renderer.text.order, renderer.compositingBatches) - if err := renderer.text.upload(renderer, renderer.pixelScale()); err != nil { + if err := renderer.text.upload(renderer, renderer.pixelScale(), renderer.textViewport(renderer.width, renderer.height)); err != nil { return false, err } return true, nil @@ -1360,7 +1360,7 @@ func (renderer *vulkanRenderer) setScaleOnce(scale float32) error { if err := vkCheck(renderer.api.deviceWaitIdle(renderer.device), "wait before scale change"); err != nil { return err } - if err := renderer.text.upload(renderer, scale); err != nil { + if err := renderer.text.upload(renderer, scale, renderer.textViewport(renderer.width, renderer.height)); err != nil { return err } return renderer.recordCommands(vkExtent2D{Width: renderer.width, Height: renderer.height}) diff --git a/internal/platform/linux/vulkan_refresh_linux.go b/internal/platform/linux/vulkan_refresh_linux.go index 3a7218296..3aae4087d 100644 --- a/internal/platform/linux/vulkan_refresh_linux.go +++ b/internal/platform/linux/vulkan_refresh_linux.go @@ -19,7 +19,7 @@ func (renderer *vulkanRenderer) refreshText() error { label.closeImage(renderer) } } - if err := renderer.text.upload(renderer, renderer.pixelScale()); err != nil { + if err := renderer.text.upload(renderer, renderer.pixelScale(), renderer.textViewport(renderer.width, renderer.height)); err != nil { return fmt.Errorf("linux: refresh text: %w", err) } return renderer.recordCommands(vkExtent2D{Width: renderer.width, Height: renderer.height}) diff --git a/internal/platform/linux/vulkan_text_linux.go b/internal/platform/linux/vulkan_text_linux.go index aadd03635..c1ffa81f7 100644 --- a/internal/platform/linux/vulkan_text_linux.go +++ b/internal/platform/linux/vulkan_text_linux.go @@ -164,6 +164,15 @@ type vulkanLabelTexture struct { scale float32 // width and height are the texture's size in device pixels. width, height int + // skip is the device column of the label the texture starts at: a line wider than a + // texture holds, wide, has a texture of the window of it that can be seen + // (platform.WideTextLabelWindow). It is 0 for every other label. + skip int + wide bool + // dropped is set when the label has no texture at scale because none holds it or, + // wide, none of it can be seen: it draws nothing, and is not rasterized every frame + // for that. + dropped bool // lcd is set when the texture holds the coverage of each channel of LCD text, to be // blended with the label's color by the LCD pipeline. lcd bool @@ -599,14 +608,75 @@ func validateTextLabel(index int, label platform.TextLabel) error { return nil } -func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32) error { +// needsUpload reports whether the label is rasterized again at scale for a scene viewport +// device pixels wide: it has no texture there, its image's texture no longer suits the size +// it is drawn at, or it is a wide line whose texture no longer holds the part of it that can +// be seen. +func (label *vulkanLabelTexture) needsUpload(scale float32, viewport int) bool { + l := label.label + if l.Value == "" && len(l.Bitmap) == 0 || l.Width <= 0 || l.Height <= 0 { + return false + } + if label.scale != scale || label.view == 0 && !label.dropped { + return true + } + if len(l.Bitmap) > 0 { + if label.view == 0 { + return platform.LabelTextureFits(platform.BitmapTextureExtent(l, scale)) + } + return bitmapTextureStale(label, scale) + } + if !label.wide { + return false + } + skip, width, _, _, ok := label.window(scale, viewport) + return ok != (label.view != 0) || ok && (skip != label.skip || width != label.width) +} + +// window is the part of a text label's texture that is rasterized at scale for a scene +// viewport device pixels wide: the device columns from skip to skip+width of the label, +// height high. A label one texture holds is rasterized whole, at the width +// labelRasterWidth reserves; a wider one from the window of it that can be seen, which +// keeps the texture it has while that still holds them; wide is set for such a line. ok +// is false when it is not drawn: none of a wide line can be seen, or no texture holds +// the label. +func (label *vulkanLabelTexture) window(scale float32, viewport int) (skip, width, height int, wide, ok bool) { + height = int(math.Ceil(float64(label.label.Height * scale))) + full := labelRasterWidth(label.label, scale, height) + haveSkip, haveWidth := 0, 0 + if label.view != 0 && label.scale == scale { + haveSkip, haveWidth = label.skip, label.width + } + skip, width, wide, ok = platform.WideTextLabelWindow(label.label, scale, full, height, viewport, haveSkip, haveWidth) + return skip, width, height, wide, ok && platform.LabelTextureFits(width, height) +} + +// drop leaves the label without a texture at scale, for one it cannot have: a label no +// texture holds is not drawn, and does not stop the window drawing the others. +func (label *vulkanLabelTexture) drop(renderer *vulkanRenderer, scale float32, wide bool) { + label.closeImage(renderer) + label.scale, label.wide, label.dropped = scale, wide, true +} + +// textViewport is the device width of the scene in a target width by height: the width a +// line wider than a texture holds is windowed to. +func (renderer *vulkanRenderer) textViewport(width, height uint32) int { + if renderer.frame.active() { + _, _, content := renderer.frame.content(width, height) + return int(content.Width) + } + return int(width) +} + +// upload rasterizes and uploads every label that needsUpload at scale, for a scene +// viewport device pixels wide. +func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, viewport int) error { if textState.services == nil || renderer.uploadCommand == 0 { return nil } dirty := false for index := range textState.labels { - label := &textState.labels[index] - if (label.label.Value != "" || len(label.label.Bitmap) > 0) && label.label.Width > 0 && label.label.Height > 0 && (label.view == 0 || label.scale != scale || bitmapTextureStale(label, scale)) { + if textState.labels[index].needsUpload(scale, viewport) { dirty = true break } @@ -627,17 +697,21 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32) err defer closeStaging() for index := range textState.labels { label := &textState.labels[index] - if label.label.Value == "" && len(label.label.Bitmap) == 0 || label.label.Width <= 0 || label.label.Height <= 0 || label.view != 0 && label.scale == scale && !bitmapTextureStale(label, scale) { + if !label.needsUpload(scale, viewport) { continue } - height := int(math.Ceil(float64(label.label.Height * scale))) - width := labelRasterWidth(label.label, scale, height) var pixels []byte - lcd := false + lcd, wide := false, false var spans []colorSpan + skip, width, height := 0, 0, 0 if len(label.label.Bitmap) > 0 { width, height = label.label.BitmapWidth, label.label.BitmapHeight - if shown, high := platform.BitmapTextureExtent(label.label, scale); shown < width || high < height { + shown, high := platform.BitmapTextureExtent(label.label, scale) + if !platform.LabelTextureFits(shown, high) { + label.drop(renderer, scale, false) + continue + } + if shown < width || high < height { // A bitmap drawn smaller than it is stored is averaged down to the device // pixels it covers; sampling a few of its texels would alias. pixels = platform.ResampleBGRA(label.label.Bitmap, label.label.BitmapStride, width, height, shown, high) @@ -647,10 +721,16 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32) err pixels = tightBitmap(label.label.Bitmap, width, height, label.label.BitmapStride) } } else { + var ok bool + skip, width, height, wide, ok = label.window(scale, viewport) + if !ok { + label.drop(renderer, scale, wide) + continue + } var err error // ClearType-style blending needs an opaque target: a window or an offscreen // image cleared opaque. - pixels, lcd, err = textState.services.rasterize(label.label, scale, width, height, renderer.dualSource && textState.lcdPipeline != 0 && renderer.color.Alpha >= 1) + pixels, lcd, err = textState.services.rasterizeWindow(label.label, scale, skip, width, height, renderer.dualSource && textState.lcdPipeline != 0 && renderer.color.Alpha >= 1) if err != nil { return fmt.Errorf("linux: rasterize label %d: %w", index, err) } @@ -662,7 +742,7 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32) err } staging = append(staging, stage) label.scale, label.lcd = scale, lcd - label.width, label.height = width, height + label.width, label.height, label.skip, label.wide = width, height, skip, wide label.spans = append(label.spans[:0], spans...) // after createImage, which clears the label } if err := vkCheck(renderer.api.endCommandBuffer(renderer.uploadCommand), "end text upload"); err != nil { @@ -693,7 +773,7 @@ func labelRasterWidth(label platform.TextLabel, scale float32, height int) int { if len(label.Runs) > 0 && label.CellWidth > 0 && height > 0 && width > 0 && ok { step := float64(label.CellWidth) * 16 reserved := min(math.Ceil(float64(label.Width)/step)*step, float64(needed)) - limit := min(16384, 16*1024*1024/height) + limit := platform.LabelTextureWidth(height) if width <= limit { width = max(width, int(min(math.Ceil(reserved*float64(scale)), float64(limit)))) } @@ -864,6 +944,7 @@ func (textState *vulkanText) record(renderer *vulkanRenderer, command uintptr, e // A grid line has a color per run: its coverage is drawn once for each, cut to the // columns of the run. origin, _ := label.pixelOrigin(scale) + origin += label.skip // the spans are the texture's columns for spanIndex := range label.spans { span := &label.spans[spanIndex] scratch.cut = scratch.scissor @@ -881,11 +962,12 @@ func (textState *vulkanText) record(renderer *vulkanRenderer, command uintptr, e // quad is where the label's texture is drawn, in logical pixels: its top left and its size are // whole device pixels, so every texel lands on one pixel and the sampler blends none with its -// neighbour. Text takes the texture's own size; an image takes the device pixels -// its logical bounds cover. +// neighbour. Text takes the texture's own size, at the columns of the label it holds; an +// image takes the device pixels its logical bounds cover. func (label *vulkanLabelTexture) quad(scale float32) [4]float32 { l := label.label x, y := label.pixelOrigin(scale) + x += label.skip width, height := label.width, label.height if len(l.Bitmap) > 0 { width, height = platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) @@ -934,6 +1016,7 @@ func labelScissor(label platform.TextLabel, scale float32, extent vkExtent2D) (s } func (label *vulkanLabelTexture) closeImage(renderer *vulkanRenderer) { + label.skip, label.wide, label.dropped = 0, false, false if renderer == nil || renderer.api == nil || renderer.device == 0 { label.image, label.memory, label.view, label.scale, label.lcd = 0, 0, 0, 0, false label.width, label.height, label.spans = 0, 0, label.spans[:0] diff --git a/internal/platform/linux/wide_label_linux_test.go b/internal/platform/linux/wide_label_linux_test.go new file mode 100644 index 000000000..42307d456 --- /dev/null +++ b/internal/platform/linux/wide_label_linux_test.go @@ -0,0 +1,254 @@ +package linux + +import ( + "bytes" + "errors" + "image" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// wideValue is a log line of 4096 characters: at 8 logical pixels a cell and 150% it is +// 49152 device pixels wide, three times what a texture holds. +var wideValue = strings.Repeat("0123456789abcdef", 256) + +func wideMonoLine(value string, x float32, runs []gfx.TextRun) platform.TextLabel { + return platform.TextLabel{ + Value: value, X: x, Y: 4, Width: float32(len(value))*8 + 8, Height: 18, FontSize: 13, CellWidth: 8, + Mono: true, Runs: runs, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Clipped: true, Clip: gfx.Rect{Width: 400, Height: 40}, + } +} + +func wholeRun(value string) []gfx.TextRun { + return []gfx.TextRun{{Bytes: int32(len(value)), Cells: int32(len(value)), Weight: 400, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}}} +} + +// wideBackends open a 400 by 40 scene at 150%, cleared to clear, with the Vulkan renderer and +// with the CPU one, and return what draws labels on it. A backend the machine cannot run skips. +var wideBackends = []struct { + name string + open func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA +}{ + {"Vulkan", func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA { + t.Helper() + offscreen, err := NewOffscreen(400, 40, 1.5, clear) + if errors.Is(err, platform.ErrNoGraphics) { + t.Skipf("no Vulkan device: %v", err) + } + if err != nil { + t.Fatal(err) + } + t.Cleanup(offscreen.Close) + return func(labels ...platform.TextLabel) *image.RGBA { return renderScene(t, offscreen, nil, labels) } + }}, + {"CPU", func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA { + t.Helper() + offscreen, err := NewCPUOffscreen(400, 40, 1.5, clear) + if err != nil { + t.Skipf("no text services: %v", err) // Pango and Cairo are system libraries + } + t.Cleanup(offscreen.Close) + return func(labels ...platform.TextLabel) *image.RGBA { + t.Helper() + if err := offscreen.Set(nil, labels); err != nil { + t.Fatal(err) + } + pixels, err := offscreen.Image() + if err != nil { + t.Fatal(err) + } + return pixels + } + }}, +} + +// A line wider than a texture holds gets a texture of the window of it that the viewport and +// its clip show, with or without runs. A scroll inside that window keeps the texture and one +// past it rasterizes the line again; a line scrolled out of view, or too tall for any texture, +// is dropped and not rasterized again every frame for that. +func TestVulkanWideLabelWindowFollowsTheViewport(t *testing.T) { + const scale, viewport = 1.5, 600 + for _, runs := range [][]gfx.TextRun{nil, wholeRun(wideValue)} { + label := vulkanLabelTexture{label: wideMonoLine(wideValue, 0, runs)} + if skip, width, height, wide, ok := label.window(scale, viewport); !ok || !wide || skip != 0 || width != 1800 || height != 27 { + t.Errorf("runs %d, start of the line: window = %d, %d, %d, %v, %v; want 0, 1800, 27, wide", len(runs), skip, width, height, wide, ok) + } + label.label.X = -20000 // 30000 device pixels scrolled off the left + if skip, width, _, _, ok := label.window(scale, viewport); !ok || skip != 30000-600 || width != 1800 { + t.Errorf("runs %d, scrolled: window = %d, %d, %v; want 29400, 1800", len(runs), skip, width, ok) + } + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a wide line without a texture is not rasterized", len(runs)) + } + label.view, label.scale, label.skip, label.width, label.height, label.wide = 1, scale, 29400, 1800, 27, true + label.label.X = -20100 + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a scroll inside the texture's window rasterizes the line again", len(runs)) + } + label.label.X = -21000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a scroll past the texture's window keeps the texture", len(runs)) + } + label.label.X = -40000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a line scrolled out of view keeps its texture", len(runs)) + } + if _, _, _, wide, ok := label.window(scale, viewport); ok || !wide { + t.Errorf("runs %d: a line scrolled out of view has a window", len(runs)) + } + label.drop(nil, scale, true) + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line out of view is rasterized again", len(runs)) + } + label.label.X = -20000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line scrolled back into view is not rasterized", len(runs)) + } + label.label.Height = 12000 // 18000 device pixels + if _, _, _, _, ok := label.window(scale, viewport); ok { + t.Errorf("runs %d: a line too tall for any texture has a window", len(runs)) + } + label.drop(nil, scale, false) + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line too tall for any texture is rasterized again", len(runs)) + } + } +} + +// A monospaced line wider than any texture, such as a long log line shown unwrapped, is drawn +// from a window of it at its start and scrolled, on an opaque target and a transparent one, +// without and with runs, by the Vulkan renderer and by the CPU one. Its pixels are the pixels +// of the start of the same line, which one texture holds, drawn where it is: the window moves +// no glyph. Drawing it whole asked for a texture larger than the bound, and the error stopped +// the window drawing anything again. The Vulkan scene draws each scroll in turn, so the +// texture of the line is windowed again as it scrolls. +func TestWideMonoLineIsDrawnFromAWindowOfIt(t *testing.T) { + scrolls := []int{0, 1000} // characters scrolled off the left + for _, backend := range wideBackends { + t.Run(backend.name, func(t *testing.T) { + for _, clear := range []platform.Color{{Alpha: 1}, {}} { + draw := backend.open(t, clear) + for _, withRuns := range []bool{false, true} { + name := map[bool]string{false: "transparent", true: "opaque"}[clear.Alpha >= 1] + + map[bool]string{false: "", true: " with runs"}[withRuns] + wide := make([]*image.RGBA, len(scrolls)) + for index, scrolled := range scrolls { + var runs []gfx.TextRun + if withRuns { + runs = wholeRun(wideValue) + } + wide[index] = draw(wideMonoLine(wideValue, -8*float32(scrolled), runs)) + } + for index, scrolled := range scrolls { + start := wideValue[:scrolled+300] + var runs []gfx.TextRun + if withRuns { + runs = wholeRun(start) + } + want := draw(wideMonoLine(start, -8*float32(scrolled), runs)) + got, painted := wide[index], 0 + for y := 0; y < 60; y++ { + for x := 0; x < 600; x++ { + if got.RGBAAt(x, y) != want.RGBAAt(x, y) { + t.Fatalf("%s, %d characters scrolled: pixel %d,%d is %v, the start of the line's is %v", + name, scrolled, x, y, got.RGBAAt(x, y), want.RGBAAt(x, y)) + } + if isPainted(got, x, y) { + painted++ + } + } + } + if painted < 1000 { + t.Errorf("%s, %d characters scrolled: %d pixels of text painted", name, scrolled, painted) + } + } + } + } + }) + } +} + +// The CPU window's scene draws a line wider than a texture holds from the window of it the +// canvas shows. A scroll inside that window keeps its picture, one past it draws a new window, +// and a line scrolled off the canvas has no picture until it is scrolled back; after each the +// canvas is what a scene built with the line where it is paints. +func TestSoftSceneDrawsAWideLineFromWhatTheCanvasShows(t *testing.T) { + services, err := newTextServices() + if err != nil { + t.Skipf("no text services: %v", err) + } + const scale = 1.5 + clear := platform.Color{Alpha: 1} + label := wideMonoLine(wideValue, 0, wholeRun(wideValue)) + live, err := newSoftScene(services, 600, 60, scale, clear, nil, []platform.TextLabel{label}) + if err != nil { + t.Fatal(err) + } + live.paint() + for _, step := range []struct { + name string + x float32 + skip int // the first column of the line's picture, or -1 for none + }{ + {"scrolled inside its picture", -100, 0}, + {"scrolled past its picture", -8000, 11400}, + {"scrolled a little", -8100, 11400}, + {"scrolled off the canvas", -40000, -1}, + {"scrolled back", -8000, 11400}, + } { + next := label + next.X = step.x + if _, err := live.apply(platform.Frame{TextLabels: []platform.TextLabel{next}}); err != nil { + t.Fatalf("%s: %v", step.name, err) + } + live.paint() + slot := &live.labels[0] + switch { + case step.skip < 0 && (slot.hasImage || slot.visible): + t.Errorf("%s: the line has a picture", step.name) + case step.skip >= 0 && (!slot.hasImage || !slot.visible || slot.image.skip != step.skip || slot.image.width != 1800): + t.Errorf("%s: picture from column %d, %d wide (drawn %v); want %d, 1800", step.name, slot.image.skip, slot.image.width, slot.hasImage, step.skip) + } + whole, err := newSoftScene(services, live.canvas.Width, live.canvas.Height, scale, clear, nil, []platform.TextLabel{next}) + if err != nil { + t.Fatal(err) + } + whole.paint() + if !bytes.Equal(live.canvas.Pix, whole.canvas.Pix) { + t.Fatalf("%s: canvas differs from a full paint", step.name) + } + } +} + +// A label no texture holds, an image larger than one or a line taller than one, is not drawn, +// and the labels beside it still are: one label a renderer cannot hold does not fail the frame. +// The CPU renderer has no texture and may draw the image. +func TestLabelNoTextureHoldsDoesNotFailTheFrame(t *testing.T) { + const imageWidth = platform.LabelTextureLimit + 16 + tall := platform.TextLabel{Value: "tall", X: 200, Y: 0, Width: 40, Height: platform.LabelTextureLimit + 1, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + wide := platform.TextLabel{X: 0, Y: 30, Width: imageWidth, Height: 2, + Bitmap: make([]byte, imageWidth*2*4), BitmapWidth: imageWidth, BitmapHeight: 2, BitmapStride: imageWidth * 4, BitmapID: 1, BitmapVersion: 1} + beside := platform.TextLabel{Value: "beside", X: 10, Y: 4, Width: 80, Height: 18, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + for _, backend := range wideBackends { + t.Run(backend.name, func(t *testing.T) { + pixels := backend.open(t, platform.Color{Alpha: 1})(tall, wide, beside) + painted := 0 + for y := 0; y < 40; y++ { // the label beside, at 150% + for x := 0; x < 150; x++ { + if isPainted(pixels, x, y) { + painted++ + } + } + } + if painted == 0 { + t.Fatal("the label beside one no texture holds was not drawn") + } + }) + } +} diff --git a/internal/platform/windows/direct_grid_windows.go b/internal/platform/windows/direct_grid_windows.go index 8bad25bf8..a2f311b2a 100644 --- a/internal/platform/windows/direct_grid_windows.go +++ b/internal/platform/windows/direct_grid_windows.go @@ -18,12 +18,14 @@ type gridPiece struct { } // gridPieces splits a fixed-pitch label into its runs. A label without runs is one piece -// of the label's own color and weight. -func (rasterizer *directRasterizer) gridPieces(label platform.TextLabel, pitch float32) []gridPiece { +// of the label's own color and weight. skip is the whole device columns of the line left of +// the texture the pieces are drawn into: each piece stands that much further left, so the +// glyphs keep the columns they have when the whole line is drawn. +func (rasterizer *directRasterizer) gridPieces(label platform.TextLabel, pitch float32, skip int) []gridPiece { rasterizer.pieces = rasterizer.pieces[:0] if len(label.Runs) == 0 { rasterizer.pieces = append(rasterizer.pieces, gridPiece{ - text: label.Value, weight: label.Weight, index: -1, + text: label.Value, weight: label.Weight, index: -1, left: -float32(skip), color: d2dColor{R: float32(label.Color.Red), G: float32(label.Color.Green), B: float32(label.Color.Blue), A: float32(label.Color.Alpha)}, }) return rasterizer.pieces @@ -42,7 +44,7 @@ func (rasterizer *directRasterizer) gridPieces(label platform.TextLabel, pitch f rasterizer.pieces = append(rasterizer.pieces, gridPiece{ text: text, run: run, weight: run.Weight, color: d2dColor{R: run.Color.Red, G: run.Color.Green, B: run.Color.Blue, A: run.Color.Alpha}, - left: float32(run.Column) * pitch, span: float32(run.Cells) * pitch, index: index, + left: float32(run.Column)*pitch - float32(skip), span: float32(run.Cells) * pitch, index: index, }) } return rasterizer.pieces @@ -66,15 +68,17 @@ type colorSpan struct { // and drawing a saturated color twice for the brightness of each channel would double the // cost of the terminal for a difference nobody sees. Runs stand on cells of the grid, so the // columns of one run never hold the glyphs of another except for the last pixel the -// ClearType filter spills over. -func (rasterizer *directRasterizer) gridLCD(pixels []byte, label platform.TextLabel, scale float32, width, height int) error { +// ClearType filter spills over. skip is as for grid: the columns a run owns are planned along +// the whole line, as its neighbours' ink reaches, and then moved onto the texture. +func (rasterizer *directRasterizer) gridLCD(pixels []byte, label platform.TextLabel, scale float32, width, height, skip int) error { family := monoFamily(label.MonoFace) fallback := rasterizer.fontFallback(label.MonoFace) size := label.FontSize * scale pitch := label.CellWidth * scale baseline := float32(platform.TextBaseline(label, height, scale)) - pieces := rasterizer.gridPieces(label, pitch) - columns := rasterizer.ownedColumns(label, pieces, family, fallback, size, pitch, width) + pieces := rasterizer.gridPieces(label, pitch, skip) + columns := rasterizer.ownedColumns(label, pieces, family, fallback, size, pitch, skip+width) + platform.ShiftGridSpans(columns, skip, width) if err := rasterizer.useGDI(pieces, family, size, width, height); err != nil { return err } diff --git a/internal/platform/windows/direct_windows.go b/internal/platform/windows/direct_windows.go index 787d5e94b..26df93e5d 100644 --- a/internal/platform/windows/direct_windows.go +++ b/internal/platform/windows/direct_windows.go @@ -295,9 +295,9 @@ func (rasterizer *directRasterizer) rasterize(label platform.TextLabel, scale fl rasterizer.spans = rasterizer.spans[:0] if label.Mono || len(label.Runs) > 0 { if allowLCD && !platform.ColorGlyphs(label.Value) { - return pixels, true, rasterizer.gridLCD(pixels, label, scale, width, height) + return pixels, true, rasterizer.gridLCD(pixels, label, scale, width, height, skip) } - return pixels, false, rasterizer.grid(pixels, label, scale, width, height) + return pixels, false, rasterizer.grid(pixels, label, scale, width, height, skip) } lcd = allowLCD && !platform.ColorGlyphs(label.Value) baseline := float32(platform.TextBaseline(label, height, scale)) @@ -485,7 +485,8 @@ func coverageOfChannels(pixels []byte, bitmap *textBitmap, width, height int, dr // weight and decorations of their own, each character on its cell of the grid (Viva's, not the // font's), or the whole value of a monospaced label. Colors are applied as the text is drawn // (premultiplied BGRA, grayscale antialiasing), so a line is one texture however many colors it holds. -func (rasterizer *directRasterizer) grid(pixels []byte, label platform.TextLabel, scale float32, width, height int) error { +// skip is the device columns of the line left of the texture, for a line wider than a texture holds. +func (rasterizer *directRasterizer) grid(pixels []byte, label platform.TextLabel, scale float32, width, height, skip int) error { family := monoFamily(label.MonoFace) fallback := rasterizer.fontFallback(label.MonoFace) size := label.FontSize * scale @@ -499,7 +500,7 @@ func (rasterizer *directRasterizer) grid(pixels []byte, label platform.TextLabel fill(scratch, width, height, d2dColor{}) target.begin(d2dColor{A: 1}, d2dAntialiasGrayscale) var drawErr error - for _, piece := range rasterizer.gridPieces(label, pitch) { + for _, piece := range rasterizer.gridPieces(label, pitch, skip) { target.setColor(piece.color) if err := rasterizer.drawRun(target, family, fallback, size, piece.weight, piece.run, piece.text, piece.left, piece.span, pitch, baseline, pieceClip{}); err != nil && drawErr == nil { drawErr = err diff --git a/internal/platform/windows/label_picture_windows.go b/internal/platform/windows/label_picture_windows.go index 3e00b4108..c7435beac 100644 --- a/internal/platform/windows/label_picture_windows.go +++ b/internal/platform/windows/label_picture_windows.go @@ -153,8 +153,8 @@ func (label *labelTexture) usePicture(picture *labelPicture) { label.spans = label.spans[:0] } -func (renderer *renderer) reuseLabelPicture(label *labelTexture, scale float32) bool { - skip, width, shown := label.window(scale) +func (renderer *renderer) reuseLabelPicture(label *labelTexture, scale float32, viewport int) bool { + skip, width, shown := label.window(scale, viewport) if !shown { return false } diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 64e71ef74..8c499d7ac 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -585,7 +585,7 @@ func (renderer *renderer) presentWithSync(width, height int, scale float32, sync func (renderer *renderer) draw(width, height int, scale float32) error { // A page that appeared has many labels to draw; draw their pixels in one // Direct2D session before any of them is composited. - if err := renderer.prepareLabels(scale); err != nil { + if err := renderer.prepareLabels(scale, width); err != nil { return err } clear := [4]float32{float32(renderer.color.Red), float32(renderer.color.Green), float32(renderer.color.Blue), float32(renderer.color.Alpha)} @@ -649,14 +649,13 @@ func (renderer *renderer) draw(width, height int, scale float32) error { label.dropTexture() continue } - skip, windowWidth, shown := label.window(scale) + skip, windowWidth, shown := label.window(scale, width) if !shown { label.close() continue } - if label.view == 0 || label.stale || label.scale != scale || label.skip != skip || skip > 0 && label.width != windowWidth || renderer.pictureChanged(label, scale, skip, windowWidth) || - len(label.label.Bitmap) > 0 && platform.BitmapTextureStale(label.label, scale, label.width, label.height) { - if err := renderer.rasterize(label, scale); err != nil { + if renderer.needsRaster(label, scale, skip, windowWidth) { + if err := renderer.rasterize(label, scale, width); err != nil { return fmt.Errorf("rasterize label %d: %w", index, err) } } @@ -681,8 +680,9 @@ func (renderer *renderer) draw(width, height int, scale float32) error { continue } // A grid line has a color per run: its coverage is drawn once for each, cut to the - // columns of the run. + // columns of the run, which count from the texture's left edge. origin, _ := label.pixelOrigin(scale) + origin += label.skip for _, span := range label.spans { cut = scissor cut.Left, cut.Right = max(cut.Left, int32(origin+span.left)), min(cut.Right, int32(origin+span.right)) diff --git a/internal/platform/windows/renderer_windows_test.go b/internal/platform/windows/renderer_windows_test.go index 0c8995d9a..75bec8bed 100644 --- a/internal/platform/windows/renderer_windows_test.go +++ b/internal/platform/windows/renderer_windows_test.go @@ -417,12 +417,12 @@ func TestGridInkWidthStopsNearTheLastRun(t *testing.T) { t.Fatal("one more typed character changed the texture width, so every key would make a new texture") } label := labelTexture{label: platform.TextLabel{Value: "x", Mono: true, Runs: runs, CellWidth: cell, Width: 100 * cell, Height: 20, FontSize: 12}} - skip, width, ok := label.window(scale) + skip, width, ok := label.window(scale, 0) if !ok || skip != 0 || width != ink { t.Fatalf("window = %d, %d, %v, want 0, %d, true", skip, width, ok, ink) } label.label.Width = 4 - if _, width, _ = label.window(scale); width > 4*scale { + if _, width, _ = label.window(scale, 0); width > 4*scale { t.Fatalf("a narrow label got a texture %d wide, wider than itself", width) } } diff --git a/internal/platform/windows/text_batch_windows.go b/internal/platform/windows/text_batch_windows.go index 91f0c45f5..b9e986891 100644 --- a/internal/platform/windows/text_batch_windows.go +++ b/internal/platform/windows/text_batch_windows.go @@ -83,14 +83,14 @@ type labelBatch struct { // add queues a label. It reports false when the label's pixels would differ // from the per-label path, and full when the batch bitmap could not hold it; // the caller then flushes and tries the label again. -func (batch *labelBatch) add(label *labelTexture, scale float32, allowLCD bool) (added, full bool, err error) { - skip, width, ok := label.window(scale) +func (batch *labelBatch) add(label *labelTexture, scale float32, viewport int, allowLCD bool) (added, full bool, err error) { + skip, width, ok := label.window(scale, viewport) if !ok { return false, false, nil } height := int(math.Ceil(float64(label.label.Height * scale))) - if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 { - return false, false, nil // the per-label path reports the bounded-size error + if !platform.LabelTextureFits(width, height) { + return false, false, nil // the per-label path leaves it without a texture } size := label.label.FontSize * scale if size <= 0 || math.IsNaN(float64(size)) || math.IsInf(float64(size), 0) { @@ -228,7 +228,7 @@ func (batch *labelBatch) draw(renderer *renderer, items []labelBatchItem, pack b // prepareLabels rasterizes the proportional labels that changed this frame in // batches. Labels it leaves untouched are drawn by the per-label path in draw. -func (renderer *renderer) prepareLabels(scale float32) error { +func (renderer *renderer) prepareLabels(scale float32, viewport int) error { if renderer.noLabelBatch { return nil } @@ -248,17 +248,14 @@ func (renderer *renderer) prepareLabels(scale float32) error { len(label.label.Bitmap) > 0 || label.label.Mono || len(label.label.Runs) > 0 { continue } - skip, windowWidth, shown := label.window(scale) - if !shown { + skip, windowWidth, shown := label.window(scale, viewport) + if !shown || !renderer.needsRaster(label, scale, skip, windowWidth) { continue } - if !(label.view == 0 || label.stale || label.scale != scale || label.skip != skip || skip > 0 && label.width != windowWidth || renderer.pictureChanged(label, scale, skip, windowWidth)) { + if renderer.reuseLabelPicture(label, scale, viewport) { continue } - if renderer.reuseLabelPicture(label, scale) { - continue - } - _, full, err := batch.add(label, scale, allowLCD) + _, full, err := batch.add(label, scale, viewport, allowLCD) if err != nil { return err } @@ -267,7 +264,7 @@ func (renderer *renderer) prepareLabels(scale float32) error { if err := flush(); err != nil { return err } - if _, _, err := batch.add(label, scale, allowLCD); err != nil { + if _, _, err := batch.add(label, scale, viewport, allowLCD); err != nil { return err } } diff --git a/internal/platform/windows/text_editing_windows_test.go b/internal/platform/windows/text_editing_windows_test.go index febc20be2..373369090 100644 --- a/internal/platform/windows/text_editing_windows_test.go +++ b/internal/platform/windows/text_editing_windows_test.go @@ -191,11 +191,11 @@ func TestNativeTextOverlayRasterizesOnlyTheVisibleColumns(t *testing.T) { Value: "value", X: -1490, Y: 0, Width: 1700, Height: 24, FontSize: 16, Clipped: true, Clip: gfx.Rect{X: 10, Y: 0, Width: 200, Height: 24}, }} - if skip, width, ok := label.window(2); !ok || skip != 3000 || width != 400 { + if skip, width, ok := label.window(2, 0); !ok || skip != 3000 || width != 400 { t.Fatalf("window = %d, %d, %v; want 3000, 400, true", skip, width, ok) } label.label.X, label.label.Width = 10, 200 - if skip, width, ok := label.window(2); !ok || skip != 0 || width != 400 { + if skip, width, ok := label.window(2, 0); !ok || skip != 0 || width != 400 { t.Fatalf("unscrolled window = %d, %d, %v; want 0, 400, true", skip, width, ok) } } diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index bb4e2f804..35153e68e 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -249,18 +249,37 @@ func (label *labelTexture) pixelOrigin(scale float32) (x, y int) { return platform.DevicePosition(l.X, l.OriginX, scale), platform.DevicePosition(l.Y, l.OriginY, scale) } -// window is the part of the label's full texture that its clip can show, in device -// pixels. A clipped line rasterizes only inside its clip, so a long scrolled -// single-line field costs the visible width, not the whole line. The text does not -// move: the skip is a whole number of device columns, so every glyph texel keeps the -// phase it has when the whole texture is drawn. Labels that are not clipped, and -// images and grid lines, keep their whole texture. -func (label *labelTexture) window(scale float32) (skip, width int, ok bool) { +// window is the part of the label's full texture that is rasterized, in device pixels: +// the columns from skip to skip+width. viewport is the width of the target in device +// pixels, or 0 when the caller has none. A clipped line rasterizes only inside its +// clip, so a long scrolled single-line field costs the visible width, not the whole +// line. A line of any kind wider than a texture holds, such as a log line of thousands +// of characters, rasterizes around the part of it the viewport and its clip show, and +// keeps its texture while a scroll stays inside it (platform.WideTextLabelWindow). The +// text does not move: the skip is a whole number of device columns, so every glyph +// texel keeps the phase it has when the whole texture is drawn. Other labels that are +// not clipped, and grid lines, keep their whole texture, and images always do. ok is +// false when nothing is drawn: none of the label can be seen, or it is too tall for +// any texture. +func (label *labelTexture) window(scale float32, viewport int) (skip, width int, ok bool) { full := int(math.Ceil(float64(label.label.Width * scale))) if label.label.Mono && len(label.label.Runs) > 0 { full = min(full, gridInkWidth(label.label.Runs, label.label.CellWidth, scale)) } - if !label.label.Clipped || label.label.Mono || len(label.label.Runs) > 0 || len(label.label.Bitmap) > 0 { + if len(label.label.Bitmap) > 0 { + return 0, full, full > 0 + } + // Every frame asks this of every label, so one a texture holds pays only this test. + if height := int(math.Ceil(float64(label.label.Height * scale))); !platform.LabelTextureFits(full, height) { + haveSkip, haveWidth := 0, 0 + if label.view != 0 && label.scale == scale { + haveSkip, haveWidth = label.skip, label.width + } + if skip, width, wide, ok := platform.WideTextLabelWindow(label.label, scale, full, height, viewport, haveSkip, haveWidth); wide { + return skip, width, ok + } + } + if !label.label.Clipped || label.label.Mono || len(label.label.Runs) > 0 { return 0, full, full > 0 } x, _ := label.pixelOrigin(scale) @@ -328,22 +347,38 @@ func sameRuns(left, right []gfx.TextRun) bool { } return true } -func (renderer *renderer) rasterize(label *labelTexture, scale float32) error { - if renderer.reuseLabelPicture(label, scale) { - return nil + +// needsRaster reports whether the label's texture must be drawn again before it is +// composited from the window skip to skip+width: it has none, what it shows or its +// scale changed, its window moved, the picture it shares no longer matches, or an +// image's texture no longer suits the size it is drawn at. +func (renderer *renderer) needsRaster(label *labelTexture, scale float32, skip, width int) bool { + if label.view == 0 || label.stale || label.scale != scale { + return true } - skip, width, ok := label.window(scale) - if !ok { - label.dropTexture() - label.scale, label.width, label.height, label.skip = scale, 0, 0, 0 + if len(label.label.Bitmap) > 0 { + return platform.BitmapTextureStale(label.label, scale, label.width, label.height) + } + return label.skip != skip || label.width != width || renderer.pictureChanged(label, scale, skip, width) +} + +// rasterize draws the label's texture for a target viewport device pixels wide (0 when +// unknown; see window). A label no texture can hold, an image larger than the device +// allows or a line too tall, is left without one and not drawn: one label the device +// cannot hold must not stop the window drawing the others. +func (renderer *renderer) rasterize(label *labelTexture, scale float32, viewport int) error { + if renderer.reuseLabelPicture(label, scale, viewport) { return nil } + skip, width, ok := label.window(scale, viewport) height := int(math.Ceil(float64(label.label.Height * scale))) - if len(label.label.Bitmap) > 0 { + if ok && len(label.label.Bitmap) > 0 { width, height = platform.BitmapTextureExtent(label.label, scale) } - if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 { - return fmt.Errorf("windows: label texture exceeds bounded size") + if !ok || !platform.LabelTextureFits(width, height) { + label.dropTexture() + label.scale = scale + return nil } var pixels []byte var err error diff --git a/internal/platform/windows/wide_label_windows_test.go b/internal/platform/windows/wide_label_windows_test.go new file mode 100644 index 000000000..8dd175038 --- /dev/null +++ b/internal/platform/windows/wide_label_windows_test.go @@ -0,0 +1,214 @@ +package windows + +import ( + "bytes" + "image" + "image/color" + "math" + "runtime" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// wideValue is a log line of 4096 characters: at 8 logical pixels a cell and 150% it is +// 49152 device pixels wide, three times what a Direct3D 11 texture holds. +var wideValue = strings.Repeat("0123456789abcdef", 256) + +func wideMonoLine(value string, x float32, runs []gfx.TextRun) platform.TextLabel { + return platform.TextLabel{ + Value: value, X: x, Y: 4, Width: float32(len(value))*8 + 8, Height: 18, FontSize: 13, CellWidth: 8, + Mono: true, Runs: runs, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Clipped: true, Clip: gfx.Rect{Width: 400, Height: 40}, + } +} + +func wholeRun(value string) []gfx.TextRun { + return []gfx.TextRun{{Bytes: int32(len(value)), Cells: int32(len(value)), Weight: 400, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}}} +} + +// A line wider than a texture holds gets a window of it around what the viewport and its +// clip show, of any kind, within the limit; one that cannot be seen, or that is too tall +// for any texture, gets none and is not drawn. +func TestWideLabelWindowFollowsTheViewport(t *testing.T) { + const scale, viewport = 1.5, 600 + for _, runs := range [][]gfx.TextRun{nil, wholeRun(wideValue)} { + label := labelTexture{label: wideMonoLine(wideValue, 0, runs)} + skip, width, ok := label.window(scale, viewport) + if !ok || skip != 0 || width != 1800 { + t.Errorf("runs %d, start of the line: window = %d, %d, %v; want 0, 1800, true", len(runs), skip, width, ok) + } + label.label.X = -20000 // 30000 device pixels scrolled off the left + skip, width, ok = label.window(scale, viewport) + if !ok || skip != 30000-600 || width != 1800 { + t.Errorf("runs %d, scrolled: window = %d, %d, %v; want 29400, 1800, true", len(runs), skip, width, ok) + } + label.label.X = -40000 + if _, _, ok = label.window(scale, viewport); ok { + t.Errorf("runs %d: a line scrolled out of the viewport has a window", len(runs)) + } + label.label.X, label.label.Clipped = 0, false + if skip, width, ok = label.window(scale, 0); !ok || width > platform.LabelTextureLimit || skip != 0 { + t.Errorf("runs %d, no viewport or clip: window = %d, %d, %v; want one texture from the start", len(runs), skip, width, ok) + } + label.label.Height = 12000 // 18000 device pixels + if _, _, ok = label.window(scale, viewport); ok { + t.Errorf("runs %d: a line too tall for any texture has a window", len(runs)) + } + } +} + +// A monospaced line wider than any texture the device makes, such as a long log line +// shown unwrapped, is rasterized from a window of it at its start and scrolled, as ClearType +// and in grayscale, without and with runs. The window's texture holds the pixels the texture +// of the start of the same line, which one texture holds, has for the columns both show: the +// window moves no glyph. +func TestWideMonoLineWindowHoldsThePixelsOfTheLine(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + rasterizer, err := newDirectRasterizer() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + defer rasterizer.close() + const scale, viewport = 1.5, 600 + raster := func(label platform.TextLabel, lcd bool) (pixels []byte, skip, width, height int) { + t.Helper() + texture := labelTexture{label: label} + skip, width, ok := texture.window(scale, viewport) + if !ok { + t.Fatalf("a line of %d characters at %v has no window", len(label.Value), label.X) + } + height = int(math.Ceil(float64(label.Height * scale))) + pixels, _, err := rasterizer.rasterize(label, scale, width, height, lcd, skip) + if err != nil { + t.Fatal(err) + } + return append([]byte(nil), pixels...), skip, width, height + } + for _, lcd := range []bool{true, false} { + for _, withRuns := range []bool{false, true} { + for _, scrolled := range []int{0, 1000} { // characters scrolled off the left + start := wideValue[:scrolled+300] + wideRuns, startRuns := []gfx.TextRun(nil), []gfx.TextRun(nil) + if withRuns { + wideRuns, startRuns = wholeRun(wideValue), wholeRun(start) + } + x := -8 * float32(scrolled) + name := map[bool]string{false: "grayscale", true: "ClearType"}[lcd] + map[bool]string{false: "", true: " with runs"}[withRuns] + wide, wideSkip, wideWidth, height := raster(wideMonoLine(wideValue, x, wideRuns), lcd) + want, wantSkip, wantWidth, _ := raster(wideMonoLine(start, x, startRuns), lcd) + if wideWidth <= 0 || wideWidth > platform.LabelTextureLimit { + t.Fatalf("%s, %d characters scrolled: the line's texture is %d wide", name, scrolled, wideWidth) + } + origin := platform.DevicePosition(x, 0, scale) + painted := 0 + for column := 0; column < viewport; column++ { // device columns of the target + got, at := column-origin-wideSkip, column-origin-wantSkip + if got < 0 || got >= wideWidth || at < 0 || at >= wantWidth { + t.Fatalf("%s, %d characters scrolled: column %d is outside a texture (%d of %d, %d of %d)", + name, scrolled, column, got, wideWidth, at, wantWidth) + } + for row := 0; row < height; row++ { + a, b := wide[(row*wideWidth+got)*4:][:4], want[(row*wantWidth+at)*4:][:4] + if !bytes.Equal(a, b) { + t.Fatalf("%s, %d characters scrolled: pixel %d,%d is %v, the start of the line's is %v", + name, scrolled, column, row, a, b) + } + if a[3] != 0 { + painted++ + } + } + } + if painted < 1000 { + t.Errorf("%s, %d characters scrolled: %d pixels of text", name, scrolled, painted) + } + } + } + } +} + +// Drawn on a target, as ClearType (an opaque one) and in grayscale (a transparent one), the +// wide line is where the start of the same line is, at its start and scrolled. Drawing it +// whole asked Direct3D 11 for a texture wider than it makes, and the error stopped the window +// drawing anything again. A channel may differ by one level: the window's texture starts off +// the target where the start's does not, so the sampler reaches the same texel centres along +// a different quad, and Direct3D's linear filter weighs texels to 8 bits, which can give a +// texel 1/256 of its neighbour. A glyph moved by a device pixel differs by far more. +func TestWideMonoLineIsDrawnFromAWindowOfIt(t *testing.T) { + for _, clearColor := range []platform.Color{black, {}} { + for _, withRuns := range []bool{false, true} { + for _, scrolled := range []int{0, 1000} { // characters scrolled off the left + start := wideValue[:scrolled+300] + wideRuns, startRuns := []gfx.TextRun(nil), []gfx.TextRun(nil) + if withRuns { + wideRuns, startRuns = wholeRun(wideValue), wholeRun(start) + } + x := -8 * float32(scrolled) + wide := renderOffscreen(t, clearColor, wideMonoLine(wideValue, x, wideRuns)) + want := renderOffscreen(t, clearColor, wideMonoLine(start, x, startRuns)) + name := map[bool]string{false: "grayscale", true: "ClearType"}[clearColor.Alpha >= 1] + + map[bool]string{false: "", true: " with runs"}[withRuns] + painted := 0 + for y := 0; y < 60; y++ { + for x := 0; x < 600; x++ { + if a, b := wide.RGBAAt(x, y), want.RGBAAt(x, y); !withinALevel(a, b) { + t.Fatalf("%s, %d characters scrolled: pixel %d,%d is %v, the start of the line's is %v", + name, scrolled, x, y, a, b) + } + if isPainted(wide, x, y) { + painted++ + } + } + } + if painted < 1000 { + t.Errorf("%s, %d characters scrolled: %d pixels of text painted", name, scrolled, painted) + } + } + } + } +} + +// withinALevel reports whether no channel of a and b differs by more than one level. +func withinALevel(a, b color.RGBA) bool { + near := func(p, q uint8) bool { return int(p)-int(q) <= 1 && int(q)-int(p) <= 1 } + return near(a.R, b.R) && near(a.G, b.G) && near(a.B, b.B) && near(a.A, b.A) +} + +// A label no texture holds, an image larger than the device allows or a line taller than +// a texture, is not drawn, and the labels beside it still are: one label the device cannot +// hold does not fail the frame. +func TestLabelNoTextureHoldsDoesNotFailTheFrame(t *testing.T) { + const imageWidth = platform.LabelTextureLimit + 16 + tall := platform.TextLabel{Value: "tall", X: 200, Y: 0, Width: 40, Height: platform.LabelTextureLimit + 1, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + wide := platform.TextLabel{X: 0, Y: 30, Width: imageWidth, Height: 2, + Bitmap: make([]byte, imageWidth*2*4), BitmapWidth: imageWidth, BitmapHeight: 2, BitmapStride: imageWidth * 4, BitmapID: 1, BitmapVersion: 1} + beside := platform.TextLabel{Value: "beside", X: 10, Y: 4, Width: 80, Height: 18, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + pixels := renderOffscreen(t, black, tall, wide, beside) + painted := 0 + for y := 0; y < 40; y++ { // the label beside, at 150% + for x := 0; x < 150; x++ { + if isPainted(pixels, x, y) { + painted++ + } + } + } + if painted == 0 { + t.Fatal("the label beside one no texture holds was not drawn") + } +} + +// renderOffscreen draws the labels on a 400 by 40 scene at 150%, cleared to clearColor. +func renderOffscreen(t *testing.T, clearColor platform.Color, labels ...platform.TextLabel) *image.RGBA { + t.Helper() + offscreen, err := NewOffscreen(400, 40, 1.5, clearColor) + if err != nil { + t.Skipf("no Direct3D 11 device: %v", err) + } + defer offscreen.Close() + return renderScene(t, offscreen, nil, labels) +} From dd53d6da0ccc1a2d619d8abadc6820fe448c89b8 Mon Sep 17 00:00:00 2001 From: ezreal <71426102+Ezreal-byte@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:02:01 +0800 Subject: [PATCH 08/16] fix(linux): raise windows with X11 activation timestamps --- internal/platform/linux/status_item_linux.go | 33 ++++-- .../linux/window_activation_linux_test.go | 108 ++++++++++++++++++ internal/platform/linux/window_linux.go | 45 +++++--- .../linux/window_protocols_linux_test.go | 4 + .../platform/linux/window_title_linux_test.go | 1 + 5 files changed, 170 insertions(+), 21 deletions(-) create mode 100644 internal/platform/linux/window_activation_linux_test.go diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 94eb75af3..076c2a573 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -180,6 +180,7 @@ func (state *linuxWindowState) command(command uint32, data []byte) error { } case commandHide: state.hidden = true + state.exposed = false win.api.unmapWindow(win.connection, win.id) win.api.flush(win.connection) // Hide may arrive before the window manager has mapped a new window: the @@ -190,6 +191,8 @@ func (state *linuxWindowState) command(command uint32, data []byte) error { state.config.OnVisibility(false) } case commandShow: + state.hidden = false + win.setUserTime(state.application.lastUserTime) win.api.mapWindow(win.connection, win.id) if win.topmostConfigured.Load() { action := uint32(0) @@ -199,7 +202,7 @@ func (state *linuxWindowState) command(command uint32, data []byte) error { win.sendToRoot(win.frame.stateAtom, [5]uint32{action, win.frame.above, 0, sourceApp}) } if state.config.WindowMode != platform.WindowPanel { - if err := win.requestActivation(); err != nil { + if err := state.requestActivation(); err != nil { return err } } @@ -216,16 +219,32 @@ func (state *linuxWindowState) command(command uint32, data []byte) error { return nil } -// requestActivation asks the window manager to bring this window forward, as a -// pager does: with a _NET_ACTIVE_WINDOW message to the root window. -func (win *window) requestActivation() error { +func (win *window) setUserTime(timestamp uint32) { + if timestamp != 0 && win.userTimeAtom != 0 { + win.api.changeProperty(win.connection, xcbPropertyReplace, win.id, win.userTimeAtom, xcbAtomCardinal, 32, 1, unsafe.Pointer(×tamp)) + } +} + +// Send the user action along with the request. A focus-stealing policy may +// reject a transfer between two application windows without this information. +func (state *linuxWindowState) requestActivation() error { + win := state.win active, err := win.api.atom(win.connection, "_NET_ACTIVE_WINDOW") if err != nil { return err } - event := xcbClientEvent{ResponseType: xcbClientMessage, Format: 32, Window: win.id, Type: active} - event.Data[0] = 1 // the request comes from an application - win.api.sendEvent(win.connection, 0, win.screen.Root, xcbEventSubstructureRedirect|xcbEventSubstructureNotify, (*byte)(unsafe.Pointer(&event))) + const xcbAtomWindow = 33 + var requestor uint32 + if data, ok := win.tracker.property(win.screen.Root, active, xcbAtomWindow); ok && len(data) == 4 { + id := binary.LittleEndian.Uint32(data) + for _, other := range state.application.windows { + if other.win.id == id { + requestor = id + break + } + } + } + win.sendToRoot(active, [5]uint32{sourceApp, state.application.lastUserTime, requestor}) return nil } diff --git a/internal/platform/linux/window_activation_linux_test.go b/internal/platform/linux/window_activation_linux_test.go new file mode 100644 index 000000000..ce0e7ad23 --- /dev/null +++ b/internal/platform/linux/window_activation_linux_test.go @@ -0,0 +1,108 @@ +package linux + +import ( + "encoding/binary" + "fmt" + "os" + "os/exec" + "testing" + "time" + + "github.com/vivaui/viva/internal/platform" +) + +// Run under a dedicated X11 display with an EWMH window manager and xdotool. +func TestUserCanRaiseSecondaryWindow(t *testing.T) { + if os.Getenv("VIVA_LINUX_WM_SMOKE") == "" { + t.Skip("set VIVA_LINUX_WM_SMOKE=1 under an isolated window manager") + } + t.Setenv("VIVA_SOFTWARE_RENDERING", "1") + application := &linuxApplication{} + t.Cleanup(application.closeAll) + open := func(title string) *nativeWindow { + control, err := application.OpenWindow(platform.Config{ + Title: title, Class: title, Width: 200, Height: 140, WindowMode: platform.WindowCustomTitlebar, + OnPointer: func(platform.PointerEvent) (platform.Frame, error) { return platform.Frame{}, nil }, + OnMinimize: func(bool) {}, + }) + if err != nil { + t.Fatal(err) + } + return control.(*nativeWindow) + } + wait := func(description string, condition func() bool) { + t.Helper() + for deadline := time.Now().Add(4 * time.Second); time.Now().Before(deadline); { + for _, state := range application.windows { + for event := state.nextEvent(); event != nil; event = state.nextEvent() { + closed, err := state.handleEvent(event) + state.win.api.free(event) + if closed || err != nil { + t.Fatalf("%s: closed=%v, err=%v", description, closed, err) + } + } + } + if condition() { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("timed out waiting for %s", description) + } + main := open("VivaMain") + win := main.state.win + root := &window{api: win.api, connection: win.connection, id: win.screen.Root} + front := func(target *nativeWindow) bool { + active, _ := windowProperty(t, root, "_NET_ACTIVE_WINDOW", 0) + stack, _ := windowProperty(t, root, "_NET_CLIENT_LIST_STACKING", 0) + id := target.state.win.id + return len(active) == 4 && binary.LittleEndian.Uint32(active) == id && + len(stack) >= 4 && binary.LittleEndian.Uint32(stack[len(stack)-4:]) == id + } + xdotool := func(args ...string) { + t.Helper() + if output, err := exec.Command("xdotool", args...).CombinedOutput(); err != nil { + t.Fatalf("xdotool %v: %v: %s", args, err, output) + } + } + wait("main window mapped", func() bool { return main.state.exposed }) + clickMain := func() { + before := application.lastUserTime + xdotool("mousemove", "--window", fmt.Sprint(win.id), "80", "80", "click", "1") + wait("user action in main window", func() bool { return application.lastUserTime != before }) + } + clickMain() + wait("clicked main window active and in front", func() bool { return front(main) }) + child := open("VivaHistory") + child.Show() + wait("new history window active and in front", func() bool { return front(child) }) + property, _ := windowProperty(t, child.state.win, "_NET_WM_USER_TIME", xcbAtomCardinal) + if len(property) != 4 || binary.LittleEndian.Uint32(property) != application.lastUserTime { + t.Fatalf("secondary window user time = %v, want %d", property, application.lastUserTime) + } + + for _, state := range []string{"covered", "minimized", "hidden"} { + switch state { + case "minimized": + xdotool("windowminimize", fmt.Sprint(child.state.win.id)) + wait("iconic history window", func() bool { return child.state.win.minimized }) + case "hidden": + child.Hide() + wait("withdrawn history window", func() bool { + data, _ := windowProperty(t, root, "_NET_CLIENT_LIST", 0) + for len(data) >= 4 { + if binary.LittleEndian.Uint32(data) == child.state.win.id { + return false + } + data = data[4:] + } + return child.state.hidden + }) + } + main.Show() + wait("main window above "+state+" history", func() bool { return front(main) }) + clickMain() + child.Show() + wait(state+" history window active and in front", func() bool { return front(child) && child.state.exposed }) + } +} diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 0daebe6fc..c95c6e2ce 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -33,6 +33,7 @@ type window struct { caretAtom uint32 closeAtom uint32 commandAtom uint32 + userTimeAtom uint32 // titleMu guards pendingTitle, the title SetTitle asked for that the event loop // has not written to the window yet. titleMu sync.Mutex @@ -157,10 +158,8 @@ type linuxWindowState struct { // frameGeometryDirty means a maximization property changed the client-side // margin before its matching ConfigureNotify supplied the final dimensions. frameGeometryDirty bool - // hidden is set by Hide: a compositor drops the contents of an unmapped - // window, so the first Expose after the window is shown again presents once. - // The same goes for the first one after the window opened: what was drawn - // before the window manager mapped it is gone. + // hidden records the application's request, independently of the asynchronous + // MapNotify/UnmapNotify events. The first Expose after a map paints in full. hidden bool exposed bool // visible is the last visibility reported to OnVisibility; a window starts as visible. @@ -168,11 +167,12 @@ type linuxWindowState struct { } type linuxApplication struct { - windows []*linuxWindowState - pollFDs []pollFD - pollStates []*linuxWindowState // parallel to pollFDs; nil for the status bus - firstErr error - quit bool + lastUserTime uint32 // X server timestamp of the last user press in any of our windows + windows []*linuxWindowState + pollFDs []pollFD + pollStates []*linuxWindowState // parallel to pollFDs; nil for the status bus + firstErr error + quit bool // desktopServices are the connections to the session bus: the status icons, the watch on the // desktop's settings and the accessibility bridge. @@ -325,7 +325,7 @@ func (application *linuxApplication) OpenWindow(config platform.Config) (platfor if state.profile { state.started = time.Now() } - win, err := openWindow(config) + win, err := application.openWindow(config) if err != nil { return nil, err } @@ -660,7 +660,7 @@ func (state *linuxWindowState) coalesceConfigures(event unsafe.Pointer) unsafe.P state.win.api.free(next) case xcbExpose: expose := (*xcbExposeEvent)(next) - if expose.Window == state.win.id && !state.hidden && state.exposed { + if expose.Window == state.win.id && (state.hidden || state.exposed) { state.win.api.free(next) continue } @@ -863,6 +863,12 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { win, config, textInput, renderer, router := state.win, state.config, state.text, state.renderer, state.router activeWindow.Store(win) kind := (*xcbGenericEvent)(event).ResponseType & 0x7f + if kind == xcbButtonPress || kind == xcbKeyPress { + if timestamp := (*xcbInputEvent)(event).Time; timestamp != 0 { + state.application.lastUserTime = timestamp + win.setUserTime(timestamp) + } + } if win.margin != 0 { win.shiftPointer(kind, event) } @@ -873,6 +879,9 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { case xcbDestroyNotify: return true, nil case xcbMapNotify, xcbUnmapNotify: + if (*xcbMapEvent)(event).Window == win.id && kind == xcbUnmapNotify { + state.exposed = false + } if kind == xcbMapNotify && (*xcbMapEvent)(event).Window == win.id && state.hidden { // The window manager mapped the window after Hide raced its first // map: ask it to go away again, rather than show a hidden window. @@ -1155,8 +1164,8 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { return true, nil } case xcbExpose: - if (state.hidden || !state.exposed) && (*xcbExposeEvent)(event).Count == 0 { - state.hidden, state.exposed = false, true + if !state.hidden && !state.exposed && (*xcbExposeEvent)(event).Count == 0 { + state.exposed = true return false, renderer.presentFull() } case xcbSelectionRequest: @@ -1300,7 +1309,7 @@ func validateConfig(config platform.Config) error { return nil } -func openWindow(config platform.Config) (*window, error) { +func (application *linuxApplication) openWindow(config platform.Config) (*window, error) { api, err := loadXCB() if err != nil { return nil, err @@ -1439,6 +1448,14 @@ func openWindow(config platform.Config) (*window, error) { } } win.setIdentity(config.Title) + if config.WindowMode == platform.WindowTitled || config.WindowMode == platform.WindowFrameless || config.WindowMode == platform.WindowCustomTitlebar { + win.userTimeAtom, err = api.atom(connection, "_NET_WM_USER_TIME") + if err != nil { + win.close() + return nil, err + } + win.setUserTime(application.lastUserTime) + } win.wmProtocols, err = api.atom(connection, "WM_PROTOCOLS") if err != nil { win.close() diff --git a/internal/platform/linux/window_protocols_linux_test.go b/internal/platform/linux/window_protocols_linux_test.go index 3f70acf2a..66c0ea238 100644 --- a/internal/platform/linux/window_protocols_linux_test.go +++ b/internal/platform/linux/window_protocols_linux_test.go @@ -11,6 +11,10 @@ import ( "github.com/vivaui/viva/internal/platform" ) +func openWindow(config platform.Config) (*window, error) { + return (&linuxApplication{}).openWindow(config) +} + // windowProperty reads a property of the window as raw bytes and its format. func windowProperty(t *testing.T, win *window, name string, kind uint32) ([]byte, uint8) { t.Helper() diff --git a/internal/platform/linux/window_title_linux_test.go b/internal/platform/linux/window_title_linux_test.go index 2398bb378..706c08146 100644 --- a/internal/platform/linux/window_title_linux_test.go +++ b/internal/platform/linux/window_title_linux_test.go @@ -20,6 +20,7 @@ func newTitleTestWindow(t *testing.T, written *[]titleProperty) *window { connection: 1, commandAtom: 50, api: &xcbAPI{ + free: func(unsafe.Pointer) {}, internAtom: func(_ uintptr, _ uint8, length uint16, name *byte) xcbAtomCookie { return xcbAtomCookie{Sequence: atoms[string(unsafe.Slice(name, int(length)))]} }, From c242c1bd1e66042aa131bc1720a1bd3da8b0d862 Mon Sep 17 00:00:00 2001 From: Dean Cen Date: Sat, 21 Nov 2026 13:02:12 +0800 Subject: [PATCH 09/16] fix(windows): keep live resize paced by the timer alone --- internal/platform/windows/api_windows.go | 3 ++ .../windows/renderer_resize_windows_test.go | 37 +++++++++++++++++++ internal/platform/windows/renderer_windows.go | 37 ++++++++++++++++--- internal/platform/windows/window_windows.go | 23 ++++++++++++ 4 files changed, 95 insertions(+), 5 deletions(-) create mode 100644 internal/platform/windows/renderer_resize_windows_test.go diff --git a/internal/platform/windows/api_windows.go b/internal/platform/windows/api_windows.go index 5a4b1a785..74c2cffc5 100644 --- a/internal/platform/windows/api_windows.go +++ b/internal/platform/windows/api_windows.go @@ -130,3 +130,6 @@ var ole = systemDLL("ole32.dll") var initializeCOM = ole.NewProc("CoInitializeEx") var uninitializeCOM = ole.NewProc("CoUninitialize") var createCOM = ole.NewProc("CoCreateInstance") +var winmm = systemDLL("winmm.dll") +var timeBeginPeriod = winmm.NewProc("timeBeginPeriod") +var timeEndPeriod = winmm.NewProc("timeEndPeriod") diff --git a/internal/platform/windows/renderer_resize_windows_test.go b/internal/platform/windows/renderer_resize_windows_test.go new file mode 100644 index 000000000..1a83a077e --- /dev/null +++ b/internal/platform/windows/renderer_resize_windows_test.go @@ -0,0 +1,37 @@ +package windows + +import "testing" + +// swapChainResize decides when the swap chain is rebuilt. A modal drag may keep +// a larger chain than the client and grow it in 64-pixel steps; every other +// present gets a chain of the exact client size, so a completed drag shrinks +// the chain back instead of leaving it skewed by the resize history. +func TestSwapChainResizeKeepsHeadroomOnlyDuringADrag(t *testing.T) { + cases := []struct { + name string + bufferWidth int + bufferHeight int + width int + height int + hasTarget bool + headroom bool + wantResize bool + wantWidth, wantHeight int + }{ + {"no chain yet", 0, 0, 800, 600, false, false, true, 800, 600}, + {"first drag frame takes headroom", 0, 0, 800, 600, false, true, true, 832, 640}, + {"drag reuses a larger chain", 832, 640, 700, 500, true, true, false, 832, 640}, + {"drag grows past the chain", 832, 640, 900, 600, true, true, true, 960, 640}, + {"drag exit shrinks to the client", 832, 640, 800, 600, true, false, true, 800, 600}, + {"no drag, same size", 800, 600, 800, 600, true, false, false, 800, 600}, + {"no drag grows exactly", 800, 600, 900, 700, true, false, true, 900, 700}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + resize, width, height := swapChainResize(c.bufferWidth, c.bufferHeight, c.width, c.height, c.hasTarget, c.headroom) + if resize != c.wantResize || width != c.wantWidth || height != c.wantHeight { + t.Fatalf("resize=%t size=%dx%d, want resize=%t size=%dx%d", resize, width, height, c.wantResize, c.wantWidth, c.wantHeight) + } + }) + } +} diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 8c499d7ac..4fc6edc28 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -146,8 +146,13 @@ type renderer struct { compositingBatches []compositingBatch color platform.Color capacity, width, height int - submissions, rebuilds, partials, labelRebuilds uint64 - labelBatches uint64 + bufferWidth, bufferHeight int + // resizeHeadroom lets a modal drag keep a larger back buffer than the + // client area, so growing it does not reallocate on every pixel. It is off + // outside a drag: every other size change gets a chain of the exact size. + resizeHeadroom bool + submissions, rebuilds, partials, labelRebuilds uint64 + labelBatches uint64 // noLabelBatch makes a frame rasterize each changed label on its own, as // before the batch path existed. Tests compare the two pixel by pixel. noLabelBatch bool @@ -556,10 +561,13 @@ func (renderer *renderer) presentWithSync(width, height int, scale float32, sync if width <= 0 || height <= 0 { return nil } - if renderer.width != width || renderer.height != height || renderer.target == 0 { + headroom := renderer.resizeHeadroom && sync == 0 && !renderer.usesComposition() + needResize, targetWidth, targetHeight := swapChainResize(renderer.bufferWidth, renderer.bufferHeight, width, height, renderer.target != 0, headroom) + if needResize { comCall(renderer.context, 33, 0, 0, 0) release(&renderer.target) - if err := hresult(comCall(renderer.swap, 13, 0, uintptr(width), uintptr(height), 0, 0)); err != nil { + comCall(renderer.context, 111) // Flush outstanding GPU commands before ResizeBuffers + if err := hresult(comCall(renderer.swap, 13, 0, uintptr(targetWidth), uintptr(targetHeight), 0, 0)); err != nil { return fmt.Errorf("resize swap chain: %w", err) } var back uintptr @@ -571,14 +579,32 @@ func (renderer *renderer) presentWithSync(width, height int, scale float32, sync if err := hresult(status); err != nil { return err } - renderer.width, renderer.height = width, height + renderer.bufferWidth, renderer.bufferHeight = targetWidth, targetHeight } + renderer.width, renderer.height = width, height if err := renderer.draw(width, height, scale); err != nil { return err } return hresult(comCall(renderer.swap, 8, sync, 0)) } +// swapChainResize reports whether a present at width by height must resize the +// swap chain, and to what size. With headroom (a modal drag's unsynced present) +// a chain already at least the client size is reused and a growing one is +// allocated in 64-pixel steps; otherwise the chain matches the client exactly. +func swapChainResize(bufferWidth, bufferHeight, width, height int, hasTarget, headroom bool) (bool, int, int) { + if headroom { + if !hasTarget || bufferWidth < width || bufferHeight < height { + return true, max(width, (width+63)&^63), max(height, (height+63)&^63) + } + return false, bufferWidth, bufferHeight + } + if !hasTarget || bufferWidth != width || bufferHeight != height { + return true, width, height + } + return false, bufferWidth, bufferHeight +} + // draw clears the bound-size render target to the clear color and paints every // compositing batch onto it. The window's present and the offscreen render // share it, so a screenshot is made of the pixels the window would show. @@ -744,6 +770,7 @@ func (renderer *renderer) releaseDevice() { renderer.labelPictures.evict(0) renderer.labelPictures = labelPictureCache{} renderer.capacity, renderer.width, renderer.height = 0, 0, 0 + renderer.bufferWidth, renderer.bufferHeight = 0, 0 renderer.releaseComposition() for _, object := range [...]*uintptr{&renderer.target, &renderer.swap, &renderer.view, &renderer.buffer, &renderer.constants, &renderer.blend, &renderer.textBlend, &renderer.raster, &renderer.sampler, &renderer.rectangleVertex, &renderer.rectangleFragment, &renderer.textVertex, &renderer.textFragment, &renderer.context, &renderer.device} { release(object) diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index bc3cc8280..4ce043a2c 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -90,6 +90,7 @@ type windowState struct { renderer renderer window uintptr ready, tracking, sizing, sizingMove bool + timerPeriodSet bool redrawRequested, paintPending, resizePending bool resizeTimerInterval uintptr resizeMonitor, resizeMonitorInterval uintptr // the monitor resizeMonitorInterval was queried for @@ -805,17 +806,31 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } if state.sizingMove || state.sizing { state.resizePending = true + // Raise the timer resolution on the first sizing message of the drag, + // not when it starts: moving a window sends WM_ENTERSIZEMOVE too, and + // a move has no frames to pace. + if state.sizingMove && !state.timerPeriodSet { + timeBeginPeriod.Call(1) + state.timerPeriodSet = true + } return 0 } state.presentClientSize(int(uint16(second)), int(uint16(second>>16))) return 0 case wmEnterSizeMove: state.sizingMove = true + state.renderer.resizeHeadroom = true state.refreshResizeTimer() return 0 case wmExitSizeMove: + if state.timerPeriodSet { + timeEndPeriod.Call(1) + state.timerPeriodSet = false + } killTimer.Call(window, resizeTimerID) state.sizingMove = false + // The drag is over: the next present sizes the chain to the client exactly. + state.renderer.resizeHeadroom = false state.resizeTimerInterval = 0 state.serviceResize() return 0 @@ -1052,6 +1067,10 @@ func (state *windowState) paceResize(interval uintptr, arm func(uintptr) error) if err := state.rearmResizeTimer(interval, arm); err == nil { return } + if state.timerPeriodSet { + timeEndPeriod.Call(1) + state.timerPeriodSet = false + } killTimer.Call(state.window, resizeTimerID) state.sizingMove = false state.resizeTimerInterval = 0 @@ -1292,6 +1311,10 @@ func (state *windowState) destroyed(window uintptr) { // Native teardown can reenter the dispatcher; retire text callbacks first. state.ready = false killTimer.Call(window, resizeTimerID) + if state.timerPeriodSet { + timeEndPeriod.Call(1) + state.timerPeriodSet = false + } state.sizingMove = false state.resizeTimerInterval = 0 state.closeText() From ee29742082c20a486a02b213ff6c120487a65e05 Mon Sep 17 00:00:00 2001 From: ezreal <71426102+Ezreal-byte@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:02:24 +0800 Subject: [PATCH 10/16] feat(base): highlight search matches in shaped text --- base/frame.go | 33 ++-- base/guide_test.go | 2 +- base/paint.go | 12 +- base/text_highlight.go | 37 ++++ base/text_highlight_test.go | 169 ++++++++++++++++++ cmd/viva/initfiles/AGENTS.md.txt | 2 +- gfx/text_highlight.go | 38 ++++ gfx/text_highlight_test.go | 75 ++++++++ .../windows/text_editing_windows_test.go | 1 + 9 files changed, 351 insertions(+), 18 deletions(-) create mode 100644 base/text_highlight.go create mode 100644 base/text_highlight_test.go create mode 100644 gfx/text_highlight.go create mode 100644 gfx/text_highlight_test.go diff --git a/base/frame.go b/base/frame.go index c8d0a5808..6682e4237 100644 --- a/base/frame.go +++ b/base/frame.go @@ -206,6 +206,7 @@ type Extra struct { tooltipSide uint8 // 1 + the TooltipSide TooltipOn opens the element's tip on; 0 is below addons int32 // 1 + the index of the field's icon and button in frame.addons, or 0 focusGroup FocusAxis // FocusGroup: the arrow keys that move the focus between the controls inside; zero is none + highlight int32 // 1 + the index of this text's query in frame.highlights; zero is none focusOrder FocusOrder // FocusOrder: how the group chooses the next member; nil is its axis layout Layout // CustomLayout: who measures and places the children swatchFlush bool // a ColorSwatch fills its border with its color @@ -274,20 +275,22 @@ type Frame struct { captionFn func(f *Frame, n *Node, control Rect) // memoFn paints, or begins (before) and ends the paint of, an element a cache // declared; it reports whether the element is painted and its paint is done. - memoFn func(f *Frame, i int32, before bool) bool - Lines []string - controls any // the layer above's control declarations: see widgetsOf - Ellipses []gfx.EllipsisCache // the cut-off ends of wrapped texts, kept between frames - Wraps []wrapCache // the full line sets of wrapped texts, kept between frames - wrapCursor int - scratch scratch // memory the layout borrows, see scratch.go - layoutCtx LayoutContext // the context a CustomLayout is handed, reused - Scrolls scrollStore // the ScrollStates of the page's ScrollAreas, by identity - Parent int32 - bounds Rect - gen uint32 // the paint this frame is declaring; a Box names it - shiftedX bool // a CustomLayout moved children after their width was solved - done bool + memoFn func(f *Frame, i int32, before bool) bool + Lines []string + highlights []textHighlight + paintHighlightFn func(*Frame, *Node, string, Rect, gfx.TextStyle, gfx.Alignment) + controls any // the layer above's control declarations: see widgetsOf + Ellipses []gfx.EllipsisCache // the cut-off ends of wrapped texts, kept between frames + Wraps []wrapCache // the full line sets of wrapped texts, kept between frames + wrapCursor int + scratch scratch // memory the layout borrows, see scratch.go + layoutCtx LayoutContext // the context a CustomLayout is handed, reused + Scrolls scrollStore // the ScrollStates of the page's ScrollAreas, by identity + Parent int32 + bounds Rect + gen uint32 // the paint this frame is declaring; a Box names it + shiftedX bool // a CustomLayout moved children after their width was solved + done bool } // view keeps the memory a page is laid out in between frames. It is the engine @@ -325,6 +328,8 @@ func (View *View) Begin(Surface *gfx.Canvas, Palette Theme, bounds Rect) *Frame f.Surface, f.Palette, f.bounds, f.done = Surface, Palette, bounds, false f.Nodes = f.Nodes[:0] f.Lines = f.Lines[:0] + clear(f.highlights) + f.highlights = f.highlights[:0] f.Exts = append(f.Exts[:0], Extra{}) f.Images = f.Images[:0] f.addons = f.addons[:0] diff --git a/base/guide_test.go b/base/guide_test.go index 35b59b9f1..0f39bb6e4 100644 --- a/base/guide_test.go +++ b/base/guide_test.go @@ -20,7 +20,7 @@ func TestTheGuideMentionsEveryMethod(t *testing.T) { } set := token.NewFileSet() var missing []string - for _, file := range []string{"frame.go", "box.go", "absolute.go", "grid.go", "popup.go", "text_wrap.go", "table.go", "tabs.go", "select.go", "dialog.go", "leaves.go", "splitter.go", "field.go", "slider.go", "scroll.go", "bases.go", "draw.go"} { + for _, file := range []string{"frame.go", "box.go", "absolute.go", "grid.go", "popup.go", "text_wrap.go", "table.go", "tabs.go", "select.go", "dialog.go", "leaves.go", "splitter.go", "field.go", "slider.go", "scroll.go", "bases.go", "draw.go", "text_highlight.go"} { parsed, err := parser.ParseFile(set, file, nil, parser.ParseComments) if err != nil { t.Fatal(err) diff --git a/base/paint.go b/base/paint.go index 793f16ca4..74c5e20f3 100644 --- a/base/paint.go +++ b/base/paint.go @@ -355,7 +355,7 @@ func (f *Frame) paintText(n *Node) { lh := n.leading() for k := int32(0); k < n.LineCount; k++ { bounds := Rect{X: r.X, Y: r.Y + float32(k)*lh, Width: r.Width, Height: lh} - f.Surface.LabelAligned(f.Lines[n.LineFirst+k], bounds, style, alignment) + f.paintLabel(n, f.Lines[n.LineFirst+k], bounds, style, alignment) } return } @@ -365,8 +365,16 @@ func (f *Frame) paintText(n *Node) { if clipped { f.Surface.Clip(r) } - f.Surface.LabelAligned(n.Text, bounds, style, alignment) + f.paintLabel(n, n.Text, bounds, style, alignment) if clipped { f.Surface.Unclip() } } + +func (f *Frame) paintLabel(n *Node, value string, bounds Rect, style gfx.TextStyle, alignment gfx.Alignment) { + if f.Exts[n.Ext].highlight != 0 && f.paintHighlightFn != nil { + f.paintHighlightFn(f, n, value, bounds, style, alignment) + return + } + f.Surface.LabelAligned(value, bounds, style, alignment) +} diff --git a/base/text_highlight.go b/base/text_highlight.go new file mode 100644 index 000000000..34bc382be --- /dev/null +++ b/base/text_highlight.go @@ -0,0 +1,37 @@ +package base + +import "github.com/vivaui/viva/gfx" + +type textHighlight struct { + query string + color Color +} + +// Highlight paints case-insensitive, non-overlapping query matches behind Text +// or Paragraph, preserving the label's shaping, wrapping and text direction. +// Matches are found within each displayed line; a query spanning a wrapped +// line break is not highlighted. Calling it again replaces the earlier query; +// an empty query or transparent color removes the highlight. +func (b Box) Highlight(query string, color Color) Box { + n := b.N() + if query == "" || color.Alpha <= 0 { + if n.Ext != 0 { + b.f.Exts[n.Ext].highlight = 0 + } + return b + } + extra := b.f.Extra(b.i) + if extra.highlight == 0 { + b.f.highlights = append(b.f.highlights, textHighlight{}) + extra.highlight = int32(len(b.f.highlights)) + } + b.f.highlights[extra.highlight-1] = textHighlight{query: query, color: color} + // Keep matching and selection geometry out of applications that never opt in. + b.f.paintHighlightFn = paintHighlightedLabel + return b +} + +func paintHighlightedLabel(f *Frame, n *Node, value string, bounds Rect, style gfx.TextStyle, alignment gfx.Alignment) { + highlight := f.highlights[f.Exts[n.Ext].highlight-1] + f.Surface.LabelHighlighted(value, bounds, style, alignment, highlight.query, fade(highlight.color, f.Opacity)) +} diff --git a/base/text_highlight_test.go b/base/text_highlight_test.go new file mode 100644 index 000000000..e2a0b88bf --- /dev/null +++ b/base/text_highlight_test.go @@ -0,0 +1,169 @@ +package base + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" +) + +func TestHighlightUsesUTF8ByteOffsetsAndPreservesClip(t *testing.T) { + var view View + canvas := testCanvas() + tint := gfx.RGB(220, 190, 80) + value := "上个月的设计资料 DESIGN" + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 80}, func(f *Frame) { + f.Column().Clip().Width(350).Children(func() { + f.Text(value).FontSize(14).Highlight("设计", tint) + f.Text("following label").FontSize(14) + }) + }) + var label gfx.Text + for _, text := range canvas.Texts() { + if text.Value == value { + label = text + break + } + } + spans := canvas.TextSelectionStyle(nil, value, label.Style, len("上个月的"), len("上个月的设计")) + found := false + for _, rect := range canvas.Rectangles() { + if rect.Color == tint { + found = true + if math.Abs(float64(rect.Bounds.X-label.Bounds.X-spans[0].X)) > .01 || math.Abs(float64(rect.Bounds.Width-spans[0].Width)) > .01 { + t.Fatalf("highlight is not on the matching Chinese text: %+v", rect.Bounds) + } + } + } + if !found { + t.Fatal("missing highlight") + } + for _, text := range canvas.Texts() { + if text.Value == "following label" && text.HasClip && text.ClipOf.Width < 300 { + t.Fatal("highlight leaked a clip into the next label") + } + } +} + +func TestHighlightCanBeReplacedRemovedAndDoesNotSurviveTheNextFrame(t *testing.T) { + var view View + canvas := testCanvas() + tint := gfx.RGB(220, 190, 80) + var box Box + draw := func(enabled bool) { + canvas.Reset() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 80}, func(f *Frame) { + box = f.Text("Design DESIGN") + if enabled { + box.Highlight("absent", tint).Highlight("design", tint) + } + }) + } + draw(true) + if len(canvas.Rectangles()) != 2 { + t.Fatal("replacement query did not highlight both matches") + } + draw(false) + if len(canvas.Rectangles()) != 0 { + t.Fatal("query leaked into the next frame") + } + canvas.Reset() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 80}, func(f *Frame) { + f.Text("design").Highlight("design", tint).Highlight("", tint) + f.Text("design").Highlight("design", tint).Highlight("design", Color{}) + }) + if len(canvas.Rectangles()) != 0 { + t.Fatal("empty query or transparent color did not remove highlighting") + } + defer func() { + if recover() == nil { + t.Fatal("Highlight accepted a stale Box") + } + }() + box.Highlight("design", tint) +} + +func TestHighlightParagraphKeepsWrappingAndInheritedOpacity(t *testing.T) { + var highlighted, plain View + canvas, reference := runeCanvas(), runeCanvas() + tint := gfx.RGB(220, 190, 80) + draw := func(view *View, surface *gfx.Canvas, enabled bool) { + view.Draw(surface, gfx.LightTheme(), gfx.Rect{Width: 100, Height: 200}, func(f *Frame) { + f.Column().Opacity(.5).Children(func() { + box := f.Wrap("design one design two").FontSize(10) + if enabled { + box.Highlight("design", tint) + } + }) + }) + } + draw(&highlighted, canvas, true) + draw(&plain, reference, false) + if len(canvas.Texts()) != len(reference.Texts()) { + t.Fatal("highlight changed wrapping") + } + for i, text := range canvas.Texts() { + want := reference.Texts()[i] + if text.Value != want.Value || text.Bounds != want.Bounds || text.Style != want.Style { + t.Fatal("highlight changed paragraph layout or text opacity") + } + } + matches := 0 + for _, rect := range canvas.Rectangles() { + if rect.Color == fade(tint, .5) { + matches++ + } + } + if matches != 2 { + t.Fatalf("faded highlights = %d, want 2", matches) + } +} + +func BenchmarkTextHighlights(b *testing.B) { + for _, query := range []string{"", "设计", "design", "missing"} { + name := query + if name == "" { + name = "disabled" + } + b.Run(name, func(b *testing.B) { + var view View + canvas := runeCanvas() + theme := gfx.LightTheme() + tint := gfx.RGB(220, 190, 80) + draw := func() { + canvas.Reset() + view.Draw(canvas, theme, gfx.Rect{Width: 800, Height: 800}, func(f *Frame) { + f.Column().Children(func() { + for range 20 { + f.Text("项目设计资料 Design DESIGN").Highlight(query, tint) + } + }) + }) + } + draw() + b.ReportAllocs() + for b.Loop() { + draw() + } + }) + } +} + +func TestHighlightCaseFoldPreservesTheOriginalText(t *testing.T) { + var view View + canvas := testCanvas() + tint := gfx.RGB(220, 190, 80) + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 80}, func(f *Frame) { f.Text("Design DESIGN").Highlight("design", tint) }) + matches := 0 + for _, rect := range canvas.Rectangles() { + if rect.Color == tint { + matches++ + } + } + if matches != 2 { + t.Fatalf("case-insensitive highlights = %d, want 2", matches) + } + if canvas.Texts()[0].Value != "Design DESIGN" { + t.Fatal("highlight changed the original label") + } +} diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 6cc220dab..0ac6f5aa5 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -430,7 +430,7 @@ func (m *model) page(c ui.C) { ### Text and icons -- Text: `FontSize`, `Weight`, `Bold`, `Color`, `Muted`, `Mono`, `MonoFace`, `TextCenter`, `TextEnd`, `TextDirection`, `LineHeight`; +- Text: `FontSize`, `Weight`, `Bold`, `Color`, `Highlight`, `Muted`, `Mono`, `MonoFace`, `TextCenter`, `TextEnd`, `TextDirection`, `LineHeight`; `Ellipsis()` keeps a Text to one line and ends it with … when it does not fit; `MaxLines(n)` lets a Text break into at most n lines (the last ends with …), `ui.Wrap(c, text)` into as many as the width needs. Lines break where Unicode (UAX #14) allows: at spaces, after hyphens and slashes, between CJK characters (kinsoku diff --git a/gfx/text_highlight.go b/gfx/text_highlight.go new file mode 100644 index 000000000..72957800b --- /dev/null +++ b/gfx/text_highlight.go @@ -0,0 +1,38 @@ +package gfx + +import ( + "strings" + "unicode/utf8" +) + +// LabelHighlighted paints case-insensitive query matches behind a shaped label. +// Match offsets are UTF-8 byte boundaries, as required by the text engine; the +// original label is emitted once, preserving accessibility and native text. +func (canvas *Canvas) LabelHighlighted(value string, bounds Rect, style TextStyle, alignment Alignment, query string, color Color) { + if query == "" || color.Alpha <= 0 { + canvas.LabelAligned(value, bounds, style, alignment) + return + } + value, bounds.X = canvas.placeLabel(value, bounds, style, alignment) + count := utf8.RuneCountInString(query) + var storage [8]TextSpan + canvas.Clip(bounds) + for start := 0; start < len(value); { + end := start + for i := 0; i < count && end < len(value); i++ { + _, size := utf8.DecodeRuneInString(value[end:]) + end += size + } + if strings.EqualFold(value[start:end], query) { + for _, span := range canvas.TextSelectionStyle(storage[:0], value, style, start, end) { + canvas.Fill(Rect{X: bounds.X + span.X, Y: bounds.Y, Width: span.Width, Height: bounds.Height}, color) + } + start = end + } else { + _, size := utf8.DecodeRuneInString(value[start:]) + start += size + } + } + canvas.Unclip() + canvas.LabelAligned(value, bounds, style, AlignLeft) +} diff --git a/gfx/text_highlight_test.go b/gfx/text_highlight_test.go new file mode 100644 index 000000000..6101dd283 --- /dev/null +++ b/gfx/text_highlight_test.go @@ -0,0 +1,75 @@ +package gfx + +import ( + "math" + "reflect" + "strings" + "testing" +) + +func TestLabelHighlightKeepsRTLAlignmentAndPaintsBeforeText(t *testing.T) { + var canvas Canvas + tint := RGB(220, 190, 80) + canvas.LabelHighlighted("שלום design", Rect{Width: 350, Height: 24}, TextStyle{Size: 14}, AlignEnd, "DESIGN", tint) + label := canvas.Texts()[0] + start := strings.Index(label.Value, "design") + spans := canvas.TextSelectionStyle(nil, label.Value, label.Style, start, start+len("design")) + for _, rect := range canvas.Rectangles() { + if rect.Color == tint { + if rect.Order >= label.Order || math.Abs(float64(rect.Bounds.X-label.Bounds.X-spans[0].X)) > .01 { + t.Fatalf("highlight lost text direction or paint order: %+v / %+v", rect, label) + } + return + } + } + t.Fatal("missing RTL highlight") +} + +func TestLabelHighlightUnicodeMatchesAndPreservesTheLabel(t *testing.T) { + tint := RGB(220, 190, 80) + for _, tc := range []struct { + name, value, query string + want int + }{ + {"chinese", "项目设计与设计资料", "设计", 2}, + {"different byte lengths", "K kelvin K", "k", 3}, + {"greek fold", "Σ σ ς", "σ", 3}, + {"emoji", "a👩‍💻b👩‍💻", "👩‍💻", 2}, + {"non overlapping", "aaaaa", "aa", 2}, + {"too long", "短", "很长的查询", 0}, + {"empty", "Design", "", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + var canvas, plain Canvas + bounds := Rect{Width: 400, Height: 24} + style := TextStyle{Size: 14} + canvas.LabelHighlighted(tc.value, bounds, style, AlignCenter, tc.query, tint) + plain.LabelAligned(tc.value, bounds, style, AlignCenter) + if len(canvas.Texts()) != 1 || canvas.Texts()[0].Value != plain.Texts()[0].Value || canvas.Texts()[0].Bounds != plain.Texts()[0].Bounds { + t.Fatal("highlight changed the original label or its alignment") + } + matches := 0 + for _, rect := range canvas.Rectangles() { + if rect.Color == tint { + matches++ + } + } + if matches != tc.want { + t.Fatalf("highlights = %d, want %d", matches, tc.want) + } + }) + } +} + +func TestLabelHighlightDisabledUsesTheUnchangedLabelPath(t *testing.T) { + for _, color := range []Color{{}, {Alpha: -1}} { + var highlighted, plain Canvas + bounds := Rect{Width: 200, Height: 24} + style := TextStyle{Size: 14, Direction: DirectionRTL} + highlighted.LabelHighlighted("Design", bounds, style, AlignEnd, "design", color) + plain.LabelAligned("Design", bounds, style, AlignEnd) + if !reflect.DeepEqual(highlighted.Texts(), plain.Texts()) || len(highlighted.Rectangles()) != 0 { + t.Fatal("disabled highlight changed the canvas output") + } + } +} diff --git a/internal/platform/windows/text_editing_windows_test.go b/internal/platform/windows/text_editing_windows_test.go index 373369090..b19b43e8f 100644 --- a/internal/platform/windows/text_editing_windows_test.go +++ b/internal/platform/windows/text_editing_windows_test.go @@ -189,6 +189,7 @@ func TestNativeTextScrollClipsAndMasksSecureFields(t *testing.T) { func TestNativeTextOverlayRasterizesOnlyTheVisibleColumns(t *testing.T) { label := labelTexture{label: platform.TextLabel{ Value: "value", X: -1490, Y: 0, Width: 1700, Height: 24, FontSize: 16, + Color: platform.Color{Alpha: 1}, Clipped: true, Clip: gfx.Rect{X: 10, Y: 0, Width: 200, Height: 24}, }} if skip, width, ok := label.window(2, 0); !ok || skip != 3000 || width != 400 { From 4a13331bdbda32eb78ca0876e6c4b42f462e6ed3 Mon Sep 17 00:00:00 2001 From: ezreal <71426102+Ezreal-byte@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:02:37 +0800 Subject: [PATCH 11/16] feat(linux): preview X11 drags in a transparent window --- .github/workflows/ci.yml | 9 +- internal/platform/linux/cpu_window_linux.go | 4 +- internal/platform/linux/status_item_linux.go | 4 + internal/platform/linux/window_linux.go | 44 +++++- .../platform/linux/window_margin_linux.go | 5 + .../platform/linux/window_preview_linux.go | 87 +++++++++++ .../linux/window_preview_linux_test.go | 145 ++++++++++++++++++ .../platform/linux/window_renderer_linux.go | 4 +- 8 files changed, 292 insertions(+), 10 deletions(-) create mode 100644 internal/platform/linux/window_preview_linux.go create mode 100644 internal/platform/linux/window_preview_linux_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index def71def6..8def9d5b5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -161,7 +161,14 @@ jobs: # The Linux package is not part of the sharded run (it drives X11), so the # titlebar contracts that do not need a server name their tests here. - name: Titlebar and window contracts - run: go test ./internal/platform/linux -run '^TestMaximizeButtonSetsBothDirections$' -count=1 -v + run: go test ./internal/platform/linux -run '^Test(MaximizeButtonSetsBothDirections|PreviewMovePreservesSizeAndFocus)$' -count=1 -v + - name: Native X11 drag preview + env: + VIVA_TEST_PREVIEW_XVFB: '1' + run: | + sudo apt-get install -y xvfb libxcb-shape0 || + { sudo apt-get update && sudo apt-get install -y xvfb libxcb-shape0; } + xvfb-run -a go test ./internal/platform/linux -run '^TestPreviewNativeX11Contract$' -count=1 -v - name: Native X11 global shortcut env: VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1' diff --git a/internal/platform/linux/cpu_window_linux.go b/internal/platform/linux/cpu_window_linux.go index 24ed33a70..69f30745f 100644 --- a/internal/platform/linux/cpu_window_linux.go +++ b/internal/platform/linux/cpu_window_linux.go @@ -368,7 +368,9 @@ func (renderer *cpuWindowRenderer) refreshText() error { return renderer.scene.r func (renderer *cpuWindowRenderer) forgetSurfaceCapabilities() {} -func (renderer *cpuWindowRenderer) alpha() bool { return renderer.margin > 0 } +func (renderer *cpuWindowRenderer) alpha() bool { + return renderer.margin > 0 || renderer.win != nil && renderer.win.preview +} func (renderer *cpuWindowRenderer) frameMargin() uint32 { return renderer.margin } diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 076c2a573..cc920eae7 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -59,6 +59,10 @@ const panelDismissWindow = 350 * time.Millisecond // panelOrigin is where a panel's window is created: beside its anchor, or in the // middle of the screen without one. func (win *window) panelOrigin(config platform.Config) (x, y int16) { + if config.WindowMode == platform.WindowPreview { + scale := win.displayScale() + return clampInt16(int(config.Origin.X * scale)), clampInt16(int(config.Origin.Y * scale)) + } monitors := win.placementMonitors() if config.WindowMode != platform.WindowPanel { if config.HasOrigin { diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index c95c6e2ce..6db989b6f 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -19,6 +19,7 @@ import ( ) type window struct { + preview bool fullscreen atomic.Bool topmost atomic.Bool topmostConfigured atomic.Bool @@ -418,7 +419,9 @@ func (application *linuxApplication) OpenWindow(config platform.Config) (platfor application.wakePosts() application.atspiOpened(state) application.retryDesktopWatch() - activeWindow.Store(win) + if !win.preview { + activeWindow.Store(win) + } if state.profile { elapsed := float64(time.Since(state.started).Microseconds()) / 1000 fmt.Fprintf(os.Stderr, "viva_first_frame_ms=%.3f\n", elapsed) @@ -794,7 +797,13 @@ func (application *linuxApplication) closeWindow(target *linuxWindowState) { if len(application.windows) == 0 { activeWindow.CompareAndSwap(target.win, nil) } else if activeWindow.Load() == target.win { - activeWindow.Store(application.windows[len(application.windows)-1].win) + activeWindow.Store(nil) + for i := len(application.windows) - 1; i >= 0; i-- { + if win := application.windows[i].win; !win.preview { + activeWindow.Store(win) + break + } + } } if target.config.OnClosed != nil { target.config.OnClosed() @@ -861,7 +870,9 @@ func (state *linuxWindowState) refreshReadOnlyTextInput() error { func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { win, config, textInput, renderer, router := state.win, state.config, state.text, state.renderer, state.router - activeWindow.Store(win) + if !win.preview { + activeWindow.Store(win) + } kind := (*xcbGenericEvent)(event).ResponseType & 0x7f if kind == xcbButtonPress || kind == xcbKeyPress { if timestamp := (*xcbInputEvent)(event).Time; timestamp != 0 { @@ -1297,7 +1308,7 @@ func validateConfig(config platform.Config) error { if config.Width < 1 || config.Height < 1 || config.Width > math.MaxUint16 || config.Height > math.MaxUint16 { return fmt.Errorf("linux: X11 window dimensions must be between 1 and %d, got %dx%d", uint32(math.MaxUint16), config.Width, config.Height) } - if config.WindowMode > platform.WindowPanel { + if config.WindowMode > platform.WindowPreview { return fmt.Errorf("linux: invalid window mode %d", config.WindowMode) } if err := validateRectangles(config.Rectangles); err != nil { @@ -1346,6 +1357,17 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window win.storeScale(scale) win.width, win.height = deviceLength(config.Width, scale), deviceLength(config.Height, scale) frameVisual := uint32(0) + if config.WindowMode == platform.WindowPreview { + win.preview = true + var ok bool + if win.compositing(screenIndex) { + frameVisual, ok = win.argbVisual() + } + if !ok { + win.close() + return nil, platform.ErrDragPreviewUnsupported + } + } if config.WindowMode == platform.WindowCustomTitlebar { // The application draws the frame of this window, and on a desktop that // composites it draws the shadow and the round corners too, in a margin. @@ -1385,11 +1407,13 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window win.backPixel = clearPixel(config.ClearColor) values := [3]uint32{win.backPixel, xcbGravityNorthWest, eventMask} x, y := win.panelOrigin(config) - if win.frameWanted { + if win.frameWanted || win.preview { win.createFrameWindow(frameVisual, eventMask, x, y) win.depth = 32 - win.setFrameExtents(win.margin) - win.updateInputRegion() + if !win.preview { + win.setFrameExtents(win.margin) + win.updateInputRegion() + } } else { api.createWindow(connection, xcbCopyFromParent, win.id, win.screen.Root, x, y, uint16(win.width), uint16(win.height), 0, xcbWindowClassInput, win.screen.RootVisual, xcbCWBackPixel|xcbCWBitGravity|xcbCWEventMask, &values[0]) win.depth = win.screen.RootDepth @@ -1504,6 +1528,12 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window return nil, err } } + if win.preview { + if err := win.markPreview(); err != nil { + win.close() + return nil, fmt.Errorf("%w: %v", platform.ErrDragPreviewUnsupported, err) + } + } api.mapWindow(connection, win.id) if api.flush(connection) <= 0 || api.connectionHasError(connection) != 0 { win.close() diff --git a/internal/platform/linux/window_margin_linux.go b/internal/platform/linux/window_margin_linux.go index fd9d17ed5..f50a88ba3 100644 --- a/internal/platform/linux/window_margin_linux.go +++ b/internal/platform/linux/window_margin_linux.go @@ -169,6 +169,11 @@ func (win *window) setFrameExtents(margin uint32) { // around it, so a press in the rest of the margin goes to the window behind. // The extension is optional; without it the whole window takes input. func (win *window) updateInputRegion() { + // A drag preview stays input-transparent across ConfigureNotify events. + // Restoring the regular zero-margin region would intercept its own drop. + if win.preview { + return + } if win.margin == 0 { if win.shapeRectangles != nil { rectangle := [4]uint16{0, 0, uint16(win.width), uint16(win.height)} diff --git a/internal/platform/linux/window_preview_linux.go b/internal/platform/linux/window_preview_linux.go new file mode 100644 index 000000000..b8f5dee42 --- /dev/null +++ b/internal/platform/linux/window_preview_linux.go @@ -0,0 +1,87 @@ +package linux + +import ( + "unsafe" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// The X11 adapter can preview where an ARGB visual, compositor and input +// shaping are available. OpenWindow checks those before mapping the surface. +func (*linuxApplication) SupportsDragPreview() {} + +func (win *window) markPreview() error { + library, err := purego.Dlopen("libxcb-shape.so.0", purego.RTLD_NOW|purego.RTLD_LOCAL) + if err != nil { + return err + } + win.shapeLibrary = library + // The checked request rejects servers without the input-shape extension. + purego.RegisterLibFunc(&win.shapeRectangles, library, "xcb_shape_rectangles_checked") + if err := win.checkRequest("preview input shape", win.shapeRectangles(win.connection, shapeSet, shapeInput, 0, win.id, 0, 0, 0, nil)); err != nil { + return err + } + return win.setPreviewProperties() +} + +func (win *window) setPreviewProperties() error { + // Override-redirect keeps the window manager from decorating, activating, + // repositioning or adding a taskbar entry for this transient drag surface. + const overrideRedirect = 1 << 9 + value := uint32(1) + if err := win.checkRequest("preview override redirect", win.api.changeWindow(win.connection, win.id, overrideRedirect, &value)); err != nil { + return err + } + for _, property := range []struct { + name string + values []string + }{ + {"_NET_WM_WINDOW_TYPE", []string{"_NET_WM_WINDOW_TYPE_DND"}}, + {"_NET_WM_STATE", []string{"_NET_WM_STATE_ABOVE", "_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_STATE_SKIP_PAGER"}}, + } { + atom, err := win.api.atom(win.connection, property.name) + if err != nil { + return err + } + values := make([]uint32, len(property.values)) + for i, name := range property.values { + values[i], err = win.api.atom(win.connection, name) + if err != nil { + return err + } + } + win.api.changeProperty(win.connection, xcbPropertyReplace, win.id, atom, xcbAtomAtom, 32, uint32(len(values)), unsafe.Pointer(&values[0])) + } + atom, err := win.api.atom(win.connection, "WM_HINTS") + if err != nil { + return err + } + hints := [9]uint32{1, 0} // InputHint, input=false + win.api.changeProperty(win.connection, xcbPropertyReplace, win.id, atom, atom, 32, uint32(len(hints)), unsafe.Pointer(&hints[0])) + return nil +} + +// MoveTo runs on the application thread, like OpenDragPreview. Only position +// changes: no resize, focus request or redraw is needed to move a retained image. +func (window *nativeWindow) MoveTo(origin gfx.Point) { + if window == nil || window.closed.Load() || window.state == nil { + return + } + win := window.state.win + win.mu.Lock() + defer win.mu.Unlock() + if win.connection == 0 { + return + } + scale := win.displayScale() + position := [2]uint32{ + uint32(int32(clampInt16(int(origin.X*scale) - int(win.margin)))), + uint32(int32(clampInt16(int(origin.Y*scale) - int(win.margin)))), + } + win.api.configureWindow(win.connection, win.id, 1|2, &position[0]) + win.api.flush(win.connection) +} + +var _ platform.WindowMover = (*nativeWindow)(nil) diff --git a/internal/platform/linux/window_preview_linux_test.go b/internal/platform/linux/window_preview_linux_test.go new file mode 100644 index 000000000..4cd7e8dc8 --- /dev/null +++ b/internal/platform/linux/window_preview_linux_test.go @@ -0,0 +1,145 @@ +package linux + +import ( + "errors" + "os" + "testing" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +func TestPreviewMovePreservesSizeAndFocus(t *testing.T) { + var mask uint16 + var values [2]uint32 + win := &window{connection: 1, id: 2, preview: true, width: 180, height: 90} + win.storeScale(1.5) + win.api = &xcbAPI{ + configureWindow: func(_ uintptr, _ uint32, m uint16, p *uint32) xcbVoidCookie { + mask = m + copy(values[:], unsafe.Slice(p, 2)) + return xcbVoidCookie{} + }, + flush: func(uintptr) int32 { return 1 }, + } + native := &nativeWindow{state: &linuxWindowState{win: win}} + native.MoveTo(gfx.Point{X: -20, Y: 30}) + if mask != 3 || int32(values[0]) != -30 || values[1] != 45 || win.width != 180 || win.height != 90 { + t.Fatalf("move mask=%d position=%v size=%dx%d", mask, values, win.width, win.height) + } + native.closed.Store(true) + mask = 0 + native.MoveTo(gfx.Point{}) + if mask != 0 { + t.Fatal("closed preview was moved") + } +} + +// Run only on a private Xvfb server. Claiming the compositor selection exercises +// the X11 protocol without taking over a real desktop's compositor ownership. +func TestPreviewNativeX11Contract(t *testing.T) { + if os.Getenv("VIVA_TEST_PREVIEW_XVFB") != "1" { + t.Skip("requires a private Xvfb server") + } + owner, err := openWindow(platform.Config{Width: 100, Height: 100}) + if err != nil { + t.Fatal(err) + } + defer owner.close() + var setFocus func(uintptr, uint8, uint32, uint32) xcbVoidCookie + var getFocus func(uintptr) xcbVoidCookie + var focusReply func(uintptr, xcbVoidCookie, *unsafe.Pointer) unsafe.Pointer + purego.RegisterLibFunc(&setFocus, owner.api.library, "xcb_set_input_focus") + purego.RegisterLibFunc(&getFocus, owner.api.library, "xcb_get_input_focus") + purego.RegisterLibFunc(&focusReply, owner.api.library, "xcb_get_input_focus_reply") + setFocus(owner.connection, 0, owner.id, 0) + checkFocus := func() { + t.Helper() + result := focusReply(owner.connection, getFocus(owner.connection), nil) + if result == nil { + t.Fatal("missing keyboard focus reply") + } + focus := *(*uint32)(unsafe.Add(result, 8)) + owner.api.free(result) + if focus != owner.id { + t.Fatalf("keyboard focus=%d, want owner %d", focus, owner.id) + } + } + checkFocus() + config := platform.Config{Width: 80, Height: 40, WindowMode: platform.WindowPreview, HasOrigin: true, Origin: gfx.Point{X: 20, Y: 30}} + if unavailable, err := openWindow(config); !errors.Is(err, platform.ErrDragPreviewUnsupported) { + if unavailable != nil { + unavailable.close() + } + t.Fatalf("no compositor: %v", err) + } + atom, err := owner.api.atom(owner.connection, "_NET_WM_CM_S0") + if err != nil { + t.Fatal(err) + } + owner.api.setSelectionOwner(owner.connection, owner.id, atom, 0) + owner.api.flush(owner.connection) + if !owner.compositing(0) { + t.Fatal("compositor selection was not claimed") + } + win, err := openWindow(config) + if err != nil { + t.Fatal(err) + } + defer win.close() + if win.depth != 32 || win.margin != 0 { + t.Fatalf("preview depth=%d margin=%d", win.depth, win.margin) + } + var attributes func(uintptr, uint32) xcbVoidCookie + var reply func(uintptr, xcbVoidCookie, *unsafe.Pointer) unsafe.Pointer + purego.RegisterLibFunc(&attributes, win.api.library, "xcb_get_window_attributes") + purego.RegisterLibFunc(&reply, win.api.library, "xcb_get_window_attributes_reply") + result := reply(win.connection, attributes(win.connection, win.id), nil) + if result == nil { + t.Fatal("missing window attributes") + } + data := unsafe.Slice((*byte)(result), 44) + override := data[27] + win.api.free(result) + if override != 1 { + t.Fatalf("preview override_redirect=%d", override) + } + // A resize/configure notification must not restore a normal input region. + win.updateInputRegion() + var rectangles func(uintptr, uint32, uint8) xcbVoidCookie + purego.RegisterLibFunc(&rectangles, win.shapeLibrary, "xcb_shape_get_rectangles") + purego.RegisterLibFunc(&reply, win.shapeLibrary, "xcb_shape_get_rectangles_reply") + result = reply(win.connection, rectangles(win.connection, win.id, shapeInput), nil) + if result == nil { + t.Fatal("missing input shape") + } + count := *(*uint32)(unsafe.Add(result, 8)) + win.api.free(result) + if count != 0 { + t.Fatalf("preview intercepts input: %d rectangles", count) + } + renderer, err := newWindowPainter(win, win.displayScale(), platform.Color{}, nil, nil) + if err != nil { + t.Fatal(err) + } + defer renderer.close() + if !renderer.alpha() { + t.Fatal("preview cannot present alpha") + } + if err := renderer.present(); err != nil { + t.Fatal(err) + } + cpu := renderer.(*cpuWindowRenderer) + if cpu.scene.canvas.Pix[3] != 0 { + t.Fatal("transparent preview corner is opaque") + } + control := &nativeWindow{state: &linuxWindowState{win: win}} + control.MoveTo(gfx.Point{X: 40, Y: 50}) + x, y := win.rootOrigin() + if x != 40 || y != 50 { + t.Fatalf("origin=%d,%d", x, y) + } + checkFocus() +} diff --git a/internal/platform/linux/window_renderer_linux.go b/internal/platform/linux/window_renderer_linux.go index d1b33fb3b..83621c76b 100644 --- a/internal/platform/linux/window_renderer_linux.go +++ b/internal/platform/linux/window_renderer_linux.go @@ -69,7 +69,9 @@ func newWindowPainter(win *window, scale float32, clear platform.Color, rectangl cpu := func() (windowRenderer, error) { return newCPUWindowRenderer(win, scale, clear, rectangles, labels) } - if softwareRenderingRequested() { + // The small drag surface needs reliable per-pixel alpha even on older + // Mesa drivers. It is painted once; moving it does not repaint its pixels. + if win.preview || softwareRenderingRequested() { return cpu() } if cpuRendererPreferred.Load() && !vulkanRenderingRequested() { From 1fd4b51b037caf0f3d991fdd708fb0655b68dd71 Mon Sep 17 00:00:00 2001 From: t8y2 Date: Sat, 21 Nov 2026 12:57:02 +0800 Subject: [PATCH 12/16] test(linux): allow linear sampling in the Vulkan wide-label test --- .../platform/linux/wide_label_linux_test.go | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/internal/platform/linux/wide_label_linux_test.go b/internal/platform/linux/wide_label_linux_test.go index 42307d456..e320d7d4f 100644 --- a/internal/platform/linux/wide_label_linux_test.go +++ b/internal/platform/linux/wide_label_linux_test.go @@ -4,6 +4,7 @@ import ( "bytes" "errors" "image" + "image/color" "strings" "testing" @@ -32,6 +33,10 @@ func wholeRun(value string) []gfx.TextRun { var wideBackends = []struct { name string open func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA + // same reports whether two composited pixels match. The Vulkan text sampler + // filters linearly, so a window starting off a texel centre can mix 1/256 of + // its neighbour; the CPU renderer samples the glyph bitmap directly. + same func(a, b color.RGBA) bool }{ {"Vulkan", func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA { t.Helper() @@ -44,7 +49,7 @@ var wideBackends = []struct { } t.Cleanup(offscreen.Close) return func(labels ...platform.TextLabel) *image.RGBA { return renderScene(t, offscreen, nil, labels) } - }}, + }, withinALevel}, {"CPU", func(t *testing.T, clear platform.Color) func(labels ...platform.TextLabel) *image.RGBA { t.Helper() offscreen, err := NewCPUOffscreen(400, 40, 1.5, clear) @@ -63,7 +68,7 @@ var wideBackends = []struct { } return pixels } - }}, + }, func(a, b color.RGBA) bool { return a == b }}, } // A line wider than a texture holds gets a texture of the window of it that the viewport and @@ -153,7 +158,7 @@ func TestWideMonoLineIsDrawnFromAWindowOfIt(t *testing.T) { got, painted := wide[index], 0 for y := 0; y < 60; y++ { for x := 0; x < 600; x++ { - if got.RGBAAt(x, y) != want.RGBAAt(x, y) { + if !backend.same(got.RGBAAt(x, y), want.RGBAAt(x, y)) { t.Fatalf("%s, %d characters scrolled: pixel %d,%d is %v, the start of the line's is %v", name, scrolled, x, y, got.RGBAAt(x, y), want.RGBAAt(x, y)) } @@ -172,6 +177,12 @@ func TestWideMonoLineIsDrawnFromAWindowOfIt(t *testing.T) { } } +// withinALevel reports whether no channel of a and b differs by more than one level. +func withinALevel(a, b color.RGBA) bool { + near := func(p, q uint8) bool { return int(p)-int(q) <= 1 && int(q)-int(p) <= 1 } + return near(a.R, b.R) && near(a.G, b.G) && near(a.B, b.B) && near(a.A, b.A) +} + // The CPU window's scene draws a line wider than a texture holds from the window of it the // canvas shows. A scroll inside that window keeps its picture, one past it draws a new window, // and a line scrolled off the canvas has no picture until it is scrolled back; after each the From 59a696ec91c129f103c7dd1749d76e9434addabb Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 21 Nov 2026 13:46:05 +0800 Subject: [PATCH 13/16] feat(platform): round and fade images and expose progress bars An Image's Radius now cuts its picture's corners and its Opacity fades it, in every renderer: the CPU rasterizer, Metal, Vulkan, WebGL, the Web Canvas2D fallback and D3D11. Radius and Fade are draw-time values on the image primitive, so an animated opacity does not rebuild a texture; a zero value takes the old square, opaque path byte for byte. The shaders reuse the rounded-box distance field the rectangle shaders already use. On the Web Canvas2D fallback the picture is clipped to a rounded path and drawn with a scaled globalAlpha. A Progress given a Label is a progress bar to assistive technology: a read-only range from 0 to 100 at the fraction (no number while indeterminate), never a keyboard stop or a press target. Frame.Progress takes the bar's identity and the page's ui.Progress names it automatically. The role and its read-only range pattern are mapped on Darwin, Windows, AT-SPI and ARIA. A bar with no Label declares no node, so it cannot take the pointer from the row holding it. The dev attribute rules let these through: Image Radius and Opacity, Progress Label, and the attributes the previous batch made real. Verified: the full affected suite and the dev build on Linux and macOS; the Vulkan and D3D11 paths with offscreen pixel tests on the private Linux machine and Windows VM; Darwin with Metal offscreen tests; the Web package under Node. Size: hello darwin 4,209,874 (+176), linux 5,484,773 (+16,384), windows 5,125,632 (+12,288), from the new shader bytecode. --- app/accessnodes.go | 2 + app/driver.go | 7 +- app/painter.go | 2 + base/attrcheck_dev.go | 9 +- base/attrcheck_dev_test.go | 11 +-- base/elements.go | 10 +- base/image_test.go | 24 +++++ base/leaves.go | 16 +++- base/leaves_test.go | 14 +-- base/page.go | 1 + base/paint.go | 3 +- gfx/canvas.go | 21 ++++- gfx/presence.go | 4 + gfx/replay.go | 2 +- gfx/role_test.go | 2 +- headless/convert.go | 1 + internal/framebuild/framebuild.go | 3 +- internal/framebuild/framebuild_test.go | 5 +- internal/platform/accessibility.go | 7 ++ internal/platform/accessibility_test.go | 4 +- internal/platform/contract.go | 4 + internal/platform/darwin/composite_test.go | 8 +- .../platform/darwin/image_shading_test.go | 54 +++++++++++ internal/platform/darwin/native.h | 4 + internal/platform/darwin/native.m | 36 +++++++- internal/platform/darwin/platform.go | 2 + internal/platform/darwin/shaders/scene.metal | 33 ++++++- .../platform/darwin/shaders/scene.metallib | Bin 21766 -> 23190 bytes internal/platform/linux/atspi_bridge.go | 2 +- internal/platform/linux/atspi_bridge_test.go | 6 ++ internal/platform/linux/atspi_model.go | 5 + .../platform/linux/cpu_offscreen_linux.go | 1 + .../linux/image_shading_linux_test.go | 44 +++++++++ internal/platform/linux/shaders/text.frag | 22 ++++- internal/platform/linux/shaders/text.frag.spv | Bin 476 -> 1812 bytes internal/platform/linux/shaders/text.vert | 4 + internal/platform/linux/shaders/text.vert.spv | Bin 1360 -> 1408 bytes internal/platform/linux/shaders/text_lcd.frag | 21 ++++- .../platform/linux/shaders/text_lcd.frag.spv | Bin 1140 -> 2344 bytes internal/platform/linux/vulkan_linux.go | 13 ++- internal/platform/linux/vulkan_text_linux.go | 7 +- internal/platform/web/accessibility.go | 2 + internal/platform/web/render.go | 40 +++++++- internal/platform/web/render_gl_js.go | 13 +++ internal/platform/web/shaders/text.frag.glsl | 18 +++- internal/platform/web/shaders/text.vert.glsl | 12 +++ .../windows/accessibility_pattern_windows.go | 13 ++- .../platform/windows/accessibility_windows.go | 41 +++++---- .../windows/accessibility_windows_test.go | 6 ++ .../windows/image_shading_windows_test.go | 42 +++++++++ internal/platform/windows/renderer_windows.go | 9 ++ .../platform/windows/shaders/manifest.json | 18 ++-- .../windows/shaders/rectangleFragment.dxbc | Bin 9612 -> 9660 bytes .../windows/shaders/rectangleVertex.dxbc | Bin 6564 -> 6612 bytes internal/platform/windows/shaders/scene.hlsl | 27 ++++-- .../windows/shaders/textFragment.dxbc | Bin 1820 -> 2576 bytes .../platform/windows/shaders/textVertex.dxbc | Bin 2052 -> 2152 bytes internal/raster/image_mask_test.go | 55 +++++++++++ internal/raster/raster.go | 51 ++++++++-- internal/reloadwire/codec.go | 5 +- internal/semantic/tree.go | 1 + ui/leaves_paint.go | 20 ++++ ui/progress_page_test.go | 87 ++++++++++++++++++ 63 files changed, 773 insertions(+), 101 deletions(-) create mode 100644 internal/platform/darwin/image_shading_test.go create mode 100644 internal/platform/linux/image_shading_linux_test.go create mode 100644 internal/platform/windows/image_shading_windows_test.go create mode 100644 internal/raster/image_mask_test.go create mode 100644 ui/progress_page_test.go diff --git a/app/accessnodes.go b/app/accessnodes.go index 00d8f37fc..eb77c3e37 100644 --- a/app/accessnodes.go +++ b/app/accessnodes.go @@ -133,6 +133,8 @@ func accessRole(role semantic.Role) gfx.Role { return gfx.RoleStatus case semantic.RoleSeparator: return gfx.RoleSeparator + case semantic.RoleProgress: + return gfx.RoleProgressBar } return 0 } diff --git a/app/driver.go b/app/driver.go index c25819600..0f5ab35bc 100644 --- a/app/driver.go +++ b/app/driver.go @@ -1075,7 +1075,11 @@ type Label struct { BitmapStride int BitmapID uint64 BitmapVersion uint32 - BitmapUpload bool + // ImageRadius and ImageFade are platform.TextLabel's: the corners of an + // image and how much of it is transparent. + ImageRadius float32 + ImageFade float32 + BitmapUpload bool // Quad, while HasQuad, is where the label's picture lands: four corners in // logical pixels with the colour multiplied into each, as gfx.Canvas.LabelQuad // draws it. Bounds stays the box the picture was rasterised in. @@ -1237,6 +1241,7 @@ func (driver *Driver) Snapshot() Snapshot { Clip: label.Clip, Clipped: label.Clipped, BitmapWidth: label.BitmapWidth, BitmapHeight: label.BitmapHeight, BitmapStride: label.BitmapStride, BitmapID: label.BitmapID, BitmapVersion: label.BitmapVersion, + ImageRadius: label.ImageRadius, ImageFade: label.ImageFade, BitmapUpload: label.BitmapUpload, Quad: label.Quad, HasQuad: label.HasQuad, } diff --git a/app/painter.go b/app/painter.go index 17ba1399a..3f3b8b1af 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1876,6 +1876,8 @@ func semanticRole(role gfx.Role) semantic.Role { return semantic.RoleStatus case gfx.RoleSeparator: return semantic.RoleSeparator + case gfx.RoleProgressBar: + return semantic.RoleProgress default: return semantic.RoleButton } diff --git a/base/attrcheck_dev.go b/base/attrcheck_dev.go index a4f5b6d79..78942cfc9 100644 --- a/base/attrcheck_dev.go +++ b/base/attrcheck_dev.go @@ -119,12 +119,6 @@ func (f *Frame) checkAttributesOf(n *Node) { } switch n.Kind { case kindImage: - if n.Flags&flagHasRadius != 0 { - f.badAttribute(n, name, "Radius", "an Image paints its bitmap over the whole rectangle; Radius does not clip it") - } - if n.Ext != 0 && f.Exts[n.Ext].fade != 0 { - f.badAttribute(n, name, "Opacity", "an Image paints its bitmap at full opacity; the element's Opacity does not fade it") - } if n.Flags&flagHasColor != 0 { f.badAttribute(n, name, "Color", "an Image paints its own colors") } @@ -442,7 +436,8 @@ func (f *Frame) checkWidgetAttributes(n *Node, name string) { rejectChildren() rejectVariant() rejectSize() - rejectLabel() + // Label names the progress bar's accessible node; it declares no hit of + // its own to name otherwise. rejectDisabled() case kindSpinner: rejectPad() diff --git a/base/attrcheck_dev_test.go b/base/attrcheck_dev_test.go index 03a4e7dc3..7ea6fc08b 100644 --- a/base/attrcheck_dev_test.go +++ b/base/attrcheck_dev_test.go @@ -63,6 +63,8 @@ func TestBareConstructorsDoNotTripTheAttributeRules(t *testing.T) { f.Input(InputSnapshot{ID: gfx.Item(4), Label: "Name", Value: "x"}) f.Textarea(TextareaSnapshot{ID: gfx.Item(5), Label: "Notes", Value: "x"}) f.Checkbox(gfx.Item(6), true).Caption("Sync") + f.Progress(gfx.ID{}, 0.5).Label("Loading") + f.Image(gfx.Bitmap{}).Radius(4).Opacity(0.5) f.Switch(gfx.Item(7), false).Caption("Run") f.Slot() }) @@ -143,12 +145,12 @@ func TestAttributesThatDoNothingReport(t *testing.T) { {"Segmented Children", []string{"Segmented", "Children"}, func(f *Frame) { f.Segmented(nil, gfx.ID{}).Children(func() { f.Text("x") }) }}, - {"Progress Pad", []string{"Progress", "Pad"}, func(f *Frame) { f.Progress(0.5).Pad(4) }}, - {"Progress FontSize", []string{"Progress", "FontSize"}, func(f *Frame) { f.Progress(0.5).FontSize(18) }}, + {"Progress Pad", []string{"Progress", "Pad"}, func(f *Frame) { f.Progress(gfx.ID{}, 0.5).Pad(4) }}, + {"Progress FontSize", []string{"Progress", "FontSize"}, func(f *Frame) { f.Progress(gfx.ID{}, 0.5).FontSize(18) }}, {"Pagination Color", []string{"Pagination", "Color"}, func(f *Frame) { f.Pagination(nil).Color(gfx.Color{Red: 1, Alpha: 1}) }}, - {"Progress Disabled", []string{"Progress", "Disabled"}, func(f *Frame) { f.Progress(0.5).Disabled(true) }}, + {"Progress Disabled", []string{"Progress", "Disabled"}, func(f *Frame) { f.Progress(gfx.ID{}, 0.5).Disabled(true) }}, {"Spinner Disabled", []string{"Spinner", "Disabled"}, func(f *Frame) { f.Spinner().Disabled(true) }}, {"Pagination Disabled", []string{"Pagination", "Disabled"}, func(f *Frame) { f.Pagination(nil).Disabled(true) @@ -181,9 +183,6 @@ func TestAttributesThatDoNothingReport(t *testing.T) { f.Checkbox(gfx.Item(1), true).Color(gfx.Color{Red: 1, Alpha: 1}) }}, {"Badge size method", []string{"Badge", "Size"}, func(f *Frame) { f.Badge("New").Small() }}, - {"Image Radius", []string{"Image", "Radius"}, func(f *Frame) { - f.Image(gfx.Bitmap{}).Radius(4) - }}, {"Checkbox type without caption", []string{"Checkbox", "FontSize/Weight/Color"}, func(f *Frame) { f.Checkbox(gfx.Item(1), true).FontSize(18) }}, diff --git a/base/elements.go b/base/elements.go index 518abf165..7bba3d6b0 100644 --- a/base/elements.go +++ b/base/elements.go @@ -47,10 +47,12 @@ func Text(c C, Value string) Box { return c.f.Text(Value) } func Textf(c C, format string, args ...any) Box { return c.f.Text(fmt.Sprintf(format, args...)) } func Spacer(c C) Box { return c.f.Spacer() } func Divider(c C) Box { return c.f.Divider() } -func Progress(c C, fraction float32) Box { return c.f.Progress(fraction) } -func Spinner(c C) Box { return c.f.Spinner() } -func Icon(c C, icon gfx.Icon) Box { return c.f.Icon(icon) } -func Image(c C, bitmap gfx.Bitmap) Box { return c.f.Image(bitmap) } +func Progress(c C, fraction float32) Box { + return c.f.Progress(c.page.ControlID(pkProgress), fraction) +} +func Spinner(c C) Box { return c.f.Spinner() } +func Icon(c C, icon gfx.Icon) Box { return c.f.Icon(icon) } +func Image(c C, bitmap gfx.Bitmap) Box { return c.f.Image(bitmap) } // Paragraph is text that wraps to the width it gets, at most maxLines lines: // zero or less takes as many lines as the width needs, as Box.MaxLines. diff --git a/base/image_test.go b/base/image_test.go index 9d861c28d..aa9c8aa00 100644 --- a/base/image_test.go +++ b/base/image_test.go @@ -84,3 +84,27 @@ func BenchmarkPageOfImages(b *testing.B) { }) } } + +// Radius rounds an Image's own pixels and Opacity fades them: both are draw-time +// values on the image, not the element's box. +func TestImageRoundsAndFadesItsPixels(t *testing.T) { + var view View + canvas := testCanvas() + var image Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 100, Height: 60}, func(f *Frame) { + image = f.Image(imageBitmap(11)).Size(40, 40).Radius(6).Opacity(0.5) + }) + images := canvas.Images() + if len(images) != 1 { + t.Fatalf("images drawn = %d, want 1", len(images)) + } + if images[0].Bounds != image.Rect() { + t.Fatalf("image bounds = %+v, want its rectangle %+v", images[0].Bounds, image.Rect()) + } + if images[0].Radius != 6 { + t.Errorf("image radius = %v, want the element's 6", images[0].Radius) + } + if diff := float64(images[0].Fade - 0.5); diff > 0.001 || diff < -0.001 { + t.Errorf("image fade = %v, want the element's opacity as 0.5", images[0].Fade) + } +} diff --git a/base/leaves.go b/base/leaves.go index 9a3bd29e4..99341ab8e 100644 --- a/base/leaves.go +++ b/base/leaves.go @@ -2,6 +2,8 @@ package base import ( "time" + + "github.com/vivaui/viva/gfx" ) // progressHeight and progressWidth are what a Progress is when it is given neither. @@ -21,13 +23,17 @@ const ( // container in a Column, 160 wide in a Row, unless given a Width, Height or Grow. // Indeterminate turns it into a bar whose segment keeps sliding, for work of unknown // length. A determinate bar never asks for a frame: change the fraction and repaint, -// as for any other state. +// as for any other state. ID names the bar to assistive technology, which reads it +// as a progress bar and never focuses or presses it; Label names it. A zero ID +// declares no accessible node. // -// f.Progress(m.done / m.total).Height(8) -// f.Progress(0).Indeterminate() -func (f *Frame) Progress(fraction float32) Box { +// f.Progress(uploadID, m.done/m.total).Label("Uploading").Height(8) +// f.Progress(gfx.ID{}, 0).Indeterminate() +func (f *Frame) Progress(ID gfx.ID, fraction float32) Box { b := f.Box(kindProgress) - f.Nodes[b.i].Natural = max(fraction, 0) + n := &f.Nodes[b.i] + n.ID = ID + n.Natural = max(fraction, 0) if fraction != fraction { f.Nodes[b.i].Natural = 0 } diff --git a/base/leaves_test.go b/base/leaves_test.go index b8771787b..49d70dc4e 100644 --- a/base/leaves_test.go +++ b/base/leaves_test.go @@ -29,8 +29,8 @@ func TestProgressAndSpinnerAskForFramesOnlyWhileTheyAreOnScreen(t *testing.T) { _, ok := canvas.NextFrame() return ok } - bar := func(f *Frame) { f.Progress(0.5).Height(8) } - indeterminate := func(f *Frame) { f.Progress(0).Indeterminate() } + bar := func(f *Frame) { f.Progress(gfx.ID{}, 0.5).Height(8) } + indeterminate := func(f *Frame) { f.Progress(gfx.ID{}, 0).Indeterminate() } spinner := func(f *Frame) { f.Spinner() } if frames(400, false, bar) || frames(0, false, bar) { @@ -55,8 +55,8 @@ func TestProgressIsFilledToItsFractionAndSizedLikeABar(t *testing.T) { var column, row Box view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 300, Height: 100}, func(f *Frame) { f.Column().Pad(10).Gap(8).Children(func() { - column = f.Progress(0.25) - f.Row().Children(func() { row = f.Progress(2) }) // more than full is full + column = f.Progress(gfx.ID{}, 0.25) + f.Row().Children(func() { row = f.Progress(gfx.ID{}, 2) }) // more than full is full }) }) near(t, "in a column", column.Rect(), gfx.Rect{X: 10, Y: 10, Width: 280, Height: 6}) @@ -315,8 +315,8 @@ func TestLeavesAndSplittersAllocateNothingOnceWarm(t *testing.T) { canvas.Reset() view.Draw(canvas, theme, gfx.Rect{Width: 600, Height: 300}, func(f *Frame) { f.Column().Fill().Pad(8).Gap(8).Children(func() { - f.Progress(0.3) - f.Progress(0).Indeterminate().Height(8) + f.Progress(gfx.ID{}, 0.3) + f.Progress(gfx.ID{}, 0).Indeterminate().Height(8) f.Row().Gap(8).Items(Center).Children(func() { f.Spinner(); f.Text("Loading") }) f.SplitButton(SplitButtonSpec{PrimaryID: tree.ID(page, "save"), MenuID: tree.ID(page, "save-more"), Label: "Save", Open: true}) f.Row().Grow(1).Children(func() { @@ -343,7 +343,7 @@ func BenchmarkProgressSpinnerSplitter(b *testing.B) { canvas.Reset() view.Draw(canvas, theme, gfx.Rect{Width: 600, Height: 300}, func(f *Frame) { f.Column().Fill().Pad(8).Gap(8).Children(func() { - f.Progress(0.3) + f.Progress(gfx.ID{}, 0.3) f.Spinner() f.Row().Grow(1).Children(func() { f.Column().Width(state.Pos) diff --git a/base/page.go b/base/page.go index 864d2bc5e..4e829b168 100644 --- a/base/page.go +++ b/base/page.go @@ -154,6 +154,7 @@ const ( pkTab pkList pkDisclosure + pkProgress pkKinds ) diff --git a/base/paint.go b/base/paint.go index 74c5e20f3..0f11fb72b 100644 --- a/base/paint.go +++ b/base/paint.go @@ -254,7 +254,8 @@ func (f *Frame) paintControl(n *Node, r Rect) { case kindIcon: canvas.DrawIconTransformed(extra.icon, Rect{X: r.X, Y: r.Y, Width: n.Pref[AxisX], Height: n.Pref[AxisY]}, n.Color, extra.iconTransform) case kindImage: - canvas.DrawBitmap(f.Images[n.Aux], r) + bitmap := f.Images[n.Aux] + canvas.DrawBitmapShaded(bitmap, Rect{Width: float32(bitmap.Width), Height: float32(bitmap.Height)}, r, n.Radius, 1-f.Opacity) case kindSlot: if extra.swatch && f.paintSwatchFn != nil { f.paintSwatchFn(f, n, r) diff --git a/gfx/canvas.go b/gfx/canvas.go index 5e9ee0441..1b7ddd3ba 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -313,6 +313,13 @@ type Image struct { // Backdrop marks an image drawn beneath every other primitive of the frame, // whatever layer they are on. See Canvas.DrawBackdrop. Backdrop bool + // Radius rounds the image's corners: the pixels outside the rounded box are + // not drawn. Zero is a square image. + Radius float32 + // Fade is how much of the image is transparent, 1-opacity, the same + // convention as Extra.fade: zero draws it fully opaque. It is a draw-time + // value: changing it does not rebuild the image's texture. + Fade float32 // DevicePixels marks an image whose Bounds and Source are whole device pixels // and whole bitmap pixels, drawn one bitmap pixel to one device pixel. The // painter keeps it so, at a fractional display scale too, instead of rounding @@ -358,6 +365,9 @@ const ( RoleHeading RoleStatus RoleSeparator + // RoleProgressBar is a read-only progress indicator: it reports a value + // between bounds while an operation runs, and activates nothing. + RoleProgressBar ) // roleNames are the names of the roles: what a selector or a printed tree calls @@ -368,7 +378,7 @@ var roleNames = [...]string{ RoleTextField: "textfield", RoleSlider: "slider", RoleTerminal: "terminal", RoleGroup: "group", RoleMenu: "menu", RoleMenubar: "menubar", RoleListBox: "listbox", RoleOption: "option", RoleGrid: "grid", RoleGridCell: "gridcell", RoleHeading: "heading", RoleStatus: "status", - RoleSeparator: "separator", + RoleSeparator: "separator", RoleProgressBar: "progressbar", } // String is the role's name as selectors and printed trees write it, such as @@ -1115,6 +1125,13 @@ func (canvas *Canvas) DrawBitmap(bitmap Bitmap, bounds Rect) { // DrawBitmapRegion appends a source region of bitmap sampled into bounds. // Source is clipped to the bitmap without allocating or copying pixels. func (canvas *Canvas) DrawBitmapRegion(bitmap Bitmap, source, bounds Rect) { + canvas.DrawBitmapShaded(bitmap, source, bounds, 0, 0) +} + +// DrawBitmapShaded appends a source region of bitmap sampled into bounds with its +// corners rounded to radius and faded by fade (1-opacity); zero keeps the plain +// square, opaque image DrawBitmapRegion draws. +func (canvas *Canvas) DrawBitmapShaded(bitmap Bitmap, source, bounds Rect, radius, fade float32) { if bitmap.Width <= 0 || bitmap.Height <= 0 || bitmap.Stride < bitmap.Width*4 || bounds.Width <= 0 || bounds.Height <= 0 { return } @@ -1133,6 +1150,8 @@ func (canvas *Canvas) DrawBitmapRegion(bitmap Bitmap, source, bounds Rect) { Bitmap: bitmap, Source: Rect{X: left, Y: top, Width: right - left, Height: bottom - top}, Bounds: bounds, + Radius: max(radius, 0), + Fade: min(max(fade, 0), 1), Layer: canvas.currentLayer(), Order: canvas.nextOrder(), } diff --git a/gfx/presence.go b/gfx/presence.go index 310648140..7fb1eba72 100644 --- a/gfx/presence.go +++ b/gfx/presence.go @@ -594,6 +594,10 @@ func (presence Presence) apply(canvas *Canvas, open presenceOpen, pivot Point, p continue } image.Bounds = transform.rect(image.Bounds) + image.Radius *= transform.scale + if fade { + image.Fade = 1 - (1-image.Fade)*transform.alpha + } if image.HasClip { image.ClipOf = transform.rect(image.ClipOf) } diff --git a/gfx/replay.go b/gfx/replay.go index 4666f3143..6c3849839 100644 --- a/gfx/replay.go +++ b/gfx/replay.go @@ -354,7 +354,7 @@ 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 && - a.Backdrop == b.Backdrop && a.DevicePixels == b.DevicePixels && a.Bitmap.Width == b.Bitmap.Width && a.Bitmap.Height == b.Bitmap.Height + a.Backdrop == b.Backdrop && a.DevicePixels == b.DevicePixels && a.Radius == b.Radius && a.Fade == b.Fade && a.Bitmap.Width == b.Bitmap.Width && a.Bitmap.Height == b.Bitmap.Height } func sameHit(a, b Hit) bool { return a == b } diff --git a/gfx/role_test.go b/gfx/role_test.go index 79d12476c..60c1767d6 100644 --- a/gfx/role_test.go +++ b/gfx/role_test.go @@ -3,7 +3,7 @@ package gfx import "testing" func TestRoleNamesRoundTrip(t *testing.T) { - for role := RoleButton; role <= RoleSeparator; role++ { + for role := RoleButton; role <= RoleProgressBar; role++ { name := role.String() if name == "" || name == "region" { t.Fatalf("role %d has no name", role) diff --git a/headless/convert.go b/headless/convert.go index 071d6bfec..e2ff33f48 100644 --- a/headless/convert.go +++ b/headless/convert.go @@ -51,6 +51,7 @@ func scenery(snapshot app.Snapshot) ([]render.Rectangle, []platform.TextLabel, * Clip: label.Clip, Clipped: label.Clipped, Bitmap: label.Bitmap, BitmapWidth: label.BitmapWidth, BitmapHeight: label.BitmapHeight, BitmapStride: label.BitmapStride, BitmapID: label.BitmapID, BitmapVersion: label.BitmapVersion, + ImageRadius: label.ImageRadius, ImageFade: label.ImageFade, BitmapUpload: len(label.Bitmap) > 0, Quad: label.Quad, HasQuad: label.HasQuad, Color: platform.Color{Red: float64(label.Color.Red), Green: float64(label.Color.Green), Blue: float64(label.Color.Blue), Alpha: float64(label.Color.Alpha)}, diff --git a/internal/framebuild/framebuild.go b/internal/framebuild/framebuild.go index 04ef159f3..425b2d587 100644 --- a/internal/framebuild/framebuild.go +++ b/internal/framebuild/framebuild.go @@ -740,6 +740,7 @@ func (builder *Builder) appendImageLabel(index int, shapesBefore uint32) { ShapesBefore: shapesBefore, Bitmap: bitmap.Pix[offset : offset+length], BitmapWidth: right - left, BitmapHeight: bottom - top, BitmapStride: bitmap.Stride, BitmapID: bitmap.ID, BitmapVersion: bitmap.Version, + ImageRadius: image.Radius, ImageFade: image.Fade, BitmapUpload: builder.bitmapUpload(image, index), }) builder.labelImage = append(builder.labelImage, int32(index)) @@ -1095,7 +1096,7 @@ func sameImages(left, right []gfx.Image) bool { } for index := range left { a, b := left[index], right[index] - if a.Bounds != b.Bounds || a.Source != b.Source || a.Layer != b.Layer || a.Order != b.Order || a.Backdrop != b.Backdrop || a.Bitmap.Width != b.Bitmap.Width || + if a.Bounds != b.Bounds || a.Source != b.Source || a.Layer != b.Layer || a.Order != b.Order || a.Backdrop != b.Backdrop || a.Radius != b.Radius || a.Fade != b.Fade || a.Bitmap.Width != b.Bitmap.Width || a.Bitmap.Height != b.Bitmap.Height || a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || a.Bitmap.Version != b.Bitmap.Version || len(a.Bitmap.Pix) != len(b.Bitmap.Pix) { return false diff --git a/internal/framebuild/framebuild_test.go b/internal/framebuild/framebuild_test.go index c28a47d68..3b2671838 100644 --- a/internal/framebuild/framebuild_test.go +++ b/internal/framebuild/framebuild_test.go @@ -79,7 +79,7 @@ func TestBuilderCharacterizesTheFrame(t *testing.T) { canvas.LabelRuns("ab", runsBounds, gfx.TextStyle{Size: 10, Mono: true, Color: textColor}, 7, runs) canvas.PushLayer(5) canvas.Fill(layerBounds, layered) - canvas.DrawBitmap(picture, imageBounds) + canvas.DrawBitmapShaded(picture, gfx.Rect{Width: 8, Height: 4}, imageBounds, 3, 0.25) canvas.Label("layered", layerText, gfx.TextStyle{Size: 12, Color: textColor}) canvas.PopLayer() canvas.LabelQuad("warped", warpBounds, warpQuad, gfx.TextStyle{Size: 12, Color: textColor}) @@ -168,7 +168,8 @@ func TestBuilderCharacterizesTheFrame(t *testing.T) { t.Errorf("runs label lost its decorations: %+v", got.Runs) } if got := labels[4]; got.BitmapID != picture.ID || got.BitmapVersion != picture.Version || got.Layer != 6 || - got.ShapesBefore != 7 || got.BitmapWidth != 8 || got.BitmapHeight != 4 || !got.BitmapUpload { + got.ShapesBefore != 7 || got.BitmapWidth != 8 || got.BitmapHeight != 4 || !got.BitmapUpload || + got.ImageRadius != 3 || got.ImageFade != 0.25 { t.Errorf("image label = %+v", got) } if got := labels[5]; got.Value != "layered" || got.Layer != 6 || got.ShapesBefore != 7 { diff --git a/internal/platform/accessibility.go b/internal/platform/accessibility.go index d8d122ec8..4fa24ef8f 100644 --- a/internal/platform/accessibility.go +++ b/internal/platform/accessibility.go @@ -28,6 +28,9 @@ const ( A11yRoleHeading A11yRoleStatus A11yRoleSeparator + // A11yRoleProgress is a read-only progress indicator: a range value it + // reports, never one it accepts. + A11yRoleProgress ) // AccessibilityAction is something assistive technology asks a node to do. @@ -124,6 +127,10 @@ func (node AccessibilityNode) Patterns() AccessibilityPatterns { patterns |= PatternRangeValue } patterns |= PatternValue + case A11yRoleProgress: + if node.Range.Set { + patterns |= PatternRangeValue + } case A11yRoleListBox: patterns |= PatternSelection } diff --git a/internal/platform/accessibility_test.go b/internal/platform/accessibility_test.go index 609e0fb2d..30f3d5b6d 100644 --- a/internal/platform/accessibility_test.go +++ b/internal/platform/accessibility_test.go @@ -22,7 +22,7 @@ func TestAccessibilityRolesMatchSemanticTree(t *testing.T) { {A11yRoleListBox, semantic.RoleListBox}, {A11yRoleOption, semantic.RoleOption}, {A11yRoleGrid, semantic.RoleGrid}, {A11yRoleGridCell, semantic.RoleGridCell}, {A11yRoleHeading, semantic.RoleHeading}, {A11yRoleStatus, semantic.RoleStatus}, - {A11yRoleSeparator, semantic.RoleSeparator}, + {A11yRoleSeparator, semantic.RoleSeparator}, {A11yRoleProgress, semantic.RoleProgress}, } { if pair.platform != uint8(pair.semantic) { t.Errorf("platform role %d is semantic role %d", pair.platform, pair.semantic) @@ -43,6 +43,8 @@ func TestAccessibilityPatternsFollowRoleAndState(t *testing.T) { {"text field", AccessibilityNode{Role: A11yRoleTextField}, PatternValue | PatternText}, {"slider with range", AccessibilityNode{Role: A11yRoleSlider, Range: rangeOf(1, 0, 10)}, PatternValue | PatternRangeValue}, {"slider without range", AccessibilityNode{Role: A11yRoleSlider}, PatternValue}, + {"progress with range", AccessibilityNode{Role: A11yRoleProgress, Range: rangeOf(1, 0, 10)}, PatternRangeValue}, + {"progress without range", AccessibilityNode{Role: A11yRoleProgress}, 0}, {"combobox", AccessibilityNode{Role: A11yRoleCombobox}, PatternValue | PatternExpandCollapse}, {"list", AccessibilityNode{Role: A11yRoleListBox}, PatternSelection}, {"heading", AccessibilityNode{Role: A11yRoleHeading}, 0}, diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 73d855e2f..5b706c453 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -422,6 +422,10 @@ type TextLabel struct { BitmapStride int BitmapID uint64 BitmapVersion uint32 + // ImageRadius rounds an image label's corners and ImageFade is how much of + // it is transparent (1-opacity); zero is the plain square, opaque image. + ImageRadius float32 + ImageFade float32 // BitmapUpload is true only when Bitmap content must cross a native // boundary. A false bitmap label references the matching retained texture. BitmapUpload bool diff --git a/internal/platform/darwin/composite_test.go b/internal/platform/darwin/composite_test.go index 715ec8645..1dbe0b70f 100644 --- a/internal/platform/darwin/composite_test.go +++ b/internal/platform/darwin/composite_test.go @@ -15,11 +15,11 @@ func TestCompositeABI(t *testing.T) { if rectangleSize != 80 || rectangleLayerOffset != 36 { t.Fatalf("viva_rectangle ABI = size %d layer offset %d, want 80 and 36", rectangleSize, rectangleLayerOffset) } - if textSize != 264 || textLayerOffset != 56 { - t.Fatalf("viva_text_label ABI = size %d layer offset %d, want 264 and 56", textSize, textLayerOffset) + if textSize != 272 || textLayerOffset != 56 { + t.Fatalf("viva_text_label ABI = size %d layer offset %d, want 272 and 56", textSize, textLayerOffset) } - if labelSize, runsOffset, runSize := labelABI(); labelSize != 264 || runsOffset != 64 || runSize != 36 { - t.Fatalf("label ABI = size %d runs offset %d run size %d, want 264, 64 and 36", labelSize, runsOffset, runSize) + if labelSize, runsOffset, runSize := labelABI(); labelSize != 272 || runsOffset != 64 || runSize != 36 { + t.Fatalf("label ABI = size %d runs offset %d run size %d, want 272, 64 and 36", labelSize, runsOffset, runSize) } if commandSize != 36 { t.Fatalf("viva_composite_command size = %d, want 36", commandSize) diff --git a/internal/platform/darwin/image_shading_test.go b/internal/platform/darwin/image_shading_test.go new file mode 100644 index 000000000..7dbc8406b --- /dev/null +++ b/internal/platform/darwin/image_shading_test.go @@ -0,0 +1,54 @@ +//go:build darwin && vivahead + +package darwin + +import ( + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +func imageLabel(radius, fade float32) []platform.TextLabel { + pixels := make([]byte, 16*16*4) + for index := range pixels { + pixels[index] = 255 // opaque white BGRA + } + return []platform.TextLabel{{ + X: 2, Y: 2, Width: 16, Height: 16, + Bitmap: pixels, BitmapWidth: 16, BitmapHeight: 16, BitmapStride: 16 * 4, BitmapID: 1, BitmapUpload: true, + ImageRadius: radius, ImageFade: fade, + }} +} + +func TestOffscreenRoundsAndFadesAnImage(t *testing.T) { + offscreen, err := NewOffscreen(20, 20, 1, Color{Alpha: 0}) + if err != nil { + t.Skipf("no Metal device: %v", err) + } + defer offscreen.Close() + if err := offscreen.Set(nil, imageLabel(8, 0), nil); err != nil { + t.Fatal(err) + } + pixels, width, _, err := offscreen.Render() + if err != nil { + t.Fatal(err) + } + if _, _, _, alpha := pixelAt(pixels, width, 3, 3); alpha != 0 { + t.Errorf("rounded corner alpha = %d, want 0", alpha) + } + if _, _, _, alpha := pixelAt(pixels, width, 10, 10); alpha < 250 { + t.Errorf("rounded image center alpha = %d, want opaque", alpha) + } + + if err := offscreen.Set(nil, imageLabel(0, 0.5), nil); err != nil { + t.Fatal(err) + } + pixels, width, _, err = offscreen.Render() + if err != nil { + t.Fatal(err) + } + _, _, _, alpha := pixelAt(pixels, width, 10, 10) + if alpha < 120 || alpha > 136 { + t.Errorf("half-faded image alpha = %d, want about 128", alpha) + } +} diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index bdc325aac..0c8d258d3 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -183,6 +183,10 @@ typedef struct { uint32_t bitmap_stride; uint64_t bitmap_id; uint32_t bitmap_version; + // image_radius rounds a bitmap label's corners, and image_fade is how much + // of it is transparent (1-opacity); zero draws the plain square, opaque image. + float image_radius; + float image_fade; // bitmap_upload is nonzero when bitmap carries pixels to compare or upload. uint32_t bitmap_upload; float clip_x; diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 423348902..29c04f6d2 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -2594,6 +2594,7 @@ @interface VivaTextLayer : NSObject { uint32_t _bitmapStride; uint64_t _bitmapID; uint32_t _bitmapVersion; + float _imageRadius; id _texture; NSMutableArray> *_additionalTextures; // A text label wider than a texture holds is rasterized in part: its textures hold the @@ -2619,6 +2620,7 @@ - (void)updateClipFromConfig:(viva_text_label)config; - (void)updateQuadFromConfig:(viva_text_label)config; - (const float *)quad; - (const float *)tint; +- (float)imageRadius; - (NSRect)frame; - (BOOL)clipped; - (NSRect)clip; @@ -2916,6 +2918,7 @@ - (void)updateQuadFromConfig:(viva_text_label)config { _tint[index] = config.tint[index]; } _hasQuad = hasQuad; + _imageRadius = hasQuad ? 0 : config.image_radius; if (hasQuad) { return; } @@ -2932,6 +2935,14 @@ - (void)updateQuadFromConfig:(viva_text_label)config { for (int index = 0; index < 16; index++) { _tint[index] = 1; } + if (config.image_fade > 0) { + // Fade is draw-time: it scales the premultiplied tint, so the picture's + // texture is untouched. + float alpha = 1 - config.image_fade; + for (int index = 0; index < 16; index++) { + _tint[index] *= alpha; + } + } } - (const float *)quad { @@ -2942,6 +2953,10 @@ - (const float *)tint { return _tint; } +- (float)imageRadius { + return _imageRadius; +} + - (BOOL)clipped { return _clipped; } @@ -3519,6 +3534,15 @@ static size_t viva_label_tile_mesh( return viva_label_tile_vertices(quad, tint, left, right, textureLeft, textureRight, vertices); } +// viva_text_label_uniform mirrors TextLabelUniform in scene.metal: where a +// label's box starts, its size, and the radius its picture's corners are cut by. +typedef struct { + float originX, originY; + float sizeX, sizeY; + float radius; + float padding; +} viva_text_label_uniform; + // viva_encode_input draws the native editor's texture. static void viva_encode_input( id encoder, @@ -3538,6 +3562,8 @@ static void viva_encode_input( viva_label_vertices(quad, tint, vertices); [encoder setRenderPipelineState:textPipeline]; [encoder setVertexBytes:vertices length:sizeof(vertices) atIndex:2]; + viva_text_label_uniform labelUniform = {0, 0, 0, 0, 0, 0}; + [encoder setVertexBytes:&labelUniform length:sizeof(labelUniform) atIndex:3]; [encoder setVertexBytes:&viewportSize length:sizeof(viewportSize) atIndex:1]; [encoder setFragmentTexture:inputTexture atIndex:0]; [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:6]; @@ -3628,6 +3654,13 @@ static void viva_encode_scene( } [encoder setRenderPipelineState:textPipeline]; [encoder setVertexBytes:&viewportSize length:sizeof(viewportSize) atIndex:1]; + NSRect layerFrame = [layer frame]; + viva_text_label_uniform labelUniform = { + (float)layerFrame.origin.x, (float)layerFrame.origin.y, + (float)layerFrame.size.width, (float)layerFrame.size.height, + [layer imageRadius], 0, + }; + [encoder setVertexBytes:&labelUniform length:sizeof(labelUniform) atIndex:3]; for (NSUInteger tile = 0; tile < [layer textureCount]; tile++) { viva_label_vertex vertices[18]; size_t count = viva_label_tile_mesh([layer quad], [layer tint], [layer frame], @@ -3730,6 +3763,7 @@ - (instancetype)initWithConfig:(viva_accessibility_node)config case 21: self.accessibilityRole = NSAccessibilityStaticTextRole; break; case 22: self.accessibilityRole = NSAccessibilityStaticTextRole; break; case 23: self.accessibilityRole = NSAccessibilitySplitterRole; break; + case 24: self.accessibilityRole = NSAccessibilityProgressIndicatorRole; break; default: self.accessibilityRole = NSAccessibilityGroupRole; break; } if (config.secure) { @@ -7384,7 +7418,7 @@ int viva_application_last_status(void) { if (config.shader_library != NULL && config.shader_library_length > 0) { viva_remember_shader_library(config.shader_library, config.shader_library_length); _Static_assert(sizeof(viva_rectangle) == 80, "rectangle ABI must be 80 bytes"); - _Static_assert(sizeof(viva_text_label) == 264, "text label ABI must be 264 bytes"); + _Static_assert(sizeof(viva_text_label) == 272, "text label ABI must be 272 bytes"); _Static_assert(sizeof(viva_text_run) == 36, "text run ABI must be 36 bytes"); _Static_assert(sizeof(viva_composite_command) == 36, "composite command ABI must be 36 bytes"); dispatch_data_t libraryData = dispatch_data_create( diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index a0fa9fc77..4eed2f46a 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -767,6 +767,8 @@ func makeNativeTextLabels(labels []TextLabel) (unsafe.Pointer, []unsafe.Pointer, bitmap_stride: C.uint32_t(max(label.BitmapStride, 0)), bitmap_id: C.uint64_t(label.BitmapID), bitmap_version: C.uint32_t(label.BitmapVersion), + image_radius: C.float(label.ImageRadius), + image_fade: C.float(label.ImageFade), bitmap_upload: C.uint32_t(boolInt(label.BitmapUpload)), clip_x: C.float(label.Clip.X), clip_y: C.float(label.Clip.Y), diff --git a/internal/platform/darwin/shaders/scene.metal b/internal/platform/darwin/shaders/scene.metal index 29a5f5827..2926a0140 100644 --- a/internal/platform/darwin/shaders/scene.metal +++ b/internal/platform/darwin/shaders/scene.metal @@ -280,6 +280,20 @@ struct TextVertexOutput { // The colour at this corner, multiplied into the picture there: a plain // label is opaque white, a warped one shades or fades as the caller asked. float4 tint; + // Where this corner falls in the label's own box, the box's size, and the + // radius an image label rounds its corners by: zero radius keeps the label a + // plain quad, warped labels stay square. + float2 local; + float2 size; + float radius; +}; + +// Per-label draw values: where the label's box starts, its size, and the radius +// its picture's corners are cut by (zero for text and for warped labels). +struct TextLabelUniform { + float2 origin; + float2 size; + float radius; }; struct TextVertex { @@ -293,6 +307,7 @@ struct TextVertex { vertex TextVertexOutput viva_text_vertex( uint vertexID [[vertex_id]], constant TextVertex *vertices [[buffer(2)]], + constant TextLabelUniform &label [[buffer(3)]], constant float2 &viewportSize [[buffer(1)]]) { TextVertex selected = vertices[vertexID]; float2 normalized = float2( @@ -304,6 +319,9 @@ vertex TextVertexOutput viva_text_vertex( output.position = float4(normalized, 0.0, 1.0); output.textureCoordinate = selected.textureCoordinate; output.tint = selected.tint; + output.local = selected.pixel - label.origin; + output.size = label.size; + output.radius = label.radius; return output; } @@ -318,5 +336,18 @@ fragment float4 viva_text_fragment( // Both the picture and the tint are premultiplied, so a tint scales all four // channels: that keeps edges and glyph coverage correct as a label fades. float4 tint = float4(input.tint.rgb * input.tint.a, input.tint.a); - return texture.sample(textureSampler, input.textureCoordinate) * tint; + float4 sample = texture.sample(textureSampler, input.textureCoordinate) * tint; + float radius = min(input.radius, min(input.size.x, input.size.y) * 0.5); + if (radius <= 0.0) { + return sample; + } + // The same rounded-box distance the rectangle fragment uses, in the label's + // own logical pixels: the picture's corners are cut and feathered over one + // device pixel. + float2 centered = input.local - input.size * 0.5; + float2 inner = input.size * 0.5 - radius; + float2 distanceVector = abs(centered) - inner; + float distance = length(max(distanceVector, 0.0)) + min(max(distanceVector.x, distanceVector.y), 0.0) - radius; + float coverage = saturate(0.5 - distance / devicePixel(input.local)); + return sample * coverage; } diff --git a/internal/platform/darwin/shaders/scene.metallib b/internal/platform/darwin/shaders/scene.metallib index 3ca084434f2e971879fa24c23afc906e7f749b32..17f2c0d83dd0fbca49ca146b9c90db3f3dba4d42 100644 GIT binary patch delta 3324 zcmai0eN+=y7JoAtCIbYRK-7UGI3!>ZB2E%M{iqWHNCjHZ)S}ix(5M^%LC~sOn@>Kf zh@qjB+HDt$cC9NeidAauE+L3iqk@awXty?6>T+7#Lp`m!U61UWtm*0LKl{$Rx%d9& zy*n@Oz5IS@IEu7?jD#2H@-q<=3UC0-0suh!>eldQ(UF&0mwy(&JU_1EYWLL1r1?MX zcRdiy>&bZW%fyUtFU39ja;W4>>PbP?iq!<@BpqqUN9a^S>s89}Gm;Q*N^7|{ul-uy zHzj|jhQtXue-Gf*{CgE9pMT@~_fN^0-v3Pl;f{P%f{tXvX}uP-GYV}Y9b>2r`KRMy zP6-n2cxfqJnyUsb0%MwK@C6|wkh?^`S603!UVnehodd7P4m1UaWZE>g%)Yz>vSl5Q z+xtEYCz{Sz+6UgCk_iMChU!TTxlGxld1H)agX|e-A(chgG#E=Epojv%+RKj~Mv#8T z$n5Bp)EyY2U}qdcR5tB`VXe4HyST%e(PmwA%DnKLR&3)fJfux`^T2a(A_{jZqKT!5 z-s#z9BtI7cG(<>ffGxAKqdy|Rq~KC+OI6VwqDW!By*Y5s(jiPM%PvIg3q!wMVL}6n zXgLVbF$T5@>!gEhH;V^W^q$N609}%Uz7(FxZE-KPqjp!Z zZD#pu!8XR@6lkU7cE(l6uQy8F%$T``!>hdN_2_iMgkm38H3CB!^4lj zG`@Qs1mp2#rhW<`EHr_y!)U_tD2>PD01MqTJwSl^3_|d?q$o8U_X7h!0raw^!}g+R zq8NtYsvK`Ota6;2TY;z@p%Jr;C98ESl&QbHhY{Ex-=Wj5V9uQ@iM!t5#D-d?v7}hp zY0WUX_QXitF_Kj5vmU)SU>nsK;#zRbm0poMWR`f$l3}y-;z5Z=udNOh+v?cHkfC%t zZ=qeA(c@~+OD>wFsn|r1CcUxFLmqPBw~dk!z02DT=cf{Uvk2_tkD*X4sn0d3}xRqRCy{cL6mt06gebp`^?PJX~qVjKtC2 zJBd?K=!B4CVe~rB@d$kdNpQTxqm9i@2@)@mfdN53gT@Ht#6ZzCQPIHobVN;oF6;4w zsTbB^{dA^Kw4Q1*)0nkIMxb#95;M2UNG!!b5|;N>B&HdaAZ0fF*<2r4m!KURV?HoO z$pJ1*(6`VXa$wbCNMewoc<`;Y7E@~~X-7TGfGI>S6bvw^xd3T~3-$5#?%rv|DI~p< zoQ7=)s07Cl8o7>l5vG76sZ;|{upetOp1@~Da1#{sSoCNJexDo5qmeOO?)W;14s7UR z=3v7%8aYW3i;8gSL0uAurvIqR$DTS0CG8UNa10PF!=%3aXkXbk$@S3f_To}Oi&T4L&v z#hWwZ8}H9$&6aq((4>m5FYByQ+@1@kffG>74nwadOue7yy@f7Jf-n4y@Qj%RyMliu zJXx*I_;73bHEL0gPPnp2xI(XZ(;^jeqB9?H48CyZ{|e8Cg~diFDBHLdaDrk|$_Z(z z#grl^I@A`^VmU!2TTIz7gRTH(DHapdoMPx!$q7%2g#>EBX0itghM1^gTvIp?>dQF< zfjY9Ku-_?giK!Y6ZuG$_C?TH{0aQD+#(__sx=sh_64oqST2 zcDBe;*cYcLxN`n@eig^uZLFvz2(q?5xOU;6f)^(K=VYSe-Mrt`isPvIcR5KIx^>fg z&2#ZDx4aWj8SdspDxh}c-|pb#LH$Wj?`dDr;&dnrR}4wVLRz}>|FyX#srh(CRU12# zlK|r@@VFu{txp1G!We4?ZD4H*gF-b0200ktmjcYp7mR>st|fIYyR#T0i3lmnkc zOr_;ie{;{XHQ5c^fK>9BcBmJG5sJrD8p^g;0`_a}9}}<&ZvG%pRa{t?Nk6d)5F|u} zMJJby7)3Dz9wn*ZQ>E8`TC{;VK!TZqJ4+e>{uPx;)yeTjp{4Zp?7h*1IiT&)eoB%< zSn7?6*BIPcomD;eiSiOjnBOtSK54);kFF|pS&;%2wvuY5DBr;3*O`t&+g}5bU#4b# zK$iNehRwx{&L*?oMi)O?S{CG_&{2FHku7fazvdW?`Nv*Lzzn4Uq9-#6?~<}oNenUb z$>_NOX>$x#$COo5Tz+CW(}d?><6Ab9w&`EW20JCLC~PM)O!gp>;;A>L6=tSTNg(kc z67sf!{uOZ}4>{uYH3QtVH82Y2wRt&4;K==wV}7Do84RORABO-i24nbh2NBT1p-n>L zn*TW$2RqVqa^nmb#X;jdN1H?}01IF&gy#2tJP%?V&H23_=hnlG_j^BH@f7!aKfW8{ zA<&@D@df?|dmzXy+3)@Mdrxt{_v1Yf7eniDl<4LMJ_{qbEt81jZJomLR`yg+L-EDg2CzQ1ERBsKtnC&Ov{{Oevi2OUwvD#yQV*WRp6woYwX%2g^qlSPJ@eoD z|Nou;&%HDAe>d&tk$t~MB9<;MG9z{r-~c#C006$CHR5HIEp09RP`}sx_knM}{b5JJ z*zE~TRMK~j{BF&%ll1s4@6mLE*eooyl&vPf^)MkFIfK%3TCb^veie7B0u&UL*5qK#&(Ak3}Q4i{&YI9l%Vf8CG8=i+bD z0L*}UFlq@IUEPdDYEL*}_qDUrt%@jewJ4mILqLTq(FzQJ5;Xw3eY4|&2*L`JFU3W`9|Hx@ ziNY~*9}6|#L}5K5oQ;nxAP_)9Hw6W-l{{N=5dn6CXeyu>EQ?rI!36_=9byHxk06|`o<_At?~nv z6`FHdTZ-#qqnXwr`ct*KBqtT?$|qJ>4s)5L?@_{KM3BvX+qSc|=Jlq=t=r3Lch_Kz z;;H~(I2O|p2TUAG=!juxQ98ns!m(;-!GVUBk#hqb;WP%Ca3p4wIpOf&CUP_59U=oU zR2>uW;!@2h)8qJ5bT{>jZn}}lc8@Y0j+ntA(zzAi1g4oVp-3O|D%nZPyBQvtcB?z* zHW?nv|zKwwP|S=(+>BgzrV20 z7-j17`UXm<1xF+cPfHf{OEQCe+0C01pRXMYj@%i~mHi{s?oC|~bw<(`ANXGI3ZKrSf?xI0PyeRY>&W|RwBmUEY1G;m@8WLl0})2T1wUONgR&;9 zbFf(#MZJ1+D|IP3cECRFZx85q-3>}DQGKdlry@UD+$7jS10X&DV;H4%g5L;V7(Vm$ z&6|ip_0JK3qzid7*CATr)J)oD-G+G>7a+v4cEYkI@(Ri+K^4|)VrST^`o`MZoC1Hg)tN^>mhE4kHaoNZc4OkfaUSLr>Wr)-tY`I@*O zksTpO3&F&NR662N3Kxpi5n)CylmIO_7@%e1><}-@OdJJFWHr?`MDo$Z1}0#~vmr`6 zNGoK<#^Mu0q$EbYNpyew-0jCr*q=#BbVrtEl+{-^;q^?mca&mG*cGzb_7}WlK$=f)dp*=9Uyc1^fthe_WU+FNhMt&>h95jRmHcUZ`Z1|WZj z;TgP11V-$~TV7lZ5J5j)GiHuEYRY#Ho<)*V8O*nG$(2>U&D(1C=-#ceC2dQo zQY<>IkvjMcH^0EcFZA+@GMW!w>AjM8uxIpOLmLQhkU>P8O%jenHfR!qe7A^&oBlgj zANa41{0Z{m{@9myMCP1?%sG7aLRx=n-}~>SXZ#VOXP{)?;t>CG#w>`ROGS`9e-Lwe zRLex{992-8`Kl!0$+2!lchYf9A|n;176xn@_(FbUjChRS*kr}*cS!J|5_DBfXX%#t zWPsfn#?5hUGN6Q$A11)TXnQoM>_hAiU;s~sw~|KIQfa22@g&ko8Zp6Gd7X?W@ayWL zyu`(=UDe$(#5zPji-zfcTA@fs9Q^z6qSe4;Nl=ZDv{}Wn7e8=Tcw*3`h?)nA*b1P) x!xBV75f9M{C}Q(G?_YEh!L~{#6*rbBY$*S^EEZ}o>s=tcU2YIou4cuA{{b7b+JOK7 diff --git a/internal/platform/linux/atspi_bridge.go b/internal/platform/linux/atspi_bridge.go index bb0a75e8b..7024fd5a2 100644 --- a/internal/platform/linux/atspi_bridge.go +++ b/internal/platform/linux/atspi_bridge.go @@ -1128,7 +1128,7 @@ func (bridge *atspiBridge) answerProperties(target atspiTarget, call *dbus.Messa name := args.String() signature := args.Signature() node, ok := target.node() - if interfaceName != atspiIfaceValue || name != "CurrentValue" || signature != "d" || !ok || !node.Range.Set { + if interfaceName != atspiIfaceValue || name != "CurrentValue" || signature != "d" || !ok || !node.Range.Set || node.Role != platform.A11yRoleSlider { return answerError("org.freedesktop.DBus.Error.PropertyReadOnly", interfaceName+"."+name) } value := decodeDouble(args) diff --git a/internal/platform/linux/atspi_bridge_test.go b/internal/platform/linux/atspi_bridge_test.go index dd5c62406..d76063054 100644 --- a/internal/platform/linux/atspi_bridge_test.go +++ b/internal/platform/linux/atspi_bridge_test.go @@ -171,6 +171,12 @@ func TestAtspiStatesAndRolesFromNodes(t *testing.T) { t.Errorf("node %d role = %d, want %d", index, role, want) } } + if role := atspiRole(platform.AccessibilityNode{Role: platform.A11yRoleProgress}); role != atspiRoleProgressBar { + t.Errorf("progress role = %d, want %d", role, atspiRoleProgressBar) + } + if name := atspiRoleName(atspiRoleProgressBar); name != "progress bar" { + t.Errorf("progress role name = %q", name) + } if role := atspiRole(platform.AccessibilityNode{Role: platform.A11yRoleTextField, Secure: true}); role != atspiRolePassword { t.Errorf("secure field role = %d", role) } diff --git a/internal/platform/linux/atspi_model.go b/internal/platform/linux/atspi_model.go index 903003527..7ece368ed 100644 --- a/internal/platform/linux/atspi_model.go +++ b/internal/platform/linux/atspi_model.go @@ -31,6 +31,7 @@ const ( atspiRoleButton = 43 atspiRoleRadioButton = 44 atspiRoleSeparator = 50 + atspiRoleProgressBar = 42 atspiRoleSlider = 51 atspiRoleStatusBar = 54 atspiRoleTable = 55 @@ -166,6 +167,8 @@ func atspiRole(node platform.AccessibilityNode) uint32 { return atspiRoleStatusBar case platform.A11yRoleSeparator: return atspiRoleSeparator + case platform.A11yRoleProgress: + return atspiRoleProgressBar } return atspiRolePanel } @@ -207,6 +210,8 @@ func atspiRoleName(role uint32) string { return "radio button" case atspiRoleSeparator: return "separator" + case atspiRoleProgressBar: + return "progress bar" case atspiRoleSlider: return "slider" case atspiRoleStatusBar: diff --git a/internal/platform/linux/cpu_offscreen_linux.go b/internal/platform/linux/cpu_offscreen_linux.go index 61b5b2d7d..b9e36ee7d 100644 --- a/internal/platform/linux/cpu_offscreen_linux.go +++ b/internal/platform/linux/cpu_offscreen_linux.go @@ -193,6 +193,7 @@ func placeLabel(l platform.TextLabel, scale float32, image labelImage, canvasWid x, y = platform.DevicePosition(l.X, 0, scale), platform.DevicePosition(l.Y, 0, scale) } label = raster.Label{Pix: image.pixels, Stride: image.width * 4, Width: image.width, Height: image.height, X: x, Y: y, Layer: l.Layer, + Image: len(l.Bitmap) > 0, Radius: l.ImageRadius, Fade: l.ImageFade, ShapesBefore: l.ShapesBefore, LCD: image.lcd, Spans: image.spans, Color: scene.Color{Red: float32(l.Color.Red), Green: float32(l.Color.Green), Blue: float32(l.Color.Blue), Alpha: float32(l.Color.Alpha)}} if len(l.Bitmap) > 0 { diff --git a/internal/platform/linux/image_shading_linux_test.go b/internal/platform/linux/image_shading_linux_test.go new file mode 100644 index 000000000..0fe90e946 --- /dev/null +++ b/internal/platform/linux/image_shading_linux_test.go @@ -0,0 +1,44 @@ +//go:build linux + +package linux + +import ( + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +func imageShadedLabel(radius, fade float32) []platform.TextLabel { + pixels := make([]byte, 16*16*4) + for index := range pixels { + pixels[index] = 255 + } + return []platform.TextLabel{{ + X: 2, Y: 2, Width: 16, Height: 16, + Bitmap: pixels, BitmapWidth: 16, BitmapHeight: 16, BitmapStride: 16 * 4, BitmapID: 1, BitmapUpload: true, + ImageRadius: radius, ImageFade: fade, + }} +} + +// A rounded image leaves its corners to what is behind it, and a faded one is +// dimmer than an opaque one: the Vulkan text shader cuts and fades the picture. +func TestOffscreenRoundsAndFadesAnImage(t *testing.T) { + square := renderScene(t, newTestOffscreen(t, 20, 20), nil, imageShadedLabel(0, 0)) + round := renderScene(t, newTestOffscreen(t, 20, 20), nil, imageShadedLabel(8, 0)) + faded := renderScene(t, newTestOffscreen(t, 20, 20), nil, imageShadedLabel(0, 0.5)) + + if !isPainted(square, 3, 3) { + t.Error("a square image does not paint its corner") + } + if isPainted(round, 3, 3) { + t.Error("the rounded corner still paints") + } + if !isPainted(round, 10, 10) { + t.Error("the rounded image's center is not painted") + } + red, _, _, _ := rgbaAt(square, 10, 10) + fadedRed, _, _, _ := rgbaAt(faded, 10, 10) + if fadedRed >= red || fadedRed == 0 { + t.Errorf("faded image red = %d, want about half of %d", fadedRed, red) + } +} diff --git a/internal/platform/linux/shaders/text.frag b/internal/platform/linux/shaders/text.frag index 2723e69d8..2612aebeb 100644 --- a/internal/platform/linux/shaders/text.frag +++ b/internal/platform/linux/shaders/text.frag @@ -2,9 +2,29 @@ layout(set = 0, binding = 0) uniform sampler2D labelTexture; +// mask is (label width, label height, corner radius, fade): the same rounded-box +// mask and opacity the scene shader draws, in the label's logical pixels. +layout(push_constant) uniform Mask { + layout(offset = 48) vec4 mask; +} m; + layout(location = 0) in vec2 inUV; +layout(location = 1) in vec2 inLocal; layout(location = 0) out vec4 outColor; void main() { - outColor = texture(labelTexture, inUV); + vec4 texel = texture(labelTexture, inUV); + float fade = clamp(1.0 - m.mask.w, 0.0, 1.0); + float radius = min(m.mask.z, min(m.mask.x, m.mask.y) * 0.5); + float coverage = 1.0; + if (radius > 0.0) { + vec2 centered = inLocal - m.mask.xy * 0.5; + vec2 inner = m.mask.xy * 0.5 - radius; + vec2 distanceVector = abs(centered) - inner; + float distance = length(max(distanceVector, 0.0)) + min(max(distanceVector.x, distanceVector.y), 0.0) - radius; + // inLocal is in logical pixels; one device pixel is its derivative. + float devicePixel = max(fwidth(inLocal.x), 1e-4); + coverage = clamp(0.5 - distance / devicePixel, 0.0, 1.0); + } + outColor = texel * (coverage * fade); } diff --git a/internal/platform/linux/shaders/text.frag.spv b/internal/platform/linux/shaders/text.frag.spv index e90347269ec93aae5491165cebce277ed9f371bd..3bb4495297ee53df35052e1dff76df77055b9941 100644 GIT binary patch literal 1812 zcmYk6>q?YS6o$8BTIP7l(#*0s&{4AjHOX{l`lG?nNy3UKwWtg-NH3s>pkLii&|P>j z(E);WWcOCZH`};Zz)q^Q@q~6q*cGLbEN(C$lTX$<;Zmu?`cXnS)&&*zt z(Vse7L^%WLP&&Xa-fnDd>lgyp!5c6LS06>vGEyIV8Ms2P?5i!^*opsoXBtH=fR)tM zl66&qjTmno`Szl2&4?c+(%3RR*s<~mQa5`EjKa4sb$c93J?U`P&DXv{A1A&ShrAL| z#Z1z+kaf@KGXDU(`K>K~klkF`<*R#UZIkG7M?gv+Y7^A*{Pt+wJ7ec)tUZ^2zE8xemw|U$0!6+T zZB@_#oR@z4loPqnB1dj#9=XpU>kHn6HlBA8yo<>Cf;ZL1vu5xvA?qu0O8c4y_GL|T z=>MG0;Www>I}QF-sg@Rv;Ac1*VtWun3KLapv}8bwkK!50DK<}^7u9u zLCivq_py}ichHQfWt(=FJ$)r!UmfVTZ|_7~16ZdH?q=Hxvi*wS-9oMdeMKf@Y!jH@ z_hg>n-bU7EjPsFuAISA?^!qN&*?Z9!-^OcXbNEj6+q>V!Z{A6~7xy3e&A!imzh`58OYvs6k@fq%`5t^b U?||R4z9rtJ{|;?`sX7n-0jj}OlmGw# delta 138 zcmbQjcZZpmnMs+Qfq{{Mn}L@>WFoJrF*^eb0|OZ6CT8XVnGBpjEC|E`49sA0pn3*( zAPXce2gD2$GmR(SF_2XNig5tB%s>oMV-4kl)G<%yWNe=NgegG84k!;25eDMFK#MJa F7yykz4Nw38 diff --git a/internal/platform/linux/shaders/text.vert b/internal/platform/linux/shaders/text.vert index 92d87882a..d72300dca 100644 --- a/internal/platform/linux/shaders/text.vert +++ b/internal/platform/linux/shaders/text.vert @@ -8,6 +8,9 @@ layout(push_constant) uniform TextFrame { } frame; layout(location = 0) out vec2 outUV; +// outLocal is where the fragment falls in the label's own box, in logical +// pixels; the fragment cuts the picture's rounded corners with it. +layout(location = 1) out vec2 outLocal; const vec2 corners[6] = vec2[]( vec2(0.0, 0.0), @@ -23,4 +26,5 @@ void main() { vec2 pixel = frame.origin + corner * frame.size; gl_Position = vec4(pixel / frame.viewport * 2.0 - 1.0, 0.0, 1.0); outUV = corner; + outLocal = corner * frame.size; } diff --git a/internal/platform/linux/shaders/text.vert.spv b/internal/platform/linux/shaders/text.vert.spv index 6bc2b5fff5d6bc24a27b9746cc54229f5c1c41c7..4c8c2cac0c393ce9a9fb06bc9d16647ef1204a54 100644 GIT binary patch delta 111 zcmcb>)xgcm%%sfDz`)4B&A`jxG?CX-o|6FtSb#V;F*6Uu76W2^Ahri$$BD7GdEJ51 qjzEqa5HoHzWlU${v<3> 0.0) { + vec2 centered = inLocal - tint.mask.xy * 0.5; + vec2 inner = tint.mask.xy * 0.5 - radius; + vec2 distanceVector = abs(centered) - inner; + float distance = length(max(distanceVector, 0.0)) + min(max(distanceVector.x, distanceVector.y), 0.0) - radius; + float devicePixel = max(fwidth(inLocal.x), 1e-4); + rounded = clamp(0.5 - distance / devicePixel, 0.0, 1.0); + } + float opacity = fade * rounded * tint.color.a; + vec3 coverage = texel.rgb * opacity; + outColor = vec4(tint.color.rgb * coverage, texel.a * opacity); + outMask = vec4(coverage, texel.a * opacity); } diff --git a/internal/platform/linux/shaders/text_lcd.frag.spv b/internal/platform/linux/shaders/text_lcd.frag.spv index 0408e32fdb9ba3899cea78ccf41accfdd345f7e4..d51c1e21dd7803160c371d5462b01e01dafdb625 100644 GIT binary patch literal 2344 zcmYk6X>X1}6o#iQwRBTkRjH?K>{TRGqq_N0l17V25wVn55-oyIL`qR#lrQS1Nc@Zb z7_lT0*Y$P|?<9BTEcaPv<~&bTWygw?DpF0VOJCB`YD|?_61M8nK0I=Er0e0M8(oJE zACOU>s!BvT4QW+c#x5qW-I>zS2#$hjFbCGa*H57|j8wRTse8_5?qqe=jW1uJw-8^0Lta5tZ6;~!&ARvGGJgZR`K>K~4ZFFt%UAc_wCzQg zyAh-`Gti3e9onNXeiQpDpxt=&=4{)5z8Sdykx#uP>-x7K7rxeOP_(df;2D z8^0F#mgBIjyAH_FK16rk?Ka?h`6k}GvG!d6eY3=>w*lv%0JUjl$<~2f0lZ)R_9-WF z??8^+zER}fiL5VpyUTdKUGVlG>kD3I8PA%*+lQ>LmQ&hm7qBmDnnVBFd=9^B{mww} z4o@nLuN!FdEtKuayYB_g(-3)_r9KdMA;^xL;@qHPFRXAq2K+X-a*6~Q}+JP7pFaznlmDFZ@Ae+L zzKFe#Y`peSzS{@vkAeRJ;j+(4;H>F?0^}GQ^ZN`r>c#v%$EH2S`F-*L literal 1140 zcmYk4$4Wy{5QfLZ-g_@M#)=T^2x7@f7lMil*Mb`ty3to~>+`x1{J!KIy#s${=AU}z zrdp}@M0CVJ3`H~AG8Pq>fa`AQtDA?L#{0)}I9>z(tT-}a3u#@(SD*Drv( zPte)kHFoqx+S6Fw=mN}8@80^pVJ`ZjKl#>|CHo814-hb~plUEB$(<(O8z}Z4LEGQi z=8vN7C2zjIH<2@c5^cWwF7xYs+|k;3bRUqjR(~OJQ}~P61+dpn@|Um`H9r${sy-B<+%4Ze$4mu&E8d!`-bU4pTT;sVc@Owy~jB4 z7LR1va{`znf6M>S+sp!aq4-wkG}*d9*MK+i-M-DcC#|O*r4O339D< z?y!~kJbycJ@=BinnfmU)nPdNZIA=G2`+5WO 0 && !label.HasQuad + needsFade := label.ImageFade > 0 + if needsRounded || needsFade { + context.Call("save") + defer context.Call("restore") + if needsRounded { + clipRounded(context, gfx.Rect{X: x, Y: y, Width: label.Width, Height: label.Height}, label.ImageRadius) + } + if needsFade { + alpha := context.Get("globalAlpha").Float() + context.Set("globalAlpha", alpha*float64(1-label.ImageFade)) + } + } + context.Call("drawImage", canvas, x, y, label.Width, label.Height) +} + +// clipRounded clips the 2D context to a rounded rectangle: the same corners the +// GPU backends cut an image's picture by. +func clipRounded(context js.Value, bounds gfx.Rect, radius float32) { + context.Call("beginPath") + radius = min(radius, min(bounds.Width, bounds.Height)*0.5) + if roundRect := context.Get("roundRect"); roundRect.Type() == js.TypeFunction { + context.Call("roundRect", bounds.X, bounds.Y, bounds.Width, bounds.Height, radius) + context.Call("clip") + return + } + x, y, w, h := bounds.X, bounds.Y, bounds.Width, bounds.Height + context.Call("moveTo", x+radius, y) + context.Call("lineTo", x+w-radius, y) + context.Call("arcTo", x+w, y, x+w, y+radius, radius) + context.Call("lineTo", x+w, y+h-radius) + context.Call("arcTo", x+w, y+h, x+w-radius, y+h, radius) + context.Call("lineTo", x+radius, y+h) + context.Call("arcTo", x, y+h, x, y+h-radius, radius) + context.Call("lineTo", x, y+radius) + context.Call("arcTo", x, y, x+radius, y, radius) + context.Call("closePath") + context.Call("clip") } // bitmapCanvas converts a label's premultiplied BGRA pixels into an offscreen diff --git a/internal/platform/web/render_gl_js.go b/internal/platform/web/render_gl_js.go index e530e0a1e..4cdbe7b1a 100644 --- a/internal/platform/web/render_gl_js.go +++ b/internal/platform/web/render_gl_js.go @@ -73,6 +73,8 @@ type glRenderer struct { uCorners [4]js.Value uTints [4]js.Value uTexture js.Value + uLabel js.Value + uMask js.Value vbo js.Value floats []float32 batches []render.Batch @@ -147,6 +149,8 @@ func newGLRenderer(runtime *runtime, canvas js.Value) (*glRenderer, error) { uTarget: ctx.Call("getUniformLocation", program, "uTargetPixels"), uOrigin: ctx.Call("getUniformLocation", program, "uOrigin"), uTexture: ctx.Call("getUniformLocation", textProgram, "uTexture"), + uLabel: ctx.Call("getUniformLocation", textProgram, "uLabel"), + uMask: ctx.Call("getUniformLocation", textProgram, "uMask"), runtime: runtime, textures: make(map[textKey]*glTexture), } @@ -344,6 +348,15 @@ func (renderer *glRenderer) drawLabel(label platform.TextLabel) { ctx.Call("activeTexture", ctx.Get("TEXTURE0")) ctx.Call("bindTexture", ctx.Get("TEXTURE_2D"), tile.texture) ctx.Call("uniform1i", renderer.uTexture, 0) + radius := label.ImageRadius + if label.HasQuad { + // A warped label's quad is not its box: the rounded mask has no + // meaning on it, so the page sees a square picture there. + radius = 0 + } + ctx.Call("uniform4f", renderer.uLabel, + label.X+label.OriginX, label.Y+label.OriginY, label.Width, label.Height) + ctx.Call("uniform2f", renderer.uMask, radius, label.ImageFade) for index := 0; index < 4; index++ { ctx.Call("uniform4f", renderer.uCorners[index], tile.corners[index][0], tile.corners[index][1], 0, 0) ctx.Call("uniform4f", renderer.uTints[index], tile.tints[index][0], tile.tints[index][1], tile.tints[index][2], tile.tints[index][3]) diff --git a/internal/platform/web/shaders/text.frag.glsl b/internal/platform/web/shaders/text.frag.glsl index 389a7dbca..c9de1ce93 100644 --- a/internal/platform/web/shaders/text.frag.glsl +++ b/internal/platform/web/shaders/text.frag.glsl @@ -5,6 +5,10 @@ uniform sampler2D uTexture; in vec2 vUV; in vec4 vTint; +in vec2 vLocal; +in vec2 vSize; +in float vRadius; +in float vFade; out vec4 outColor; void main() { @@ -12,5 +16,17 @@ void main() { vec4 texel = texture(uTexture, vUV).bgra; // vTint is straight RGBA; premultiply it before multiplying the texel. vec4 tint = vec4(vTint.rgb * vTint.a, vTint.a); - outColor = texel * tint; + float coverage = 1.0; + float radius = min(vRadius, min(vSize.x, vSize.y) * 0.5); + if (radius > 0.0) { + vec2 centered = vLocal - vSize * 0.5; + vec2 inner = vSize * 0.5 - radius; + vec2 distanceVector = abs(centered) - inner; + float distance = length(max(distanceVector, 0.0)) + min(max(distanceVector.x, distanceVector.y), 0.0) - radius; + // vLocal is in logical pixels; one device pixel is its derivative. + float devicePixel = max(fwidth(vLocal.x), 1e-4); + coverage = clamp(0.5 - distance / devicePixel, 0.0, 1.0); + } + float opacity = clamp(1.0 - vFade, 0.0, 1.0); + outColor = texel * tint * coverage * opacity; } diff --git a/internal/platform/web/shaders/text.vert.glsl b/internal/platform/web/shaders/text.vert.glsl index 6b6f48a76..f1386a449 100644 --- a/internal/platform/web/shaders/text.vert.glsl +++ b/internal/platform/web/shaders/text.vert.glsl @@ -5,9 +5,17 @@ uniform vec2 uViewport; // Top-left, top-right, bottom-left, bottom-right, in logical pixels. uniform vec4 uCorners[4]; uniform vec4 uTint[4]; +// uLabel is the label's box in logical pixels (origin x, y, size x, y); uMask +// is its corner radius and how much of it is transparent (1-opacity). +uniform vec4 uLabel; +uniform vec2 uMask; out vec2 vUV; out vec4 vTint; +out vec2 vLocal; +out vec2 vSize; +out float vRadius; +out float vFade; const vec2 uv[6] = vec2[]( vec2(0.0, 0.0), @@ -28,4 +36,8 @@ void main() { 0.0, 1.0); vUV = uv[gl_VertexID]; vTint = uTint[index]; + vLocal = pixel - uLabel.xy; + vSize = uLabel.zw; + vRadius = uMask.x; + vFade = uMask.y; } diff --git a/internal/platform/windows/accessibility_pattern_windows.go b/internal/platform/windows/accessibility_pattern_windows.go index a6ec26bf2..11d5e236e 100644 --- a/internal/platform/windows/accessibility_pattern_windows.go +++ b/internal/platform/windows/accessibility_pattern_windows.go @@ -153,7 +153,13 @@ func (provider *uiaProvider) offers(node platform.AccessibilityNode, kind uiaPat return false } switch kind { - case patternInvoke, patternToggle, patternSelectionItem, patternExpandCollapse, patternRangeValue: + case patternRangeValue: + if node.Role == platform.A11yRoleProgress { + // A progress bar reports a range and accepts no number. + return node.Range.Set + } + fallthrough + case patternInvoke, patternToggle, patternSelectionItem, patternExpandCollapse: // These act on the control, which a window with no way back to the // application cannot do. provider.Tree.mu.RLock() @@ -321,7 +327,7 @@ func uiaRangeSetValueBits(this, bits uintptr) uintptr { return status } number := math.Float64frombits(uint64(bits)) - if !node.Range.Set { + if !node.Range.Set || node.Role == platform.A11yRoleProgress { return windowsResult(resultNotSupported) } if math.IsNaN(number) || number < node.Range.Min || number > node.Range.Max { @@ -343,6 +349,9 @@ func uiaGetRangeIsReadOnly(this, result uintptr) uintptr { if status != 0 { return status } + if node.Role == platform.A11yRoleProgress { + return writeBool(result, true) + } return writeBool(result, node.Disabled) } diff --git a/internal/platform/windows/accessibility_windows.go b/internal/platform/windows/accessibility_windows.go index 1a1803af7..c7aa6ba28 100644 --- a/internal/platform/windows/accessibility_windows.go +++ b/internal/platform/windows/accessibility_windows.go @@ -61,25 +61,26 @@ const ( uiaTextChangedEvent = 20015 uiaLiveRegionChangedEvent = 20024 - uiaButtonControlType = 50000 - uiaCheckBoxControlType = 50002 - uiaComboBoxControlType = 50003 - uiaEditControlType = 50004 - uiaHyperlinkControlType = 50005 - uiaImageControlType = 50006 - uiaListItemControlType = 50007 - uiaListControlType = 50008 - uiaMenuControlType = 50009 - uiaMenuBarControlType = 50010 - uiaMenuItemControlType = 50011 - uiaRadioControlType = 50013 - uiaSliderControlType = 50015 - uiaTabItemControlType = 50019 - uiaTextControlType = 50020 - uiaGroupControlType = 50026 - uiaDataItemControlType = 50029 - uiaWindowControlType = 50032 - uiaSeparatorControlType = 50038 + uiaButtonControlType = 50000 + uiaCheckBoxControlType = 50002 + uiaComboBoxControlType = 50003 + uiaEditControlType = 50004 + uiaHyperlinkControlType = 50005 + uiaImageControlType = 50006 + uiaListItemControlType = 50007 + uiaListControlType = 50008 + uiaMenuControlType = 50009 + uiaMenuBarControlType = 50010 + uiaMenuItemControlType = 50011 + uiaProgressBarControlType = 50012 + uiaRadioControlType = 50013 + uiaSliderControlType = 50015 + uiaTabItemControlType = 50019 + uiaTextControlType = 50020 + uiaGroupControlType = 50026 + uiaDataItemControlType = 50029 + uiaWindowControlType = 50032 + uiaSeparatorControlType = 50038 variantEmpty = 0 variantI4 = 3 @@ -1130,6 +1131,8 @@ func controlType(role uint8) int32 { return uiaCheckBoxControlType case platform.A11yRoleSlider: return uiaSliderControlType + case platform.A11yRoleProgress: + return uiaProgressBarControlType case platform.A11yRoleImage: return uiaImageControlType case platform.A11yRoleLink: diff --git a/internal/platform/windows/accessibility_windows_test.go b/internal/platform/windows/accessibility_windows_test.go index 1ab05ad12..73744959f 100644 --- a/internal/platform/windows/accessibility_windows_test.go +++ b/internal/platform/windows/accessibility_windows_test.go @@ -53,6 +53,7 @@ func TestUIAControlTypeMapping(t *testing.T) { {platform.A11yRoleOption, uiaListItemControlType}, {platform.A11yRoleHeading, uiaTextControlType}, {platform.A11yRoleSeparator, uiaSeparatorControlType}, + {platform.A11yRoleProgress, uiaProgressBarControlType}, {0, uiaGroupControlType}, {255, uiaGroupControlType}, } @@ -211,6 +212,7 @@ func TestUIAOffersPatternsFromTheNode(t *testing.T) { {ID: gfx.Item(2), Role: platform.A11yRoleCheckbox}, {ID: gfx.Item(3), Role: platform.A11yRoleSlider, Range: gfx.ValueRange{Now: 1, Max: 10, Set: true}}, {ID: gfx.Item(4), Role: platform.A11yRoleTextField, Value: "hello"}, + {ID: gfx.Item(5), Role: platform.A11yRoleProgress, Range: gfx.ValueRange{Now: 4, Min: 0, Max: 10, Set: true}}, {Role: platform.A11yRoleHeading}, } tree := engagedTree(t, true, nodes) @@ -219,6 +221,7 @@ func TestUIAOffersPatternsFromTheNode(t *testing.T) { {patternToggle}, {patternRangeValue, patternValue}, {patternValue, patternText}, + {patternRangeValue}, {}, } for index, kinds := range want { @@ -239,6 +242,9 @@ func TestUIAOffersPatternsFromTheNode(t *testing.T) { if passive.children[0].supports(patternInvoke) || passive.children[2].supports(patternRangeValue) { t.Error("an action pattern is offered without a handler") } + if !passive.children[4].supports(patternRangeValue) { + t.Error("a progress bar's read-only range was not offered without a handler") + } if !passive.children[3].supports(patternText) { t.Error("reading text needs no handler") } diff --git a/internal/platform/windows/image_shading_windows_test.go b/internal/platform/windows/image_shading_windows_test.go new file mode 100644 index 000000000..d081ae571 --- /dev/null +++ b/internal/platform/windows/image_shading_windows_test.go @@ -0,0 +1,42 @@ +package windows + +import ( + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +func imageShadedLabel(radius, fade float32) []platform.TextLabel { + pixels := make([]byte, 16*16*4) + for index := range pixels { + pixels[index] = 255 + } + return []platform.TextLabel{{ + X: 2, Y: 2, Width: 16, Height: 16, + Bitmap: pixels, BitmapWidth: 16, BitmapHeight: 16, BitmapStride: 16 * 4, BitmapID: 1, BitmapUpload: true, + ImageRadius: radius, ImageFade: fade, + }} +} + +// A rounded image leaves its corners to what is behind it, and a faded one is +// dimmer than an opaque one: the D3D11 text shader cuts and fades the picture. +func TestOffscreenRoundsAndFadesAnImage(t *testing.T) { + square := renderScene(t, newOffscreen(t, 20, 20, 1), nil, imageShadedLabel(0, 0)) + round := renderScene(t, newOffscreen(t, 20, 20, 1), nil, imageShadedLabel(8, 0)) + faded := renderScene(t, newOffscreen(t, 20, 20, 1), nil, imageShadedLabel(0, 0.5)) + + if !isPainted(square, 3, 3) { + t.Error("a square image does not paint its corner") + } + if isPainted(round, 3, 3) { + t.Error("the rounded corner still paints") + } + if !isPainted(round, 10, 10) { + t.Error("the rounded image's center is not painted") + } + red := square.RGBAAt(10, 10).R + fadedRed := faded.RGBAAt(10, 10).R + if fadedRed >= red || fadedRed == 0 { + t.Errorf("faded image red = %d, want about half of %d", fadedRed, red) + } +} diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 4fc6edc28..3af8a5a6b 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -90,6 +90,9 @@ type frameConstants struct { TextMode uint32 Bounds [4]float32 TextColor [4]float32 + // TextShape is the label's box size and its image corner radius and fade + // (xy size, z radius, w fade). + TextShape [4]float32 PixelSize float32 Padding [3]float32 } @@ -690,6 +693,12 @@ func (renderer *renderer) draw(width, height int, scale float32) error { continue } frame.Bounds = label.quad(scale) + frame.TextShape = [4]float32{float32(label.label.Width), float32(label.label.Height), label.label.ImageRadius, label.label.ImageFade} + if label.label.HasQuad { + // A warped label's quad is not its box: a rounded mask has no + // meaning on it. + frame.TextShape[2] = 0 + } frame.TextMode = 0 if label.lcd { frame.TextMode = 1 diff --git a/internal/platform/windows/shaders/manifest.json b/internal/platform/windows/shaders/manifest.json index fb7c9ebc4..462c7f3ac 100644 --- a/internal/platform/windows/shaders/manifest.json +++ b/internal/platform/windows/shaders/manifest.json @@ -1,31 +1,31 @@ { - "source_sha256": "8afa5b2bccec5c6bec76fcbd00bbf862a840804a09d12c9a8fca6d2469368b8e", + "source_sha256": "5083c9723999eac26132facf2b8ce704824dfc4719b56fe9b8974de7d91b2524", "compiler": "d3dcompiler_47.dll", "flags": 34816, "entries": [ { "name": "rectangleVertex", "profile": "vs_5_0", - "sha256": "62325e4aa5e48a7665bdc4d3ba5f3c15f71e36e23ee1bafc83add5a9252dbd07", - "bytes": 6564 + "sha256": "edf06eb99b4bbbc8f0386f1ddc0fbce58e20e61721c2c810073b7ab040873a03", + "bytes": 6612 }, { "name": "rectangleFragment", "profile": "ps_5_0", - "sha256": "0a478acda63ee4e1e17d7dc003d647d57a62e735b1af704471591c8b3883afd6", - "bytes": 9612 + "sha256": "820e508861cefb20e957f6cd042110ab33f63220ee6a134c59b8c84f1ed60db1", + "bytes": 9660 }, { "name": "textVertex", "profile": "vs_5_0", - "sha256": "77f2581eac80085d32171f2cf3bb53ef7856f01bed1d67aca1a1e5ac52719ef7", - "bytes": 2052 + "sha256": "701be5fdd0a737b4f23d8807f92451955d587b0e91b4c6e8423b70236a3195c7", + "bytes": 2152 }, { "name": "textFragment", "profile": "ps_5_0", - "sha256": "5f03fd2e43310823d7545a06b299f1ab48e5bc7c2638c8e2bfe5d2794f4e3001", - "bytes": 1820 + "sha256": "43278ce7f746c6d9b366868be6388938e5dec229a01d4c4e78be043236954542", + "bytes": 2576 } ] } diff --git a/internal/platform/windows/shaders/rectangleFragment.dxbc b/internal/platform/windows/shaders/rectangleFragment.dxbc index 25d3ee0cb23d2a8ab0cbf884c2a8720d337152b6..261e021d9c82ec9407d38d3a2b6220f7c8db4156 100644 GIT binary patch delta 445 zcmeD2-s5fM65-@L*}!?@qR+eU%Q59#yEwUR5+efx!yZ)z238<#0>lB#3=CUX7#Lmv zu>w#$$i>x7gn6Qs6yuwTq5i5IKqWOGWk3uAdq8FY0Z0x6&P@C$F8Bc`2oeAq0|p$E z9T~+1b(k0!crZjwfuaIHQ4j_J53t%Cpr`_nhbmeI6g9vQZ2*co07XHz0htUFz$R<~ zGF^Z?kc}X40wg;50;2)r(aDTV){Orr+cMc}I{;Ocq*jzT=jY@Xfmy*Bi3O<)1(_A8 zIl-A#sSIg3`H3Y!{mhf)nPeHeChui3XFRz1E7M~}M%KwUS@tusOrFUa3?vzqB_^}7 z0a=?P*_@ex0&_X!ftUtD_Ls* delta 461 zcmdnv-Q#WL65-@r_0>gBJ|}4Jc9&N7Zo_@Sj0_A6J*o^0tU%fXh!vO_7+P2u7I~a6$Hu56?_ilY;F}bX9QAv#k4`1UP}B1a-K?p LIGY7!R&xRXc@Svx diff --git a/internal/platform/windows/shaders/rectangleVertex.dxbc b/internal/platform/windows/shaders/rectangleVertex.dxbc index 44ad93cc063b0bc3d4de9ad914ff32718a783144..f8f28333cc1b3d94a4d469a5f2475f72f36db230 100644 GIT binary patch delta 521 zcmZ2te8t$(CBn%$`9k7E1HK1r&C6%S)$DtIf{}rN;ff>!11pd=0pbc4ARmY=*nk)) z9^~TcW;4-Jnn{FZVpx?O2T;iYAPxXx7^ndSLX#K|<-jme79d2%C@y+#XAO-X7+iF1BVei4`z zoRL_N%21G5k(v{nS(VC=mXn`Y!Z7&(lLF(p$&AeAqO3sAM}PwW5*|Pk7(Pt)We#R+ znY@r$J~kUDR|1uv0cC^yF%QaC0J4`r*&xrXhO!-iY)~{YGKhd#TY%!|AaS!SOEVKA e>*j@Qli3(qCY$nRGqP-6$UB=ENZAUea{vHTgH193 delta 488 zcmca&yu{ejCBn)1O?j-Ru>JHSQkR!4J1%Ww&&a^Qutbu9ffY!b0I>%PkPpNhY(NYY z4{~vJ-1 z0Z%t6F^arzd&Y#z#Wk2WE&;}riYA^^O&p{r6;dsvR8-!Dl18?C~?lu$uD9k z$gD`s3C^raWk}1(Pb^_ry?U|$vjXFs$%f44qE~@RH9-CYf&d@}av2Uxu4N8pjG26q zSw7YpDCYu|&w#Q)F3p3o6@cs#C>!M7YAD+Q$Ogp%BZCN-)dCbp2Zoz{S(=#`SvFr} ao6N?@JUNv&n~{0*Mc&!WKq^--odW=<(ngN} diff --git a/internal/platform/windows/shaders/scene.hlsl b/internal/platform/windows/shaders/scene.hlsl index 3927ec1e0..8387c9b9c 100644 --- a/internal/platform/windows/shaders/scene.hlsl +++ b/internal/platform/windows/shaders/scene.hlsl @@ -1,6 +1,8 @@ // textMode is 0 when the label texture is premultiplied color, 1 when it holds the coverage // of ClearType text in its three color channels, to be blended with textColor per channel. -cbuffer Frame : register(b0) { float2 viewport; uint instanceOffset; uint textMode; float4 textBounds; float4 textColor; float pixelSize; float3 framePadding; }; +// textShape is the label's box size and its image corner radius and fade: +// xy = size, z = radius, w = fade (1-opacity). +cbuffer Frame : register(b0) { float2 viewport; uint instanceOffset; uint textMode; float4 textBounds; float4 textColor; float4 textShape; float pixelSize; float3 framePadding; }; // shade1 and shade2 are a triangle's colors at its second and third corner; color is the first's. struct Rectangle { float4 bounds; float4 color; float4 style; float4 shade1; float4 shade2; }; StructuredBuffer rectangles : register(t0); @@ -242,6 +244,9 @@ Vertex textVertex(uint vertex : SV_VertexID) { float2 pixel = textBounds.xy+corner(vertex)*textBounds.zw; output.position = float4(pixel/viewport*float2(2,-2)+float2(-1,1),0,1); output.uv = corner(vertex); + output.local = corner(vertex)*textBounds.zw; + output.size = textShape.xy; + output.radius = textShape.z; return output; } // Text is blended with dual-source blending: color is what is added to the target and mask @@ -249,14 +254,24 @@ Vertex textVertex(uint vertex : SV_VertexID) { struct TextTarget { float4 color : SV_Target0; float4 mask : SV_Target1; }; TextTarget textFragment(Vertex input) { float4 texel = labelTexture.Sample(labelSampler,input.uv); + // An image label cuts its picture's rounded corners and fades the whole + // picture; ordinary text has a zero radius and fade and keeps the fast path. + float radius = min(input.radius, min(input.size.x,input.size.y)*0.5); + float rounded = 1; + if (radius > 0) { + float2 distanceVector = abs(input.local-input.size*0.5)-input.size*0.5+radius; + float distance = length(max(distanceVector,0))+min(max(distanceVector.x,distanceVector.y),0)-radius; + rounded = saturate(0.5 - distance / pixelSize); + } + float opacity = saturate(1 - textShape.w) * rounded; TextTarget output; if (textMode == 1) { - float3 coverage = texel.rgb * textColor.a; - output.color = float4(textColor.rgb * coverage, texel.a * textColor.a); - output.mask = float4(coverage, texel.a * textColor.a); + float3 coverage = texel.rgb * textColor.a * opacity; + output.color = float4(textColor.rgb * coverage, texel.a * textColor.a * opacity); + output.mask = float4(coverage, texel.a * textColor.a * opacity); } else { - output.color = texel; - output.mask = texel.aaaa; + output.color = texel * opacity; + output.mask = texel.aaaa * opacity; } return output; } diff --git a/internal/platform/windows/shaders/textFragment.dxbc b/internal/platform/windows/shaders/textFragment.dxbc index ee10a8cbeb780eac4f3cc1dd70d26b755f2705af..d11331f54bfdd84dda5fe70cd93a77865aaaeb80 100644 GIT binary patch literal 2576 zcmbtVOKclu5T3;3Wzuw2T2v}3t*Rcp_k0g4KVUzvoajwbm}J zIDo0>0U_Xm5C;xDA&~E!%B67bi31Wh4ydlD@B}SV6G4svqpIJLs z$z=c9d3534zZ-Y%UcPhgw@-I|9TO2NDKde55&Tm^WEPhSxHBVC%H^E~WW?PA<0zNG zGO@oeUx?%&DCJTq%1(l9@I3e|cot0h0Zh9=qEGVA;Bhc>cn-V|Qr!{Ue*q68#WbqB zUc;^KwHjV1(WUI&>f8uDal-1J7uiq4!5`qQK1atH6hs~AthqBj@4Bx+P7HG+?To;E z4moQkj*wBfub{M`CzI}u@b^39HuS_1G79$q%8So{`xCeo;55I7bPCcsb)QAEa*%8P zY|}i|>;94N-E0M6N9v8B+F3v^6JX;s@_cwX4VB+)cdE^+Ua?+pdmX9W48of9dOeXB zV9SmUr*~o7L030}nim~1!Hs6E9fw|&UL0FH^t6xfjeRy~1YzXByQga$lO1^Gf-d0Xb5Z1OW3xa@uWk#mMt2ju+Di7yP16aRLfoJWL=YIEQDU@K_*9Y1JF zwpb{Zq)^PJ3*xR{$xA7nTi%v4`2jSn0lGKaBLTg4~4cBEsE#Xh7z@U8Fr zn#hdWYd-2H#&nnAV@B&)>e>fB5^%2=_E7z(z52_Ge0g7_o83MkkIh?scOsrw=acyD zbmr-Y7|!9OsnMB>G0;t`y~>_^V*?q_t=jTF%r-Q!opCcOw{1eBSg)dIw~cG#EW#A#mKS%YGT@5kUOPmaczH{s4Lr_0|$b{ZV@4Lg6&UIf#Y RqY5S`t-oOdAc69Q@=VxxtLq8JmzMDx)JK_e*G2u4r>5s7eG#E@Pwtc@Uu zjTUJHL2Ly7f?#PcqJ;=r`Ss?`10M`C@9o>!o!x`ZV}C5YFrB(G?kkUz{*kYvtrbxn zcosy|(?sM$9!1z1(SuIZ520!h&89QiiF&MCbk^t3XJDjzL=xfQgVnmZU*y&}-I1hpBQRg~na1(dB|91Pp>9zzX*vC3XoJwrJJ=JmaHybn-$9`4O} zWmV2ikI*~zfp)y)j zK1o&4b_J<#Ex^YOs$soD3c3vIVG+z>@Ep`UV%;RMh&yHXLtxxx+t;UVef<`=+0G-V zHVYRrBZm0~D%GjkwQFvo#1BwbLgHM5AK-cnzf}8MkMkC2Q6lRt)Jpv31~f+2@2-8c qxVq=zwf`RH9C&%}B$1fQ2d46eApDcwYqCkIJu4xky0a20sp-GL#9Gh* diff --git a/internal/platform/windows/shaders/textVertex.dxbc b/internal/platform/windows/shaders/textVertex.dxbc index 0910eb490208e0e97b2b47af8ba29d9d1fe4447f..6e01f92827ac42a32d69bda17fc7eda6d176b49a 100644 GIT binary patch delta 590 zcmZXRyGsK>5XNUO_b?%tL2sAv>7o8|jVYXEJ7vJ|hwEQ7`wTD&Gqajj-_Gy%EKlqJ9IVqg)IC delta 517 zcmaDM&>~>v65-@rx1@RI|3>5d*JlFH{fMl;%*epNz{0`6zzU>IfLMWhEYk;5GT Ddwynn diff --git a/internal/raster/image_mask_test.go b/internal/raster/image_mask_test.go new file mode 100644 index 000000000..ba6003f0e --- /dev/null +++ b/internal/raster/image_mask_test.go @@ -0,0 +1,55 @@ +package raster + +import ( + "testing" + + "github.com/vivaui/viva/internal/scene" +) + +// coverageBitmap is a 16x16 opaque white BGRA bitmap. +func coverageBitmap() []byte { + pix := make([]byte, 16*16*4) + for i := range pix { + pix[i] = 255 + } + return pix +} + +func TestImageLabelRoundsItsCorners(t *testing.T) { + draw := func(radius float32) *Canvas { + canvas := NewCanvas(32, 32) + var drawer Rasterizer + drawer.Draw(canvas, Params{Scale: 1}, nil, []Label{{ + Pix: coverageBitmap(), Stride: 16 * 4, Width: 16, Height: 16, X: 8, Y: 8, + Image: true, Radius: radius, + Color: scene.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + }}) + return canvas + } + square := draw(0) + round := draw(8) + alpha := func(c *Canvas, x, y int) byte { return c.Pix[y*c.Stride+x*4+3] } + if alpha(square, 8, 8) != 255 || alpha(square, 23, 23) != 255 { + t.Fatalf("a square image does not cover its corner: got %d", alpha(square, 23, 23)) + } + if got := alpha(round, 23, 23); got != 0 { + t.Errorf("the rounded corner kept %d alpha, want 0", got) + } + if got := alpha(round, 16, 16); got != 255 { + t.Errorf("the rounded image's center kept %d alpha, want 255", got) + } +} + +func TestImageLabelFadesByItsOpacity(t *testing.T) { + canvas := NewCanvas(32, 32) + var drawer Rasterizer + drawer.Draw(canvas, Params{Scale: 1}, nil, []Label{{ + Pix: coverageBitmap(), Stride: 16 * 4, Width: 16, Height: 16, X: 8, Y: 8, + Image: true, Fade: 0.5, + Color: scene.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + }}) + got := canvas.Pix[16*canvas.Stride+16*4+3] + if got < 120 || got > 136 { + t.Errorf("half-faded image alpha = %d, want about 128", got) + } +} diff --git a/internal/raster/raster.go b/internal/raster/raster.go index 257560f1a..797e546ba 100644 --- a/internal/raster/raster.go +++ b/internal/raster/raster.go @@ -35,6 +35,12 @@ type Label struct { LCD bool Color scene.Color Spans []Span + // Image marks a label drawn from a bitmap rather than text; Radius rounds its + // corners (logical pixels) and Fade is how much of it is transparent + // (1-opacity). Both are zero for an ordinary square, opaque image. + Image bool + Radius float32 + Fade float32 } // Span is a range of device columns [From, To) of an LCD label's picture that @@ -204,6 +210,9 @@ func drawLabel(c *Canvas, damage render.Scissor, l *Label) { if empty(area) { return } + if l.Image && l.Fade >= 1 { + return + } if l.SourceWidth > 0 { drawScaledBitmap(c, area, l) return @@ -248,13 +257,17 @@ func drawScaledBitmap(canvas *Canvas, area render.Scissor, label *Label) { left := int(sourceX) right := min(left+1, width-1) weightX := float32(sourceX - float64(left)) + mask := imageMask(label, x, y) + if mask <= 0 { + continue + } var sample [4]float32 for channel := range sample { top := float32(label.Pix[upper*label.Stride+left*4+channel])*(1-weightX) + float32(label.Pix[upper*label.Stride+right*4+channel])*weightX bottom := float32(label.Pix[lower*label.Stride+left*4+channel])*(1-weightX) + float32(label.Pix[lower*label.Stride+right*4+channel])*weightX sample[channel] = (top*(1-weightY) + bottom*weightY) * (1.0 / 255) } - over(canvas.Pix, y*canvas.Stride+x*4, sample[2], sample[1], sample[0], sample[3]) + over(canvas.Pix, y*canvas.Stride+x*4, sample[2]*mask, sample[1]*mask, sample[0]*mask, sample[3]*mask) } } } @@ -267,16 +280,29 @@ func drawPremultipliedLabel(c *Canvas, area render.Scissor, l *Label) { src := l.Pix[(y-l.Y)*l.Stride+(area.Left-l.X)*4:] di := y*c.Stride + area.Left*4 for x := area.Left; x < area.Right; x++ { - a := src[3] + sr, sg, sb, a := src[0], src[1], src[2], src[3] + if l.Image { + mask := imageMask(l, x, y) + if mask <= 0 { + src, di = src[4:], di+4 + continue + } + if mask < 1 { + a = unorm8(float32(a) * inv * mask) + sr = unorm8(float32(sr) * inv * mask) + sg = unorm8(float32(sg) * inv * mask) + sb = unorm8(float32(sb) * inv * mask) + } + } switch a { case 0: case 255: - c.Pix[di], c.Pix[di+1], c.Pix[di+2], c.Pix[di+3] = src[0], src[1], src[2], 255 + c.Pix[di], c.Pix[di+1], c.Pix[di+2], c.Pix[di+3] = sr, sg, sb, 255 default: k := 1 - float32(a)*inv - c.Pix[di] = unorm8(float32(src[0])*inv + float32(c.Pix[di])*inv*k) - c.Pix[di+1] = unorm8(float32(src[1])*inv + float32(c.Pix[di+1])*inv*k) - c.Pix[di+2] = unorm8(float32(src[2])*inv + float32(c.Pix[di+2])*inv*k) + c.Pix[di] = unorm8(float32(sr)*inv + float32(c.Pix[di])*inv*k) + c.Pix[di+1] = unorm8(float32(sg)*inv + float32(c.Pix[di+1])*inv*k) + c.Pix[di+2] = unorm8(float32(sb)*inv + float32(c.Pix[di+2])*inv*k) c.Pix[di+3] = unorm8(float32(a)*inv + float32(c.Pix[di+3])*inv*k) } src = src[4:] @@ -285,6 +311,19 @@ func drawPremultipliedLabel(c *Canvas, area render.Scissor, l *Label) { } } +// imageMask is how much of device pixel (x, y) an image label draws: its rounded +// corner coverage times its opacity. A square, opaque image covers fully. +func imageMask(l *Label, x, y int) float32 { + if !l.Image { + return 1 + } + mask := 1 - l.Fade + if l.Radius > 0 { + mask *= Coverage(scene.Rect{X: float32(l.X), Y: float32(l.Y), Width: float32(l.Width), Height: float32(l.Height)}, l.Radius, 1, x, y) + } + return mask +} + // drawLCDLabel tints the per-channel coverage of white text with color and // composites it over the target, the blend the GPU's text_lcd shader does: // each channel keeps 1 minus its own coverage, and alpha keeps 1 minus the diff --git a/internal/reloadwire/codec.go b/internal/reloadwire/codec.go index ee9dfdf55..cc6dc4bb8 100644 --- a/internal/reloadwire/codec.go +++ b/internal/reloadwire/codec.go @@ -523,6 +523,8 @@ func encodeCanvas(value CanvasSnapshot) ([]byte, error) { result.u32(image.Bitmap.Version) encodeRect(&result, image.Source) encodeRect(&result, image.Bounds) + result.f32(image.Radius) + result.f32(image.Fade) result.u16(image.Layer) encodeRect(&result, image.ClipOf) result.bool(image.HasClip) @@ -655,7 +657,8 @@ func decodeCanvas(data []byte) (CanvasSnapshot, error) { ID: value.u64(), Version: value.u32(), } result.Images[index] = gfx.Image{ - Bitmap: bitmap, Source: decodeRect(&value), Bounds: decodeRect(&value), Layer: value.u16(), + Bitmap: bitmap, Source: decodeRect(&value), Bounds: decodeRect(&value), + Radius: value.f32(), Fade: value.f32(), Layer: value.u16(), ClipOf: decodeRect(&value), HasClip: value.bool(), Order: value.u32(), } invalid := bitmap.Width <= 0 || bitmap.Height <= 0 || bitmap.Width > MaxFrameBytes/4 || bitmap.Stride < bitmap.Width*4 diff --git a/internal/semantic/tree.go b/internal/semantic/tree.go index 0d3a6cfc3..36a256ac0 100644 --- a/internal/semantic/tree.go +++ b/internal/semantic/tree.go @@ -30,6 +30,7 @@ const ( RoleHeading RoleStatus RoleSeparator + RoleProgress ) // Operation describes an incremental accessibility-tree update. diff --git a/ui/leaves_paint.go b/ui/leaves_paint.go index 4126b064d..9dd9e8893 100644 --- a/ui/leaves_paint.go +++ b/ui/leaves_paint.go @@ -2,12 +2,14 @@ package ui import ( "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" ) func paintProgress(f *Frame, n *Node) { r := n.Rect if n.Natural >= 0 { components.Progress(f.Surface, f.Palette, r, n.Natural) + paintProgressHit(f, n, r, n.Natural) return } canvas := f.Surface @@ -30,6 +32,24 @@ func paintProgress(f *Frame, n *Node) { canvas.Clip(r) canvas.Rounded(Rect{X: x, Y: r.Y, Width: segment, Height: r.Height}, r.Height/2, f.Palette.Primary) canvas.Unclip() + paintProgressHit(f, n, r, -1) +} + +// paintProgressHit declares the accessible progress bar: a read-only range for a +// determinate bar, no number while it is indeterminate, and never a keyboard stop +// or a press target. A bar is exposed when it is named: Label is what assistive +// technology announces, and an unnamed bar would be an empty node that also took +// the pointer from whatever holds it. +func paintProgressHit(f *Frame, n *Node, r Rect, fraction float32) { + if n.ID.IsZero() || n.Label == "" { + return + } + options := gfx.HitOptions{Role: gfx.RoleProgressBar, SkipFocus: true, Range: gfx.ValueRange{Min: 0, Max: 100}} + if fraction >= 0 { + options.Range.Set = true + options.Range.Now = float64(min(max(fraction, 0), 1)) * 100 + } + f.Surface.HitWithOptions(n.ID, r, n.Label, options) } func paintSpinner(f *Frame, n *Node) { diff --git a/ui/progress_page_test.go b/ui/progress_page_test.go new file mode 100644 index 000000000..bac61c93e --- /dev/null +++ b/ui/progress_page_test.go @@ -0,0 +1,87 @@ +package ui_test + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A named Progress is a progress bar to assistive technology: a read-only range +// from 0 to 100 at the fraction, never a keyboard stop. +func TestNamedProgressIsAProgressBar(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(10).Children(func() { + ui.Progress(c, 0.64).Label("Uploading") + }) + }) + snapshot := d.driver.Snapshot() + var hit gfx.Hit + for _, h := range snapshot.Hits { + if h.Role == gfx.RoleProgressBar { + hit = h + } + } + if hit.Role != gfx.RoleProgressBar { + t.Fatalf("no progressbar hit in %+v", snapshot.Hits) + } + if !hit.Range.Set || math.Abs(hit.Range.Now-64) > 0.01 || hit.Range.Min != 0 || hit.Range.Max != 100 { + t.Errorf("range = %+v, want 64 of 0..100", hit.Range) + } + if hit.Focusable { + t.Errorf("progress bar is a keyboard stop: %+v", hit) + } + if hit.Label != "Uploading" { + t.Errorf("label = %q, want Uploading", hit.Label) + } + + nodes := d.driver.Accessibility() + found := false + for _, node := range nodes { + if node.ID != hit.ID { + continue + } + found = true + if node.Role != gfx.RoleProgressBar { + t.Errorf("accessible role = %v, want progressbar", node.Role) + } + if !node.Range.Set || math.Abs(node.Range.Now-64) > 0.01 { + t.Errorf("accessible range = %+v, want 64 of 0..100", node.Range) + } + if node.Label != "Uploading" { + t.Errorf("accessible label = %q", node.Label) + } + } + if !found { + t.Error("the progress bar is missing from the accessibility tree") + } +} + +// An indeterminate bar reports no number, and an unnamed bar declares no node: +// a bare progress bar would otherwise take the pointer from the row holding it. +func TestUnnamedAndIndeterminateProgress(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(10).Children(func() { + ui.Progress(c, 0.3) + ui.Progress(c, 0).Label("Working").Indeterminate() + }) + }) + snapshot := d.driver.Snapshot() + bars := 0 + for _, hit := range snapshot.Hits { + if hit.Role != gfx.RoleProgressBar { + continue + } + bars++ + if hit.Label != "Working" { + t.Errorf("unnamed progress declared a bar: %+v", hit) + } + if hit.Range.Set { + t.Errorf("indeterminate bar reported a number: %+v", hit.Range) + } + } + if bars != 1 { + t.Errorf("%d progress bars declared, want only the named one", bars) + } +} From 4f8466c434bf66cb1b67ad51a01320bce8dc8c1a Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Fri, 20 Nov 2026 21:48:02 -0800 Subject: [PATCH 14/16] test(darwin): compare Dock icon colors across display profiles --- internal/platform/darwin/testdata/status_item.m | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/platform/darwin/testdata/status_item.m b/internal/platform/darwin/testdata/status_item.m index 4030f411d..6e077bbac 100644 --- a/internal/platform/darwin/testdata/status_item.m +++ b/internal/platform/darwin/testdata/status_item.m @@ -68,8 +68,12 @@ int main(void) { NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[[NSApp applicationIconImage] TIFFRepresentation]]; NSColor *pixel = [[rep colorAtX:rep.pixelsWide / 2 y:rep.pixelsHigh / 2] colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]]; - int matches = pixel != nil && (color == 0 ? pixel.redComponent > 0.9 && pixel.blueComponent < 0.1 - : pixel.blueComponent > 0.9 && pixel.redComponent < 0.1); + // AppKit can color-manage the pixels when it snapshots the Dock image. + // Distinguish the two icon colors without requiring device-specific RGB values. + CGFloat primary = color == 0 ? pixel.redComponent : pixel.blueComponent; + CGFloat other = color == 0 ? pixel.blueComponent : pixel.redComponent; + int matches = pixel != nil && rep.pixelsWide == icon.size && rep.pixelsHigh == icon.size && + primary > other && primary > pixel.greenComponent && pixel.alphaComponent > 0; if (!matches) { fprintf(stderr, "Dock image %ldx%ld center: %s\n", (long)rep.pixelsWide, (long)rep.pixelsHigh, [[pixel description] UTF8String]); From 9bb305b540a9cc8c99be0ae285a63c8d55a9d1ac Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Fri, 20 Nov 2026 21:57:22 -0800 Subject: [PATCH 15/16] test(windows): check the frame shader layout with image shaping --- internal/platform/windows/api_windows_test.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/internal/platform/windows/api_windows_test.go b/internal/platform/windows/api_windows_test.go index 6e2f58b1a..eb95872b1 100644 --- a/internal/platform/windows/api_windows_test.go +++ b/internal/platform/windows/api_windows_test.go @@ -49,7 +49,7 @@ func TestNativeStructureABI(t *testing.T) { {"DWRITE_LINE_METRICS", unsafe.Sizeof(lineMetrics{}), 24}, {"DWRITE_TEXT_METRICS", unsafe.Sizeof(textMetrics{}), 36}, {"rectangle shader instance", unsafe.Sizeof(rectangleInstance{}), rectangleInstanceBytes}, - {"frame shader constants", unsafe.Sizeof(frameConstants{}), 64}, + {"frame shader constants", unsafe.Sizeof(frameConstants{}), 80}, {"DEVMODEW", unsafe.Sizeof(displayMode{}), 220}, } { if layout.size != layout.want { @@ -63,8 +63,21 @@ func TestNativeStructureABI(t *testing.T) { if textureIID != wantTextureIID { t.Fatal("ID3D11Texture2D GUID mismatch") } - if offset := unsafe.Offsetof(frameConstants{}.InstanceOffset); offset != 8 { - t.Fatalf("frame shader instance offset = %d, want 8", offset) + // Match the registers of Frame in shaders/scene.hlsl. + for _, field := range []struct { + name string + offset uintptr + want uintptr + }{ + {"instanceOffset", unsafe.Offsetof(frameConstants{}.InstanceOffset), 8}, + {"textBounds", unsafe.Offsetof(frameConstants{}.Bounds), 16}, + {"textColor", unsafe.Offsetof(frameConstants{}.TextColor), 32}, + {"textShape", unsafe.Offsetof(frameConstants{}.TextShape), 48}, + {"pixelSize", unsafe.Offsetof(frameConstants{}.PixelSize), 64}, + } { + if field.offset != field.want { + t.Errorf("frame shader %s offset = %d, want %d", field.name, field.offset, field.want) + } } } From 4a007bc55dffcdc12038e7f37b138aa79fa17500 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Fri, 20 Nov 2026 21:58:58 -0800 Subject: [PATCH 16/16] test(darwin): check the Dock icon size in points --- internal/platform/darwin/testdata/status_item.m | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/internal/platform/darwin/testdata/status_item.m b/internal/platform/darwin/testdata/status_item.m index 6e077bbac..a594d730b 100644 --- a/internal/platform/darwin/testdata/status_item.m +++ b/internal/platform/darwin/testdata/status_item.m @@ -65,14 +65,17 @@ int main(void) { rgba[i + 2] = color == 0 ? 0 : 255; } check(viva_application_update_icon(icon) == 1, "Dock update accepted"); - NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[[NSApp applicationIconImage] TIFFRepresentation]]; + NSImage *dockIcon = [NSApp applicationIconImage]; + NSSize points = NSMakeSize(icon.size / 2.0, icon.size / 2.0); + check(NSEqualSizes(dockIcon.size, points), "Dock keeps the expected size in points"); + NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[dockIcon TIFFRepresentation]]; NSColor *pixel = [[rep colorAtX:rep.pixelsWide / 2 y:rep.pixelsHigh / 2] colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]]; - // AppKit can color-manage the pixels when it snapshots the Dock image. - // Distinguish the two icon colors without requiring device-specific RGB values. + // AppKit can resample and color-manage the snapshot for the current display. + // Distinguish the two icon colors independently of scale and color profile. CGFloat primary = color == 0 ? pixel.redComponent : pixel.blueComponent; CGFloat other = color == 0 ? pixel.blueComponent : pixel.redComponent; - int matches = pixel != nil && rep.pixelsWide == icon.size && rep.pixelsHigh == icon.size && + int matches = pixel != nil && primary > other && primary > pixel.greenComponent && pixel.alphaComponent > 0; if (!matches) { fprintf(stderr, "Dock image %ldx%ld center: %s\n", (long)rep.pixelsWide, (long)rep.pixelsHigh,