Handle drags: 1:1 finger tracking with cross-flip; fix caret/taps on empty lines

Selection handles now track the finger 1:1 (anchor grab point + displacement)
instead of snapping by whole lines, and crossing the opposite handle flips
the selection (native behaviour) instead of clearing it.

Caret and tap/handle line resolution use VisualLineStarts instead of the
min-Y baseline: the window's first visual line may be an empty line with no
recorded glyphs, which used to draw boundary carets one line too low per
leading empty line and land taps/dragged handles one line below the finger.
New exported ui.CaretPoint centralises byte->insertion-point mapping.

The off-screen caret no longer clamps to the window edge: EditorLayout ships
the true (possibly negative / past-end) window-relative cursor and the
renderer skips the caret when the cursor is outside the shaped window, so
scrolling past the caret no longer makes it jump onto the top/bottom line.

IME/router replay fixes: key.FocusCmd is issued only on a focus transition
(a per-frame no-op still takes the immediate-command path and re-queues all
pointer events), and the key.SelectionCmd IME sync is deferred while a
handle drag is in progress (each push re-injected the drag into every
gesture). Handle drags forward only Grabbed events; a tap inside a handle
grab box is a no-op.

Also: key.FocusEvent no longer logs as unexpected in main; dead code removed
(worker taskWrapper, browser applyXxxResult stubs, scrollIndex, mock_setup
sortModeKey/lineSpan helpers); mock FileSystem.ListPaths prefix match uses
strings.HasPrefix; build scripts run the new scripts/check.sh static gate
(go vet + staticcheck). Tests: caret_point_test, touch_selection updates
(flip/empty-line cases), off-window caret e2e, selection drag e2e grab step.
This commit is contained in:
gmp
2026-08-19 22:34:12 -04:00
parent 110c92e3fa
commit d8b5bc704b
21 changed files with 955 additions and 377 deletions
+153
View File
@@ -0,0 +1,153 @@
package ui
import "testing"
// TestCaretPoint_EmptyFirstLine is a regression test for the caret jumping
// to an adjacent line while scrolling: when the shaped window's first visual
// line is empty (no recorded glyphs), the old code anchored the case-B
// baseline on the smallest recorded Y — the first NON-empty line — so every
// boundary caret (line-end "\n", an empty line's lone byte, EOF) drew one
// line too low per leading empty line, and the caret visibly jumped a line
// when the window scrolled past the empty line.
func TestCaretPoint_EmptyFirstLine(t *testing.T) {
const (
lh = Dp(16.8)
ascent = Dp(13.3)
)
// Window text starting on an empty line: line 0 is a lone "\n" (byte 0,
// no glyphs), line 1 is "abc" (bytes 1-3, "\n" at 4), line 2 is "def"
// (bytes 5-7, no trailing newline). Baselines are the uniform shaper
// grid: line i at ascent + i*lh; line 0 has no recorded glyphs.
str := "\nabc\ndef"
layout := GlyphLayout{
LineHeight: lh,
// VisualLineStarts: one entry per line start (0, 1, 5). The last
// line has no trailing break; the entry for it is byte 5.
VisualLineStarts: []int{0, 1, 5},
ByteOffsets: []int{1, 2, 3, 5, 6, 7},
X: []Dp{0, 10, 20, 0, 10, 20},
Y: []Dp{ascent + lh, ascent + lh, ascent + lh, ascent + 2*lh, ascent + 2*lh, ascent + 2*lh},
Advance: []Dp{10, 10, 10, 10, 10, 10},
}
near := func(got, want Dp) bool {
d := float64(got - want)
return d < 0.01 && d > -0.01
}
check := func(name string, byteOff int, wantX, wantY Dp) {
t.Helper()
x, y := CaretPoint(layout, str, byteOff, ascent, lh)
if !near(x, wantX) || !near(y, wantY) {
t.Errorf("%s: CaretPoint(%d) = (%v, %v); want (%v, %v)", name, byteOff, x, y, wantX, wantY)
}
}
// Case A: a glyph-start byte is unaffected (always was) — "a" of line 1.
check("glyph start (line 1)", 1, 0, ascent+lh)
// Case B: the empty first line's lone insertion point sits on line 0.
// Old code: minY = ascent+lh, line 0 -> y = ascent+lh (one line low).
check("empty line 0 origin", 0, 0, ascent)
// Case B: the terminating "\n" of line 1 sits at line 1's right edge.
// Old code: minY = ascent+lh, line 1 -> y = ascent+2*lh (one line low).
check("line 1 end (\\n)", 4, 30, ascent+lh)
// Case B: EOF on the last line sits at line 2's right edge.
// Old code: y = ascent+lh+2*lh (one line low).
check("EOF (line 2 end)", 8, 30, ascent+2*lh)
}
// TestCaretPoint_EmptyFirstLines covers several leading empty lines: the
// anchor must walk back j full line heights, not one.
func TestCaretPoint_EmptyFirstLines(t *testing.T) {
const (
lh = Dp(16.8)
ascent = Dp(13.3)
)
// Two empty lines, then "abc".
str := "\n\nabc"
layout := GlyphLayout{
LineHeight: lh,
VisualLineStarts: []int{0, 1, 2},
ByteOffsets: []int{2, 3, 4},
X: []Dp{0, 10, 20},
Y: []Dp{ascent + 2*lh, ascent + 2*lh, ascent + 2*lh},
Advance: []Dp{10, 10, 10},
}
near := func(got, want Dp) bool {
d := float64(got - want)
return d < 0.01 && d > -0.01
}
// End of the "abc" line (no trailing newline): right edge of line 2.
x, y := CaretPoint(layout, str, 5, ascent, lh)
wantX, wantY := Dp(30), ascent+2*lh
if !near(x, wantX) || !near(y, wantY) {
t.Errorf("EOF after two empty lines = (%v, %v); want (%v, %v)", x, y, wantX, wantY)
}
// The second empty line's origin: line 1.
x, y = CaretPoint(layout, str, 1, ascent, lh)
wantX, wantY = Dp(0), ascent+lh
if !near(x, wantX) || !near(y, wantY) {
t.Errorf("empty line 1 origin = (%v, %v); want (%v, %v)", x, y, wantX, wantY)
}
}
// TestCaretPoint_NonEmptyFirstLine guards against regressions in the common
// case: with a glyph on the window's first line the anchor is the first
// recorded baseline (the old behaviour), unchanged.
func TestCaretPoint_NonEmptyFirstLine(t *testing.T) {
const (
lh = Dp(16.8)
ascent = Dp(13.3)
)
str := "abc\ndef"
layout := GlyphLayout{
LineHeight: lh,
VisualLineStarts: []int{0, 4},
ByteOffsets: []int{0, 1, 2, 4, 5, 6},
X: []Dp{0, 10, 20, 0, 10, 20},
Y: []Dp{ascent, ascent, ascent, ascent + lh, ascent + lh, ascent + lh},
Advance: []Dp{10, 10, 10, 10, 10, 10},
}
near := func(got, want Dp) bool {
d := float64(got - want)
return d < 0.01 && d > -0.01
}
// Line 0's "\n": line 0's right edge at line 0's baseline (ascent).
x, y := CaretPoint(layout, str, 3, ascent, lh)
wantX, wantY := Dp(30), ascent
if !near(x, wantX) || !near(y, wantY) {
t.Errorf("line 0 end = (%v, %v); want (%v, %v)", x, y, wantX, wantY)
}
// EOF: line 1's right edge.
x, y = CaretPoint(layout, str, 7, ascent, lh)
wantX, wantY = Dp(30), ascent+lh
if !near(x, wantX) || !near(y, wantY) {
t.Errorf("EOF = (%v, %v); want (%v, %v)", x, y, wantX, wantY)
}
}
// TestCaretPoint_NoGlyphs covers a window of pure newlines: the ascent
// fallback anchor applies.
func TestCaretPoint_NoGlyphs(t *testing.T) {
const (
lh = Dp(16.8)
ascent = Dp(13.3)
)
str := "\n\n\n"
layout := GlyphLayout{
LineHeight: lh,
VisualLineStarts: []int{0, 1, 2},
}
near := func(got, want Dp) bool {
d := float64(got - want)
return d < 0.01 && d > -0.01
}
// The second empty line's origin: line 1.
x, y := CaretPoint(layout, str, 1, ascent, lh)
wantX, wantY := Dp(0), ascent+lh
if !near(x, wantX) || !near(y, wantY) {
t.Errorf("pure-newline window, empty line 1 = (%v, %v); want (%v, %v)", x, y, wantX, wantY)
}
}
+25 -7
View File
@@ -234,7 +234,15 @@ func (tf TextField) Draw(gtx layout.Context, r *Renderer) {
}
r.lastIMEField = tf.id
r.lastWasFocused = true
gtx.Execute(key.FocusCmd{Tag: tf.id})
// Issue key.FocusCmd only on a focus transition (see
// Renderer.lastFocusCmdID): a per-frame no-op FocusCmd still triggers
// the router's immediate-command path, which re-queues the frame's
// pointer events and replays every touch event into every gesture.
r.focusSeenThisFrame = true
if r.lastFocusCmdID != tf.id {
r.lastFocusCmdID = tf.id
gtx.Execute(key.FocusCmd{Tag: tf.id})
}
// Raise the soft keyboard only when the logic layer pulses it (focus
// gain, file open, editor tap), not every frame. A per-frame show was
// harmless while the app only redrew on user events, but the IME
@@ -293,13 +301,23 @@ func (tf TextField) Draw(gtx layout.Context, r *Renderer) {
selEnd = runeCount(tf.Value, tf.CursorPosition)
}
if selStart != r.lastSelStart || selEnd != r.lastSelCaret {
r.lastSelStart = selStart
r.lastSelCaret = selEnd
rng := key.Range{Start: selStart, End: selEnd}
if selStart < 0 {
rng = key.Range{Start: selEnd, End: selEnd}
// While a selection/caret handle drag is in progress, defer the
// IME selection sync (see Renderer.selDragActive): pushing a
// SelectionCmd every frame the drag moves the selection triggers the
// input router's immediate-command replay of the frame's pointer
// events, which re-injects the drag into every gesture and makes the
// selection jump. The final selection is pushed on the first frame
// after the drag ends (lastSelStart/lastSelCaret were not updated,
// so the mismatch persists until then).
if !r.selDragActive {
r.lastSelStart = selStart
r.lastSelCaret = selEnd
rng := key.Range{Start: selStart, End: selEnd}
if selStart < 0 {
rng = key.Range{Start: selEnd, End: selEnd}
}
gtx.Execute(key.SelectionCmd{Tag: tf.id, Range: rng, Caret: key.Caret{}})
}
gtx.Execute(key.SelectionCmd{Tag: tf.id, Range: rng, Caret: key.Caret{}})
}
} else if r.lastIMEField == tf.id {
// This (previously-focused) field lost focus: forget it so the next focus
+194 -35
View File
@@ -92,6 +92,20 @@ type Renderer struct {
lastSelCaret int // window-relative rune index of last-pushed selection end/caret
lastIMEShowSeq uint64 // last ShowIMESeq value that issued SoftKeyboardCmd{Show:true}
// FocusCmd dedup (main-owned, persistent across frames). key.FocusCmd is
// issued ONLY on a focus transition, never per frame: even a no-op FocusCmd
// (same focus) takes the router's "immediate command" path, which re-queues
// the frame's pending pointer events and re-delivers every touch event to
// every gesture. During a selection-handle drag that replayed each event
// several times per frame, making the selection unusable. The key queue
// keeps the focus until the handler stops registering as focusable, so one
// command per transition is sufficient.
lastFocusCmdID string
// focusSeenThisFrame is reset at the start of each Draw; if no focused
// TextField was drawn in the frame, lastFocusCmdID is cleared so a field
// regaining focus later re-issues the command.
focusSeenThisFrame bool
// 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
@@ -124,6 +138,15 @@ type Renderer struct {
// (-1 = none), set by CheckGestures and read by drawWrappedText to
// enlarge the grabbed handle, as the framework does while dragging.
selDraggingWhich int
// selDragActive reports that a selection/caret drag is in progress.
// TextField.Draw skips the key.SelectionCmd IME sync while it is set:
// the command triggers the router's immediate-command path, which
// re-queues the frame's pointer events and replays every drag event
// into the gestures (a replay storm — each re-queued event lands in
// q.changes and is re-queued again on the next SelectionCmd). The IME
// only needs the final selection, pushed on the first frame after the
// drag ends.
selDragActive bool
// gestureExclusions holds the selection-handle grab boxes (view-local
// px, [x0, y0, x1, y1]) collected by drawWrappedText for the current
// frame. On Android the main loop forwards them to
@@ -136,6 +159,19 @@ type Renderer struct {
// frame (see gestureExclusions).
func (r *Renderer) GestureExclusions() [][4]int { return r.gestureExclusions }
// pointInHandleBox reports whether the window-pixel point lies inside one of
// the last frame's selection/caret handle grab boxes (gestureExclusions holds
// those boxes, clipped to the editor region).
func (r *Renderer) pointInHandleBox(p image.Point) bool {
for _, b := range r.gestureExclusions {
// Boxes are [x0, y0, x1, y1].
if p.X >= b[0] && p.X < b[2] && p.Y >= b[1] && p.Y < b[3] {
return true
}
}
return false
}
// New creates a new Renderer.
func New(th Theme, shp *text.Shaper) *Renderer {
r := &Renderer{
@@ -201,6 +237,7 @@ func (r *Renderer) toDp(px Px) Dp {
// reads logic state directly).
func (r *Renderer) Draw(gtx layout.Context, elems []Element, scale float32) {
r.scale = scale
r.focusSeenThisFrame = false // per-frame reset for FocusCmd dedup
// Gio sets constraints to layout.Exact(windowSize), so Min==Max. Use (0,0) as Min.
winW := gtx.Constraints.Max.X
winH := gtx.Constraints.Max.Y
@@ -216,6 +253,13 @@ func (r *Renderer) Draw(gtx layout.Context, elems []Element, scale float32) {
r.drawElement(gtx, e)
}
// If no focused TextField was drawn this frame, the key queue will drop
// the focus (the focused handler stops registering as focusable). Clear the
// dedup so the same field re-issues key.FocusCmd when it regains focus.
if !r.focusSeenThisFrame {
r.lastFocusCmdID = ""
}
clipRect.Pop()
}
@@ -319,6 +363,16 @@ func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
if reg.longFired {
break // the press was consumed as a long press
}
if r.pointInHandleBox(evt.Position) {
// A tap inside a handle grab box is a handle touch that
// never reached the drag slop (or a deliberate light
// touch on the handle): it must be a no-op, not a text
// tap. Forwarding it would clear the selection and move
// the caret, so a light touch on a handle destroyed the
// selection. (Native Android: tapping a handle does
// nothing.)
break
}
if evt.NumClicks >= 2 {
events = append(events, InputEvent{
Handler: reg.handler,
@@ -364,8 +418,18 @@ func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
}
switch e.Kind {
case pointer.Drag:
// Forward only grabbed events: gesture.Drag also returns the
// pre-grab (Shared priority) moves, and acting on those would
// start moving the selection at the press position — the grab
// jitter. The first Grabbed event lands just past the touch slop,
// matching native Android, where the handle follows only after
// the slop.
if e.Priority != pointer.Grabbed {
continue
}
r.selDragEmitting[which] = true
r.selDraggingWhich = which
r.selDragActive = true
events = append(events, InputEvent{
Handler: r.selDragHandler,
Data: SelectionDragEvent{Which: which, X: r.toDp(Px(e.Position.X)), Y: r.toDp(Px(e.Position.Y))},
@@ -384,6 +448,21 @@ func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
}
}
}
// Safety net: if no gesture is still dragging but a selection/caret drag
// was active (e.g. the release was never delivered), clear the flag so the
// IME selection sync (key.SelectionCmd) resumes — see TextField.Draw.
if r.selDragActive {
stillDragging := false
for _, d := range drags {
if d.Dragging() {
stillDragging = true
break
}
}
if !stillDragging {
r.selDragActive = false
}
}
for _, reg := range r.scrolls {
// gesture.Scroll.Update returns scroll delta in pixels.
// ScrollY range: Min = -scrollOffset (remaining above), Max = large (content height unknown yet).
@@ -397,6 +476,7 @@ func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
})
}
}
return events
}
@@ -735,10 +815,21 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
// Record layout data for this glyph.
// g.X is in fixed.Int26_6 — shift >> 6 for device pixels, divide by scale for Dp.
// g.Y is the baseline in device pixels.
layout.ByteOffsets = append(layout.ByteOffsets, byteOffset)
layout.X = append(layout.X, Dp(float32(g.X>>6)/r.scale))
layout.Y = append(layout.Y, Dp(float32(g.Y)/r.scale))
layout.Advance = append(layout.Advance, Dp(float32(g.Advance>>6)/r.scale))
// The shaper flags the LAST glyph of every visual line with
// FlagLineBreak. For hard lines that is the zero-width "\n" cluster
// glyph (and, after a trailing "\n", one more synthetic end-of-text
// glyph) — not a character, so it is skipped to keep ByteOffsets a 1:1
// map to bytes. For SOFT-wrapped lines (and a final line without a
// trailing newline) the flag instead sits on the line's last visible
// character, which MUST stay in the layout: dropping it would make taps
// on the right half of that character and selection highlights of it
// miss. Zero width is the discriminator (a real glyph always advances).
if g.Flags&text.FlagLineBreak == 0 || g.Advance != 0 {
layout.ByteOffsets = append(layout.ByteOffsets, byteOffset)
layout.X = append(layout.X, Dp(float32(g.X>>6)/r.scale))
layout.Y = append(layout.Y, Dp(float32(g.Y)/r.scale))
layout.Advance = append(layout.Advance, Dp(float32(g.Advance>>6)/r.scale))
}
// Advance byteOffset by g.Runes.
for i := uint16(0); i < g.Runes; i++ {
@@ -794,32 +885,35 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
call := m.Stop()
call.Add(gtx.Ops)
// Determine cursor position from `layout` and `cursorPos`
var cursorX, cursorY Dp
if len(layout.ByteOffsets) == 0 {
cursorX = reg.X
cursorY = reg.Y
} else {
idx := sort.Search(len(layout.ByteOffsets), func(i int) bool {
return layout.ByteOffsets[i] >= cursorPos
})
if idx < len(layout.ByteOffsets) {
cursorX = reg.X + layout.X[idx]
cursorY = reg.Y - scrollOffset + layout.Y[idx] - ascent
} else {
cursorX = reg.X + layout.X[len(layout.X)-1] + layout.Advance[len(layout.Advance)-1]
cursorY = reg.Y - scrollOffset + layout.Y[len(layout.Y)-1] - ascent
}
// caretPoint maps a window-relative byte offset to the insertion
// point's region-relative (x, y) in Dp, where y is the line's baseline
// (see CaretPoint).
caretPoint := func(byteOff int) (x, y Dp) {
return CaretPoint(layout, str, byteOff, ascent, lineH)
}
// Draw the cursor (thin vertical bar)
cursorRegion := Region{
X: cursorX,
Y: cursorY,
W: Dp(2),
H: lineH, // line height (font-scale aware)
// Draw the caret only when the cursor's byte is inside the shaped window
// (window-relative: [0, len(str)]). The window covers the viewport
// exactly, so an out-of-range cursor is off-screen and its caret must not
// be drawn; the caller used to clamp it to 0, which made the caret jump
// onto the top (or, past the end, the bottom) visible line whenever the
// user scrolled past it. The boundary values are on-screen: 0 is the
// window's first byte and len(str) is the window's last insertion point.
if cursorPos >= 0 && cursorPos <= len(str) {
// Determine cursor position from `layout` and `cursorPos`
cursorX, cursorY := caretPoint(cursorPos)
cursorX = reg.X + cursorX
cursorY = reg.Y - scrollOffset + cursorY - ascent
// Draw the cursor (thin vertical bar)
cursorRegion := Region{
X: cursorX,
Y: cursorY,
W: Dp(2),
H: lineH, // line height (font-scale aware)
}
r.drawBg(gtx, cursorRegion, Color{R: 0, G: 0, B: 0, A: 255})
}
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
@@ -831,14 +925,8 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
// 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] - ascent
}
n := len(layout.X) - 1
return reg.X + layout.X[n] + layout.Advance[n], reg.Y - scrollOffset + layout.Y[n] - ascent
hx, hy := caretPoint(byteOff)
return reg.X + hx, reg.Y - scrollOffset + hy - ascent
}
// The visual handle (drawHandle) is a ~20dp teardrop centred at
// (hx, hy+lineH+handleRadius); the GRAB region is a 48dp box around
@@ -1024,3 +1112,74 @@ func (r *Renderer) drawPng(gtx layout.Context, img image.Image, reg Region, widt
scale.Pop()
offset.Pop()
}
// CaretPoint maps a window-relative byte offset to the insertion point's
// (x, y) in Dp relative to the shaped window's origin, where y is the
// line's baseline. A byte at a real glyph's start sits at the glyph's left
// edge; any other insertion point (a line's terminating "\n", an empty
// line's lone byte, EOF, or a wrapped line's first byte) sits on the visual
// line whose first byte is at or before it — the last such line — at the
// line origin for a line's first byte, and at the last glyph's right edge
// otherwise. (The first glyph at/past such a byte sits on the NEXT line,
// so it cannot be used for the line resolution.)
//
// The line's baseline comes from the uniform shaper grid
// (firstBaseline + line*lineH). firstBaseline is the window's FIRST visual
// line's baseline. When that line is empty (no recorded glyphs), the
// smallest recorded Y is the first NON-empty line's baseline =
// firstBaseline + j*lineH, j being the first recorded glyph's visual line;
// anchoring on the smallest Y instead drew every boundary caret one line
// too low per leading empty line, and the caret visibly jumped a line when
// the window scrolled past the empty line.
func CaretPoint(layout GlyphLayout, str string, byteOff int, ascent, lineH Dp) (x, y Dp) {
if idx := sort.Search(len(layout.ByteOffsets), func(i int) bool {
return layout.ByteOffsets[i] >= byteOff
}); idx < len(layout.ByteOffsets) && layout.ByteOffsets[idx] == byteOff {
return layout.X[idx], layout.Y[idx]
}
line := 0
lineStart, lineEnd := 0, len(str)
if starts := layout.VisualLineStarts; len(starts) > 0 {
k := sort.Search(len(starts), func(i int) bool {
return starts[i] > byteOff
})
if k > 0 {
line = k - 1
}
lineStart = starts[line]
if k < len(starts) {
lineEnd = starts[k]
}
}
var anchor Dp
if len(layout.ByteOffsets) > 0 {
j := 0
if starts := layout.VisualLineStarts; len(starts) > 0 {
if k := sort.Search(len(starts), func(i int) bool {
return starts[i] > layout.ByteOffsets[0]
}); k > 0 {
j = k - 1
}
}
anchor = layout.Y[0] - Dp(j)*lineH
} else {
anchor = ascent // no glyphs in the window (pure newlines)
}
y = anchor + Dp(line)*lineH
if byteOff == lineStart {
return 0, y // line origin (empty line, or wrapped line start)
}
// The line's "\n" (or EOF on the last line): the last glyph's right
// edge on the line.
var rightX Dp
found := false
for i, bo := range layout.ByteOffsets {
if bo < lineStart || bo >= lineEnd {
continue
}
if xe := layout.X[i] + layout.Advance[i]; !found || xe > rightX {
rightX, found = xe, true
}
}
return rightX, y
}