Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ jobs:
# it, and a symbol that needs one usually needs a typed one instead.
- name: API discipline
run: go run ./tools/apicheck ./ui ./components ./app ./gfx
# Nothing keeps the framework busy while an application is idle: no ticker,
# no file access while painting, no frame asked for forever. A line that
# needs one says why with //appaudit:allow.
- name: Idle and window-thread audit
run: go run ./tools/appaudit ./...

# 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
Expand Down Expand Up @@ -388,6 +393,16 @@ jobs:
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$passed = $events | ConvertFrom-Json | Where-Object { $_.Action -eq 'pass' -and $_.Test -eq $test }
if (-not $passed) { throw "$test did not pass on the Windows runner" }
# Shared media textures are opened on the WARP device and sampled under
# their keyed mutex. The tests skip when the offscreen renderer or a
# shared NT handle is unavailable on the runner.
- name: Offscreen shared video textures
run: go test ./internal/platform/windows -run '^TestOffscreen(DrawsASharedTexture|ClipsASharedTexture|SweepsAgedSharedTexture)$' -count=1 -v -timeout=2m
# The media engine's notify object, its shared texture registry and the
# renderer adapter choice need no codec; a runner without Media
# Foundation skips the first, and one without a Direct3D device the last.
- name: Media engine references and adapter
run: go test ./internal/media -run '^Test(NotifyRefCountAndDetach|SharedTextureErrorReporting|NewVideoDevice)$' -count=1 -v -timeout=2m
- name: Web view partitions
run: go test ./internal/platform/windows -run '^Test(APageWithoutAPartitionAsksForNoProfileOfItsOwn|APartitionNamesTheWebView2Profile|AnEphemeralPartitionIsAnOffTheRecordProfile|EphemeralPagesWithoutAPartitionEachGetAProfileOfTheirOwn)$' -count=1 -v
- name: Terminal keyboard routing
Expand Down
9 changes: 9 additions & 0 deletions app/painter.go
Original file line number Diff line number Diff line change
Expand Up @@ -1635,6 +1635,15 @@ func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextS
return painter.nativeText.State, nil
}
}
if active.Paste != nil && !explicit &&
(event.Kind == platform.TextPasteNoText || event.Kind == platform.TextPaste && appEvent.Text != "") &&
active.Paste(appEvent.Text) {
// The field took the paste itself: what it shows has not changed, but
// what it took may change the page, so the window paints again.
native := painter.nativeText.State
native.Redraw = true
return native, nil
}
if !explicit && !painter.nativeText.Multiline && !painter.nativeText.Terminal &&
event.Kind == platform.TextCommandEvent &&
(event.Command == platform.TextInsertNewline || event.Command == platform.TextInsertLineBreak) {
Expand Down
22 changes: 15 additions & 7 deletions base/edit_menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,21 @@ func (p *Page) declareEditMenu(c C, entry editMenuEntry, labels EditMenuLabels)
}
}
if menu.Item(labels.Paste).Keys(Primary, "v").Disabled(!editable).Clicked() && chosen() {
if value, err := ClipboardText(); err == nil {
if !entry.area {
value = text.SingleLine(value)
}
if value != "" {
editor.Paste(value)
}
value, err := ClipboardText()
if err != nil {
value = ""
}
folded := value
if !entry.area {
folded = text.SingleLine(value)
}
switch paste := p.fieldPaste(id); {
case value != "" && folded == "":
// None of the text is left on one line: there is nothing to paste.
case paste != nil && paste(folded):
// Box.OnPaste took it, as it takes a paste from the keyboard.
case folded != "":
editor.Paste(folded)
}
}
menu.Separator()
Expand Down
63 changes: 63 additions & 0 deletions base/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,69 @@ func (b Box) OnKey(handler func(gfx.KeyEvent) gfx.EventResult) Box {
panic("ui: OnKey must be chained on a TextField")
}

// OnPaste gives a TextField or a TextArea a look at every paste into it before
// the field takes it, from the keyboard, the edit menu or the system's menu.
// The handler gets the text the paste would insert (a TextField's with its
// lines folded into one), or nothing when the clipboard holds something else,
// such as a picture or the files a file manager copied.
// Returning true takes the paste and leaves the field as it was; returning
// false lets the text paste as usual. A chat box uses it to attach what was
// copied:
//
// prompt := ui.TextArea(c, &m.prompt, "Message", "").Height(80)
// prompt.OnPaste(func(text string) bool {
// if files, err := app.ClipboardFiles(); err == nil {
// m.attach(files...)
// return true
// }
// if text != "" {
// return false
// }
// if png, err := app.ClipboardImagePNG(); err == nil {
// m.attachPicture(png)
// return true
// }
// return false
// })
//
// Ask for the files first: most file managers put the file names on the
// clipboard as text too. A cut is not a paste and is not offered.
//
// Not inside a Memo, whose copied fields are not declared.
func (b Box) OnPaste(handler func(text string) bool) Box {
n := b.N()
if n.Kind != kindInput && n.Kind != kindTextarea {
panic("ui: OnPaste is for a TextField or a TextArea")
}
if handler == nil {
panic("ui: OnPaste needs a handler")
}
if b.f.memoDepth > 0 {
panic("ui: OnPaste in a Memo: a copied field is not declared, so its handler would disappear; declare it outside the Memo")
}
p := b.f.page
if p == nil {
panic("ui: OnPaste is for a field of a page")
}
for i := len(p.fields) - 1; i >= 0; i-- {
if p.fields[i].ID == n.ID {
p.fields[i].paste = handler
return b
}
}
panic("ui: OnPaste must be chained on a TextField or a TextArea")
}

// fieldPaste is the Box.OnPaste handler of the field id, or nil.
func (p *Page) fieldPaste(id gfx.ID) func(string) bool {
for i := len(p.fields) - 1; i >= 0; i-- {
if p.fields[i].ID == id {
return p.fields[i].paste
}
}
return nil
}

// Fields answers Config.TextInput for the fields: the platform asks which editor
// belongs to the focused control, and gets the one of the field declared with that
// identity.
Expand Down
38 changes: 38 additions & 0 deletions base/flex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -837,3 +837,41 @@ func TestViewTrimReleasesLargePageNodes(t *testing.T) {
t.Fatalf("nodes capacity after a large page = %d, want the spike released", got)
}
}

// A container as wide as it measured gives its child the whole width, even where
// float32 sums the sizes to a few ulps less when it shares them out: a label that
// fits exactly is not cut to an ellipsis, with or without padding of its own,
// whether the container flows along the label's width or across it.
func TestAContainerAtItsMeasuredWidthKeepsAnEllipsizedLabelWhole(t *testing.T) {
for _, across := range []bool{false, true} {
for _, pad := range []float32{0, 3} {
for i := range 2000 {
scale := 0.5 + float32(i)*0.000731
canvas := &gfx.Canvas{}
canvas.SetTree(&tree)
canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 { return float32(len(Value)) * Size * scale })
var view View
var label Box
f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 40})
f.Row().Height(40).Gap(6).Children(func() {
f.Spacer()
if across {
f.Column().PadX(9).Children(func() {
label = f.Text("High").FontSize(12).PadX(pad).Ellipsis()
})
return
}
f.Row().PadX(9).Gap(5).Children(func() {
f.Slot().Width(12)
label = f.Text("High").FontSize(12).PadX(pad).Ellipsis()
f.Slot().Width(11)
})
})
f.End()
if got := f.Lines[f.Nodes[label.GetI()].LineFirst]; got != "High" {
t.Fatalf("across=%v, glyph %v wide and padding %v, the label reads %q in %v, want High", across, 12*scale, pad, got, label.Rect().Width)
}
}
}
}
}
24 changes: 22 additions & 2 deletions base/layout.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,12 @@ func (f *Frame) measure(axis int) {
n.TextDecor &^= textTruncated
first := int32(len(f.Lines))
// An empty text has no line at all, as WrapLines gives it none; anything
// else that fits is one line and needs no breaking.
if n.Text != "" && n.Natural <= n.Rect.Width-n.PadX() && strings.IndexByte(n.Text, '\n') < 0 {
// else that fits is one line and needs no breaking. The width it needs is
// summed as its preferred width was, so a text given exactly that fits. A
// container across the flow derives the room by subtracting its insets, so
// float32 can leave the text a few ulps short of the same sum; that is
// rounding, not a lack of room.
if n.Text != "" && n.Natural+n.PadX() <= n.Rect.Width+roundingSlack(n.Rect.Width, 1) && strings.IndexByte(n.Text, '\n') < 0 {
f.Lines = append(f.Lines, n.Text)
} else {
f.Lines = f.wrapText(f.Lines, n)
Expand Down Expand Up @@ -378,6 +382,15 @@ func shrinksToRoom(n *Node, extra *Extra) bool {
return breaksAnywhere(n, extra) && n.Size[AxisX].Kind == dimAuto && n.Flags&flagBasis == 0
}

// roundingSlack is the most that summing terms sizes of a container of the given
// size can be off by in float32: two ulps of the size for each term, the insets and
// gaps included. It is far below a device pixel, so a shortfall within it is never a
// real lack of room.
func roundingSlack(size float32, terms int) float32 {
const ulp = 1.0 / (1 << 23) // the float32 machine epsilon
return float32(2*(terms+3)) * ulp * max(size, 1)
}

func offset(align Align, free float32) float32 {
switch align {
case Center:
Expand Down Expand Up @@ -455,6 +468,13 @@ func (f *Frame) solveFlow(n *Node, First, stop int32, axis int, start, avail flo
room = max(avail, baseSum+frozenSize+fixed)
}
free := room - frozenSize - baseSum - fixed
if free < 0 && -free <= roundingSlack(room, count) {
// A container placed at the size it measured sums the same sizes again here,
// in another order, and float32 can leave it a few ulps short. That is
// rounding, not a lack of room: taking it from a child would cut a text that
// fits exactly down to an ellipsis.
free = 0
}
var violation float32
for c := First; c != stop; c = f.Nodes[c].Next {
child := &f.Nodes[c]
Expand Down
1 change: 1 addition & 0 deletions base/names.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,5 @@ type fieldEntry struct {
field *Field
box int32 // the field's element, for routing inside a wheel panel
key func(gfx.KeyEvent) gfx.EventResult // Box.OnKey, while this field has the keyboard
paste func(string) bool // Box.OnPaste, offered every paste into this field
}
1 change: 1 addition & 0 deletions base/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,7 @@ func (p *Page) TextInput(context window.TextInputContext) *window.TextInput {
if entry.ID == context.ID && !context.ID.IsZero() {
entry.field.input.Alignment = context.Alignment
entry.field.input.Editor = entry.field.ensure()
entry.field.input.Paste = entry.paste
return &entry.field.input
}
}
Expand Down
6 changes: 5 additions & 1 deletion cmd/viva/initfiles/AGENTS.md.txt
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func (m *model) page(c ui.C) {
`ui/chart`, `ui/sidebar`. Its state type is named by role, not by repeating the package: `calendar.State`,
`message.Row`, `attachment.Card`. Use `cal`, `msg`, `pic` for locals; a model field may keep the noun
(`m.calendar`) because a selector never shadows a package.
- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`,
- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/video`, `ui/calendar`, `ui/carousel`,
`ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`,
`ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`,
`ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`,
Expand Down Expand Up @@ -263,6 +263,10 @@ func (m *model) page(c ui.C) {
repaint that delivers Enter, not for a click; `OnKey` is not needed). The label (first string) is never empty.
- Several rows: `ui.TextArea(c, &m.notes, "Notes", "").Height(120)` (Enter is a new line). Arrow keys and Page Up/Down
move by row while the platform edits it, and the page routes them; no `OnKey` is needed.
- A field that takes more than text (a chat box that attaches copied files or a screenshot) chains
`.OnPaste(func(text string) bool { ... })` on its TextField or TextArea: it sees every paste first, with the text the
paste would insert or "" when the clipboard has none; return true to take it (read `app.ClipboardFiles()` before the
text, then `app.ClipboardImagePNG()`), false to let the text paste.
- Other fields: `ui.TextField(...).Icon(plus)` puts an icon before the text, `.Action(cross, "Clear")` a button at its end
(`.ActionClicked()` reads it), `.AutoFocus()` takes the focus as it appears and `.Secure()` makes it a password field.
A search box is a TextField with `.Icon(search)` and `.Action(cross, "Clear")`, as above.
Expand Down
Loading
Loading