Touch selection (v1): long-press/double-tap word selection, drag handles, floating copy/cut/paste menu

Implement the Android-native touch selection model, verified on-device:
- long-press selects the word under the finger (blank -> caret + paste-only
  menu); double-tap selects the word; drag handles resize the selection,
  drag the highlighted body to move it; floating menu offers copy/cut/paste
  (selection) or paste (bare caret), closing on any item tap.
- Renderer reports finger positions (app-local Dp) as tap/double-tap/
  long-press/selection-drag events; the logic goroutine owns all geometry
  (EditorRegion, menu rect, hit-testing, handles) and the renderer only
  draws the frame snapshot.
- Long press: 400 ms still-press on the editor, cancelled by movement
  (non-grabbing raw pointer probe) or by a scroll/handle grab. The main
  loop keeps invalidating while a press is pending (Gio renders on demand;
  a stationary finger produces no frames).
- Clipboard crosses the goroutine boundary via buffered channels
  (clipboardSetChan/pasteReqChan logic->main, pasteChan main->logic);
  main executes the Gio ops and, on Android, invalidates after ReadCmd
  because a queued transfer.DataEvent schedules no frame of its own.

Renderer fixes found while validating on-device:
- clickReg was stored by value in a map; range yielded copies so per-frame
  press bookkeeping (long-press state) was silently discarded. Now pointers.
- On Android a tap's press+release arrive in the same frame and
  gesture.Click/Drag return one event per Update call; without draining
  each gesture's queue every frame the release was lost on an idle window
  and every menu tap was swallowed (needed a second tap to 'rescue' it).
  Click and drag loops now drain to exhaustion (scroll already does).
- pointer.Filter queries must name Kinds: a zero-kinds filter matches
  nothing (the press-probe query was dead).
- Menu.Draw offsets items by the menu origin; the clippable drawElement
  branch registers SelDrag (handles now draw for the TextField).

Tests: internal/editor/touch_selection_test.go (word range, long-press,
double-tap, tap/menu guards, handle drags, menu actions, selection edits)
and internal/test/e2e/touch_selection_e2e_test.go; full suite green under
-race. Docs: spec.md §2.2 + §7, architecture.md §6.3a, development_plan.md
Phases 8-9.
This commit is contained in:
gmp
2026-08-17 08:57:55 -04:00
parent ec11abf8f1
commit 2a16c0017c
10 changed files with 1720 additions and 56 deletions
+92 -5
View File
@@ -192,10 +192,13 @@ type TextField struct {
// in-app highlight.
SelectionStart int
SelectionEnd int
ScrollOffset Dp
VisibleLines []Line
WordWrap bool
WrapWidth Dp
// CaretDrag is set after a long press on blank space: a single caret
// handle is shown and can be dragged to move the caret.
CaretDrag bool
ScrollOffset Dp
VisibleLines []Line
WordWrap bool
WrapWidth Dp
}
func (tf TextField) Type() string { return "textfield" }
@@ -290,7 +293,7 @@ func (tf TextField) Draw(gtx layout.Context, r *Renderer) {
r.lastSelStart = -1
r.lastSelCaret = -1
}
r.drawWrappedText(gtx, tf.Value, tf.region, tf.WrapWidth, tf.ScrollOffset, tf.CursorPosition, tf.SelectionStart, tf.SelectionEnd)
r.drawWrappedText(gtx, tf.Value, tf.region, tf.WrapWidth, tf.ScrollOffset, tf.CursorPosition, tf.SelectionStart, tf.SelectionEnd, tf.CaretDrag)
}
// runeCount returns the number of UTF-8 runes in s[:bytePos] (bytePos is a
@@ -849,6 +852,10 @@ const (
Scroll
KeyDown
KeyUp
// SelDrag is a selection-handle / selection-body / caret-handle drag.
// The renderer registers the underlying gesture.Drag ops itself (it owns
// the handle geometry); this interaction just delivers the logic handler.
SelDrag
)
// Interaction pairs a gesture type with a handler function.
@@ -877,6 +884,86 @@ type Point struct {
X, Y Dp
}
// LongPressPoint is a touch that was held still for the long-press duration.
// Coordinates are app-local window Dp (the same space as Point from a tap).
type LongPressPoint struct {
X, Y Dp
}
// DoubleTapPoint is the second tap of a double tap. App-local window Dp.
type DoubleTapPoint struct {
X, Y Dp
}
// SelectionDragEvent is emitted while a selection handle (Which 0 = start,
// 1 = end), the selection body (Which 2 = move whole selection) or the
// caret drag handle (Which 3) is being dragged. X/Y are app-local window Dp.
type SelectionDragEvent struct {
Which int
X, Y Dp
}
// SelectionDragEnd is emitted when a selection/caret drag is released.
type SelectionDragEnd struct{}
// MenuItem is one button in the selection menu.
// X/Y/W/H are relative to the Menu region.
type MenuItem struct {
Icon string // "copy", "cut", "paste"
Label string
X, Y, W, H Dp
}
// Menu is the floating selection menu (Copy / Cut / Paste). The logic goroutine
// positions it and decides the items; the renderer draws it and routes a tap
// to the element's Tap interaction with the tapped Point, which the logic
// hit-tests against its own items (single source of truth for geometry).
type Menu struct {
id string
region Region
visible bool
items []MenuItem
tap []Interaction
}
func NewMenu(id string, region Region, items []MenuItem, tapHandler func(any)) Menu {
return Menu{
id: id,
region: region,
visible: true,
items: items,
tap: []Interaction{{Gesture: Tap, Handler: tapHandler}},
}
}
func (m Menu) Type() string { return "menu" }
func (m Menu) Region() Region { return m.region }
func (m Menu) Visible() bool { return m.visible }
func (m Menu) ID() string { return m.id }
func (m Menu) Interactions() []Interaction { return m.tap }
func (m Menu) Items() []MenuItem { return m.items }
func (m Menu) String() string {
return fmt.Sprintf("Menu[%s] region=%+v items=%d", m.id, m.region, len(m.items))
}
// Draw renders the menu panel and its items. Click registration happens in
// the renderer's leaf-element path (Tap over the whole panel).
func (m Menu) Draw(gtx layout.Context, r *Renderer) {
// Panel background (light, like an Android floating menu).
r.drawBg(gtx, m.region, Color{R: 245, G: 245, B: 245, A: 255})
for _, it := range m.items {
// Item X/Y are relative to the menu region; offset to app coordinates.
ofx, ofy := m.region.X, m.region.Y
img := r.icon(it.Icon)
iconSize := it.H / 2
iconX := ofx + it.X + (it.W-iconSize)/2
iconY := ofy + it.Y + 2
r.drawPng(gtx, img, Region{X: iconX, Y: iconY, W: iconSize, H: iconSize}, iconSize, iconSize)
r.drawText(gtx, it.Label, unit.Sp(10), Region{X: ofx + it.X, Y: ofy + it.Y + iconSize + 3, W: it.W, H: 12}, AlignCenter, Color{R: 30, G: 30, B: 30, A: 255}, "")
}
}
// InputEvent represents a user input event with its handler.
type InputEvent struct {
Handler func(any)
+283 -17
View File
@@ -36,8 +36,21 @@ var iconFS embed.FS
type clickReg struct {
click *gesture.Click
handler func(any)
// pressAt/pressPos record the current press (set on KindPress) so the
// per-frame long-press check knows how long the finger has been still.
pressAt time.Time
pressPos image.Point
longFired bool
}
// longPressDuration is how long a still press must hold before a long-press
// fires (Android uses ~500ms; 400ms feels snappier for text selection).
const longPressDuration = 400 * time.Millisecond
// longPressSlopPx is how far the finger may drift (px) before a pending
// long press is cancelled (that motion becomes a scroll/drag instead).
const longPressSlopPx = 8
// keyReg pairs a handler for key events.
type keyReg struct {
Handler func(any)
@@ -59,7 +72,7 @@ type Renderer struct {
shp *text.Shaper
scale float32 // px-per-Dp for the current draw pass; set in Draw
icons map[string]image.Image
clicks map[string]clickReg
clicks map[string]*clickReg
Keys map[string]keyReg // Exported Keys map
scrolls map[string]scrollReg
gioEditors map[string]*widget.Editor // main-owned widget editors by element ID
@@ -77,6 +90,35 @@ type Renderer struct {
lastSnippet key.Snippet
lastSelStart int // window-relative rune index of last-pushed selection start; -1 = no selection
lastSelCaret int // window-relative rune index of last-pushed selection end/caret
// Long-press detection. pressProbe is a plain event tag observing raw
// pointer events inside the editor text region: gesture.Click reports
// nothing until release, so a long press (finger held still for
// longPressDuration) can only be detected this way. ppMoved cancels the
// pending long press once the finger leaves longPressSlopPx (it is a
// scroll/drag then, not a press). longPressID gates the long-press to the
// editor's click reg (browser rows etc. don't long-press). ppLast is in
// f32.Point because pointer.Event.Position is window-space f32.
pressProbe struct{}
ppLast f32.Point
ppActive bool
ppMoved bool
longPressID string
// Selection / caret drag handles (0 = start, 1 = end, 2 = body, 3 = caret
// handle). Registered clipped in drawWrappedText only while a selection or
// caret handle is visible; a gesture.Drag grabs the pointer once movement
// exceeds slop, which cancels the scroll and click handlers so a handle
// drag never fights a fling. selDragEmitting tracks whether a Drag event
// was delivered for the current gesture (so a plain tap on a handle does
// not emit a spurious SelectionDragEnd).
selDragStart gesture.Drag
selDragEnd gesture.Drag
selDragBody gesture.Drag
selDragCaret gesture.Drag
selDragsOn [4]bool
selDragEmitting [4]bool
selDragHandler func(any)
}
// New creates a new Renderer.
@@ -85,7 +127,7 @@ func New(th Theme, shp *text.Shaper) *Renderer {
theme: th,
shp: shp,
icons: make(map[string]image.Image),
clicks: make(map[string]clickReg),
clicks: make(map[string]*clickReg),
Keys: make(map[string]keyReg),
scrolls: make(map[string]scrollReg),
gioEditors: make(map[string]*widget.Editor),
@@ -169,10 +211,10 @@ func (r *Renderer) registerInteraction(id string, interaction Interaction, gtx l
case Tap:
reg, ok := r.clicks[id]
if !ok {
reg = clickReg{click: &gesture.Click{}}
reg = &clickReg{click: &gesture.Click{}}
r.clicks[id] = reg
}
reg.handler = interaction.Handler
r.clicks[id] = reg
// Register click within current clip context
reg.click.Add(gtx.Ops)
case Scroll:
@@ -184,6 +226,11 @@ func (r *Renderer) registerInteraction(id string, interaction Interaction, gtx l
reg.scroll.Add(gtx.Ops)
reg.handler = interaction.Handler
r.scrolls[id] = reg
case SelDrag:
// The renderer registers the actual gesture.Drag ops in
// drawWrappedText (it owns the handle geometry); this only records the
// logic handler that receives the drag events.
r.selDragHandler = interaction.Handler
}
}
@@ -193,10 +240,10 @@ func (r *Renderer) registerInteraction(id string, interaction Interaction, gtx l
func (r *Renderer) RegisterClick(gtx layout.Context, id string, region Region, handler func(any)) {
reg, ok := r.clicks[id]
if !ok {
reg = clickReg{click: &gesture.Click{}}
reg = &clickReg{click: &gesture.Click{}}
r.clicks[id] = reg
}
reg.handler = handler
r.clicks[id] = reg
// Clip to the specified region for click area
clickClip := clip.Rect{
Min: image.Point{X: int(r.toPx(region.X)), Y: int(r.toPx(region.Y))},
@@ -219,17 +266,101 @@ func (r *Renderer) RegisterScroll(gtx layout.Context, id string, region Region,
reg.scroll.Add(gtx.Ops)
}
// PendingLongPress reports whether a press is currently held still on the
// editor (long-press armed but not yet fired). Gio renders on demand: with a
// stationary finger there are no pointer events, hence no frames, and the
// 400 ms threshold could never be checked. The main loop calls this and
// invalidates the window while it is true, keeping frames flowing until the
// long press fires or the finger moves up.
func (r *Renderer) PendingLongPress() bool {
reg, ok := r.clicks[r.longPressID]
return ok && reg.click.Pressed() && !reg.longFired && !r.ppMoved && !reg.pressAt.IsZero()
}
// CheckGestures checks all registered gestures and returns any events.
func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
var events []InputEvent
for _, reg := range r.clicks {
evt, ok := reg.click.Update(q)
if ok {
if evt.Kind == gesture.KindClick {
// Long-press motion probe first: it must see the press/drag events before
// the click loop decides about a long press.
r.consumePressProbe(q)
for id, reg := range r.clicks {
// Drain every queued event for this gesture in this frame.
// gesture.Click returns one event per Update call, but on Android a
// tap's press and release routinely arrive in the same frame. Without
// draining, the release would sit unprocessed until the next redraw —
// which on an idle window may never come — and the tap is swallowed.
for {
evt, ok := reg.click.Update(q)
if !ok {
break
}
switch evt.Kind {
case gesture.KindPress:
reg.pressAt = time.Now()
reg.pressPos = evt.Position
reg.longFired = false
case gesture.KindClick:
if reg.longFired {
break // the press was consumed as a long press
}
if evt.NumClicks >= 2 {
events = append(events, InputEvent{
Handler: reg.handler,
Data: DoubleTapPoint{X: r.toDp(Px(evt.Position.X)), Y: r.toDp(Px(evt.Position.Y))},
})
} else {
events = append(events, InputEvent{
Handler: reg.handler,
Data: Point{X: r.toDp(Px(evt.Position.X)), Y: r.toDp(Px(evt.Position.Y))},
})
}
case gesture.KindCancel:
reg.pressAt = time.Time{}
reg.longFired = false
}
}
// Long press: the finger must still be down on the probed (editor)
// region, held still, for the long-press duration.
if id == r.longPressID && reg.click.Pressed() && !reg.longFired &&
!r.ppMoved && !reg.pressAt.IsZero() && time.Since(reg.pressAt) >= longPressDuration {
reg.longFired = true
events = append(events, InputEvent{
Handler: reg.handler,
Data: LongPressPoint{X: r.toDp(Px(reg.pressPos.X)), Y: r.toDp(Px(reg.pressPos.Y))},
})
}
}
// Selection / caret drags before scroll: a handle grab must win over fling.
drags := [4]*gesture.Drag{&r.selDragStart, &r.selDragEnd, &r.selDragBody, &r.selDragCaret}
for which, d := range drags {
if !r.selDragsOn[which] || r.selDragHandler == nil {
continue
}
// wasDragging is captured before Update: Update resets Dragging() on
// Release/Cancel, so it would read false afterwards.
wasDragging := d.Dragging()
// Drain all queued events for this drag in this frame (same
// one-event-per-Update rationale as the click loop above).
for {
e, ok := d.Update(m, q, gesture.Both)
if !ok {
break
}
switch e.Kind {
case pointer.Drag:
r.selDragEmitting[which] = true
events = append(events, InputEvent{
Handler: reg.handler,
Data: Point{X: r.toDp(Px(evt.Position.X)), Y: r.toDp(Px(evt.Position.Y))},
Handler: r.selDragHandler,
Data: SelectionDragEvent{Which: which, X: r.toDp(Px(e.Position.X)), Y: r.toDp(Px(e.Position.Y))},
})
case pointer.Release, pointer.Cancel:
if wasDragging && r.selDragEmitting[which] {
events = append(events, InputEvent{
Handler: r.selDragHandler,
Data: SelectionDragEnd{},
})
}
r.selDragEmitting[which] = false
}
}
}
@@ -249,6 +380,38 @@ func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
return events
}
// consumePressProbe drains the raw pointer events of the long-press probe
// and updates ppLast/ppMoved. It runs before the click loop each frame.
func (r *Renderer) consumePressProbe(q input.Source) {
for {
evt, ok := q.Event(pointer.Filter{Target: r.pressProbe, Kinds: pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel})
if !ok {
return
}
pe, ok := evt.(pointer.Event)
if !ok {
continue
}
switch pe.Kind {
case pointer.Press:
r.ppLast = pe.Position
r.ppActive = true
r.ppMoved = false
case pointer.Drag:
if r.ppActive {
dx, dy := pe.Position.X-r.ppLast.X, pe.Position.Y-r.ppLast.Y
if dx*dx+dy*dy > float32(longPressSlopPx*longPressSlopPx) {
r.ppMoved = true
}
}
r.ppLast = pe.Position
case pointer.Release, pointer.Cancel:
r.ppMoved = false
r.ppActive = false
}
}
}
// DisplayLineCount returns the number of display lines from the last
// drawWrappedText call. Used by the main loop to report back to logic.
func (r *Renderer) DisplayLineCount() int {
@@ -321,12 +484,17 @@ func (r *Renderer) drawElement(gtx layout.Context, e Element) {
if interaction.Gesture == Tap {
reg, ok := r.clicks[interactive.ID()]
if !ok {
reg = clickReg{click: &gesture.Click{}}
reg = &clickReg{click: &gesture.Click{}}
r.clicks[interactive.ID()] = reg
}
reg.handler = interaction.Handler
r.clicks[interactive.ID()] = reg
reg.click.Add(gtx.Ops)
}
if interaction.Gesture == SelDrag {
// Store the logic handler; the drag ops themselves are added
// clipped in drawWrappedText where the handle geometry is known.
r.registerInteraction(interactive.ID(), interaction, gtx)
}
}
}
e.Draw(gtx, r)
@@ -352,10 +520,10 @@ func (r *Renderer) drawElement(gtx layout.Context, e Element) {
if interaction.Gesture == Tap {
reg, ok := r.clicks[interactive.ID()]
if !ok {
reg = clickReg{click: &gesture.Click{}}
reg = &clickReg{click: &gesture.Click{}}
r.clicks[interactive.ID()] = reg
}
reg.handler = interaction.Handler
r.clicks[interactive.ID()] = reg
}
// For non-text elements, register click immediately
if _, isLabel := e.(Label); !isLabel {
@@ -482,7 +650,7 @@ func (r *Renderer) drawLine(gtx layout.Context, line []text.Glyph, x, y Dp, col
// detection via WrapHeuristically. Long words overflow the wrap width.
// Line spacing is fixed: LineHeight = fontSize × LineHeightScale, independent
// of glyph metrics. The shaper's first.Y accounts for line spacing.
func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, wrapWidth Dp, scrollOffset Dp, cursorPos, selStart, selEnd int) {
func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, wrapWidth Dp, scrollOffset Dp, cursorPos, selStart, selEnd int, caretDrag bool) {
if str == "" {
return
}
@@ -620,6 +788,96 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
}
r.drawBg(gtx, cursorRegion, Color{R: 0, G: 0, B: 0, A: 255})
// Long-press probe and selection/caret drag handles. The probe op and the
// (clipped) drag registrations live in the text clip so they only respond
// inside the editor region.
r.selDragsOn = [4]bool{}
event.Op(gtx.Ops, r.pressProbe)
r.longPressID = "editor_text"
if r.selDragHandler != nil && (selStart >= 0 && selEnd > selStart || caretDrag) {
lineH := Dp(r.theme.FontSize) * 1.2
// handleAt mirrors the cursor computation above: window-relative byte
// offset -> screen Dp of the caret insertion point.
handleAt := func(byteOff int) (x, y Dp) {
idx := sort.Search(len(layout.ByteOffsets), func(i int) bool {
return layout.ByteOffsets[i] >= byteOff
})
if idx < len(layout.ByteOffsets) {
return reg.X + layout.X[idx], reg.Y - scrollOffset + layout.Y[idx] - Dp(r.theme.FontSize)
}
n := len(layout.X) - 1
return reg.X + layout.X[n] + layout.Advance[n], reg.Y - scrollOffset + layout.Y[n] - Dp(r.theme.FontSize)
}
registerDrag := func(d *gesture.Drag, hx, hy Dp) {
hc := clip.Rect{
Min: image.Point{X: int(r.toPx(hx - 8)), Y: int(r.toPx(hy - 6))},
Max: image.Point{X: int(r.toPx(hx + 8)), Y: int(r.toPx(hy + lineH + 6))},
}.Push(gtx.Ops)
d.Add(gtx.Ops)
hc.Pop()
}
if selStart >= 0 && selEnd > selStart {
sx, sy := handleAt(selStart)
ex, ey := handleAt(selEnd)
registerDrag(&r.selDragStart, sx, sy)
r.selDragsOn[0] = true
registerDrag(&r.selDragEnd, ex, ey)
r.selDragsOn[1] = true
// Body: bounding box of the selected glyphs (only for 2+ glyphs; a
// single-glyph selection is already covered by its two handles).
var bx0, by0, bx1, by1 Dp
hasGlyph := false
for i := range layout.ByteOffsets {
b0 := layout.ByteOffsets[i]
b1 := len(str)
if i+1 < len(layout.ByteOffsets) {
b1 = layout.ByteOffsets[i+1]
}
if b0 >= selEnd || b1 <= selStart {
continue
}
gx := reg.X + layout.X[i]
gy := reg.Y - scrollOffset + layout.Y[i] - Dp(r.theme.FontSize)
gw := layout.Advance[i]
gh := lineH
if !hasGlyph {
bx0, by0, bx1, by1 = gx, gy, gx+gw, gy+gh
hasGlyph = true
} else {
if gx < bx0 {
bx0 = gx
}
if gy < by0 {
by0 = gy
}
if gx+gw > bx1 {
bx1 = gx + gw
}
if gy+gh > by1 {
by1 = gy + gh
}
}
}
if hasGlyph {
bc := clip.Rect{
Min: image.Point{X: int(r.toPx(bx0)), Y: int(r.toPx(by0))},
Max: image.Point{X: int(r.toPx(bx1)), Y: int(r.toPx(by1))},
}.Push(gtx.Ops)
r.selDragBody.Add(gtx.Ops)
bc.Pop()
r.selDragsOn[2] = true
}
r.drawHandle(gtx, sx, sy, lineH)
r.drawHandle(gtx, ex, ey, lineH)
} else {
// Caret drag (long press on blank space): a single handle on the caret.
cx, cy := handleAt(cursorPos)
registerDrag(&r.selDragCaret, cx, cy)
r.selDragsOn[3] = true
r.drawHandle(gtx, cx, cy, lineH)
}
}
textClip.Pop()
r.displayLineCount = lineCount
// Store captured layout; derive lastLineY from it.
@@ -629,6 +887,14 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
}
}
// drawHandle draws a selection handle: a short vertical stem with a filled
// square foot at the line's bottom (v1 approximation of Android's circle).
func (r *Renderer) drawHandle(gtx layout.Context, x, y, lineH Dp) {
col := Color{R: 51, G: 153, B: 255, A: 255}
r.drawBg(gtx, Region{X: x - 1, Y: y, W: 2, H: lineH}, col)
r.drawBg(gtx, Region{X: x - 5, Y: y + lineH - 2, W: 10, H: 10}, col)
}
func (r *Renderer) drawPng(gtx layout.Context, img image.Image, reg Region, width, height Dp) {
if img == nil {
return