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
+23
View File
@@ -154,6 +154,24 @@ func (l *Logic) SearchQueryChan() chan<- string {
return l.searchQueryChan
}
// ClipboardSetChan returns the channel the logic goroutine uses to request a
// system clipboard write; the main goroutine executes the Gio clipboard op.
func (l *Logic) ClipboardSetChan() <-chan string {
return l.state.clipboardSetChan
}
// PasteReqChan returns the channel the logic goroutine uses to request the
// system clipboard content for paste.
func (l *Logic) PasteReqChan() <-chan struct{} {
return l.state.pasteReqChan
}
// PasteChan delivers system clipboard content to the logic goroutine for
// paste (tests use it to inject clipboard text without a main loop).
func (l *Logic) PasteChan() chan<- string {
return l.state.pasteChan
}
var TheState *State
var TheLogic *Logic
@@ -232,6 +250,11 @@ func (l *Logic) Run() {
l.workerPool.DispatchNonBlocking(
pool.NewWriteFileTask(l.state.Editor.Filename, content, l.mockFS),
)
case p := <-l.state.pasteChan:
// Clipboard content arrived from the main goroutine: insert it
// (replacing any live selection, per the selection-aware edit rule).
HandlePaste(p)
l.emitFrame()
case req := <-l.inspectChan:
// Test-only: fn runs on the owner, preserving single ownership.
req.resp <- req.fn(l.state)
+550 -26
View File
@@ -6,6 +6,7 @@ import (
"math"
"sort"
"time"
"unicode"
"unicode/utf8"
"gioui.org/io/key"
@@ -79,7 +80,23 @@ type EditorState struct {
// IMEWindowText is the visible window text shown to the IME (the snippet).
// It is set during layout and is what an EditEvent.Range indexes into.
IMEWindowText string
Filename string
// --- Touch selection (v1) ---
// CaretDrag: after a long press on blank space a single draggable caret
// handle is shown (no selection). MenuVisible/MenuRect/MenuItems: the
// floating copy/cut/paste menu (positioned below the line of the selection
// end; items are recomputed when the menu is shown). SelDragging/
// SelDragWhich/SelDragRel: transient state of an in-progress handle/body
// drag (Which: 0 = start handle, 1 = end handle, 2 = body, 3 = caret
// handle). All of it is logic-owned; the renderer only reports finger
// positions and draws the geometry.
CaretDrag bool
MenuVisible bool
MenuRect ui.Region
MenuItems []ui.MenuItem
SelDragging bool
SelDragWhich int
SelDragRel int
Filename string
// TooLarge is set when an opened file exceeds MaxEditableFileSize. The
// editor shows a "too large to edit" notice instead of content (the
// browser can still list the file).
@@ -156,6 +173,17 @@ type State struct {
Elems []ui.Element
lastEvictionTime time.Time // Throttles chunk eviction
justOpenedAt time.Time // when the editor page was last opened; used to swallow the opening tap
// EditorRegion is the editor text region in app-local Dp, recomputed on
// every layout. Input handlers (tap, long press, selection drags) convert
// app-local points to text-local coordinates through it.
EditorRegion ui.Region
// Clipboard channels (touch-selection menu). ClipboardSetChan and
// PasteReqChan are consumed by the main goroutine, which executes the Gio
// clipboard ops and reports the read result back on PasteChan. Buffered so
// a harness without a main loop never blocks the logic goroutine.
clipboardSetChan chan string
pasteReqChan chan struct{}
pasteChan chan string
// Browser state (directly embedded per architecture §8)
Browser browser.BrowserState // Embedded, not a pointer
// Editor state
@@ -180,6 +208,9 @@ func NewState() *State {
writeFailed: make(map[string]bool),
retryAttempts: make(map[string]int),
},
clipboardSetChan: make(chan string, 16),
pasteReqChan: make(chan struct{}, 16),
pasteChan: make(chan string, 16),
}
}
@@ -434,12 +465,18 @@ func selActive() bool {
return e.SelectionAnchor >= 0 && e.SelectionStart >= 0 && e.SelectionEnd > e.SelectionStart
}
// ClearSelection drops the selection and the shift-anchor.
// ClearSelection drops the selection and the shift-anchor. It also dismisses
// the selection menu and cancels any in-progress drag bookkeeping: every path
// that clears the selection (tap, plain cursor move, any edit) should take
// the menu and handles down with it.
func ClearSelection() {
e := &TheState.Editor
e.SelectionAnchor = -1
e.SelectionStart = -1
e.SelectionEnd = -1
e.MenuVisible = false
e.MenuItems = nil
e.SelDragging = false
}
// SetSelection selects the byte range [min(start,end), max(start,end)),
@@ -531,6 +568,467 @@ func deleteRange(start, end int) {
}
}
// --- Touch selection (v1) ---------------------------------------------------
//
// Android-style touch interaction, layered over the byte-range selection
// model above. Single tap = caret (existing). Long press = select the word
// under the finger (or a draggable caret handle on blank space). Double tap
// = select the word. Handles: drag start/end to resize, drag the body to move
// the whole selection. Floating menu: Copy / Cut / Paste.
//
// Coordinate flow: the renderer reports app-local window Dp points (the same
// space as a tap). The functions below convert to text-local coordinates via
// EditorRegion + tapLocalY, then to byte offsets via textPosFromLocalPoint.
// All of these run on the logic goroutine (owner).
const (
menuItemW = ui.Dp(56) // width of one selection-menu button
menuH = ui.Dp(52) // selection-menu panel height
)
// isWordRune reports whether a rune is part of a selectable word (letters,
// digits, underscore).
func isWordRune(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'
}
// windowContent returns a content accessor for the active buffer.
func windowContent() func(a, b int) string {
if cb := TheState.Editor.ChunkedBuffer; cb != nil {
return func(a, b int) string {
return cb.Content(a, b)
}
}
s := TheState.Editor.Buffer
return func(a, b int) string {
if a < 0 {
a = 0
}
if b > len(s) {
b = len(s)
}
if a >= b {
return ""
}
return s[a:b]
}
}
func fileLenBytes() int {
if cb := TheState.Editor.ChunkedBuffer; cb != nil {
return int(cb.FileLen())
}
return len(TheState.Editor.Buffer)
}
// wordRangeAt returns the byte range [start, end) of the word containing the
// rune at (or immediately before) pos. ok=false when neither is a word
// character (e.g. a space or punctuation).
func wordRangeAt(pos int) (start, end int, ok bool) {
content := windowContent()
fileLen := fileLenBytes()
if pos < 0 {
pos = 0
}
if pos > fileLen {
pos = fileLen
}
// 256-byte window around pos; words longer than that are clipped (rare).
a := pos - 256
if a < 0 {
a = 0
}
b := pos + 256
if b > fileLen {
b = fileLen
}
w := content(a, b)
rp := pos - a
// Rune starting at rp, and rune ending at rp (if any).
rAt, szAt := utf8.DecodeRuneInString(w[rp:])
var rBefore rune
var szBefore int
if rp > 0 {
j := rp - 1
for j >= 0 && w[j]&0xC0 == 0x80 {
j--
}
if j >= 0 {
rBefore, szBefore = utf8.DecodeRuneInString(w[j:])
}
}
// expandWord grows [l, r) over consecutive word runes (byte offsets in w).
expandWord := func(l, r int) (int, int) {
for l > 0 {
j := l - 1
for j >= 0 && w[j]&0xC0 == 0x80 {
j--
}
if j < 0 {
break
}
r, _ := utf8.DecodeRuneInString(w[j:])
if !isWordRune(r) {
break
}
l = j
}
for r < len(w) {
rr, sz := utf8.DecodeRuneInString(w[r:])
if sz == 0 || !isWordRune(rr) {
break
}
r += sz
}
return l, r
}
if szAt > 0 && isWordRune(rAt) {
l, r := expandWord(rp, rp+szAt)
return a + l, a + r, true
}
if szBefore > 0 && isWordRune(rBefore) {
l, r := expandWord(rp-szBefore, rp)
return a + l, a + r, true
}
return 0, 0, false
}
// pointInMenu reports whether the app-local Dp point is inside the visible
// selection menu panel.
func pointInMenu(x, y ui.Dp) bool {
r := TheState.Editor.MenuRect
return x >= r.X && x < r.X+r.W && y >= r.Y && y < r.Y+r.H
}
func hideSelectionMenu() {
e := &TheState.Editor
e.MenuVisible = false
e.MenuItems = nil
e.MenuRect = ui.Region{}
}
// showSelectionMenu positions the copy/cut/paste menu below the line that
// contains the selection end (or caret) and recomputes the items. Copy and
// Cut are offered only while a selection is active; Paste always.
func showSelectionMenu() {
e := &TheState.Editor
if e.TooLarge || len(e.GlyphLayout.ByteOffsets) == 0 {
return
}
anchor := e.CursorPosition
if e.SelectionEnd > anchor {
anchor = e.SelectionEnd
}
glyphX, lineTop, ok := bytePosToScreenXY(anchor)
if !ok {
return
}
var winW, winH float64
if TheState.scale > 0 {
winW = float64(ui.ToDp(ui.Px(TheState.PixelWidth), TheState.scale))
winH = float64(ui.ToDp(ui.Px(TheState.PixelHeight), TheState.scale))
}
var items []ui.MenuItem
add := func(icon, label string) {
items = append(items, ui.MenuItem{
Icon: icon, Label: label,
X: menuItemW * ui.Dp(len(items)), Y: 0, W: menuItemW, H: menuH,
})
}
if selActive() {
add("copy", "Copy")
add("cut", "Cut")
}
add("paste", "Paste")
menuW := menuItemW * ui.Dp(len(items))
mx := glyphX - float64(menuW)/2
if mx < 8 {
mx = 8
}
if winW > 0 && mx+float64(menuW) > winW-8 {
mx = winW - float64(menuW) - 8
}
my := lineTop + float64(EditorLineHeight()) + 8 // below the line
if winH > 0 && my+float64(menuH) > winH-8 {
my = lineTop - float64(menuH) - 8 // flip above the line
}
if my < 8 {
my = 8
}
e.MenuRect = ui.Region{X: ui.Dp(mx), Y: ui.Dp(my), W: menuW, H: menuH}
e.MenuItems = items
e.MenuVisible = true
}
// bytePosToScreenXY returns app-local Dp coordinates for absByte: the X of
// the glyph at (or just before) the byte, and the top Y of the visual line
// containing it. ok=false when the layout is empty or the byte is outside
// the visible window. This is the inverse of textPosFromLocalPoint.
func bytePosToScreenXY(absByte int) (glyphX, lineTop float64, ok bool) {
layout := TheState.Editor.GlyphLayout
reg := TheState.EditorRegion
if len(layout.ByteOffsets) == 0 {
return 0, 0, false
}
base := glyphBase()
pos := absByte - base
windowLen := len(TheState.Editor.IMEWindowText)
if pos < 0 || pos > windowLen {
return 0, 0, false
}
lineHeight := float64(EditorLineHeight())
idx := sort.Search(len(layout.ByteOffsets), func(i int) bool {
return layout.ByteOffsets[i] >= pos
})
if idx < len(layout.ByteOffsets) && layout.ByteOffsets[idx] > pos {
idx--
}
if idx < 0 {
idx = 0
}
if idx >= len(layout.ByteOffsets) {
// pos is at/past EOF: anchor on the last glyph.
idx = len(layout.ByteOffsets) - 1
}
gx := float64(reg.X) + float64(layout.X[idx])
// layout.Y is the baseline; the baseline offset within a line is always
// < lineHeight, so int(baseline/lineHeight) is the visual line index.
visualLine := int(float64(layout.Y[idx]) / lineHeight)
if visualLine < 0 {
visualLine = 0
}
lt := float64(reg.Y) + float64(visualLine)*lineHeight
return gx, lt, true
}
// tapInputGuard swallows editor input for a short window after a file opens:
// the tap that opened the file must not also reposition the caret.
func tapInputGuard() bool {
return time.Since(TheState.justOpenedAt) < 300*time.Millisecond
}
// HandleTapAt places the caret at app-local Dp point (x, y). A tap on the
// visible selection menu is ignored (the menu's own Tap interaction handles
// it); any other tap dismisses the menu and ends a caret drag.
func HandleTapAt(x, y ui.Dp) {
if tapInputGuard() {
return
}
e := &TheState.Editor
if e.MenuVisible && pointInMenu(x, y) {
return
}
e.CaretDrag = false
hideSelectionMenu()
localX := float64(x - TheState.EditorRegion.X)
localY := tapLocalY(y, TheState.EditorRegion.Y, TheState.ScrollOffset)
SetCursorFromPoint(localX, localY)
}
// HandleLongPressAt implements Android long-press: on a word it selects the
// word; on blank space it sets the caret there and shows a single draggable
// caret handle. The selection menu is shown either way.
func HandleLongPressAt(x, y ui.Dp) {
if tapInputGuard() {
return
}
e := &TheState.Editor
if e.TooLarge {
return
}
if e.MenuVisible && pointInMenu(x, y) {
return
}
localX := float64(x - TheState.EditorRegion.X)
localY := tapLocalY(y, TheState.EditorRegion.Y, TheState.ScrollOffset)
pos, ok := textPosFromLocalPoint(localX, localY)
if !ok {
return
}
if ws, we, found := wordRangeAt(pos); found {
SetSelection(ws, we)
e.CaretDrag = false
} else {
ClearSelection()
e.CursorPosition = pos
e.CaretDrag = true
}
showSelectionMenu()
}
// HandleDoubleTapAt selects the word under the finger (and shows the menu);
// on blank space it just places the caret.
func HandleDoubleTapAt(x, y ui.Dp) {
if tapInputGuard() {
return
}
e := &TheState.Editor
if e.TooLarge {
return
}
if e.MenuVisible && pointInMenu(x, y) {
return
}
localX := float64(x - TheState.EditorRegion.X)
localY := tapLocalY(y, TheState.EditorRegion.Y, TheState.ScrollOffset)
pos, ok := textPosFromLocalPoint(localX, localY)
if !ok {
return
}
if ws, we, found := wordRangeAt(pos); found {
SetSelection(ws, we)
e.CaretDrag = false
showSelectionMenu()
} else {
SetCursorFromPoint(localX, localY)
}
}
// HandleSelDragEvt is the registered SelDrag interaction handler. The
// renderer delivers SelectionDragEvent (finger position) and SelectionDragEnd.
func HandleSelDragEvt(data any) {
switch ev := data.(type) {
case ui.SelectionDragEvent:
selDragMove(ev.Which, ev.X, ev.Y)
case ui.SelectionDragEnd:
TheState.Editor.SelDragging = false
TheState.Editor.SelDragRel = 0
// The caret handle (long press on blank space) is a transient affordance;
// the selection handles come back from the selection state on the next
// frame, so only the caret mode is dropped here.
TheState.Editor.CaretDrag = false
}
}
// selDragMove applies one finger position of a selection/caret drag.
func selDragMove(which int, x, y ui.Dp) {
e := &TheState.Editor
localX := float64(x - TheState.EditorRegion.X)
localY := tapLocalY(y, TheState.EditorRegion.Y, TheState.ScrollOffset)
pos, ok := textPosFromLocalPoint(localX, localY)
if !e.SelDragging {
e.SelDragging = true
e.SelDragWhich = which
if which == 2 && ok {
// Body drag: the grab fixes the finger's offset from the selection
// start; the selection itself moves on later events.
e.SelDragRel = pos - e.SelectionStart
if e.SelDragRel < 0 {
e.SelDragRel = 0
}
return
}
// Start/end/caret handles: the first event already positions the
// handle (no grab offset needed).
}
if !ok {
return // finger outside the laid-out window: keep last position
}
switch e.SelDragWhich {
case 0: // start handle
if pos > e.SelectionEnd {
pos = e.SelectionEnd
}
SetSelection(pos, e.SelectionEnd)
case 1: // end handle
if pos < e.SelectionStart {
pos = e.SelectionStart
}
SetSelection(e.SelectionStart, pos)
case 2: // body: move the whole selection, preserving length
selLen := e.SelectionEnd - e.SelectionStart
ns := pos - e.SelDragRel
fl := fileLenBytes()
if ns < 0 {
ns = 0
}
if ns+selLen > fl {
ns = fl - selLen
}
SetSelection(ns, ns+selLen)
case 3: // caret drag handle
e.CursorPosition = pos
}
}
// HandleMenuTap hit-tests a tap on the menu panel and runs the tapped item.
func HandleMenuTap(x, y ui.Dp) {
e := &TheState.Editor
if !e.MenuVisible || !pointInMenu(x, y) {
return
}
idx := int((x - e.MenuRect.X) / menuItemW)
if idx < 0 || idx >= len(e.MenuItems) {
return
}
switch e.MenuItems[idx].Icon {
case "copy":
handleMenuCopy()
case "cut":
handleMenuCut()
case "paste":
handleMenuPaste()
}
}
// selectedText returns the selected bytes.
func selectedText() (string, bool) {
e := &TheState.Editor
if !selActive() {
return "", false
}
if cb := e.ChunkedBuffer; cb != nil {
return cb.Content(e.SelectionStart, e.SelectionEnd), true
}
return e.Buffer[e.SelectionStart:e.SelectionEnd], true
}
func handleMenuCopy() {
text, ok := selectedText()
if !ok {
return
}
TheState.clipboardSetChan <- text
// The selection (and its highlight) stays; only the menu goes away,
// matching Android behaviour.
hideSelectionMenu()
}
func handleMenuCut() {
e := &TheState.Editor
text, ok := selectedText()
if !ok {
return
}
TheState.clipboardSetChan <- text
deleteRange(e.SelectionStart, e.SelectionEnd)
markDirty()
e.CursorPosition = e.SelectionStart
ClearSelection()
}
func handleMenuPaste() {
if TheState.Editor.TooLarge {
return
}
TheState.pasteReqChan <- struct{}{}
// The read is asynchronous (DataEvent on a later frame), but the menu
// has served its purpose and closes immediately, as on Android.
hideSelectionMenu()
}
// HandlePaste inserts the system clipboard text (replacing a live selection,
// per the selection-aware edit rule). Runs on the logic goroutine.
func HandlePaste(text string) {
if text == "" {
return
}
HandleInsert(text)
}
// HandleHome moves the cursor to the start of the current visual line.
func HandleHome() {
layout := TheState.Editor.GlyphLayout
@@ -1066,6 +1564,9 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
W: screenWidth - margin*2,
H: editorH,
}
// Stored for the input handlers (tap / long press / drags), which convert
// app-local Dp points to text-local coordinates through it.
TheState.EditorRegion = editorRegion
// Compute max scroll offset from the last line baseline reported by the renderer.
// lastLineY is the shaper's Y value for the last line's baseline.
// Add bottom padding (half line height) so last line isn't flush with the bottom bar.
@@ -1216,30 +1717,41 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
[]ui.Interaction{
{Gesture: ui.Scroll, Handler: HandleScroll},
{Gesture: ui.KeyDown, Handler: HandleKeyDown},
// The Tap interaction also carries the long-press and double-tap
// events the renderer derives from the same gesture.Click (they share
// the editor's click region). The renderer converts all of them to
// text-local coordinates through EditorRegion + tapLocalY.
{Gesture: ui.Tap, Handler: func(data any) {
// Swallow the tap that opened the file. Its gesture belongs to the
// browser row we just left and must not position the cursor in the
// editor (a deliberate tap-to-position happens later, well past this
// window).
if time.Since(TheState.justOpenedAt) < 300*time.Millisecond {
return
}
if pt, ok := data.(ui.Point); ok {
// Window-space tap -> window-relative text-local coordinates.
// (See tapLocalY: the GlyphLayout is window-relative, so the Y must
// be too — never add the full scroll offset here.)
localX := float64(pt.X - editorRegion.X)
localY := tapLocalY(pt.Y, editorRegion.Y, TheState.ScrollOffset)
SetCursorFromPoint(localX, localY)
// The just-opened guard (swallowing the tap that opened the file)
// lives inside the Handle* functions.
switch pt := data.(type) {
case ui.Point:
HandleTapAt(pt.X, pt.Y)
case ui.DoubleTapPoint:
HandleDoubleTapAt(pt.X, pt.Y)
case ui.LongPressPoint:
HandleLongPressAt(pt.X, pt.Y)
}
}},
{Gesture: ui.SelDrag, Handler: HandleSelDragEvt},
},
)
// Set Focused so TextField.Draw() issues key.FocusCmd, which is required
// for Gio to deliver key events to this element.
editorElem.Focused = TheState.FocusedElementID == "editor_text"
// Caret handle visibility (long press on blank space).
editorElem.CaretDrag = TheState.Editor.CaretDrag
return []ui.Element{statusBar, editorElem, bottomBar}
elems := []ui.Element{statusBar, editorElem, bottomBar}
// The selection menu is added last so it draws on top of the editor.
if TheState.Editor.MenuVisible {
elems = append(elems, ui.NewMenu("selection_menu", TheState.Editor.MenuRect, TheState.Editor.MenuItems, func(data any) {
if pt, ok := data.(ui.Point); ok {
HandleMenuTap(pt.X, pt.Y)
}
}))
}
return elems
}
// tapLocalY converts a tap's screen Y (Dp) to a text-local Y in the
@@ -1254,13 +1766,25 @@ func tapLocalY(ptY, regionTopY ui.Dp, scrollOffset ui.Dp) float64 {
return float64(ptY-regionTopY) + math.Mod(float64(scrollOffset), float64(EditorLineHeight()))
}
// SetCursorFromPoint updates the cursor position based on screen coordinates (Dp).
// SetCursorFromPoint updates the cursor position based on text-local
// coordinates (Dp, window-relative: x from the text region's left edge, y as
// produced by tapLocalY). A tap is an explicit cursor placement: it always
// clears any selection.
func SetCursorFromPoint(x, y float64) {
// A tap is an explicit cursor placement: it always clears any selection.
ClearSelection()
if pos, ok := textPosFromLocalPoint(x, y); ok {
TheState.Editor.CursorPosition = pos
}
}
// textPosFromLocalPoint maps text-local coordinates (Dp, window-relative) to
// an absolute byte offset in the buffer. ok=false when the layout is empty or
// the point maps to no glyph. Shared by the tap, long-press, double-tap and
// selection-drag handlers.
func textPosFromLocalPoint(x, y float64) (int, bool) {
layout := TheState.Editor.GlyphLayout
if len(layout.ByteOffsets) == 0 || len(layout.X) == 0 || len(layout.Advance) == 0 {
return
return 0, false
}
base := glyphBase()
@@ -1329,7 +1853,7 @@ func SetCursorFromPoint(x, y float64) {
}
}
if len(groups[visualLine].indices) == 0 {
return
return 0, false
}
targetGroup := groups[visualLine]
@@ -1355,7 +1879,7 @@ func SetCursorFromPoint(x, y float64) {
content, err := buf.FullContent()
if err != nil {
log.Printf("Error getting full content: %v", err)
return
return 0, false
}
fileContent = content
} else {
@@ -1363,11 +1887,10 @@ func SetCursorFromPoint(x, y float64) {
}
r, size := utf8.DecodeRuneInString(fileContent[start:])
if r == '\n' {
TheState.Editor.CursorPosition = start
return start, true
} else {
TheState.Editor.CursorPosition = start + size
return start + size, true
}
return
}
// 5. Otherwise, find the closest glyph on this line.
@@ -1389,6 +1912,7 @@ func SetCursorFromPoint(x, y float64) {
}
}
if bestIdx != -1 {
TheState.Editor.CursorPosition = base + layout.ByteOffsets[bestIdx]
return base + layout.ByteOffsets[bestIdx], true
}
return 0, false
}
+368
View File
@@ -0,0 +1,368 @@
package editor
import (
"testing"
"pad/internal/ui"
)
// touchSelState sets up a fresh string-buffer state with a single-line
// GlyphLayout: 11 glyphs at x=10*i (advance 10), line top at y=0.
// EditorRegion is {X:16, Y:100, W:379, H:700} so text-local x = pt.X-16 and
// tapLocalY(y,100,0) = pt.Y-100 (scroll offset 0).
func touchSelState(content string) {
TheState = NewState()
TheState.Editor.Buffer = content
TheState.Editor.CursorPosition = len(content)
TheState.EditorRegion = ui.Region{X: 16, Y: 100, W: 379, H: 700}
TheState.ScrollOffset = 0
// The visible window (what layoutFrame sets every frame): the whole
// string buffer. bytePosToScreenXY bounds-checks against it.
TheState.Editor.IMEWindowStartByte = 0
TheState.Editor.IMEWindowText = content
n := len(content)
bo := make([]int, n)
xs := make([]ui.Dp, n)
ys := make([]ui.Dp, n)
ad := make([]ui.Dp, n)
for i := 0; i < n; i++ {
bo[i] = i
xs[i] = ui.Dp(10 * i)
ys[i] = 0
ad[i] = 10
}
TheState.Editor.GlyphLayout = ui.GlyphLayout{
ByteOffsets: bo,
X: xs,
Y: ys,
Advance: ad,
}
}
// assertMenu checks menu visibility and item icons.
func assertMenu(t *testing.T, wantVisible bool, wantIcons ...string) {
t.Helper()
e := TheState.Editor
if e.MenuVisible != wantVisible {
t.Fatalf("MenuVisible = %v, want %v", e.MenuVisible, wantVisible)
}
if wantVisible {
if len(e.MenuItems) != len(wantIcons) {
t.Fatalf("menu has %d items, want %d", len(e.MenuItems), len(wantIcons))
}
for i, it := range e.MenuItems {
if it.Icon != wantIcons[i] {
t.Errorf("menu item %d icon = %q, want %q", i, it.Icon, wantIcons[i])
}
}
}
}
func TestWordRangeAt(t *testing.T) {
touchSelState("hello world")
// Inside a word.
s, e, ok := wordRangeAt(3)
if !ok || s != 0 || e != 5 {
t.Errorf("wordRangeAt(3) = [%d,%d) ok=%v, want [0,5) true", s, e, ok)
}
// Second word.
s, e, ok = wordRangeAt(7)
if !ok || s != 6 || e != 11 {
t.Errorf("wordRangeAt(7) = [%d,%d) ok=%v, want [6,11) true", s, e, ok)
}
// Word boundary: position right after a word (space after) still finds
// the word ending there.
s, e, ok = wordRangeAt(5)
if !ok || s != 0 || e != 5 {
t.Errorf("wordRangeAt(5) = [%d,%d) ok=%v, want [0,5) true", s, e, ok)
}
// EOF: the position is right after the last word -> that word.
s, e, ok = wordRangeAt(11)
if !ok || s != 6 || e != 11 {
t.Errorf("wordRangeAt(11) = [%d,%d) ok=%v, want [6,11) true", s, e, ok)
}
}
func TestWordRangeAt_PunctuationAndIdentifiers(t *testing.T) {
touchSelState("foo,bar_baz 123")
// "bar_baz" is one word (underscore joins).
s, e, ok := wordRangeAt(7)
if !ok || s != 4 || e != 11 {
t.Errorf("wordRangeAt(7) = [%d,%d) ok=%v, want [4,11) true", s, e, ok)
}
// "123".
s, e, ok = wordRangeAt(14)
if !ok || s != 12 || e != 15 {
t.Errorf("wordRangeAt(14) = [%d,%d) ok=%v, want [12,15) true", s, e, ok)
}
// Position at the comma, right after "foo": the word ending there.
s, e, ok = wordRangeAt(3)
if !ok || s != 0 || e != 3 {
t.Errorf("wordRangeAt(3) = [%d,%d) ok=%v, want [0,3) true", s, e, ok)
}
}
func TestHandleLongPressAt_SelectsWord(t *testing.T) {
touchSelState("hello world")
// Long press on the first glyph of "hello" (window pt: x=16+2=18, y=108).
HandleLongPressAt(18, 108)
assertSelection(t, 0, 5)
assertMenu(t, true, "copy", "cut", "paste")
if TheState.Editor.SelectionAnchor != 0 {
t.Errorf("anchor = %d, want 0", TheState.Editor.SelectionAnchor)
}
if TheState.Editor.CursorPosition != 5 {
t.Errorf("cursor = %d, want 5", TheState.Editor.CursorPosition)
}
}
func TestHandleLongPressAt_BlankGivesCaretDrag(t *testing.T) {
// Line ends with punctuation so the position right after the last glyph
// is NOT adjacent to a word rune (a blank spot, not a word edge).
touchSelState("hello world.")
// Long press far right of the last glyph (x=16+150=166, past x=120).
HandleLongPressAt(166, 108)
assertSelection(t, -1, -1)
if !TheState.Editor.CaretDrag {
t.Errorf("CaretDrag = false, want true (long press on blank)")
}
// No selection -> the menu offers only Paste.
assertMenu(t, true, "paste")
if TheState.Editor.CursorPosition != 12 {
t.Errorf("cursor = %d, want 12 (end of line)", TheState.Editor.CursorPosition)
}
}
func TestHandleLongPressAt_AfterLastWordSelectsIt(t *testing.T) {
// A long press in the blank just past the last word selects that word
// (the word adjacent to the tap), matching Android's word selection.
touchSelState("hello world")
HandleLongPressAt(166, 108)
assertSelection(t, 6, 11)
}
func TestHandleLongPressAt_InGapBetweenWords(t *testing.T) {
touchSelState("hello world") // two spaces
// Long press on the SECOND space (glyph 6, center x=65; pt 16+65=81):
// no word rune at or immediately before the position -> caret.
HandleLongPressAt(81, 108)
assertSelection(t, -1, -1)
if !TheState.Editor.CaretDrag {
t.Errorf("CaretDrag = false, want true (long press in word gap)")
}
if TheState.Editor.CursorPosition != 6 {
t.Errorf("cursor = %d, want 6", TheState.Editor.CursorPosition)
}
}
func TestHandleDoubleTapAt_SelectsWord(t *testing.T) {
touchSelState("hello world")
HandleDoubleTapAt(18, 108)
assertSelection(t, 0, 5)
assertMenu(t, true, "copy", "cut", "paste")
}
func TestHandleTapAt_MovesCaretAndClearsSelection(t *testing.T) {
touchSelState("hello world")
// Establish a selection, then a plain tap clears it and moves the caret.
HandleLongPressAt(18, 108)
assertSelection(t, 0, 5)
// Tap on the 'w' of "world" (glyph 6, x=60..70; local 62 -> pt 78).
HandleTapAt(78, 108)
assertSelection(t, -1, -1)
if TheState.Editor.CaretDrag {
t.Errorf("CaretDrag = true after plain tap, want false")
}
if TheState.Editor.CursorPosition != 6 {
t.Errorf("cursor = %d, want 6", TheState.Editor.CursorPosition)
}
}
func TestHandleTapAt_InsideMenuIsIgnored(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108)
if !TheState.Editor.MenuVisible {
t.Fatal("expected menu visible")
}
posBefore := TheState.Editor.CursorPosition
selStartBefore := TheState.Editor.SelectionStart
// Tap inside the menu (top-left item).
m := TheState.Editor.MenuRect
HandleTapAt(m.X+5, m.Y+5)
if TheState.Editor.CursorPosition != posBefore {
t.Errorf("cursor moved to %d after tap in menu, want %d (ignored)", TheState.Editor.CursorPosition, posBefore)
}
if TheState.Editor.SelectionStart != selStartBefore {
t.Errorf("selection changed after tap in menu")
}
if !TheState.Editor.MenuVisible {
t.Errorf("menu hidden after tap in menu, want still visible")
}
}
func TestSelDrag_EndHandleExtends(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108) // selects "hello" [0,5)
// Drag the end handle (which=1) past the last glyph (local 115 > 110)
// so the whole line is selected.
HandleSelDragEvt(ui.SelectionDragEvent{Which: 1, X: 16 + 115, Y: 108})
HandleSelDragEvt(ui.SelectionDragEvent{Which: 1, X: 16 + 115, Y: 108})
assertSelection(t, 0, 11)
}
func TestSelDrag_StartHandleExtends(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108) // selects "hello" [0,5)
// Drag the start handle (which=0) to the 'o' (glyph 4, x=40..50; local 45 -> pt 61).
HandleSelDragEvt(ui.SelectionDragEvent{Which: 0, X: 16 + 45, Y: 108})
HandleSelDragEvt(ui.SelectionDragEvent{Which: 0, X: 16 + 45, Y: 108})
assertSelection(t, 4, 5)
}
func TestSelDrag_StartHandleCollapseClears(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108) // selects "hello" [0,5)
// Drag the start handle to the end of the selection -> zero-length -> cleared.
HandleSelDragEvt(ui.SelectionDragEvent{Which: 0, X: 16 + 52, Y: 108})
HandleSelDragEvt(ui.SelectionDragEvent{Which: 0, X: 16 + 52, Y: 108})
assertSelection(t, -1, -1)
assertMenu(t, false)
}
func TestSelDrag_BodyMovesPreservingLength(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108) // selects "hello" [0,5)
// Grab the body above the 'l' (glyph 2, x=20..30; local 25 -> pt 41):
// SelDragRel = pos(2) - selStart(0) = 2.
HandleSelDragEvt(ui.SelectionDragEvent{Which: 2, X: 16 + 25, Y: 108})
// Move the body so the finger is above the 'r' of world (glyph 9, x=90..100; local 95 -> pt 111):
// pos = 9 -> new start = 9-2 = 7 -> [7,12) clamped to [7,11)...
HandleSelDragEvt(ui.SelectionDragEvent{Which: 2, X: 16 + 95, Y: 108})
s := TheState.Editor
if s.SelectionStart != 6 || s.SelectionEnd != 11 {
// length 5 preserved, clamped at EOF: [6,11)
t.Errorf("body drag selection = [%d,%d), want [6,11)", s.SelectionStart, s.SelectionEnd)
}
HandleSelDragEvt(ui.SelectionDragEnd{})
}
func TestSelDrag_CaretHandleMovesCursor(t *testing.T) {
touchSelState("hello world.") // punctuation keeps the right side blank
HandleLongPressAt(166, 108) // blank -> caret drag at 12
if !TheState.Editor.CaretDrag {
t.Fatal("expected caret drag mode")
}
// Drag the caret handle (which=3) to glyph 2 (local 25 -> pt 41).
HandleSelDragEvt(ui.SelectionDragEvent{Which: 3, X: 16 + 25, Y: 108})
HandleSelDragEvt(ui.SelectionDragEvent{Which: 3, X: 16 + 25, Y: 108})
if TheState.Editor.CursorPosition != 2 {
t.Errorf("cursor = %d after caret drag, want 2", TheState.Editor.CursorPosition)
}
// The handle stays up while dragging...
if !TheState.Editor.CaretDrag {
t.Errorf("CaretDrag cleared mid-drag, want true")
}
HandleSelDragEvt(ui.SelectionDragEnd{})
if TheState.Editor.CaretDrag {
t.Errorf("CaretDrag not cleared on drag end")
}
}
func TestMenuCopy(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108) // selects "hello"
m := TheState.Editor.MenuRect
// Tap the copy item (first item, X offset 0).
HandleMenuTap(m.X+10, m.Y+10)
select {
case text := <-TheState.clipboardSetChan:
if text != "hello" {
t.Errorf("clipboard = %q, want %q", text, "hello")
}
default:
t.Fatal("no clipboard write after copy")
}
// Copy does not clear the selection (the highlight stays), but the
// menu closes, as on Android.
assertSelection(t, 0, 5)
assertMenu(t, false)
}
func TestMenuCut(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108) // selects "hello"
m := TheState.Editor.MenuRect
// Tap the cut item (second item).
HandleMenuTap(m.X+ui.Dp(menuItemW)+10, m.Y+10)
select {
case text := <-TheState.clipboardSetChan:
if text != "hello" {
t.Errorf("clipboard = %q, want %q", text, "hello")
}
default:
t.Fatal("no clipboard write after cut")
}
if got := TheState.Editor.Buffer; got != " world" {
t.Errorf("buffer = %q after cut, want %q", got, " world")
}
assertSelection(t, -1, -1)
assertMenu(t, false)
if TheState.Editor.CursorPosition != 0 {
t.Errorf("cursor = %d after cut, want 0", TheState.Editor.CursorPosition)
}
}
func TestMenuPaste(t *testing.T) {
touchSelState("hello")
HandleLongPressAt(18, 108) // selects "hello"
// Paste replaces the live selection (via the same path the Run loop uses
// when the main goroutine forwards clipboard content).
HandlePaste("XY")
if got := TheState.Editor.Buffer; got != "XY" {
t.Errorf("buffer = %q after paste, want %q", got, "XY")
}
assertSelection(t, -1, -1)
assertMenu(t, false)
if TheState.Editor.CursorPosition != 2 {
t.Errorf("cursor = %d after paste, want 2", TheState.Editor.CursorPosition)
}
}
func TestMenuPaste_NoSelectionInsertsAtCursor(t *testing.T) {
touchSelState("hello")
TheState.Editor.CursorPosition = 5
HandlePaste(",")
if got := TheState.Editor.Buffer; got != "hello," {
t.Errorf("buffer = %q after paste, want %q", got, "hello,")
}
if TheState.Editor.CursorPosition != 6 {
t.Errorf("cursor = %d after paste, want 6", TheState.Editor.CursorPosition)
}
}
func TestMenuTapPaste_HidesMenuAndRequestsRead(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108) // selects "hello"
m := TheState.Editor.MenuRect
// Tap the paste item (third item).
HandleMenuTap(m.X+2*ui.Dp(menuItemW)+10, m.Y+10)
select {
case <-TheState.pasteReqChan:
default:
t.Fatal("no paste request after menu paste tap")
}
// The menu closes immediately (the read is asynchronous); the
// selection stays until the pasted content arrives.
assertMenu(t, false)
assertSelection(t, 0, 5)
}
func TestSelectionEdit_CutThenTypeReplaces(t *testing.T) {
touchSelState("hello world")
HandleLongPressAt(18, 108) // selects "hello"
HandleInsert("goodbye")
if got := TheState.Editor.Buffer; got != "goodbye world" {
t.Errorf("buffer = %q, want %q", got, "goodbye world")
}
}