Skip to content
Closed
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
9 changes: 9 additions & 0 deletions app/painter.go
Original file line number Diff line number Diff line change
Expand Up @@ -1634,6 +1634,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 @@ -309,6 +309,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
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
4 changes: 4 additions & 0 deletions cmd/viva/initfiles/AGENTS.md.txt
Original file line number Diff line number Diff line change
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
149 changes: 149 additions & 0 deletions ui/field_paste_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package ui_test

import (
"bytes"
"image"
"image/png"
"path/filepath"
"testing"

"github.com/vivaui/viva/text"
"github.com/vivaui/viva/ui"
)

func pastedPNG(t *testing.T) []byte {
t.Helper()
var out bytes.Buffer
if err := png.Encode(&out, image.NewNRGBA(image.Rect(0, 0, 2, 2))); err != nil {
t.Fatal(err)
}
return out.Bytes()
}

func (d *pageDriver) paste() {
d.t.Helper()
if handled, err := d.driver.Shortcut('v'); err != nil || !handled {
d.t.Fatalf("paste: handled=%v err=%v", handled, err)
}
}

// OnPaste sees every paste into a TextArea before the field does: a paste it
// takes leaves the field as it was and paints the page again, text it leaves
// pastes as usual, and a clipboard of no text is offered as nothing. A cut is
// not a paste.
func TestTextAreaOnPasteTakesOrLeavesThePaste(t *testing.T) {
var notes ui.Field
editor := text.NewEditor("")
notes.Bind(editor)
var offered []string
attached := ""
take := true
d := openPage(t, func(c ui.C) {
ui.Column(c).Pad(16).Gap(8).Children(func() {
ui.TextArea(c, &notes, "Notes", "").Height(120).OnPaste(func(value string) bool {
offered = append(offered, value)
if take {
attached = value
}
return take
})
if attached != "" {
ui.Button(c, "Attached "+attached)
}
})
})
d.click("Notes")

d.driver.SetClipboardFiles([]string{filepath.Join(t.TempDir(), "report.txt")})
d.paste()
if notes.Text() != "" || len(offered) != 1 || offered[0] != "report.txt" {
t.Fatalf("a paste the handler took: text %q, offered %q", notes.Text(), offered)
}
if !d.has("Attached report.txt") {
t.Fatal("the page did not paint again after the handler took the paste")
}

if err := d.driver.SetClipboardImage(pastedPNG(t)); err != nil {
t.Fatal(err)
}
d.paste()
if notes.Text() != "" || len(offered) != 2 || offered[1] != "" {
t.Fatalf("a paste of a picture: text %q, offered %q", notes.Text(), offered)
}

take = false
d.driver.SetClipboard("one\ntwo")
d.paste()
if notes.Text() != "one\ntwo" || len(offered) != 3 || offered[2] != "one\ntwo" {
t.Fatalf("a paste the handler left: text %q, offered %q", notes.Text(), offered)
}
if !editor.CanUndo() {
t.Fatal("the paste the handler left is not an edit the field can undo")
}

editor.SetSelection(text.Range{Start: 0, End: 3})
d.repaint()
if handled, err := d.driver.Shortcut('x'); err != nil || !handled {
t.Fatalf("cut: handled=%v err=%v", handled, err)
}
if notes.Text() != "\ntwo" || len(offered) != 3 {
t.Fatalf("a cut: text %q, offered %q", notes.Text(), offered)
}
}

// A single-line field's handler sees the text the paste would insert, its lines
// folded into one, as the system hands a single-line field its paste.
func TestTextFieldOnPasteSeesTheTextTheFieldWouldTake(t *testing.T) {
var name ui.Field
offered := ""
d := openPage(t, func(c ui.C) {
ui.TextField(c, &name, "Name", "").OnPaste(func(value string) bool {
offered = value
return false
})
})
d.click("Name")
d.driver.SetClipboard("a\nb")
d.paste()
if offered != "a b" || name.Text() != "a b" {
t.Fatalf("offered %q, field %q", offered, name.Text())
}
}

// The edit menu's Paste is offered to the handler too.
func TestEditMenuPasteIsOfferedToOnPaste(t *testing.T) {
var notes ui.Field
var offered []string
d := openCanvasMenus(t, func(c ui.C) {
ui.TextArea(c, &notes, "Notes", "").Height(120).OnPaste(func(value string) bool {
offered = append(offered, value)
return true
})
})
d.driver.SetClipboardFiles([]string{filepath.Join(t.TempDir(), "plan.md")})
d.secondaryClick("Notes")
d.click("Paste")
if notes.Text() != "" || len(offered) != 1 || offered[0] != "plan.md" {
t.Fatalf("the edit menu's Paste: text %q, offered %q", notes.Text(), offered)
}
}

// OnPaste is for a TextField or a TextArea, with a handler.
func TestOnPasteNeedsATextFieldAndAHandler(t *testing.T) {
for name, view := range map[string]func(ui.C){
"container": func(c ui.C) { ui.Column(c).OnPaste(func(string) bool { return false }) },
"no handler": func(c ui.C) {
var field ui.Field
ui.TextField(c, &field, "Name", "").OnPaste(nil)
},
} {
t.Run(name, func(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("OnPaste did not panic")
}
}()
openPage(t, view)
})
}
}
12 changes: 12 additions & 0 deletions window/text_input.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,18 @@ type TextInput struct {
// while native editing continues. It combines with the declaration on the
// focused Canvas hit.
HideNativeOverlays bool
// Paste, when set, is offered every paste into the field before the field
// takes it, whether the keyboard, a menu or the system asked for it: text
// is what the paste would insert (a single-line field's with its lines
// folded into one), or empty when the clipboard holds no text (a
// TextPasteNoText). Returning true takes the paste: neither Editor
// nor OnEvent sees it, the field stays as it was and the window paints
// again, so a chat box can attach the files or the picture on the
// clipboard (ClipboardFiles, ClipboardImagePNG) rather than paste their
// names. Returning false lets the paste go on as usual. A cut, which
// arrives as a paste of nothing over the selection, is not offered. It
// runs on the window's thread, between paints.
Paste func(text string) bool
}

// Apply routes one native text event into editor. The event kinds and commands are
Expand Down
Loading