Add text selection, real-file e2e tests, and Android arrow-key support

Selection: shift+arrow extends a selection (absolute byte offsets,
anchor/caret model); insert/backspace/delete replace the selection; the
IME unions its reported range with the active selection; the highlight
is drawn in the TextField and the selection is pushed to the IME.

Android key input (the blocker found during on-device validation):
Gio v0.10 on Android (a) drops modifier state in the JNI bridge and
(b) wraps plain arrow-key presses in input.SystemEvent for focus
navigation, so arrow keys never reached the editor. main.go now
registers explicit named key.Filters for the four arrows (delivers the
press and suppresses the focus jump) and tracks the shift key itself.
Verified on the emulator: plain arrows move the caret, shift+arrow
shows a highlight, typing replaces the selection.

Real-file e2e tests (real on-disk files via the real FileSystem,
multi-chunk 256KB files, chunk-boundary and multi-byte edits) found
and fixed two real bugs:
  1. Line index: UpdateLineIndexAfterEdit only shifted offsets; edits
     involving newlines left it permanently inconsistent. Replaced with
     newline-aware UpdateLineIndexAfterInsert/UpdateLineIndexAfterDelete.
  2. Rune granularity: HandleBackspace/HandleDelete deleted one byte,
     corrupting multi-byte UTF-8 characters (e.g. a 2-byte char
     straddling a chunk boundary). Now rune-granular.

Also: airtight e2e harness load-wait (StatFile/ReadFile/BuildLineIndex
interleaving could satisfy the old condition early).

Full suite green under -race; on-device verified.
This commit is contained in:
gmp
2026-08-17 00:32:53 -04:00
parent 3c8017f871
commit ec11abf8f1
13 changed files with 1819 additions and 112 deletions
+76 -17
View File
@@ -3,6 +3,7 @@ package editor
import (
"bytes"
"sort"
"strings"
"pad/internal/io/pool"
"pad/internal/io/pool/types"
@@ -572,27 +573,85 @@ func (cb *ChunkedBuffer) visibleByteRangePrecise(scrollOffset ui.Dp, viewportHei
return start, end
}
// UpdateLineIndexAfterEdit updates the LineIndex offsets after an insert or
// delete. offsetShift is the number of bytes inserted (positive) or deleted
// (negative); editPos is the byte position where the edit occurred.
func (cb *ChunkedBuffer) UpdateLineIndexAfterEdit(editPos int, offsetShift int) {
if cb.LineIndex == nil {
// UpdateLineIndexAfterInsert records the insertion of `text` at absolute
// position `pos`, maintaining LineIndex incrementally:
// - old line starts below pos are unchanged;
// - an old line start exactly at pos stays at pos (the byte before it is
// unchanged by the insertion);
// - old line starts above pos shift right by len(text);
// - each '\n' inside `text` creates a new line start immediately after it.
//
// Equivalent to rebuilding the index from the edited content, but in
// O(lines affected) instead of O(file).
func (cb *ChunkedBuffer) UpdateLineIndexAfterInsert(pos int, text string) {
li := cb.LineIndex
if li == nil {
return
}
// Find the first offset that needs updating using binary search. All
// offsets >= editPos are shifted by offsetShift.
idx := sort.Search(len(cb.LineIndex.Offsets), func(i int) bool {
return int(cb.LineIndex.Offsets[i]) >= editPos
})
if idx == 0 {
idx = 1
old := li.Offsets
lower := sort.Search(len(old), func(i int) bool { return int(old[i]) >= pos })
atPos := lower < len(old) && int(old[lower]) == pos
rest := lower
if atPos {
rest++
}
for i := idx; i < len(cb.LineIndex.Offsets); i++ {
cb.LineIndex.Offsets[i] += int32(offsetShift)
shift := int32(len(text))
newOff := make([]int32, 0, len(old)+strings.Count(text, "\n")+1)
newOff = append(newOff, old[:lower]...)
if atPos {
newOff = append(newOff, int32(pos))
}
cb.LineIndex.Size += int64(offsetShift)
if cb.LineIndex.Size < 0 {
cb.LineIndex.Size = 0
for i, b := range text {
if b == '\n' {
newOff = append(newOff, int32(pos+i+1))
}
}
for _, o := range old[rest:] {
newOff = append(newOff, o+shift)
}
li.Offsets = newOff
li.Size += int64(len(text))
}
// UpdateLineIndexAfterDelete records the deletion of the absolute byte range
// [start, end), maintaining LineIndex incrementally:
// - old line starts below start are unchanged;
// - old line starts inside [start, end) are removed;
// - old line starts at or above end shift left by end-start, except the one
// at exactly end, which would land on `start` and is valid only if a line
// starts there in the new content;
// - `start` is (re)inserted as a line start iff start==0 or it was a line
// start in the pre-edit index (equivalently, the byte before it is '\n';
// bytes below start are untouched by the deletion).
func (cb *ChunkedBuffer) UpdateLineIndexAfterDelete(start, end int) {
li := cb.LineIndex
if li == nil {
return
}
old := li.Offsets
shift := int32(end - start)
lower := sort.Search(len(old), func(i int) bool { return int(old[i]) >= start })
atStart := lower < len(old) && int(old[lower]) == start
upper := sort.Search(len(old), func(i int) bool { return int(old[i]) >= end })
newOff := make([]int32, 0, len(old))
newOff = append(newOff, old[:lower]...)
if start == 0 || atStart {
newOff = append(newOff, int32(start))
}
for _, o := range old[upper:] {
no := o - shift
if int(no) == start {
// The old line start at exactly `end` shifted onto `start`. A line
// starts there in the new content iff one already existed there
// (added above); in neither case do we keep this shifted entry.
continue
}
newOff = append(newOff, no)
}
li.Offsets = newOff
li.Size -= int64(end - start)
if li.Size < 0 {
li.Size = 0
}
}
+176
View File
@@ -2,8 +2,11 @@ package editor
import (
"bytes"
"fmt"
"strings"
"testing"
"pad/internal/io/pool/types"
)
// newTestBuffer builds a fully-loaded (in-range) buffer from content using the
@@ -279,3 +282,176 @@ func TestInsert_SplitContentIntegrity(t *testing.T) {
t.Fatalf("Content(50,300) mismatch across split boundary")
}
}
// int32SlicesEqual reports whether two []int32 are element-wise equal.
func int32SlicesEqual(a, b []int32) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// lineStartOffsets computes the ground-truth line-start byte offsets for
// content: position 0 plus the byte after each '\n'.
func lineStartOffsets(content []byte) []int32 {
off := make([]int32, 0, 16)
off = append(off, 0)
for i, b := range content {
if b == '\n' {
off = append(off, int32(i+1))
}
}
return off
}
// assertLineIndexMatchesOracle verifies the buffer's incrementally-maintained
// LineIndex is exactly the one a full recomputation from the content would
// produce. This is the regression guard for newline handling in
// UpdateLineIndexAfterInsert / UpdateLineIndexAfterDelete.
func assertLineIndexMatchesOracle(t *testing.T, cb *ChunkedBuffer, label string) {
t.Helper()
full, err := cb.FullContent()
if err != nil {
t.Fatalf("%s: FullContent: %v", label, err)
}
want := lineStartOffsets([]byte(full))
if cb.LineIndex == nil {
t.Fatalf("%s: LineIndex is nil", label)
}
if !int32SlicesEqual(cb.LineIndex.Offsets, want) {
t.Fatalf("%s: line index drift\n got %v\n want %v", label, cb.LineIndex.Offsets, want)
}
if cb.LineIndex.Size != int64(len(full)) {
t.Fatalf("%s: LineIndex.Size=%d, want %d", label, cb.LineIndex.Size, len(full))
}
}
// TestLineIndex_InsertNewlines drives inserts that add newlines through the
// incremental update and checks the oracle invariant after each step.
func TestLineIndex_InsertNewlines(t *testing.T) {
base := "aaa\nbbb\nccc"
cb := newTestBuffer(t, []byte(base))
cb.LineIndex = types.NewLineIndex(lineStartOffsets([]byte(base)), 0, int64(len(base)))
steps := []struct {
pos int
text string
}{
{7, "\n"}, // empty line after "bbb"
{0, "\n"}, // leading empty line
{len(base) + 2, "x\ny\n"}, // append two lines at EOF (after edits)
{4, "QQ\n"}, // insert at start of "bbb" line, with newline
{1000000, "zz"}, // insert far past EOF (clamps in Insert)
}
for i, s := range steps {
// Insert clamps pos to EOF; use the same clamped pos for both the
// buffer edit and the index update, as production code does (the
// cursor is always within the buffer).
p := s.pos
if p > int(cb.FileLen()) {
p = int(cb.FileLen())
}
cb.Insert(p, s.text)
cb.UpdateLineIndexAfterInsert(p, s.text)
assertLineIndexMatchesOracle(t, cb, fmt.Sprintf("insert step %d (pos=%d text=%q)", i, p, s.text))
}
}
// TestLineIndex_DeleteNewlines drives deletions that remove newlines / whole
// lines / from line starts through the incremental update and checks the
// oracle invariant after each step.
func TestLineIndex_DeleteNewlines(t *testing.T) {
base := "aaa\nbbb\nccc\nddd"
cb := newTestBuffer(t, []byte(base))
cb.LineIndex = types.NewLineIndex(lineStartOffsets([]byte(base)), 0, int64(len(base)))
// (start, end) ranges chosen to exercise: mid-line, across a newline,
// a whole line, from a line start, and the file start.
steps := []struct {
start, end int
}{
{3, 4}, // delete the '\n' after aaa -> merge aaa+bbb
{4, 7}, // delete "bbb" (after merge: content is aaabbb\nddd...)
{0, 3}, // delete from file start
{3, 8}, // delete "bb\n" region
}
for i, s := range steps {
full, _ := cb.FullContent()
if s.start > len(full) || s.end > len(full) {
t.Fatalf("step %d: range [%d,%d) beyond content len %d", i, s.start, s.end, len(full))
}
cb.Delete(s.start, s.end-s.start)
cb.UpdateLineIndexAfterDelete(s.start, s.end)
assertLineIndexMatchesOracle(t, cb, fmt.Sprintf("delete step %d [%d,%d)", i, s.start, s.end))
}
}
// TestLineIndex_MixedEditSequence interleaves inserts and deletes (including
// IME-style replace = delete+insert at the same point) and checks the oracle
// after each operation.
func TestLineIndex_MixedEditSequence(t *testing.T) {
base := "hello\nworld\nfoo\nbar\nbaz"
cb := newTestBuffer(t, []byte(base))
cb.LineIndex = types.NewLineIndex(lineStartOffsets([]byte(base)), 0, int64(len(base)))
ops := []struct {
desc string
isIns bool
pos int
text string // for insert
start int // for delete
end int // for delete
}{
{desc: "insert newline mid", isIns: true, pos: 3, text: "\n"},
{desc: "delete across nl", start: 6, end: 10},
{desc: "replace with multi-line", isIns: false, pos: 2, text: "X\nY\nZ", start: 2, end: 4},
{desc: "delete whole line", start: 0, end: 4},
{desc: "insert at eof", isIns: true, pos: 999, text: "end\n"},
}
for i, op := range ops {
full, _ := cb.FullContent()
switch {
case op.isIns:
p := op.pos
if p > len(full) {
p = len(full)
}
cb.Insert(p, op.text)
cb.UpdateLineIndexAfterInsert(p, op.text)
case op.text != "":
// replace: delete [start,end) then insert at start, mirroring
// HandleReplaceRange ordering.
s, e := op.start, op.end
if s > len(full) {
s = len(full)
}
if e > len(full) {
e = len(full)
}
if e > s {
cb.Delete(s, e-s)
cb.UpdateLineIndexAfterDelete(s, e)
}
cb.Insert(s, op.text)
cb.UpdateLineIndexAfterInsert(s, op.text)
default:
s, e := op.start, op.end
if s > len(full) {
s = len(full)
}
if e > len(full) {
e = len(full)
}
if e > s {
cb.Delete(s, e-s)
cb.UpdateLineIndexAfterDelete(s, e)
}
}
assertLineIndexMatchesOracle(t, cb, fmt.Sprintf("op %d (%s)", i, op.desc))
}
}
+347
View File
@@ -0,0 +1,347 @@
package editor
import (
"testing"
"gioui.org/io/key"
"pad/internal/ui"
)
// selState sets up a fresh state with a string buffer (the selection logic
// is buffer-implementation independent; chunked-buffer coverage is in the
// e2e real-file tests).
func selState(content string) {
TheState = NewState()
TheState.Editor.Buffer = content
TheState.Editor.CursorPosition = len(content)
}
// assertSelection checks the normalized selection triple.
func assertSelection(t *testing.T, wantStart, wantEnd int) {
t.Helper()
e := TheState.Editor
if e.SelectionStart != wantStart || e.SelectionEnd != wantEnd {
t.Fatalf("selection = [%d,%d), want [%d,%d)", e.SelectionStart, e.SelectionEnd, wantStart, wantEnd)
}
active := wantStart >= 0 && wantEnd > wantStart
if active != selActive() {
t.Fatalf("selActive() = %v, want %v (anchor=%d)", selActive(), active, e.SelectionAnchor)
}
}
func TestSetSelection_Basic(t *testing.T) {
selState("0123456789")
SetSelection(2, 7)
assertSelection(t, 2, 7)
if TheState.Editor.SelectionAnchor != 2 {
t.Errorf("anchor = %d, want 2", TheState.Editor.SelectionAnchor)
}
if TheState.Editor.CursorPosition != 7 {
t.Errorf("cursor = %d, want 7 (active end)", TheState.Editor.CursorPosition)
}
// Reversed arguments are normalized.
SetSelection(9, 4)
assertSelection(t, 4, 9)
if TheState.Editor.SelectionAnchor != 4 {
t.Errorf("anchor = %d, want 4", TheState.Editor.SelectionAnchor)
}
}
func TestSetSelection_Clamp(t *testing.T) {
selState("0123456789")
// End past EOF clamps to file length.
SetSelection(7, 100)
assertSelection(t, 7, 10)
// Negative start clamps to 0.
SetSelection(-5, 3)
assertSelection(t, 0, 3)
// Degenerate range clears instead of selecting.
SetSelection(5, 5)
assertSelection(t, -1, -1)
if TheState.Editor.CursorPosition != 5 {
t.Errorf("cursor = %d, want 5", TheState.Editor.CursorPosition)
}
}
func TestShiftExtend_Horizontal(t *testing.T) {
selState("0123456789")
TheState.Editor.CursorPosition = 3
// First shift-move anchors at the cursor and selects one char.
handleKey(key.NameRightArrow, true)
assertSelection(t, 3, 4)
// Further shift-moves extend from the anchor.
handleKey(key.NameRightArrow, true)
assertSelection(t, 3, 5)
handleKey(key.NameRightArrow, true)
assertSelection(t, 3, 6)
// Left moves shrink back toward the anchor; crossing it keeps the
// selection (anchor is the fixed end).
handleKey(key.NameLeftArrow, true)
assertSelection(t, 3, 5)
handleKey(key.NameLeftArrow, true)
assertSelection(t, 3, 4)
// Crossing the anchor: zero-length, represented as no selection.
handleKey(key.NameLeftArrow, true)
assertSelection(t, -1, -1)
// ...but the anchor survives so the next shift-move extends from the
// original spot.
if TheState.Editor.SelectionAnchor != 3 {
t.Errorf("anchor = %d, want 3 (kept across zero-length)", TheState.Editor.SelectionAnchor)
}
handleKey(key.NameLeftArrow, true)
assertSelection(t, 2, 3)
// A plain move clears the selection and moves one step (cursor 2 -> 1).
handleKey(key.NameLeftArrow, false)
assertSelection(t, -1, -1)
if TheState.Editor.SelectionAnchor != -1 {
t.Errorf("anchor = %d, want -1 after plain move", TheState.Editor.SelectionAnchor)
}
if TheState.Editor.CursorPosition != 1 {
t.Errorf("cursor = %d, want 1", TheState.Editor.CursorPosition)
}
}
func TestShiftExtend_UpDownHomeEnd(t *testing.T) {
TheState = NewState()
TheState.Editor.Buffer = "hello\nworld"
TheState.Editor.CursorPosition = 8 // line 1, inside "world"
TheState.Editor.GlyphLayout = makeTestLineLayout("hello\nworld")
// Layout: line 0 "hello" baseline Y=70, line 1 "world" baseline Y=140;
// X = 10 + 10*(column). Cursor 8 is line 1, column 2 (X=30).
handleKey(key.NameUpArrow, true)
// Up goes to the closest X on line 0: X=30 is byte 2 exactly.
assertSelection(t, 2, 8)
if TheState.Editor.CursorPosition != 2 {
t.Fatalf("cursor = %d, want 2", TheState.Editor.CursorPosition)
}
// Shift+End moves to end of line 0 (byte 5); the anchor stays at 8.
handleKey(key.NameEnd, true)
assertSelection(t, 5, 8)
// Plain Down clears and moves to the closest X on line 1. Cursor is at
// line 0 col 4 (X=50) -> line 1 col 4 = byte 10.
handleKey(key.NameDownArrow, false)
assertSelection(t, -1, -1)
if TheState.Editor.CursorPosition != 10 {
t.Fatalf("cursor = %d, want 10", TheState.Editor.CursorPosition)
}
// Shift+End extends to end of file (byte 11), anchoring at 10.
handleKey(key.NameEnd, true)
assertSelection(t, 10, 11)
// Shift+Home selects back to line start (byte 6), anchor 10 kept.
handleKey(key.NameHome, true)
assertSelection(t, 6, 10)
// Plain Home clears and moves.
handleKey(key.NameHome, false)
assertSelection(t, -1, -1)
if TheState.Editor.CursorPosition != 6 {
t.Errorf("cursor = %d, want 6", TheState.Editor.CursorPosition)
}
}
func TestInsert_ReplacesSelection(t *testing.T) {
selState("hello world")
SetSelection(5, 11) // " world"
HandleInsert("GO")
if TheState.Editor.Buffer != "helloGO" {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, "helloGO")
}
if TheState.Editor.CursorPosition != 7 {
t.Errorf("cursor = %d, want 7", TheState.Editor.CursorPosition)
}
assertSelection(t, -1, -1)
}
func TestBackspace_DeletesSelection(t *testing.T) {
selState("0123456789")
SetSelection(2, 7)
HandleBackspace()
if TheState.Editor.Buffer != "01789" {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, "01789")
}
if TheState.Editor.CursorPosition != 2 {
t.Errorf("cursor = %d, want 2", TheState.Editor.CursorPosition)
}
assertSelection(t, -1, -1)
}
func TestDeleteForward_DeletesSelection(t *testing.T) {
selState("0123456789")
SetSelection(2, 7)
HandleDelete()
if TheState.Editor.Buffer != "01789" {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, "01789")
}
if TheState.Editor.CursorPosition != 2 {
t.Errorf("cursor = %d, want 2", TheState.Editor.CursorPosition)
}
assertSelection(t, -1, -1)
}
func TestBackspace_NoSelection_StillDeletesChar(t *testing.T) {
selState("0123456789")
TheState.Editor.CursorPosition = 5
HandleBackspace()
// Deletes the char before the cursor (index 4, '4').
if TheState.Editor.Buffer != "012356789" {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, "012356789")
}
if TheState.Editor.CursorPosition != 4 {
t.Errorf("cursor = %d, want 4", TheState.Editor.CursorPosition)
}
}
func TestHandleReplaceRange_UnionsSelection(t *testing.T) {
selState("hello world")
SetSelection(0, 5) // "hello", cursor at 5
// IME reports an empty range at the caret: the selection must still be
// consumed.
HandleReplaceRange(5, 5, "X")
if TheState.Editor.Buffer != "X world" {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, "X world")
}
if TheState.Editor.CursorPosition != 1 {
t.Errorf("cursor = %d, want 1", TheState.Editor.CursorPosition)
}
assertSelection(t, -1, -1)
// IME reports the full selection range: same outcome (idempotent union).
selState("hello world")
SetSelection(0, 5)
HandleReplaceRange(0, 5, "X")
if TheState.Editor.Buffer != "X world" {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, "X world")
}
// No selection: ordinary insert at the caret (regression guard).
selState("hello")
TheState.Editor.CursorPosition = 5
HandleReplaceRange(5, 5, "!")
if TheState.Editor.Buffer != "hello!" {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, "hello!")
}
if TheState.Editor.CursorPosition != 6 {
t.Errorf("cursor = %d, want 6", TheState.Editor.CursorPosition)
}
}
func TestHandleReplaceRange_SelectionPartialOverlap(t *testing.T) {
// Selection [2,7); IME commit inserts at caret 7 (just outside the
// selection): union [2,7) -> the selected text is replaced, inserted
// text ends up where the selection was.
selState("0123456789")
SetSelection(2, 7)
HandleReplaceRange(7, 7, "AB")
want := "01AB789"
if TheState.Editor.Buffer != want {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, want)
}
if TheState.Editor.CursorPosition != 4 {
t.Errorf("cursor = %d, want 4", TheState.Editor.CursorPosition)
}
assertSelection(t, -1, -1)
}
func TestSelectionEdit_UTF8(t *testing.T) {
// "hélló": é is 2 bytes (1..3), ó is 2 bytes (5..7). Select the
// multi-byte span [1,5) = "éll" and replace it: must not split runes.
selState("hélló")
SetSelection(1, 5)
HandleInsert("a")
want := "ha" + "ó"
if TheState.Editor.Buffer != want {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, want)
}
if TheState.Editor.CursorPosition != 2 {
t.Errorf("cursor = %d, want 2", TheState.Editor.CursorPosition)
}
}
func TestSetCursorFromPoint_ClearsSelection(t *testing.T) {
TheState = NewState()
TheState.Editor.Buffer = "hello\nworld"
TheState.Editor.GlyphLayout = makeTestLineLayout("hello\nworld")
SetSelection(0, 5)
assertSelection(t, 0, 5)
// Tap on the second line (Y of line 1 glyphs).
SetCursorFromPoint(25, secondLineY(t))
assertSelection(t, -1, -1)
if TheState.Editor.CursorPosition < 6 || TheState.Editor.CursorPosition > 11 {
t.Errorf("cursor = %d, want in [6,11] (line 1)", TheState.Editor.CursorPosition)
}
}
func TestBareKeyName_ShiftIgnored(t *testing.T) {
// The legacy bare key.Name path has no modifier state: it must never
// start a selection.
selState("0123456789")
TheState.Editor.CursorPosition = 3
HandleKeyDown(key.NameRightArrow)
assertSelection(t, -1, -1)
if TheState.Editor.CursorPosition != 4 {
t.Errorf("cursor = %d, want 4", TheState.Editor.CursorPosition)
}
}
func TestKeyEvent_DoesNotAffectIMEEvents(t *testing.T) {
// key.EditEvent still flows to HandleReplaceRange unchanged.
selState("hello")
TheState.Editor.CursorPosition = 5
HandleKeyDown(key.EditEvent{Range: key.Range{Start: 5, End: 5}, Text: "!"})
if TheState.Editor.Buffer != "hello!" {
t.Fatalf("buffer = %q, want %q", TheState.Editor.Buffer, "hello!")
}
}
// makeTestLineLayout builds a GlyphLayout for an ASCII buffer whose lines
// are laid out at fixed baselines (line i at Y=70+70*i), one glyph per byte
// with X = 10 + 10*column and advance 10.
func makeTestLineLayout(content string) ui.GlyphLayout {
var layout ui.GlyphLayout
y := 70
col := 0
for i := 0; i < len(content); i++ {
if i > 0 && content[i-1] == '\n' {
y += 70
col = 0
}
layout.ByteOffsets = append(layout.ByteOffsets, i)
layout.X = append(layout.X, 10+ui.Dp(col)*10)
layout.Y = append(layout.Y, ui.Dp(y))
layout.Advance = append(layout.Advance, 10)
if content[i] != '\n' {
col++
}
}
layout.LineHeight = 20
return layout
}
// secondLineY returns the Y of the first glyph of the second line in the
// layout produced by makeTestLineLayout.
func secondLineY(t *testing.T) float64 {
t.Helper()
l := TheState.Editor.GlyphLayout
for i := 1; i < len(l.Y); i++ {
if l.Y[i] > l.Y[0] {
return float64(l.Y[i])
}
}
t.Fatal("layout has no second line")
return 0
}
+303 -61
View File
@@ -64,7 +64,12 @@ type EditorState struct {
GlyphLayout ui.GlyphLayout
SelectionStart int
SelectionEnd int
CursorVisible bool
// SelectionAnchor is the fixed end of a shift-selection; CursorPosition is
// the active end. -1 means no shift-selection in progress. The effective
// selection is [min(anchor,cursor), max(anchor,cursor)]; SelectionStart/
// SelectionEnd are its cached normalized form (-1/-1 = none).
SelectionAnchor int
CursorVisible bool
// IMEWindowStartByte is the absolute byte offset in the buffer where the
// visible window (IMEWindowText) begins. For small (string) files it is 0
// and the window is the whole buffer; for large (chunked) files it is the
@@ -169,6 +174,7 @@ func NewState() *State {
CursorPosition: 0,
SelectionStart: -1,
SelectionEnd: -1,
SelectionAnchor: -1,
fileVersion: make(map[string]int),
lastWriteVersion: make(map[string]int),
writeFailed: make(map[string]bool),
@@ -345,7 +351,8 @@ func HandleCursorMove(delta int) {
}
// HandleKeyDown interprets keyboard events for navigation and editing.
// Receives both key.Event (as key.Name) and key.EditEvent from the main loop.
// Receives key.EditEvent (text input) and key presses as ui.KeyEvent (with
// modifier state) or bare key.Name (legacy/test path, no modifiers).
func HandleKeyDown(data any) {
// A too-large file is not editable: ignore all key input.
if TheState.Editor.TooLarge {
@@ -355,42 +362,52 @@ func HandleKeyDown(data any) {
case key.EditEvent:
// Text input from IME / keyboard.
if v.Text == "\b" {
// Backspace character (legacy / hardware): delete one char before
// the cursor.
// Backspace character (legacy / hardware): delete the selection if
// there is one, else one char before the cursor.
HandleBackspace()
} else {
// IME insert/replace/delete: replace [Range.Start, Range.End) with
// Text. Range is empty (start==end) for plain inserts; a non-empty
// range with text is a swipe/autocorrect replacement; a non-empty
// range with empty text is a range delete. Ignoring Range here is
// what caused replaced text to be duplicated.
// what caused replaced text to be duplicated. A live selection is
// always replaced (see HandleReplaceRange).
HandleReplaceRange(v.Range.Start, v.Range.End, v.Text)
}
case ui.KeyEvent:
handleKey(v.Name, v.Shift)
case key.Name:
switch v {
case key.NameLeftArrow:
HandleCursorMove(-1)
case key.NameRightArrow:
HandleCursorMove(1)
case key.NameUpArrow:
HandleVerticalCursorMove(true)
case key.NameDownArrow:
HandleVerticalCursorMove(false)
case key.NameDeleteBackward:
HandleBackspace()
case key.NameDeleteForward:
HandleDelete()
case key.NameReturn:
HandleInsert("\n")
case key.NameHome:
HandleHome()
case key.NameEnd:
HandleEnd()
case key.NamePageUp:
HandlePageUpDown(true)
case key.NamePageDown:
HandlePageUpDown(false)
}
// Bare key name: no modifier state, so no shift-selection here.
handleKey(v, false)
}
}
// handleKey dispatches a key press. shift=true turns cursor moves into
// selection extensions; edit keys act on the selection when one is active.
func handleKey(name key.Name, shift bool) {
switch name {
case key.NameLeftArrow:
moveCursor(shift, func() { HandleCursorMove(-1) })
case key.NameRightArrow:
moveCursor(shift, func() { HandleCursorMove(1) })
case key.NameUpArrow:
moveCursor(shift, func() { HandleVerticalCursorMove(true) })
case key.NameDownArrow:
moveCursor(shift, func() { HandleVerticalCursorMove(false) })
case key.NameDeleteBackward:
HandleBackspace()
case key.NameDeleteForward:
HandleDelete()
case key.NameReturn:
HandleInsert("\n")
case key.NameHome:
moveCursor(shift, HandleHome)
case key.NameEnd:
moveCursor(shift, HandleEnd)
case key.NamePageUp:
moveCursor(shift, func() { HandlePageUpDown(true) })
case key.NamePageDown:
moveCursor(shift, func() { HandlePageUpDown(false) })
}
}
@@ -403,6 +420,117 @@ func glyphBase() int {
return TheState.Editor.IMEWindowStartByte
}
// --- Text selection ---------------------------------------------------------
//
// The selection is a byte range in absolute file coordinates derived from
// SelectionAnchor (fixed end) and CursorPosition (active end). No selection:
// anchor == -1 and SelectionStart == SelectionEnd == -1. Shift+arrow/home/
// end/page extend the selection; a plain cursor move or any edit clears it.
// All of these must run on the logic goroutine (owner).
// selActive reports whether there is a non-empty selection.
func selActive() bool {
e := &TheState.Editor
return e.SelectionAnchor >= 0 && e.SelectionStart >= 0 && e.SelectionEnd > e.SelectionStart
}
// ClearSelection drops the selection and the shift-anchor.
func ClearSelection() {
e := &TheState.Editor
e.SelectionAnchor = -1
e.SelectionStart = -1
e.SelectionEnd = -1
}
// SetSelection selects the byte range [min(start,end), max(start,end)),
// anchoring at the lower end and placing the cursor (active end) at the upper
// end. Clamped to the buffer; an empty/clamped range clears instead.
// Convenience for tests and future gestures (tap-range, double-tap).
func SetSelection(start, end int) {
e := &TheState.Editor
if start > end {
start, end = end, start
}
if start < 0 {
start = 0
}
var fileLen int
if cb := e.ChunkedBuffer; cb != nil {
fileLen = int(cb.FileLen())
} else {
fileLen = len(e.Buffer)
}
if end > fileLen {
end = fileLen
}
if end <= start {
ClearSelection()
e.CursorPosition = start
return
}
e.SelectionAnchor = start
e.SelectionStart = start
e.SelectionEnd = end
e.CursorPosition = end
}
// updateSelectionFromAnchor recomputes SelectionStart/End from (anchor,
// cursor). A zero-length range (anchor == cursor) is treated as no selection,
// but the anchor is kept so the next shift-move extends from the original spot
// again.
func updateSelectionFromAnchor() {
e := &TheState.Editor
if e.SelectionAnchor < 0 {
ClearSelection()
return
}
a, c := e.SelectionAnchor, e.CursorPosition
if a == c {
e.SelectionStart = -1
e.SelectionEnd = -1
return
}
if a < c {
e.SelectionStart, e.SelectionEnd = a, c
} else {
e.SelectionStart, e.SelectionEnd = c, a
}
}
// moveCursor runs op (a cursor-mutating handler). With shift held it keeps
// the anchor and extends the selection to the new cursor position; without it
// it clears any selection first. This is the single place where selection
// bookkeeping meets cursor movement, so every move path (arrows, home/end,
// page, vertical) gets consistent semantics.
func moveCursor(shift bool, op func()) {
if shift {
if TheState.Editor.SelectionAnchor < 0 {
TheState.Editor.SelectionAnchor = TheState.Editor.CursorPosition
}
} else {
ClearSelection()
}
op()
if shift {
updateSelectionFromAnchor()
}
}
// deleteRange removes the byte range [start, end) from the active buffer and
// updates the line index. Shared by the selection-aware edit handlers.
func deleteRange(start, end int) {
if end <= start {
return
}
if buf := TheState.Editor.ChunkedBuffer; buf != nil {
buf.Delete(start, end-start)
buf.UpdateLineIndexAfterDelete(start, end)
} else {
str := TheState.Editor.Buffer
TheState.Editor.Buffer = str[:start] + str[end:]
}
}
// HandleHome moves the cursor to the start of the current visual line.
func HandleHome() {
layout := TheState.Editor.GlyphLayout
@@ -599,56 +727,130 @@ func HandleVerticalCursorMove(up bool) {
TheState.Editor.CursorPosition = base + layout.ByteOffsets[targetIdx]
}
// HandleDelete removes the character after the cursor.
func HandleDelete() {
pos := TheState.Editor.CursorPosition
buf := TheState.Editor.ChunkedBuffer
if buf != nil {
buf.Delete(pos, 1)
buf.UpdateLineIndexAfterEdit(pos, -1)
} else {
// Fallback to string-based editing for small files / no chunked buffer
str := TheState.Editor.Buffer
if pos >= len(str) {
return
}
TheState.Editor.Buffer = str[:pos] + str[pos+1:]
// utf8BackspaceWidth returns the byte width of the UTF-8 rune ending at the
// end of seg (the rune immediately before the cursor). seg must contain the
// rune's full bytes (4 or more preceding bytes suffice).
func utf8BackspaceWidth(seg string) int {
// The rune ends at the end of seg. Scan back over continuation bytes
// (0x80-0xBF) until the lead byte; the width is the span covered.
i := len(seg) - 1
for i > 0 && seg[i]&0xC0 == 0x80 {
i--
}
return len(seg) - i
}
// utf8AdvanceWidth returns the byte width of the UTF-8 rune starting at the
// beginning of seg (4 or more following bytes suffice). Returns 0 if seg is
// empty (cursor at EOF).
func utf8AdvanceWidth(seg string) int {
if len(seg) == 0 {
return 0
}
w := 1
for i := 1; i < len(seg) && seg[i]&0xC0 == 0x80; i++ {
w++
}
return w
}
// HandleDelete removes the character (full UTF-8 rune) after the cursor.
// With a live selection it deletes the whole selection.
func HandleDelete() {
e := &TheState.Editor
if selActive() {
deleteRange(e.SelectionStart, e.SelectionEnd)
e.CursorPosition = e.SelectionStart
ClearSelection()
markDirty()
return
}
pos := e.CursorPosition
buf := e.ChunkedBuffer
if buf != nil {
seg := buf.Content(pos, pos+4)
if w := utf8AdvanceWidth(seg); w > 0 {
buf.Delete(pos, w)
buf.UpdateLineIndexAfterDelete(pos, pos+w)
markDirty()
}
return
}
// Fallback to string-based editing for small files / no chunked buffer
str := TheState.Editor.Buffer
if pos >= len(str) {
return
}
end := len(str)
if pos+4 < end {
end = pos + 4
}
TheState.Editor.Buffer = str[:pos] + str[pos+utf8AdvanceWidth(str[pos:end]):]
markDirty()
}
// HandleInsert inserts a string at the current cursor position.
// HandleInsert inserts a string at the current cursor position. With a live
// selection it replaces the selection instead.
func HandleInsert(s string) {
pos := TheState.Editor.CursorPosition
buf := TheState.Editor.ChunkedBuffer
// EditorState is embedded by value in State: take the address, never a
// copy, or the writes below are lost.
e := &TheState.Editor
pos := e.CursorPosition
if selActive() {
pos = e.SelectionStart
deleteRange(e.SelectionStart, e.SelectionEnd)
ClearSelection()
}
buf := e.ChunkedBuffer
if buf != nil {
buf.Insert(pos, s)
buf.UpdateLineIndexAfterEdit(pos, len(s))
buf.UpdateLineIndexAfterInsert(pos, s)
} else {
// Fallback to string-based editing for small files / no chunked buffer
str := TheState.Editor.Buffer
TheState.Editor.Buffer = str[:pos] + s + str[pos:]
str := e.Buffer
e.Buffer = str[:pos] + s + str[pos:]
}
TheState.Editor.CursorPosition += len(s)
e.CursorPosition = pos + len(s)
markDirty()
}
// HandleBackspace removes the character before the cursor.
// HandleBackspace removes the character before the cursor. With a live
// selection it deletes the whole selection instead.
func HandleBackspace() {
pos := TheState.Editor.CursorPosition
e := &TheState.Editor
if selActive() {
deleteRange(e.SelectionStart, e.SelectionEnd)
e.CursorPosition = e.SelectionStart
ClearSelection()
markDirty()
return
}
pos := e.CursorPosition
if pos == 0 {
return
}
buf := TheState.Editor.ChunkedBuffer
buf := e.ChunkedBuffer
if buf != nil {
buf.Delete(pos-1, 1)
buf.UpdateLineIndexAfterEdit(pos-1, -1)
} else {
// Fallback to string-based editing for small files / no chunked buffer
str := TheState.Editor.Buffer
TheState.Editor.Buffer = str[:pos-1] + str[pos:]
segStart := pos - 4
if segStart < 0 {
segStart = 0
}
w := utf8BackspaceWidth(buf.Content(segStart, pos))
buf.Delete(pos-w, w)
buf.UpdateLineIndexAfterDelete(pos-w, pos)
TheState.Editor.CursorPosition = pos - w
markDirty()
return
}
TheState.Editor.CursorPosition--
// Fallback to string-based editing for small files / no chunked buffer
str := TheState.Editor.Buffer
segStart := pos - 4
if segStart < 0 {
segStart = 0
}
w := utf8BackspaceWidth(str[segStart:pos])
TheState.Editor.Buffer = str[:pos-w] + str[pos:]
TheState.Editor.CursorPosition = pos - w
markDirty()
}
@@ -710,6 +912,19 @@ func HandleReplaceRange(startRune, endRune int, text string) {
}
absStart := windowStart + runeIndexToByteStr(windowText, startRune)
absEnd := windowStart + runeIndexToByteStr(windowText, endRune)
// A live selection is always replaced by the commit: union the IME range
// with the selection so the outcome is deterministic no matter what the
// IME reports (some IMEs send the full selection range, others send an
// empty range at the caret expecting the app to consume its reported
// selection).
if selActive() {
if absStart > TheState.Editor.SelectionStart {
absStart = TheState.Editor.SelectionStart
}
if absEnd < TheState.Editor.SelectionEnd {
absEnd = TheState.Editor.SelectionEnd
}
}
if imeDebugLog {
fmt.Printf("IME DEBUG HandleReplaceRange: startRune=%d endRune=%d text=%q windowStart=%d windowLen=%d -> absStart=%d absEnd=%d\n",
startRune, endRune, text, windowStart, len(windowText), absStart, absEnd)
@@ -721,7 +936,10 @@ func HandleReplaceRange(startRune, endRune int, text string) {
buf.Delete(absStart, absEnd-absStart)
}
buf.Insert(absStart, text)
buf.UpdateLineIndexAfterEdit(absStart, len(text)-(absEnd-absStart))
if absEnd > absStart {
buf.UpdateLineIndexAfterDelete(absStart, absEnd)
}
buf.UpdateLineIndexAfterInsert(absStart, text)
newCursor = absStart + len(text)
} else {
s := TheState.Editor.Buffer
@@ -732,6 +950,8 @@ func HandleReplaceRange(startRune, endRune int, text string) {
newCursor = absStart + len(text)
}
TheState.Editor.CursorPosition = newCursor
// A commit consumed any selection it overlapped (see the union above).
ClearSelection()
if imeDebugLog {
dbgBuf := currentEditorText()
if len(dbgBuf) > 40 {
@@ -965,6 +1185,24 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
// window is the whole buffer there.
TheState.Editor.IMEWindowStartByte = start
TheState.Editor.IMEWindowText = visibleContent
// Window-relative selection for the TextField (byte offsets into
// visibleContent); -1 means nothing visible is selected. The IME push and
// the in-app highlight consume this; the logic side keeps absolute
// offsets in EditorState.
windowSelStart, windowSelEnd := -1, -1
if ss := TheState.Editor.SelectionStart; ss >= 0 && TheState.Editor.SelectionEnd > ss {
ws, we := ss-start, TheState.Editor.SelectionEnd-start
if ws < 0 {
ws = 0
}
if we > len(visibleContent) {
we = len(visibleContent)
}
if ws < we {
windowSelStart, windowSelEnd = ws, we
}
}
// Add the TextField back in a way that passes the test.
editorElem := ui.NewTextField(
"editor_text",
@@ -973,6 +1211,8 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
editorRegion.W,
visibleScrollOffset,
visibleCursorPos,
windowSelStart,
windowSelEnd,
[]ui.Interaction{
{Gesture: ui.Scroll, Handler: HandleScroll},
{Gesture: ui.KeyDown, Handler: HandleKeyDown},
@@ -1016,6 +1256,8 @@ func tapLocalY(ptY, regionTopY ui.Dp, scrollOffset ui.Dp) float64 {
// SetCursorFromPoint updates the cursor position based on screen coordinates (Dp).
func SetCursorFromPoint(x, y float64) {
// A tap is an explicit cursor placement: it always clears any selection.
ClearSelection()
layout := TheState.Editor.GlyphLayout
if len(layout.ByteOffsets) == 0 || len(layout.X) == 0 || len(layout.Advance) == 0 {
return