From 54981a3c52fe2beed47df555206cec6e3e03e9a2 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 20 Nov 2026 19:20:01 +0800 Subject: [PATCH 1/3] feat(ui): compose themed buttons and joined icon actions Resolve button surfaces through the typed element style and box model. Allow caller-owned content in themed buttons and add icon-only actions with selection semantics to the public button group. Paired Motty change: use joined icon actions for note view modes and pin this framework commit in its CI. Reusable appearance and input primitives stay in Viva; note mode persistence stays in Motty. --- base/accessors.go | 4 + base/box.go | 30 ++- base/button_node_test.go | 275 +++++++++++++++++++++++++ base/frame.go | 59 +++--- base/hooks.go | 10 + base/paint.go | 14 +- base/recipe.go | 102 ++++++++- base/style.go | 24 ++- cmd/viva/templates/button.go.txt | 110 ++++++---- cmd/viva/templates/button_group.go.txt | 12 +- cmd/viva/templates/split_button.go.txt | 2 +- components/button.go | 110 ++++++---- components/button_group.go | 12 +- components/doc.go | 6 +- components/split_button.go | 2 +- style/button.go | 48 +++++ ui/button_density_bench_test.go | 65 ++++++ ui/buttongroup/buttongroup.go | 35 +++- ui/buttongroup/icons_test.go | 91 ++++++++ ui/controls_paint.go | 104 ++++++---- ui/hooks_install.go | 1 + ui/recipe_paint.go | 12 ++ 22 files changed, 960 insertions(+), 168 deletions(-) create mode 100644 base/button_node_test.go create mode 100644 style/button.go create mode 100644 ui/button_density_bench_test.go create mode 100644 ui/buttongroup/icons_test.go diff --git a/base/accessors.go b/base/accessors.go index 71dbe238d..f51583bf1 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -2136,3 +2136,7 @@ func NewTreeRow(index, key int, node int32, gen uint32, item style.TreeItem) Tre // SetRectsCells writes the cell rectangle scratch of Widgets. func (x *Widgets) SetRectsCells(v []Rect) { x.rects = v } + +// GetButtonLook reads the look the recipe gave the themed button being painted, for the +// styled painting layer that paints its content. +func (x *Frame) GetButtonLook() style.ButtonLook { return x.buttonPainted } diff --git a/base/box.go b/base/box.go index 4329ea81f..8a419b5d9 100644 --- a/base/box.go +++ b/base/box.go @@ -29,9 +29,23 @@ func (b Box) N() *Node { return &b.f.Nodes[b.i] } +// The sides of Pad a caller set, as Node.PadSet holds them. +const ( + padTop uint8 = 1 << iota + padRight + padBottom + padLeft +) + // Children declares what is inside the element. fn runs at once, and is not kept. +// +// A Button given Children holds what they declare in place of its label and icon: it is +// 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 { - b.N() + if b.N().Kind == kindButton { + b.f.buttonHoldsChildren(b.i) + } saved := b.f.Parent b.f.Parent = b.i b.N().Flags |= flagChildren @@ -172,36 +186,36 @@ func (b Box) Shrink(v float32) Box { func (b Box) Pad(v float32) Box { return b.PadSides(v, v, v, v) } func (b Box) PadX(v float32) Box { n := b.N() - n.Pad[1], n.Pad[3], n.Flags = v, v, n.Flags|flagSetPad + n.Pad[1], n.Pad[3], n.Flags, n.PadSet = v, v, n.Flags|flagSetPad, n.PadSet|padRight|padLeft return b } func (b Box) PadY(v float32) Box { n := b.N() - n.Pad[0], n.Pad[2], n.Flags = v, v, n.Flags|flagSetPad + n.Pad[0], n.Pad[2], n.Flags, n.PadSet = v, v, n.Flags|flagSetPad, n.PadSet|padTop|padBottom return b } func (b Box) PadTop(v float32) Box { n := b.N() n.Pad[0] = v - n.Flags |= flagSetPad + n.Flags, n.PadSet = n.Flags|flagSetPad, n.PadSet|padTop return b } func (b Box) PadRight(v float32) Box { n := b.N() n.Pad[1] = v - n.Flags |= flagSetPad + n.Flags, n.PadSet = n.Flags|flagSetPad, n.PadSet|padRight return b } func (b Box) PadBottom(v float32) Box { n := b.N() n.Pad[2] = v - n.Flags |= flagSetPad + n.Flags, n.PadSet = n.Flags|flagSetPad, n.PadSet|padBottom return b } func (b Box) PadLeft(v float32) Box { n := b.N() n.Pad[3] = v - n.Flags |= flagSetPad + n.Flags, n.PadSet = n.Flags|flagSetPad, n.PadSet|padLeft return b } func (b Box) Margin(v float32) Box { return b.MarginSides(v, v, v, v) } @@ -225,7 +239,7 @@ func (b Box) MarginLeft(v float32) Box { } func (b Box) PadSides(top, right, bottom, left float32) Box { n := b.N() - n.Pad, n.Flags = [4]float32{top, right, bottom, left}, n.Flags|flagSetPad + n.Pad, n.Flags, n.PadSet = [4]float32{top, right, bottom, left}, n.Flags|flagSetPad, padTop|padRight|padBottom|padLeft return b } func (b Box) MarginSides(top, right, bottom, left float32) Box { diff --git a/base/button_node_test.go b/base/button_node_test.go new file mode 100644 index 000000000..fca19723f --- /dev/null +++ b/base/button_node_test.go @@ -0,0 +1,275 @@ +package base_test + +import ( + "testing" + + . "github.com/vivaui/viva/base" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// A themed Button is an element like any other: Pad, Weight and Color on it are the +// padding, weight and color of its content, and its surface, its hit region and the room +// it takes in the layout are one rectangle. + +type buttonProbe struct { + box Rect + surface Rect // the first rectangle painted + hit Rect + label gfx.Text + texts []gfx.Text + canvas *gfx.Canvas +} + +func probeButton(t *testing.T, state func(*gfx.Canvas), declare func(f *Frame) Box) buttonProbe { + t.Helper() + var view View + canvas := testCanvas() + if state != nil { + state(canvas) + } + var box Box + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 600, Height: 200}, func(f *Frame) { + f.Row().Items(Start).Children(func() { box = declare(f) }) + }) + p := buttonProbe{box: box.Rect(), texts: canvas.Texts(), canvas: canvas} + if rects := canvas.Rectangles(); len(rects) > 0 { + p.surface = rects[0].Bounds + } + if hits := canvas.Hits(); len(hits) > 0 { + p.hit = hits[0].Bounds + } + if len(p.texts) > 0 { + p.label = p.texts[0] + } + return p +} + +// textMidX is where a label's glyphs are centered across: the middle of the width the +// canvas measures, from the origin it placed them at. +func textMidX(canvas *gfx.Canvas, text gfx.Text) float32 { + return text.Bounds.X + canvas.TextWidthWeight(text.Value, text.Style.Size, text.Style.Weight)/2 +} + +func TestButtonPadIsThePaddingOfItsContent(t *testing.T) { + plain := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save") }) + padded := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save").PadX(30) }) + // The padding either side of the label is the caller's instead of the size's. + if got, want := padded.box.Width-plain.box.Width, float32(2*(30-10)); got != want { + t.Errorf("PadX(30) widened the button by %v, want %v", got, want) + } + for name, p := range map[string]buttonProbe{"plain": plain, "padded": padded} { + if p.surface != p.box || p.hit != p.box { + t.Errorf("%s: layout %v, surface %v, hit %v: want one rectangle", name, p.box, p.surface, p.hit) + } + if mid, want := textMidX(p.canvas, p.label), p.box.X+p.box.Width/2; mid < want-0.01 || mid > want+0.01 { + t.Errorf("%s: the label is centered on %v, the button on %v", name, mid, want) + } + } +} + +// Padding one side leaves the others as the size gives them: the recipe pads what the +// caller did not. +func TestButtonPaddedOnOneSideKeepsTheOthers(t *testing.T) { + plain := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save") }) + top := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save").PadTop(2) }) + if top.box.Width != plain.box.Width { + t.Errorf("PadTop widened the button from %v to %v", plain.box.Width, top.box.Width) + } + left := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save").PadLeft(40) }) + if got, want := left.box.Width-plain.box.Width, float32(40-10); got != want { + t.Errorf("PadLeft(40) widened the button by %v, want %v", got, want) + } +} + +// A button grows to hold padding that its height does not, and keeps its size's height +// when the padding fits in it. +func TestButtonGrowsToItsVerticalPadding(t *testing.T) { + theme := gfx.LightTheme() + small := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save").PadY(2) }) + if small.box.Height != theme.Metrics.ControlHeight { + t.Errorf("PadY(2) made the button %v tall, want its size's %v", small.box.Height, theme.Metrics.ControlHeight) + } + big := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save").PadY(20) }) + if big.box.Height <= theme.Metrics.ControlHeight { + t.Errorf("PadY(20) left the button %v tall", big.box.Height) + } + if big.surface != big.box || big.hit != big.box { + t.Errorf("layout %v, surface %v, hit %v: want one rectangle", big.box, big.surface, big.hit) + } +} + +func TestButtonWeightAndColorStyleItsLabel(t *testing.T) { + plain := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save").Outline() }) + red := gfx.Color{Red: 1, Alpha: 1} + styled := probeButton(t, nil, func(f *Frame) Box { return f.Button(save, "Save").Outline().Weight(gfx.WeightBold).Color(red) }) + if styled.label.Style.Weight != gfx.WeightBold || plain.label.Style.Weight == gfx.WeightBold { + t.Errorf("weights: plain %v, styled %v", plain.label.Style.Weight, styled.label.Style.Weight) + } + if styled.label.Style.Color != red || plain.label.Style.Color == red { + t.Errorf("colors: plain %v, styled %v", plain.label.Style.Color, styled.label.Style.Color) + } +} + +// A button is restyled with the looks any element takes, over what its recipe gives. +func TestButtonTakesHoverAndPressedLooks(t *testing.T) { + theme := gfx.LightTheme() + over := gfx.Color{Red: 0.2, Green: 0.9, Blue: 0.4, Alpha: 1} + declare := func(f *Frame) Box { + return f.Button(save, "Save").Outline().Hover(Look{}.Background(over)) + } + rest := probeButton(t, nil, declare) + hovered := probeButton(t, func(c *gfx.Canvas) { c.SetInteraction(save, gfx.ID{}, gfx.ID{}, false) }, declare) + fill := func(p buttonProbe) gfx.Color { + rects := p.canvas.Rectangles() + return rects[len(rects)-1].Color // the fill is painted over the line it sits in + } + if fill(hovered) != over { + t.Errorf("hovered fill = %v, want %v", fill(hovered), over) + } + if fill(rest) == over || fill(rest) != theme.Background { + t.Errorf("resting fill = %v, want the recipe's %v", fill(rest), theme.Background) + } +} + +// What a button is given as Children is its content, in place of its label and icon; the +// button around it is the same one, as tall as its size and as wide as its content and Pad. +func TestButtonHoldsChildrenInPlaceOfItsLabel(t *testing.T) { + theme := gfx.LightTheme() + 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, "Deploy").Icon(icon).Children(func() { + f.Text("Go") + f.Text("⌘D") + }) + }) + for _, text := range p.texts { + if text.Value == "Deploy" { + t.Errorf("the label was painted over the children: %+v", p.texts) + } + } + if len(p.texts) != 2 { + t.Fatalf("texts = %d, want the two children", len(p.texts)) + } + if p.box.Height != theme.Metrics.ControlHeight { + t.Errorf("the button is %v tall, want its size's %v", p.box.Height, theme.Metrics.ControlHeight) + } + if p.surface != p.box || p.hit != p.box { + t.Errorf("layout %v, surface %v, hit %v: want one rectangle", p.box, p.surface, p.hit) + } + hits := p.canvas.Hits() + if len(hits) != 1 || hits[0].Role != gfx.RoleButton || hits[0].Label != "Deploy" || !hits[0].Focusable { + t.Errorf("hits = %+v, want one focusable button named by its label", hits) + } + // The content is inside the padding, in order, with the gap between. + first, second := p.texts[0].Bounds, p.texts[1].Bounds + if first.X < p.box.X+10 || second.X+second.Width > p.box.X+p.box.Width-10 || second.X < first.X+first.Width { + t.Errorf("children at %v and %v do not sit in order inside the button %v", first, second, p.box) + } + if gap := second.X - (first.X + first.Width); gap != 8 { + t.Errorf("the children are %v apart, want the button's gap of 8", gap) + } +} + +// Children take the color the recipe gives the label, in every state and variant, unless +// they have a color of their own; so a destructive or a disabled button needs nothing said +// of what is inside it. +func TestButtonChildrenTakeTheLabelColor(t *testing.T) { + theme := gfx.LightTheme() + own := gfx.Color{Blue: 1, Alpha: 1} + cases := []struct { + name string + variant func(Box) Box + state func(*gfx.Canvas) + disable bool + }{ + {"default", func(b Box) Box { return b }, nil, false}, + {"outline", func(b Box) Box { return b.Outline() }, nil, false}, + {"destructive", func(b Box) Box { return b.Destructive() }, nil, false}, + {"disabled", func(b Box) Box { return b }, nil, true}, + } + for _, tc := range cases { + p := probeButton(t, tc.state, func(f *Frame) Box { + b := tc.variant(f.Button(save, "x")) + if tc.disable { + b = b.Disabled(true) + } + return b.Children(func() { + f.Text("inherits") + f.Text("own").Color(own) + }) + }) + look := components.ButtonRecipe(theme, variantOf(tc.name), gfx.State{Disabled: tc.disable}) + if got := p.texts[0].Style.Color; got != look.Foreground { + t.Errorf("%s: the child is %v, want the label color %v", tc.name, got, look.Foreground) + } + if got := p.texts[1].Style.Color; got != own { + t.Errorf("%s: a child with a color of its own is %v, want %v", tc.name, got, own) + } + } +} + +func variantOf(name string) components.ButtonVariant { + switch name { + case "outline": + return components.ButtonOutline + case "destructive": + return components.ButtonDestructive + } + return components.ButtonDefault +} + +// A button given Children and one that paints its label are the same button to the +// keyboard and to the page: the same surface, the same focus ring. +func TestButtonWithChildrenIsDressedAsOneWithALabel(t *testing.T) { + focused := func(c *gfx.Canvas) { c.SetInteraction(gfx.ID{}, gfx.ID{}, save, true) } + label := probeButton(t, focused, func(f *Frame) Box { return f.Button(save, "Save").Outline() }) + held := probeButton(t, focused, func(f *Frame) Box { + return f.Button(save, "Save").Outline().Children(func() { f.Text("Save") }) + }) + a, b := label.canvas.Rectangles(), held.canvas.Rectangles() + if len(a) != len(b) || len(a) == 0 { + t.Fatalf("rectangles: %d with a label, %d with children", len(a), len(b)) + } + for i := range a { + if a[i].Color != b[i].Color || a[i].Radius != b[i].Radius { + t.Errorf("rectangle %d: %+v with a label, %+v with children", i, a[i], b[i]) + } + } +} + +// Whatever a button is padded, sized and styled with, one rectangle is its layout, its +// surface and its hit region, and its label is inside it. +func TestButtonIsOneRectangleWhateverItIsGiven(t *testing.T) { + icon := gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(4, 4), gfx.LineTo(20, 20)}} + declares := map[string]func(f *Frame) Box{ + "pad": func(f *Frame) Box { return f.Button(save, "Save").Pad(14) }, + "padX": func(f *Frame) Box { return f.Button(save, "Save").PadX(3) }, + "padLeft": func(f *Frame) Box { return f.Button(save, "Save").PadLeft(25) }, + "icon+padX": func(f *Frame) Box { return f.Button(save, "Save").Icon(icon).PadX(22) }, + "small": func(f *Frame) Box { return f.Button(save, "Save").Small().Ghost() }, + "large pad": func(f *Frame) Box { return f.Button(save, "Save").Large().PadX(5) }, + "height": func(f *Frame) Box { return f.Button(save, "Save").Height(50) }, + "font+bold": func(f *Frame) Box { return f.Button(save, "Save").FontSize(18).Bold() }, + "gap": func(f *Frame) Box { return f.Button(save, "Save").Icon(icon).Gap(20) }, + "icon only": func(f *Frame) Box { return f.Button(save, "").IconOnly().Icon(icon) }, + "link+pad": func(f *Frame) Box { return f.Button(save, "Save").Link().Pad(9) }, + "empty pad": func(f *Frame) Box { return f.Button(save, "").PadX(0) }, + "destructiv": func(f *Frame) Box { return f.Button(save, "Delete").Destructive().PadX(16) }, + } + for name, declare := range declares { + p := probeButton(t, nil, declare) + if p.hit != p.box { + t.Errorf("%s: layout %v, hit %v", name, p.box, p.hit) + } + if p.surface != (Rect{}) && p.surface != p.box { + t.Errorf("%s: layout %v, surface %v", name, p.box, p.surface) + } + for _, text := range p.texts { + if text.Bounds.X < p.box.X-0.01 || text.Bounds.X+p.canvas.TextWidthWeight(text.Value, text.Style.Size, text.Style.Weight) > p.box.X+p.box.Width+0.01 { + t.Errorf("%s: the label %v is outside the button %v", name, text.Bounds, p.box) + } + } + } +} diff --git a/base/frame.go b/base/frame.go index 12a1f8c33..ccf84897c 100644 --- a/base/frame.go +++ b/base/frame.go @@ -123,6 +123,7 @@ 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 @@ -219,29 +220,35 @@ type Extra struct { // gives the frame the declarations. Tests and previews that need the engine // paint through a View; applications do not reach a frame. type Frame struct { - Surface *gfx.Canvas - Palette Theme - styles *Styles // the page's recipe overrides; nil keeps the theme's - 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 + Surface *gfx.Canvas + Palette Theme + 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 // 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. @@ -615,7 +622,11 @@ func (f *Frame) Button(ID gfx.ID, Label string) Box { b := f.Box(kindButton) n := &f.Nodes[b.i] n.ID, n.Label = ID, Label - n.Flags |= flagHasHit + n.Flags |= flagHasHit | flagThemed + // What a button holds, once Children gives it content of its own, is a row centered + // on both axes with the gap an icon keeps from its label, as a ButtonBase's is. Each + // is the element's to change with the call any element takes. + 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 d6e1592e5..4aa391d2c 100644 --- a/base/hooks.go +++ b/base/hooks.go @@ -31,6 +31,7 @@ var ( PaintTreeRow func(s *TreeState, i int, box Box) 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 @@ -146,6 +147,15 @@ func (f *Frame) Popover(anchor Box, spec PopoverSpec) Box { return Box{} } +// buttonLook is the look the theme's recipe gives the button element n in a state: the +// element's own ButtonRecipe, else the page's Styles.Button, else the theme's. +func (f *Frame) buttonLook(n *Node, palette *Theme, state gfx.State) style.ButtonLook { + if ButtonLookFn != nil { + return ButtonLookFn(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/paint.go b/base/paint.go index 777679845..46ad483b1 100644 --- a/base/paint.go +++ b/base/paint.go @@ -48,6 +48,10 @@ func (f *Frame) PaintChild(i int32) { s.scope = canvas.FocusScope() } style := f.resolve(n, extra) + if n.Kind == kindContainer && n.Flags&flagThemed != 0 { + defer func(color Color, has bool) { f.inherited, f.hasInherited = color, has }(f.inherited, f.hasInherited) + f.inherited, f.hasInherited = style.Color, true + } // What the element is drawn with fades with it and with what it is inside; the // controls inside it are painted with a theme faded the same way. parentOpacity, parentTheme := f.Opacity, Theme{} @@ -68,8 +72,8 @@ func (f *Frame) PaintChild(i int32) { canvas.ElevateFaded(r, n.Radius, style.shadow, f.Opacity) } switch { - case n.BorderWidth > 0 && !style.dashed && extra.gradient == 0 && f.Opacity >= 1 && background.Alpha >= 1: - canvas.RoundedBorder(r, n.Radius, n.BorderWidth, border, background) + 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) 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 @@ -86,11 +90,11 @@ func (f *Frame) PaintChild(i int32) { if extra.gradient != 0 { f.paintGradient(n, extra) } - if n.BorderWidth > 0 { + if style.borderWidth > 0 { if style.dashed { - canvas.DashedRoundedOutline(n.Rect, n.Radius, n.BorderWidth, border) + canvas.DashedRoundedOutline(n.Rect, n.Radius, style.borderWidth, border) } else { - canvas.RoundedOutline(r, n.Radius, n.BorderWidth, border) + canvas.RoundedOutline(r, n.Radius, style.borderWidth, border) } } } diff --git a/base/recipe.go b/base/recipe.go index 671cfb06f..09d62d0fb 100644 --- a/base/recipe.go +++ b/base/recipe.go @@ -2,6 +2,7 @@ package base import ( "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) // A control declared with the theme's look (Input, and the controls that follow it) is a @@ -53,15 +54,54 @@ func (f *Frame) applyRecipes() { if n.Kind == kindTextarea && n.MinS[AxisY] == 0 { n.MinS[AxisY] = 64 // the official minimum height } + case kindButton, kindContainer: + 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. +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 + } + if n.PadSet&padRight == 0 { + n.Pad[1] = padding + } + if n.PadSet&padLeft == 0 { + n.Pad[3] = padding + } + if n.Kind != kindContainer || n.Size[AxisY].Kind != dimAuto { + 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 + } + n.Size[AxisY] = Dimension{dimPx, height} +} + // themedDefaults fills in, for the state the element is in now, the colors of the resolved // look the element did not set itself. func (f *Frame) themedDefaults(n *Node, Extra *Extra, s *resolved) { var state gfx.State switch n.Kind { + case kindButton, kindContainer: + f.themedButtonDefaults(n, Extra, s) + return case kindInput: snapshot := &WidgetsOf(f).inputs[n.Aux] state = gfx.State{Focused: snapshot.Focused || f.Focused(n), Invalid: snapshot.Invalid, Disabled: snapshot.Disabled} @@ -94,7 +134,7 @@ 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 { + 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)} } @@ -131,3 +171,63 @@ func textEntryInsets(Palette *Theme, k Kind) (x, y float32) { } return x, y } + +// themedButtonDefaults fills in, for the state the button is in now, what the recipe gives +// the resolved look and the element did not set itself: the fill, the border and its width, +// the shadow, the ring and the color of its content. A Hover, Pressed or Focus look applies +// over them as it does over any element. +func (f *Frame) themedButtonDefaults(n *Node, Extra *Extra, s *resolved) { + theme := f.RecipeTheme(n, &f.scratch.theme) + var state gfx.State + 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 + look := f.buttonLook(n, theme, state) + f.buttonPainted = look + if n.Flags&flagSetBackground == 0 { + s.Background = gfx.Color{} + if look.Filled { + s.Background = look.Background + } + } + // Over an opaque page a filled border is flattened onto it and painted as one shape + // (RoundedBorder); over a translucent one the fill goes down whole and the line over it. + 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 + } +} + +// 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 + } +} diff --git a/base/style.go b/base/style.go index 8d54e106f..3480ad069 100644 --- a/base/style.go +++ b/base/style.go @@ -282,15 +282,30 @@ type resolved struct { ringWidth, Opacity float32 shadow gfx.ShadowLevel dashed bool + // borderWidth is the width the border is drawn at: the element's own, or a themed + // control's recipe's, which never takes room. splitBorder says to paint the fill + // and then the line over it even where one shape could paint both. + borderWidth float32 + splitBorder bool + // ringFilled paints the ring as a disc under the element rather than a line around + // it, and a nonzero ringLine is the width the line is drawn at: how a control's + // recipe draws its focus ring over an opaque page and over a translucent one. + ringFilled bool + ringLine float32 } func (f *Frame) resolve(n *Node, Extra *Extra) resolved { s := resolved{ Background: n.Background, border: Extra.border, Color: n.Color, ring: Extra.ring, ringWidth: Extra.ringWidth, Opacity: 1 - Extra.fade, shadow: Extra.shadow, dashed: Extra.borderDashed, + borderWidth: n.BorderWidth, } if n.Flags&flagThemed != 0 { f.themedDefaults(n, Extra, &s) + } else if f.hasInherited && n.Flags&flagHasColor == 0 && (n.Kind == kindText || n.Kind == kindIcon) { + // What a themed button holds takes the color its recipe gives its label, in every + // state, unless the content has a color of its own. + s.Color = f.inherited } if Extra.States == 0 { return s @@ -374,7 +389,14 @@ func (f *Frame) paintRing(r Rect, Radius float32, s *resolved) { if Radius > 0 { Radius += w } - f.Surface.RoundedOutline(outer, Radius, w, color) + switch { + case s.ringFilled: + f.Surface.Rounded(outer, Radius, color) + case s.ringLine > 0: + f.Surface.RoundedOutline(outer, Radius, s.ringLine, color) + default: + f.Surface.RoundedOutline(outer, Radius, w, color) + } } // paintGradient draws the gradient of an element over its whole rectangle. diff --git a/cmd/viva/templates/button.go.txt b/cmd/viva/templates/button.go.txt index 0adbcd5cf..017e57471 100644 --- a/cmd/viva/templates/button.go.txt +++ b/cmd/viva/templates/button.go.txt @@ -174,17 +174,15 @@ func (button Button) Disabled() Button { } // The leading icon keeps one square, one gap and one vertical inset in every -// size, so SizeToFit and paint agree and a narrow control shrinks the icon -// instead of drawing it past its own edge. +// size (package style), so SizeToFit and paint agree and a narrow control shrinks +// the icon instead of drawing it past its own edge. const ( - buttonIconSize = 16 - buttonIconGap = 8 - buttonIconInset = 8 + buttonIconSize = style.ButtonIconSize + buttonIconGap = style.ButtonIconGap + buttonIconInset = style.ButtonIconInset ) -func buttonIconExtent(height float32) float32 { - return max(0, min(float32(buttonIconSize), height-buttonIconInset)) -} +func buttonIconExtent(height float32) float32 { return style.ButtonIconExtent(height) } // SizeToFit widens the button to its label plus the selected size padding. func (button Button) SizeToFit(label string) Button { @@ -420,10 +418,10 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { 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, style) + paintButtonLabel(button.canvas, label, text, fontSize, gfx.WeightMedium, style) } } else { - paintButtonLabel(button.canvas, label, button.bounds, fontSize, style) + paintButtonLabel(button.canvas, label, button.bounds, fontSize, gfx.WeightMedium, style) } if !button.id.IsZero() { button.canvas.HitWithOptions(button.id, button.bounds, label, gfx.HitOptions{ @@ -434,30 +432,7 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { } func (button Button) geometry() (height, padding, fontSize float32, iconOnly bool) { - metrics := button.theme.Metrics - height = metrics.ControlHeight - padding = 10 - fontSize = metrics.FontSizeM - switch button.size { - case ButtonSizeXSmall: - height, padding, fontSize = metrics.ControlHeight-8, 8, metrics.FontSizeS - case ButtonSizeSmall: - height = metrics.ControlHeight - 4 - case ButtonSizeLarge: - height = metrics.ControlHeight + 4 - case ButtonSizeIcon: - iconOnly = true - case ButtonSizeIconXSmall: - height, iconOnly = metrics.ControlHeight-8, true - fontSize = metrics.FontSizeS - case ButtonSizeIconSmall: - height, iconOnly = metrics.ControlHeight-4, true - case ButtonSizeIconLarge: - height, iconOnly = metrics.ControlHeight+4, true - } - if height < 20 { - height = 20 - } + height, padding, fontSize, iconOnly = style.ButtonGeometry(button.theme.Metrics, button.size) if button.height > 0 { height = button.height } @@ -639,15 +614,76 @@ func buttonStyleFor(theme *gfx.Theme, variant ButtonVariant, hovered, pressed bo return style } +// ButtonContent is what a button holds when it paints its own content: a leading icon, a +// label, or an icon alone. The button's surface is not part of it; whoever painted the +// surface paints this inside the area the button leaves for its content. +type ButtonContent struct { + Label string + // Icon is the leading icon; an icon with no commands or layers is none. IconTransform + // moves it inside its square without moving the square. + Icon gfx.Icon + IconTransform gfx.IconTransform + // FontSize, Weight and Color style the label, and the icon takes Color. + FontSize float32 + Weight float32 + Color gfx.Color + // Gap is the room between the icon and the label. + Gap float32 + // Height is the height of the button the content is in, which the icon's square follows. + Height float32 + // IconOnly says the button holds the icon alone: the label is then its accessible hint. + IconOnly bool + // Underlined underlines the label, as a hovered link is. + Underlined bool +} + +// PaintButtonContent paints a button's icon and label centered in area and returns the +// hint an icon-only button gives assistive technology, which is its label. It is the +// content half of the paint the Button does: the same placement, the same shrinking of +// the icon when the area is too narrow for it. +func PaintButtonContent(canvas *gfx.Canvas, area gfx.Rect, content ButtonContent) (hint string) { + if canvas == nil || area.Width <= 0 { + return "" + } + look := buttonStyle{foreground: content.Color, underlined: content.Underlined} + label := content.Label + if len(content.Icon.Commands) == 0 && len(content.Icon.Layers) == 0 { + paintButtonLabel(canvas, label, area, content.FontSize, content.Weight, look) + return "" + } + size := min(buttonIconExtent(content.Height), area.Width) + width := size + if !content.IconOnly && label != "" { + width = min(area.Width, width+content.Gap+canvas.TextWidthWeight(label, content.FontSize, content.Weight)) + } + x := area.X + (area.Width-width)/2 + if size > 0 { + canvas.DrawIconTransformed( + content.Icon, + gfx.Rect{X: x, Y: area.Y + (area.Height-size)/2, Width: size, Height: size}, + content.Color, + content.IconTransform, + ) + } + if content.IconOnly { + return label + } + if label != "" { + text := gfx.Rect{X: x + size + content.Gap, Y: area.Y, Width: max(0, width-size-content.Gap), Height: area.Height} + paintButtonLabel(canvas, label, text, content.FontSize, content.Weight, look) + } + return "" +} + // paintButtonLabel centers a button's label and, for a hovered link, underlines it. -func paintButtonLabel(canvas *gfx.Canvas, label string, bounds gfx.Rect, fontSize float32, style buttonStyle) { +func paintButtonLabel(canvas *gfx.Canvas, label string, bounds gfx.Rect, fontSize, weight float32, style buttonStyle) { canvas.LabelCenter(label, bounds, gfx.TextStyle{ - Size: fontSize, Weight: gfx.WeightMedium, Color: style.foreground, + Size: fontSize, Weight: weight, Color: style.foreground, }) if !style.underlined { return } - width := min(canvas.TextWidthWeight(label, fontSize, gfx.WeightMedium), bounds.Width) + width := min(canvas.TextWidthWeight(label, fontSize, weight), bounds.Width) canvas.Fill(gfx.Rect{ X: bounds.X + (bounds.Width-width)/2, Y: bounds.Y + bounds.Height/2 + fontSize*0.6, Width: width, Height: 1, diff --git a/cmd/viva/templates/button_group.go.txt b/cmd/viva/templates/button_group.go.txt index cb7e4552a..d71bbdb5c 100644 --- a/cmd/viva/templates/button_group.go.txt +++ b/cmd/viva/templates/button_group.go.txt @@ -8,6 +8,11 @@ type ButtonGroupOption struct { Label string Variant ButtonVariant Disabled bool + // Icon is the leading glyph. IconOnly keeps Label as the accessible name + // and tooltip without painting it. Selected exposes the caller's choice. + Icon gfx.Icon + IconOnly bool + Selected bool } // ButtonGroupOrientation selects a row or column of connected actions. @@ -114,10 +119,15 @@ func (group ButtonGroup) Paint() ButtonGroupResult { style.foreground.Alpha *= 0.50 } paintJoinedSurface(group.canvas, surface, radius, fill, index, count, vertical) - paintButtonLabel(group.canvas, option.Label, bounds, metrics.FontSizeM, style) + hint := PaintButtonContent(group.canvas, bounds, ButtonContent{ + Label: option.Label, Icon: option.Icon, IconOnly: option.IconOnly, + FontSize: metrics.FontSizeM, Weight: gfx.WeightMedium, Color: style.foreground, + Gap: buttonIconGap, Height: bounds.Height, Underlined: style.underlined, + }) if !option.ID.IsZero() { group.canvas.HitWithOptions(option.ID, bounds, option.Label, gfx.HitOptions{ Role: gfx.RoleButton, Disabled: group.disabled || option.Disabled, + Selected: option.Selected, Hint: hint, }) } if index > 0 { diff --git a/cmd/viva/templates/split_button.go.txt b/cmd/viva/templates/split_button.go.txt index 2b5373867..47109a219 100644 --- a/cmd/viva/templates/split_button.go.txt +++ b/cmd/viva/templates/split_button.go.txt @@ -98,7 +98,7 @@ func (button SplitButton) Paint() SplitButtonResult { if button.options.Disabled { style.foreground.Alpha *= 0.50 } - paintButtonLabel(button.canvas, button.options.Label, geometry.Primary, theme.Metrics.FontSizeM, style) + paintButtonLabel(button.canvas, button.options.Label, geometry.Primary, theme.Metrics.FontSizeM, gfx.WeightMedium, style) icon := button.options.Icon if len(icon.Commands) == 0 && len(icon.Layers) == 0 { icon = chevronDownIcon diff --git a/components/button.go b/components/button.go index 6dc5dcbb7..f1313490d 100644 --- a/components/button.go +++ b/components/button.go @@ -174,17 +174,15 @@ func (button Button) Disabled() Button { } // The leading icon keeps one square, one gap and one vertical inset in every -// size, so SizeToFit and paint agree and a narrow control shrinks the icon -// instead of drawing it past its own edge. +// size (package style), so SizeToFit and paint agree and a narrow control shrinks +// the icon instead of drawing it past its own edge. const ( - buttonIconSize = 16 - buttonIconGap = 8 - buttonIconInset = 8 + buttonIconSize = style.ButtonIconSize + buttonIconGap = style.ButtonIconGap + buttonIconInset = style.ButtonIconInset ) -func buttonIconExtent(height float32) float32 { - return max(0, min(float32(buttonIconSize), height-buttonIconInset)) -} +func buttonIconExtent(height float32) float32 { return style.ButtonIconExtent(height) } // SizeToFit widens the button to its label plus the selected size padding. func (button Button) SizeToFit(label string) Button { @@ -420,10 +418,10 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { 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, style) + paintButtonLabel(button.canvas, label, text, fontSize, gfx.WeightMedium, style) } } else { - paintButtonLabel(button.canvas, label, button.bounds, fontSize, style) + paintButtonLabel(button.canvas, label, button.bounds, fontSize, gfx.WeightMedium, style) } if !button.id.IsZero() { button.canvas.HitWithOptions(button.id, button.bounds, label, gfx.HitOptions{ @@ -434,30 +432,7 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { } func (button Button) geometry() (height, padding, fontSize float32, iconOnly bool) { - metrics := button.theme.Metrics - height = metrics.ControlHeight - padding = 10 - fontSize = metrics.FontSizeM - switch button.size { - case ButtonSizeXSmall: - height, padding, fontSize = metrics.ControlHeight-8, 8, metrics.FontSizeS - case ButtonSizeSmall: - height = metrics.ControlHeight - 4 - case ButtonSizeLarge: - height = metrics.ControlHeight + 4 - case ButtonSizeIcon: - iconOnly = true - case ButtonSizeIconXSmall: - height, iconOnly = metrics.ControlHeight-8, true - fontSize = metrics.FontSizeS - case ButtonSizeIconSmall: - height, iconOnly = metrics.ControlHeight-4, true - case ButtonSizeIconLarge: - height, iconOnly = metrics.ControlHeight+4, true - } - if height < 20 { - height = 20 - } + height, padding, fontSize, iconOnly = style.ButtonGeometry(button.theme.Metrics, button.size) if button.height > 0 { height = button.height } @@ -639,15 +614,76 @@ func buttonStyleFor(theme *gfx.Theme, variant ButtonVariant, hovered, pressed bo return style } +// ButtonContent is what a button holds when it paints its own content: a leading icon, a +// label, or an icon alone. The button's surface is not part of it; whoever painted the +// surface paints this inside the area the button leaves for its content. +type ButtonContent struct { + Label string + // Icon is the leading icon; an icon with no commands or layers is none. IconTransform + // moves it inside its square without moving the square. + Icon gfx.Icon + IconTransform gfx.IconTransform + // FontSize, Weight and Color style the label, and the icon takes Color. + FontSize float32 + Weight float32 + Color gfx.Color + // Gap is the room between the icon and the label. + Gap float32 + // Height is the height of the button the content is in, which the icon's square follows. + Height float32 + // IconOnly says the button holds the icon alone: the label is then its accessible hint. + IconOnly bool + // Underlined underlines the label, as a hovered link is. + Underlined bool +} + +// PaintButtonContent paints a button's icon and label centered in area and returns the +// hint an icon-only button gives assistive technology, which is its label. It is the +// content half of the paint the Button does: the same placement, the same shrinking of +// the icon when the area is too narrow for it. +func PaintButtonContent(canvas *gfx.Canvas, area gfx.Rect, content ButtonContent) (hint string) { + if canvas == nil || area.Width <= 0 { + return "" + } + look := buttonStyle{foreground: content.Color, underlined: content.Underlined} + label := content.Label + if len(content.Icon.Commands) == 0 && len(content.Icon.Layers) == 0 { + paintButtonLabel(canvas, label, area, content.FontSize, content.Weight, look) + return "" + } + size := min(buttonIconExtent(content.Height), area.Width) + width := size + if !content.IconOnly && label != "" { + width = min(area.Width, width+content.Gap+canvas.TextWidthWeight(label, content.FontSize, content.Weight)) + } + x := area.X + (area.Width-width)/2 + if size > 0 { + canvas.DrawIconTransformed( + content.Icon, + gfx.Rect{X: x, Y: area.Y + (area.Height-size)/2, Width: size, Height: size}, + content.Color, + content.IconTransform, + ) + } + if content.IconOnly { + return label + } + if label != "" { + text := gfx.Rect{X: x + size + content.Gap, Y: area.Y, Width: max(0, width-size-content.Gap), Height: area.Height} + paintButtonLabel(canvas, label, text, content.FontSize, content.Weight, look) + } + return "" +} + // paintButtonLabel centers a button's label and, for a hovered link, underlines it. -func paintButtonLabel(canvas *gfx.Canvas, label string, bounds gfx.Rect, fontSize float32, style buttonStyle) { +func paintButtonLabel(canvas *gfx.Canvas, label string, bounds gfx.Rect, fontSize, weight float32, style buttonStyle) { canvas.LabelCenter(label, bounds, gfx.TextStyle{ - Size: fontSize, Weight: gfx.WeightMedium, Color: style.foreground, + Size: fontSize, Weight: weight, Color: style.foreground, }) if !style.underlined { return } - width := min(canvas.TextWidthWeight(label, fontSize, gfx.WeightMedium), bounds.Width) + width := min(canvas.TextWidthWeight(label, fontSize, weight), bounds.Width) canvas.Fill(gfx.Rect{ X: bounds.X + (bounds.Width-width)/2, Y: bounds.Y + bounds.Height/2 + fontSize*0.6, Width: width, Height: 1, diff --git a/components/button_group.go b/components/button_group.go index fc73305a3..d5977ddf1 100644 --- a/components/button_group.go +++ b/components/button_group.go @@ -8,6 +8,11 @@ type ButtonGroupOption struct { Label string Variant ButtonVariant Disabled bool + // Icon is the leading glyph. IconOnly keeps Label as the accessible name + // and tooltip without painting it. Selected exposes the caller's choice. + Icon gfx.Icon + IconOnly bool + Selected bool } // ButtonGroupOrientation selects a row or column of connected actions. @@ -114,10 +119,15 @@ func (group ButtonGroup) Paint() ButtonGroupResult { style.foreground.Alpha *= 0.50 } paintJoinedSurface(group.canvas, surface, radius, fill, index, count, vertical) - paintButtonLabel(group.canvas, option.Label, bounds, metrics.FontSizeM, style) + hint := PaintButtonContent(group.canvas, bounds, ButtonContent{ + Label: option.Label, Icon: option.Icon, IconOnly: option.IconOnly, + FontSize: metrics.FontSizeM, Weight: gfx.WeightMedium, Color: style.foreground, + Gap: buttonIconGap, Height: bounds.Height, Underlined: style.underlined, + }) if !option.ID.IsZero() { group.canvas.HitWithOptions(option.ID, bounds, option.Label, gfx.HitOptions{ Role: gfx.RoleButton, Disabled: group.disabled || option.Disabled, + Selected: option.Selected, Hint: hint, }) } if index > 0 { diff --git a/components/doc.go b/components/doc.go index 9b7394f16..5130076e7 100644 --- a/components/doc.go +++ b/components/doc.go @@ -74,7 +74,9 @@ // - Button: `BeginButton` paints a labeled control with Default, Secondary, // Outline, and Ghost variants; hover, press, and focus states, metrics- // scaled geometry, and the hit declaration are built in. -// `ButtonRecipe` is the look of a variant in a state as plain values. +// `ButtonRecipe` is the look of a variant in a state as plain values, and +// `PaintButtonContent` paints a button's icon and label alone, centered in +// the area a surface the caller painted leaves for them. // - Icon hover: `IconHover` plays one short gesture after an icon-only // control's pointer rests, and `Button.IconTransform` paints the resulting // transform inside the button's hit region. @@ -82,7 +84,7 @@ // edge of a footer, each as wide as its label, shrinking together when // they do not fit. // - Button group: `BeginButtonGroup` joins a row of buttons into one -// bordered control. +// bordered control, with labels or icon-only actions and caller-owned selection. // - Split button: `BeginSplitButton` joins a primary action to a fixed-width, // independently focusable menu trigger while sharing one visual surface. // - Toggle: `BeginToggle` paints a two-state icon button. diff --git a/components/split_button.go b/components/split_button.go index db300cc9d..75c1ffbbd 100644 --- a/components/split_button.go +++ b/components/split_button.go @@ -98,7 +98,7 @@ func (button SplitButton) Paint() SplitButtonResult { if button.options.Disabled { style.foreground.Alpha *= 0.50 } - paintButtonLabel(button.canvas, button.options.Label, geometry.Primary, theme.Metrics.FontSizeM, style) + paintButtonLabel(button.canvas, button.options.Label, geometry.Primary, theme.Metrics.FontSizeM, gfx.WeightMedium, style) icon := button.options.Icon if len(icon.Commands) == 0 && len(icon.Layers) == 0 { icon = chevronDownIcon diff --git a/style/button.go b/style/button.go new file mode 100644 index 000000000..5abcf42d2 --- /dev/null +++ b/style/button.go @@ -0,0 +1,48 @@ +package style + +import "github.com/vivaui/viva/gfx" + +// The leading icon of a button keeps one square, one gap and one vertical inset in every +// size, so measuring and painting agree and a narrow control shrinks the icon instead of +// drawing it past its own edge. +const ( + ButtonIconSize = 16 + ButtonIconGap = 8 + ButtonIconInset = 8 +) + +// ButtonIconExtent is the side of the icon square in a button height tall. +func ButtonIconExtent(height float32) float32 { + return max(0, min(float32(ButtonIconSize), height-ButtonIconInset)) +} + +// ButtonGeometry is what a size gives a button at a theme's metrics: its height, the +// padding either side of its content, the size of its label, and whether it holds an +// icon alone (then it is as wide as it is tall). A caller that asks for a Height or a +// FontSize of its own replaces those two; the rest stays the size's. +func ButtonGeometry(m gfx.Metrics, size Size) (height, padding, fontSize float32, iconOnly bool) { + height = m.ControlHeight + padding = 10 + fontSize = m.FontSizeM + switch size { + case SizeXSmall: + height, padding, fontSize = m.ControlHeight-8, 8, m.FontSizeS + case SizeSmall: + height = m.ControlHeight - 4 + case SizeLarge: + height = m.ControlHeight + 4 + case SizeIcon: + iconOnly = true + case SizeIconXSmall: + height, iconOnly = m.ControlHeight-8, true + fontSize = m.FontSizeS + case SizeIconSmall: + height, iconOnly = m.ControlHeight-4, true + case SizeIconLarge: + height, iconOnly = m.ControlHeight+4, true + } + if height < 20 { + height = 20 + } + return height, padding, fontSize, iconOnly +} diff --git a/ui/button_density_bench_test.go b/ui/button_density_bench_test.go new file mode 100644 index 000000000..b40a6bc10 --- /dev/null +++ b/ui/button_density_bench_test.go @@ -0,0 +1,65 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var denseIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(4, 4), gfx.LineTo(20, 20), +}} + +var denseLabels = [...]string{"Save", "Cancel", "Deploy", "Connect", "Open", "Rename", "Delete", "Refresh"} + +// denseButtons is a page made of buttons, as a toolbar-heavy workbench is: every +// variant and size, with and without an icon, in a few rows of a table. It has no +// other control, so a change in what a button costs is the change in the page. +func denseButtons(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(8).Children(func() { + ui.Row(c).Gap(6).Children(func() { + for i := 0; i < 8; i++ { + ui.Button(c, denseLabels[i]).Small().Ghost().Icon(denseIcon) + } + }) + ui.Row(c).Gap(6).Children(func() { + ui.Button(c, "Default") + ui.Button(c, "Secondary").Secondary() + ui.Button(c, "Outline").Outline() + ui.Button(c, "Ghost").Ghost() + ui.Button(c, "Link").Link() + ui.Button(c, "Destructive").Destructive() + ui.Button(c, "XSmall").XSmall() + ui.Button(c, "Large").Large() + ui.Button(c, "").IconOnly().Icon(denseIcon) + }) + for r := 0; r < 40; r++ { + ui.Row(c).FillWidth().Gap(6).Children(func() { + ui.Text(c, "row").Grow(1) + ui.Button(c, denseLabels[r%len(denseLabels)]).Small().Outline() + ui.Button(c, "More").Small().Ghost().Icon(denseIcon) + }) + } + }) +} + +// BenchmarkPageButtons is the page-level cost of themed buttons: 8 + 9 + 80 of them. +func BenchmarkPageButtons(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, denseButtons) + } +} + +// A steady page of buttons allocates nothing, whatever a button is made of. +func TestPageOfButtonsAllocatesNothing(t *testing.T) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + for range 3 { + drawPage(page, canvas, denseButtons) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, denseButtons) }); allocs != 0 { + t.Fatalf("a steady page of buttons allocates %v times", allocs) + } +} diff --git a/ui/buttongroup/buttongroup.go b/ui/buttongroup/buttongroup.go index 0e35be8b6..39f88888e 100644 --- a/ui/buttongroup/buttongroup.go +++ b/ui/buttongroup/buttongroup.go @@ -17,9 +17,12 @@ // runtime activates the focused action with Enter or Space. The group itself is // a non-focusable group region named by View's label. // -// The caller owns everything mutable. Selected names the action painted with -// the secondary treatment, and a click does not change it: OnClick receives the -// action's index and identity, like the form control a page updates itself. +// The caller owns everything mutable. Item(...).Icon(icon) adds a leading glyph; +// IconOnly keeps the item's label as its accessible name and tooltip without +// painting it. Selected names the action painted with the secondary treatment +// and exposes that selection to assistive technology. A click does not change it: +// OnClick receives the action's index and identity, like the form control a page +// updates itself. // Clicked reports the same pair for a caller that reads after the paint. // // Declarations are rebuilt every paint: call Reset, declare the actions in @@ -64,9 +67,11 @@ type Group struct { // action is one declared item. The zero Variant is the default look. type action struct { - id gfx.ID - label string - variant components.ButtonVariant + id gfx.ID + label string + variant components.ButtonVariant + icon gfx.Icon + iconOnly bool } // New returns a button group with no actions and no selection. @@ -92,6 +97,23 @@ func (g *Group) Item(id gfx.ID, label string) *Group { return g } +// Icon sets the leading glyph of the action declared last. +func (g *Group) Icon(icon gfx.Icon) *Group { + if n := len(g.items); n > 0 { + g.items[n-1].icon = icon + } + return g +} + +// IconOnly hides the visible label of the action declared last, keeping it as +// the accessible name and tooltip. Give that action an Icon. +func (g *Group) IconOnly() *Group { + if n := len(g.items); n > 0 { + g.items[n-1].iconOnly = true + } + return g +} + // Variant sets the look of the action declared last. func (g *Group) Variant(variant Variant) *Group { if n := len(g.items); n > 0 { @@ -232,6 +254,7 @@ func (g *Group) draw(d *ui.DrawContext) { } options = append(options, components.ButtonGroupOption{ ID: item.id, Label: item.label, Variant: variant, + Icon: item.icon, IconOnly: item.iconOnly, Selected: index == selected, }) } g.options = options diff --git a/ui/buttongroup/icons_test.go b/ui/buttongroup/icons_test.go new file mode 100644 index 000000000..78e34027f --- /dev/null +++ b/ui/buttongroup/icons_test.go @@ -0,0 +1,91 @@ +package buttongroup_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/buttongroup" +) + +var groupIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{ + gfx.MoveTo(4, 12), gfx.LineTo(20, 12), +}} + +type iconGroupModel struct { + group buttongroup.Group + selected int + ids [3]gfx.ID +} + +func newIconGroupModel() *iconGroupModel { + var tree gfx.Tree + scope := tree.Feature("mode-group") + m := &iconGroupModel{ids: [3]gfx.ID{tree.ID(scope, "source"), tree.ID(scope, "split"), tree.ID(scope, "preview")}, selected: 2} + m.group.OnClick(func(index int, _ gfx.ID) { m.selected = index }) + return m +} + +func (m *iconGroupModel) view(c ui.C) { + g := &m.group + g.Reset() + for i, label := range [...]string{"Source", "Split", "Preview"} { + g.Item(m.ids[i], label).Icon(groupIcon).IconOnly().Outline() + } + g.Selected(m.selected).View(c, "View mode").Size(96, 28) +} + +// An icon-only group keeps names, tooltips and caller-owned selection, not +// visible text labels. Its items share edges and stay independently actionable. +func TestIconOnlyItemsKeepNamesAndSelection(t *testing.T) { + m := newIconGroupModel() + page, canvas := open(t, m.view) + check := func() { + t.Helper() + hits := actions(canvas) + if len(hits) != len(m.ids) { + t.Fatalf("action hits = %d", len(hits)) + } + for i, h := range hits { + if h.ID != m.ids[i] || h.Label == "" || h.Hint != h.Label || h.Selected != (i == m.selected) { + t.Fatalf("item %d: %+v", i, h) + } + if i > 0 && !near(hits[i-1].Bounds.Right(), h.Bounds.X) { + t.Fatal("items do not share their edges") + } + } + if len(canvas.Texts()) != 0 { + t.Fatal("icon-only items painted visible labels") + } + if len(canvas.Triangles()) == 0 { + t.Fatal("icon-only items painted no glyphs") + } + } + check() + drawClick(page, canvas, m.view, m.ids[0]) + draw(page, canvas, m.view) + if m.selected != 0 { + t.Fatal("the first item did not activate") + } + check() +} + +func TestIconOnlyGroupWarmPaintAllocatesNothing(t *testing.T) { + m := newIconGroupModel() + page, canvas := open(t, m.view) + for range 3 { + draw(page, canvas, m.view) + } + if n := testing.AllocsPerRun(100, func() { draw(page, canvas, m.view) }); n != 0 { + t.Fatalf("allocs = %v", n) + } +} + +func BenchmarkIconOnlyViewPaint(b *testing.B) { + m := newIconGroupModel() + page, canvas := open(b, m.view) + b.ReportAllocs() + for b.Loop() { + draw(page, canvas, m.view) + } +} diff --git a/ui/controls_paint.go b/ui/controls_paint.go index 5c2b72e9c..61dfc9131 100644 --- a/ui/controls_paint.go +++ b/ui/controls_paint.go @@ -1,8 +1,6 @@ package ui import ( - "math" - "github.com/vivaui/viva/base" "github.com/vivaui/viva/components" @@ -115,15 +113,7 @@ func paintSegmented(f *Frame, v ControlView) { func measureControls(f *Frame, n *Node) { switch n.Kind { case KindButton: - button := components.BeginButton(f.Surface, f.Palette, gfx.ID{}, Rect{}).Size(n.ButtonSize).WithIcon(f.Exts[n.Ext].GetIcon()) - if d := n.Size[AxisY]; d.Kind == DimPx { - button = button.Height(d.Value) // an icon button is as wide as it is tall - } - button = button.SizeToFit(n.Label) - n.Pref = [2]float32{button.BoundsWidth(), button.BoundsHeight()} - if n.ButtonSize >= components.ButtonSizeIcon { - n.Pref[AxisX] = n.Pref[AxisY] - } + n.Pref = measureButton(f, n) case KindBadge: w, h := components.BadgeExtent(f.Surface, f.Palette, n.Text) n.Pref = [2]float32{w, h} @@ -217,40 +207,68 @@ func measureControls(f *Frame, n *Node) { } } +// 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 { + return n.Weight + } + return gfx.WeightMedium +} + +// measureButton is the size a button that paints its own label and icon is laid out at: +// its size's height, and its content's width inside the element's Pad (which is the +// recipe's, the size's padding, unless the caller set it). A Height of the element's +// is the button's height, and an icon alone is as wide as it is tall. Padded down the +// 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 d := n.Size[AxisY]; d.Kind == DimPx { + height = d.Value + } + if n.ButtonSize >= components.ButtonSizeIcon { + return [2]float32{height, height} // an icon button is as wide as it is tall + } + width := n.PadX() + f.Surface.TextWidthWeight(n.Label, fontSize, buttonWeight(n)) + if icon := f.Exts[n.Ext].GetIcon(); len(icon.Commands) > 0 || len(icon.Layers) > 0 { + width += style.ButtonIconExtent(height) + if n.Label != "" { + width += n.Gap + } + } + if n.Flags&FlagSetPad != 0 { + height = max(height, fontSize+7+n.PadY()) + } + return [2]float32{width, height} +} + +// buttonContentArea is the room a button's content is centered in: the height inside its +// Pad and Border, and across, the widest span centered where the content is, which is +// the whole button when it is padded the same on both sides. The padding is not taken out +// of a label's width, so a label wider than a narrow button still centers on it. +func buttonContentArea(f *Frame, n *Node) Rect { + content := f.ContentRect(n) + center := content.X + content.Width/2 + half := min(center-n.Rect.X, n.Rect.X+n.Rect.Width-center) + return Rect{X: center - half, Y: content.Y, Width: 2 * half, Height: content.Height} +} + +// 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. func paintButton(f *Frame, n *Node) { - r := n.Rect extra := &f.Exts[n.Ext] - button := components.BeginButton(f.Surface, f.Palette, n.ID, Rect{X: r.X, Y: r.Y, Width: r.Width}).Size(n.ButtonSize). - WithIcon(extra.GetIcon()).IconTransform(extra.GetIconTransform()) - if f.GetStyles() != nil && f.GetStyles().Button != nil { - button = button.Recipe(f.GetStyles().Button) - } - if extra.GetButtonRecipe() != nil { - button = button.Recipe(extra.GetButtonRecipe()) - } - // A button is as tall as its size says unless the element was given more or less - // room: a Height, or a Grow along a column. It then fills that room. - if h := r.Height; h > 0 && math.Abs(float64(h-button.BoundsHeight())) > 0.01 { - button = button.Height(h) - } - if n.Flags&FlagDisabled != 0 { - button = button.Disabled() - } - switch n.Variant { - case components.ButtonSecondary: - button.Secondary(n.Label) - case components.ButtonOutline: - button.Outline(n.Label) - case components.ButtonGhost: - button.Ghost(n.Label) - case components.ButtonLink: - button.Link(n.Label) - case components.ButtonDestructive: - button.Destructive(n.Label) - case components.ButtonDestructiveOutline: - button.DestructiveOutline(n.Label) - default: - button.Default(n.Label) + _, _, fontSize, iconOnly := style.ButtonGeometry(f.Palette.Metrics, n.ButtonSize) + hint := components.PaintButtonContent(f.Surface, buttonContentArea(f, n), 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, + }) } } diff --git a/ui/hooks_install.go b/ui/hooks_install.go index 0626919f7..44ef2d3de 100644 --- a/ui/hooks_install.go +++ b/ui/hooks_install.go @@ -36,6 +36,7 @@ func useControls() { base.SetControlPainter(KindPagination, paintPaginationControl) base.ControlMeasurer = measureControls base.ControlBaseline = controlBaseline + base.ButtonLookFn = frameButtonLook base.SliderPointer = sliderPointer base.PaintTooltip = paintTooltip }) diff --git a/ui/recipe_paint.go b/ui/recipe_paint.go index 05a5a3c2b..1bd55ce8a 100644 --- a/ui/recipe_paint.go +++ b/ui/recipe_paint.go @@ -13,3 +13,15 @@ func frameTextEntryLook(f *Frame, Palette *Theme, state gfx.State) components.Te } return components.TextEntryRecipe(*Palette, state) } + +// frameButtonLook is the recipe a themed button is dressed with: its own ButtonRecipe, else +// the page's Styles.Button, else the theme's. +func frameButtonLook(f *Frame, n *Node, Palette *Theme, state gfx.State) components.ButtonLook { + if recipe := f.Exts[n.Ext].GetButtonRecipe(); recipe != nil { + return recipe(*Palette, n.Variant, state) + } + if f.GetStyles() != nil && f.GetStyles().Button != nil { + return f.GetStyles().Button(*Palette, n.Variant, state) + } + return components.ButtonRecipe(*Palette, n.Variant, state) +} From 80b8f0c9286af7b6c1e445c80bcd8b6b3d3776e1 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 20 Nov 2026 23:44:54 +0800 Subject: [PATCH 2/3] perf(windows): keep terminal grid text formats and layouts A terminal row of many colors is one run per color, and rasterizing it made a DirectWrite text format and text layout for every run. Scrolling into a colored stretch therefore paid that cost again for each row entering view. Keep both for the rasterizer's lifetime, keyed by everything drawRun passes to DirectWrite, and release them with it. A 100-cell line split into 70 color runs rasterizes in 0.33 ms once its formats and layouts are kept, against 0.36 ms when each run makes them; a dense scrollback drag of the same text in Motty #1246 drops its p90 frame from 21.7 ms to 18.9 ms on the Windows test machine. --- internal/platform/windows/direct_windows.go | 53 +----- .../platform/windows/grid_cache_windows.go | 165 ++++++++++++++++++ .../windows/grid_cache_windows_test.go | 121 +++++++++++++ 3 files changed, 295 insertions(+), 44 deletions(-) create mode 100644 internal/platform/windows/grid_cache_windows.go create mode 100644 internal/platform/windows/grid_cache_windows_test.go diff --git a/internal/platform/windows/direct_windows.go b/internal/platform/windows/direct_windows.go index 2e159b37d..787d5e94b 100644 --- a/internal/platform/windows/direct_windows.go +++ b/internal/platform/windows/direct_windows.go @@ -3,10 +3,8 @@ package windows import ( "fmt" "math" - "syscall" "unsafe" - "github.com/ebitengine/purego" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" ) @@ -188,6 +186,8 @@ type directRasterizer struct { owner platform.GridOwner // which run owns which column of a grid label ink []platform.GridInk // how far each run's glyphs reach past its cells inkCache map[inkKey]platform.GridInk + formats map[gridFormatKey]uintptr + shaped map[gridLayoutKey]*gridLayout gdi *gdiGridRasterizer // the GDI face of fixed-pitch runs, made on first use directOnly bool // draw fixed-pitch runs with DirectWrite alone; tests compare the two } @@ -232,6 +232,7 @@ func (rasterizer *directRasterizer) close() { rasterizer.gdi.close() rasterizer.gdi = nil } + rasterizer.releaseGridCache() rasterizer.releaseFontFallbacks() release(&rasterizer.factory) } @@ -520,37 +521,14 @@ func (rasterizer *directRasterizer) grid(pixels []byte, label platform.TextLabel // exactly the pitch of the grid, a single wider character is centered on its cells, and // the run's decorations are DirectWrite's own. func (rasterizer *directRasterizer) drawRun(target *directTarget, family string, fallback uintptr, size, weight float32, run gfx.TextRun, piece string, left, span, pitch, baseline float32, clip pieceClip) error { - format, err := rasterizer.services.formatMono(family, size, weight, run.Italic) + formatKey, format, err := rasterizer.gridFormat(family, size, weight, run.Italic, fallback) if err != nil { return err } - defer release(&format) - setFontFallback(format, fallback) - units, err := syscall.UTF16FromString(piece) + shaped, err := rasterizer.gridShaped(formatKey, format, piece, run, span, pitch) if err != nil { return err } - var layout uintptr - if err := hresult(rasterizer.services.createLayout(rasterizer.services.write, &units[0], uint32(len(units)-1), format, 1<<20, 1<<20, &layout)); err != nil { - return fmt.Errorf("windows: lay out grid text: %w", err) - } - defer release(&layout) - var metrics textMetrics - if err := hresult(comCall(layout, writeGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil { - return err - } - var line lineMetrics - var lines uint32 - if err := hresult(comCall(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&line)), 1, uintptr(unsafe.Pointer(&lines)))); err != nil && lines == 0 { - return err - } - all := uint64(len(units)-1) << 32 - if run.Underline { - comCall(layout, writeSetUnderline, 1, uintptr(all)) - } - if run.Strike { - comCall(layout, writeSetStrikethrough, 1, uintptr(all)) - } x := left scaled := false if clip.height > 0 { @@ -566,28 +544,15 @@ func (rasterizer *directRasterizer) drawRun(target *directTarget, family string, // it is used only when the widths differ. // Terminal padding occupies cells too. Width excludes trailing spaces // and would stretch a short command across its following blank cells. - scaled = metrics.WidthTrailing > 0 && span > 0 && metrics.WidthTrailing != span + scaled = shaped.metrics.WidthTrailing > 0 && span > 0 && shaped.metrics.WidthTrailing != span if scaled { - scale := span / metrics.WidthTrailing + scale := span / shaped.metrics.WidthTrailing target.setTransform(d2dMatrix{M11: scale, M22: 1, DX: left * (1 - scale)}) } - case pitch > 0 && printableASCII(piece): - // Every character stands on its cell, whatever the advance of the font. - advance := metrics.WidthTrailing / float32(len(units)-1) - if reduction := advance - pitch; reduction != 0 { - var extended uintptr - if comCall(layout, 0, uintptr(unsafe.Pointer(&writeLayout1IID)), uintptr(unsafe.Pointer(&extended))) == 0 && extended != 0 { - if rasterizer.spacing == nil { - purego.RegisterFunc(&rasterizer.spacing, vtable(extended, writeSetCharacterSpacing)) - } - rasterizer.spacing(extended, 0, -reduction, 0, all) - release(&extended) - } - } case run.Cells > 0 && isSingleCharacter(piece): - x = left + (span-metrics.Width)/2 + x = left + (span-shaped.metrics.Width)/2 } - target.draw(x, baseline-line.Baseline, layout, d2dEnableColorFont) + target.draw(x, baseline-shaped.line.Baseline, shaped.layout, d2dEnableColorFont) if scaled { target.setTransform(identityMatrix) } diff --git a/internal/platform/windows/grid_cache_windows.go b/internal/platform/windows/grid_cache_windows.go new file mode 100644 index 000000000..558c55159 --- /dev/null +++ b/internal/platform/windows/grid_cache_windows.go @@ -0,0 +1,165 @@ +package windows + +import ( + "fmt" + "syscall" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/gfx" +) + +// A terminal row of many colors is drawn as one run per color. Rasterizing it +// would otherwise make a DirectWrite text format and a text layout per run, and +// a screen being scrolled into view is dozens of such rows: the frame blows its +// budget exactly on the colored stretches. Both objects are immutable once the +// run's text, font and decorations are fixed, so the rasterizer keeps them and a +// repeated run costs a map lookup, as a text engine's layout cache does. + +// gridFormatKey names a fixed-pitch text format. fonts is the registered-fonts +// revision: a font registration can change which face a family resolves to. +type gridFormatKey struct { + family string + size float32 + weight uint32 // the DirectWrite weight the run is drawn at + italic bool + fallback uintptr + fonts uint32 +} + +// gridFormatLimit bounds the formats kept. A terminal uses a handful of weights +// and sizes; past the limit the cache starts over rather than growing forever. +const gridFormatLimit = 64 + +// gridLayoutKey names a shaped run: everything drawRun passes to DirectWrite +// that changes the layout, its metrics, or the character spacing applied to it. +type gridLayoutKey struct { + format gridFormatKey + text string + span float32 // device pixels the run covers + pitch float32 // device pixels per cell + ligatures bool + underline bool + strike bool +} + +// gridLayoutLimit bounds the shaped runs kept. A terminal draws its rows from a +// small alphabet, so a screen of colored text fits many times over. +const gridLayoutLimit = 4096 + +// gridLayout is a shaped run and the metrics drawRun places it with. +type gridLayout struct { + layout uintptr + metrics textMetrics + line lineMetrics + chars uint32 // UTF-16 units the run's decorations cover +} + +// gridFormat returns the text format for a run, making it once. The handle is +// owned by the rasterizer: callers must not release it. +func (rasterizer *directRasterizer) gridFormat(family string, size, weight float32, italic bool, fallback uintptr) (gridFormatKey, uintptr, error) { + customFonts.RLock() + fonts := customFonts.revision + customFonts.RUnlock() + key := gridFormatKey{ + family: family, size: size, weight: rasterizer.services.monoWeight(weight), + italic: italic, fallback: fallback, fonts: fonts, + } + if format, ok := rasterizer.formats[key]; ok { + return key, format, nil + } + format, err := rasterizer.services.formatWeight(family, size, key.weight, italic) + if err != nil { + return key, 0, err + } + setFontFallback(format, fallback) + if rasterizer.formats == nil || len(rasterizer.formats) >= gridFormatLimit { + for _, old := range rasterizer.formats { + release(&old) + } + rasterizer.formats = make(map[gridFormatKey]uintptr, gridFormatLimit) + } + rasterizer.formats[key] = format + return key, format, nil +} + +// gridShaped returns the shaped run for piece, making it once. The layout is +// owned by the rasterizer: callers must not release it. +func (rasterizer *directRasterizer) gridShaped(format gridFormatKey, handle uintptr, piece string, run gfx.TextRun, span, pitch float32) (*gridLayout, error) { + key := gridLayoutKey{ + format: format, text: piece, span: span, pitch: pitch, + ligatures: run.Ligatures, underline: run.Underline, strike: run.Strike, + } + if shaped, ok := rasterizer.shaped[key]; ok { + return shaped, nil + } + units, err := syscall.UTF16FromString(piece) + if err != nil { + return nil, err + } + var layout uintptr + if err := hresult(rasterizer.services.createLayout(rasterizer.services.write, &units[0], uint32(len(units)-1), handle, 1<<20, 1<<20, &layout)); err != nil { + return nil, fmt.Errorf("windows: lay out grid text: %w", err) + } + shaped := &gridLayout{layout: layout, chars: uint32(len(units) - 1)} + ok := false + defer func() { + if !ok { + release(&layout) + } + }() + if err := hresult(comCall(layout, writeGetMetrics, uintptr(unsafe.Pointer(&shaped.metrics)))); err != nil { + return nil, err + } + var lines uint32 + if err := hresult(comCall(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&shaped.line)), 1, uintptr(unsafe.Pointer(&lines)))); err != nil && lines == 0 { + return nil, err + } + all := uint64(shaped.chars) << 32 + if run.Underline { + comCall(layout, writeSetUnderline, 1, uintptr(all)) + } + if run.Strike { + comCall(layout, writeSetStrikethrough, 1, uintptr(all)) + } + if !run.Ligatures && pitch > 0 && printableASCII(piece) { + // Every character stands on its cell, whatever the advance of the font. + advance := shaped.metrics.WidthTrailing / float32(shaped.chars) + if reduction := advance - pitch; reduction != 0 { + rasterizer.setCharacterSpacing(layout, -reduction, all) + } + } + if rasterizer.shaped == nil || len(rasterizer.shaped) >= gridLayoutLimit { + for _, old := range rasterizer.shaped { + release(&old.layout) + } + rasterizer.shaped = make(map[gridLayoutKey]*gridLayout, gridLayoutLimit) + } + rasterizer.shaped[key] = shaped + ok = true + return shaped, nil +} + +// setCharacterSpacing gives a layout direct-write's per-range character spacing. +func (rasterizer *directRasterizer) setCharacterSpacing(layout uintptr, trailing float32, span uint64) { + var extended uintptr + if comCall(layout, 0, uintptr(unsafe.Pointer(&writeLayout1IID)), uintptr(unsafe.Pointer(&extended))) != 0 || extended == 0 { + return + } + defer release(&extended) + if rasterizer.spacing == nil { + purego.RegisterFunc(&rasterizer.spacing, vtable(extended, writeSetCharacterSpacing)) + } + rasterizer.spacing(extended, 0, trailing, 0, span) +} + +// releaseGridCache frees the formats and layouts the rasterizer keeps. +func (rasterizer *directRasterizer) releaseGridCache() { + for _, format := range rasterizer.formats { + release(&format) + } + for _, shaped := range rasterizer.shaped { + release(&shaped.layout) + } + rasterizer.formats, rasterizer.shaped = nil, nil +} diff --git a/internal/platform/windows/grid_cache_windows_test.go b/internal/platform/windows/grid_cache_windows_test.go new file mode 100644 index 000000000..ca57bf309 --- /dev/null +++ b/internal/platform/windows/grid_cache_windows_test.go @@ -0,0 +1,121 @@ +package windows + +import ( + "bytes" + "fmt" + "runtime" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// gridCacheLabel is a row whose runs exercise every part of the layout key: +// plain cells, a decorated run, a ligature run and a wide character. +func gridCacheLabel() platform.TextLabel { + value := "ab-cd-界-ef" + label := platform.TextLabel{Value: value, Mono: true, CellWidth: 8, Width: float32(len(value)) * 8, Height: 20, FontSize: 14, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + runs := []gfx.TextRun{ + {Column: 0, Bytes: 1, Cells: 1, Color: gfx.Color{Red: 1, Alpha: 1}}, + {Column: 1, Bytes: 1, Cells: 1, Color: gfx.Color{Green: 1, Alpha: 1}, Underline: true}, + {Column: 2, Bytes: 1, Cells: 1, Color: gfx.Color{Blue: 1, Alpha: 1}}, + {Column: 3, Bytes: 1, Cells: 1, Color: gfx.Color{Red: 1, Alpha: 1}, Strike: true}, + {Column: 4, Bytes: 1, Cells: 1, Color: gfx.Color{Green: 1, Alpha: 1}}, + {Column: 5, Bytes: 3, Cells: 2, Color: gfx.Color{Blue: 1, Alpha: 1}}, + {Column: 7, Bytes: 1, Cells: 1, Color: gfx.Color{Red: 1, Alpha: 1}}, + {Column: 8, Bytes: 2, Cells: 2, Color: gfx.Color{Green: 1, Alpha: 1}, Italic: true}, + } + label.Runs = runs + return label +} + +// TestGridLayoutCacheKeepsRendering is the layout cache's correctness check: +// a rasterizer that has already shaped other runs must render a row exactly as +// one that has not, so a key that misses an input cannot reuse a wrong layout. +func TestGridLayoutCacheKeepsRendering(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + warm, err := newDirectRasterizer() + if err != nil { + t.Fatal(err) + } + defer warm.close() + cold, err := newDirectRasterizer() + if err != nil { + t.Fatal(err) + } + defer cold.close() + + // Render the target after a differently-shaped line on the warm rasterizer, + // and as the first line on the cold one. + first := platform.TextLabel{Value: "wx-界", Mono: true, CellWidth: 8, Width: 24, Height: 20, FontSize: 14, Color: platform.Color{Alpha: 1}} + first.Runs = []gfx.TextRun{ + {Column: 0, Bytes: 1, Cells: 1, Color: gfx.Color{Red: 1, Alpha: 1}}, + {Column: 1, Bytes: 1, Cells: 1, Color: gfx.Color{Green: 1, Alpha: 1}, Underline: true}, + {Column: 2, Bytes: 3, Cells: 2, Color: gfx.Color{Blue: 1, Alpha: 1}, Ligatures: true}, + } + target := gridCacheLabel() + warmPixels, warmLCD, err := warm.rasterize(first, 1, 80, 20, true, 0) + if err != nil { + t.Fatal(err) + } + _ = warmPixels + warmPixels, warmLCD, err = warm.rasterize(target, 1, 88, 20, true, 0) + if err != nil { + t.Fatal(err) + } + coldPixels, coldLCD, err := cold.rasterize(target, 1, 88, 20, true, 0) + if err != nil { + t.Fatal(err) + } + if warmLCD != coldLCD { + t.Fatalf("cached rasterization lcd=%v, fresh %v", warmLCD, coldLCD) + } + if !bytes.Equal(warmPixels, coldPixels) { + t.Fatal("a rasterizer that shaped other runs painted this row differently") + } +} + +// BenchmarkGridRasterizeColors is one 100-cell terminal line in one color and +// in seventy, the density a colorizer gives a log line. The layout cache makes +// the run-per-color cost a map lookup after the first row of its alphabet. +func BenchmarkGridRasterizeColors(b *testing.B) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + rasterizer, err := newDirectRasterizer() + if err != nil { + b.Fatal(err) + } + defer rasterizer.close() + for _, runs := range []int{1, 70} { + b.Run(fmt.Sprintf("runs-%d", runs), func(b *testing.B) { + label := cacheBenchLine(100, runs) + b.ReportAllocs() + for range b.N { + if _, _, err := rasterizer.rasterize(label, 1, 800, 20, true, 0); err != nil { + b.Fatal(err) + } + } + }) + } +} + +// cacheBenchLine is a 100-cell row split into runs colors, each a cell or more. +func cacheBenchLine(cells, runs int) platform.TextLabel { + value := make([]byte, cells) + for index := range value { + value[index] = byte('a' + index%26) + } + label := platform.TextLabel{Value: string(value), Mono: true, CellWidth: 8, Width: float32(cells) * 8, Height: 20, FontSize: 14, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + per := cells / runs + colors := []gfx.Color{{Red: 1, Green: 1, Blue: 1, Alpha: 1}, {Green: 1, Alpha: 1}, {Red: 1, Alpha: 1}, {Red: 0.2, Green: 0.4, Blue: 1, Alpha: 1}, {Red: 1, Green: 1, Alpha: 1}} + for index := 0; index < runs; index++ { + from := index * per + to := from + per + if index == runs-1 { + to = cells + } + label.Runs = append(label.Runs, gfx.TextRun{Column: int32(from), Bytes: int32(to - from), Cells: int32(to - from), Color: colors[index%len(colors)]}) + } + return label +} From 33de1510b496d65a72b30f0cce53abd68ffd5469 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 21 Nov 2026 00:11:38 +0800 Subject: [PATCH 3/3] perf(windows): draw a colored terminal row in one GDI call per pass Rasterizing a row of many colors called ExtTextOut once per run, so a colorizer's line cost a syscall and a font select for every word or cell, and scrolling into a colored stretch spent the frame there. Draw the whole pass's text in one call: the other passes' cells are spaces in its string, and every character keeps the cell drawPiece puts it on. A 100-cell line split into 70 runs rasterizes in 0.15 ms against 0.36 ms with a call per run; a dense scrollback drag in Motty #1246 drops its p90 frame from 20.1 ms to 16.8 ms on the Windows test machine. A test proves a batched row has the piecewise row's exact pixels. --- .../platform/windows/direct_gdi_windows.go | 93 +++++++++++++++++++ .../windows/grid_cache_windows_test.go | 44 +++++++++ 2 files changed, 137 insertions(+) diff --git a/internal/platform/windows/direct_gdi_windows.go b/internal/platform/windows/direct_gdi_windows.go index d6627ef9b..f24668529 100644 --- a/internal/platform/windows/direct_gdi_windows.go +++ b/internal/platform/windows/direct_gdi_windows.go @@ -60,6 +60,7 @@ type gdiGridRasterizer struct { fonts map[gdiFontKey]uintptr text []uint16 // the characters of the run being drawn spacing []int32 // the advance of each of them + noBatch bool // draw each piece on its own; tests compare it with one call a pass } func (rasterizer *gdiGridRasterizer) close() { @@ -164,6 +165,15 @@ func (rasterizer *gdiGridRasterizer) draw(pieces []gridPiece, light bool, pitch gdiSetTextAlign.Call(bitmap.dc, 24) // TA_LEFT | TA_BASELINE var stock uintptr var drawErr error + // A line whose pieces all use one GDI font is drawn in one ExtTextOut: a colorizer + // changes a log line's color at every word or cell, and a call per run is what made + // such a line expensive. Every character is still drawn at its cell; only the columns + // of the pieces this pass reads are taken from the bitmap, and printable ASCII ink + // stays inside its cell. + if !rasterizer.noBatch && rasterizer.drawWhole(bitmap, pieces, light, pitch, baseline) { + gdiFlush.Call() + return bitmap, nil + } for index := range pieces { piece := &pieces[index] if piece.font == 0 || isLight(piece.color) != light || piece.text == "" { @@ -224,8 +234,91 @@ func (rasterizer *gdiGridRasterizer) drawPiece(bitmap *textBitmap, piece *gridPi return nil } +// drawWhole draws a pass's pieces in one ExtTextOut when they all use one GDI font. +// A colorizer changes a log line's colour at every word or cell, and a call per run is +// what made such a line expensive. Only the pieces of this pass are written into the +// string — the other passes' cells are spaces — so a glyph never sees ink of another +// brightness, and every character still starts at the cell drawPiece would put it on. +// It reports false when a piece needs another font, or DirectWrite. +func (rasterizer *gdiGridRasterizer) drawWhole(bitmap *textBitmap, pieces []gridPiece, light bool, pitch float32, baseline int) bool { + font := uintptr(0) + pass := 0 + end := 0 + for index := range pieces { + piece := &pieces[index] + if piece.font == 0 || isLight(piece.color) != light { + continue + } + if piece.text == "" || !printableASCII(piece.text) { + return false + } + if font == 0 { + font = piece.font + } else if piece.font != font { + return false + } + pass++ + end = max(end, int(piece.run.Column+piece.run.Cells)) + } + if pass == 0 || end <= 0 { + return false + } + if cap(rasterizer.text) < end { + rasterizer.text = make([]uint16, end) + } + text := rasterizer.text[:end] + for index := range text { + text[index] = ' ' + } + if cap(rasterizer.spacing) < end { + rasterizer.spacing = make([]int32, end) + } + spacing := rasterizer.spacing[:end] + for index := range spacing { + spacing[index] = 0 + } + // cursor is where the advances written so far leave the string: each piece starts at + // the x drawPiece rounds its cell column to, and the gap cells before it take up the + // difference. + cursor := 0 + step := float64(pitch) + for index := range pieces { + piece := &pieces[index] + if piece.font == 0 || isLight(piece.color) != light { + continue + } + column := int(piece.run.Column) + left := float64(piece.left) + start := int(math.Floor(left + 0.5)) + if column > 0 { + spacing[column-1] += int32(start - cursor) + } + edge := start + for offset := 0; offset < len(piece.text); offset++ { + if at := column + offset; at >= 0 && at < len(text) { + text[at] = uint16(piece.text[offset]) + } + next := int(math.Floor(left + float64(offset+1)*step + 0.5)) + if offset < len(piece.text)-1 { + spacing[column+offset] = int32(next - edge) + } + edge = next + } + cursor = start + for offset := 0; offset < len(piece.text)-1; offset++ { + cursor += int(spacing[column+offset]) + } + } + previous, _, _ := selectObject.Call(bitmap.dc, font) + defer selectObject.Call(bitmap.dc, previous) + drawn, _, _ := gdiExtTextOut.Call(bitmap.dc, 0, uintptr(int32(baseline)), 0, 0, + uintptr(unsafe.Pointer(&text[0])), uintptr(len(text)), uintptr(unsafe.Pointer(&spacing[0]))) + return drawn != 0 +} + // useGDI sets the font of every piece that GDI draws, and clears it for the others. size is // the device size of the line. + func (rasterizer *directRasterizer) useGDI(pieces []gridPiece, family string, size float32, width, height int) error { emHeight := int32(math.Floor(float64(size) + 0.5)) if rasterizer.directOnly || emHeight < 1 { diff --git a/internal/platform/windows/grid_cache_windows_test.go b/internal/platform/windows/grid_cache_windows_test.go index ca57bf309..406b470b1 100644 --- a/internal/platform/windows/grid_cache_windows_test.go +++ b/internal/platform/windows/grid_cache_windows_test.go @@ -119,3 +119,47 @@ func cacheBenchLine(cells, runs int) platform.TextLabel { } return label } + +// TestGDIBatchKeepsPixels is the batching's correctness check: a row drawn in one GDI +// call per brightness pass must have the very pixels of the same row drawn piece by +// piece, or a colorizer's line would shimmer every time it entered the viewport. +func TestGDIBatchKeepsPixels(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + label := cacheBenchLine(100, 70) + batched, err := newDirectRasterizer() + if err != nil { + t.Fatal(err) + } + defer batched.close() + piecewise, err := newDirectRasterizer() + if err != nil { + t.Fatal(err) + } + defer piecewise.close() + piecewise.gdi = &gdiGridRasterizer{noBatch: true} + got, lcd, err := batched.rasterize(label, 1, 800, 20, true, 0) + if err != nil { + t.Fatal(err) + } + want, wantLCD, err := piecewise.rasterize(label, 1, 800, 20, true, 0) + if err != nil { + t.Fatal(err) + } + if lcd != wantLCD { + t.Fatalf("batched rasterization lcd=%v, piecewise %v", lcd, wantLCD) + } + if !bytes.Equal(got, want) { + different, maxDelta := 0, 0 + for index := range got { + if delta := int(got[index]) - int(want[index]); delta != 0 { + different++ + if delta < 0 { + delta = -delta + } + maxDelta = max(maxDelta, delta) + } + } + t.Fatalf("batched row differs from piecewise in %d bytes (max delta %d)", different, maxDelta) + } +}