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
+66 -7
View File
@@ -74,8 +74,22 @@ Key invariants:
`frame.Scale`, sends `ScaleEvent` (after the draw).
2. Under the handoff lock: reads the `Frame` snapshot, calls
`renderer.Draw(gtx, frame.Elems, scale)`, then `renderer.CheckGestures`
and the focused element's key/edit events (via `key.Filter` +
`key.FocusFilter`), then `e.Frame(&ops)`.
and the focused element's key/edit events, then `e.Frame(&ops)`.
Key events are queried with a catch-all `key.Filter{Focus: id}` **plus
one named filter per arrow key**. This is required on Android: the
window layer wraps plain arrow-key *presses* in `input.SystemEvent`
(it wants them for focus navigation), and system events match only
filters that name the key explicitly. Matching a named filter both makes
the press deliverable and suppresses the focus-move side effect (a
matched event makes `WakeupTime` report handled, skipping the window's
`moveFocus`). The **shift key is tracked here** (`shiftDown`): Gio's
Android JNI bridge never reads `KeyEvent.getMetaState`, so
`key.Event.Modifiers` is always 0 and shift+arrow is otherwise
indistinguishable from a plain arrow. `NameShift` press/release do
arrive as plain events; the tracked state is attached to the
`ui.KeyEvent{Shift: ...}` forwarded to the logic (OR-ed with the
Modifiers field so desktop behavior is unchanged). Shift state is
reset when no element is focused.
3. Outside the lock: sends `[]ui.InputEvent` (if any) to `InputChan`,
the search text (if it differs from `frame.Query`) to `SearchQueryChan`,
and `renderer.GlyphLayout()` to `LayoutChan`.
@@ -188,11 +202,26 @@ Rules:
chunk lengths. There is no lazy loading and no eviction (both existed as
plans and were removed).
- **Byte-indexed** throughout: `CursorPosition`, chunk offsets, and glyph
`ByteOffsets` are byte offsets.
`ByteOffsets` are byte offsets. All edit primitives are **rune-granular**:
`HandleBackspace`/`HandleDelete` compute the UTF-8 rune width at the cursor
(a byte-granular delete corrupts multi-byte characters, e.g. a two-byte
character straddling a chunk boundary); IME edits arrive as rune ranges;
tap-to-position lands on rune starts.
- Edits splice the affected chunk(s) only; chunks are not rebalanced.
- `LineIndex` (per-line byte offsets, `int32`) is built asynchronously by
`BuildLineIndexTask` and stored on `cb.LineIndex` — the single source of
truth (the old parallel `EditorState.LineIndex` field was removed).
truth (the old parallel `EditorState.LineIndex` field was removed). A file
ending in `'\n'` has a trailing empty line (one offset past the last `\n`,
equal to the file length).
- **Incremental line-index maintenance.** Every buffer edit updates the index
in place instead of rebuilding it: `UpdateLineIndexAfterInsert(pos, text)`
(shifts starts above `pos` right, keeps a start at `pos`, adds one start per
inserted `\n`) and `UpdateLineIndexAfterDelete(start, end)` (drops starts in
`[start, end)`, shifts the rest left, re-inserts `start` iff it is a line
start in the new content). A start exactly at `end` always drops: it was
created by the `'\n'` at `end-1`, which the deletion removes (line merge).
These must be called in the same order as the buffer splice, and an IME
replace is `Delete` then `Insert` at the same position.
- **Size guard:** files larger than `MaxEditableFileSize` (**50 MB**,
measured on-device) open into a `TooLarge` state: the editor shows a notice
and edit handlers are no-ops; the browser still lists the file.
@@ -219,7 +248,29 @@ Only the visible byte range is shaped and drawn each frame:
searching the offsets. For a whole-file window the base is 0 (a no-op).
Getting this wrong snaps the cursor to the window top on scrolled large files.
### 6.3 IME (Android soft keyboard)
### 6.3 Selection and caret
- Key presses arrive as `ui.KeyEvent{Name, Shift}` (main.go), not bare
`key.Name`, so handlers can distinguish shift+arrow from plain arrow.
On Android the `Shift` bit comes from main.go's own shift tracking, not
from Gio's Modifiers (see §2.1); arrow-key presses reach the handler only
because main.go registers the explicit named key filters.
- **Shift+arrow extends a selection**, plain arrow moves the caret and clears
it. `SelectionAnchor` is the fixed end, `CursorPosition` the active end; both
are **absolute file byte offsets**. No selection ⇔ `SelectionAnchor == -1`.
A zero-length shift selection keeps the anchor (`SelectionStart/End == -1`)
so the next shift-move extends from the original spot.
- Insert / backspace / delete with a live selection delete the whole selection
first (`deleteRange`), then insert; the selection is cleared afterwards.
- IME: with an active selection, `HandleReplaceRange` unions the IME-reported
range with the selection before splicing, so replacement is deterministic
whether the IME reports the caret (empty range) or the full range.
- Rendering: the `TextField` element carries **window-relative** selection
start/end into the visible `Value` (−1 = none) for the highlight, drawn
before the glyphs; the IME `SelectionCmd` push dedups on the
(selectionStart, caret) pair.
### 6.4 IME (Android soft keyboard)
- The editor exposes to the IME a **windowed snippet**: `IMEWindowText` is the
visible viewport text, `IMEWindowStartByte` its absolute start. While the
@@ -235,7 +286,7 @@ Only the visible byte range is shaped and drawn each frame:
`deleteSurroundingText` (backspace/autocorrect replacement), and composition
all arrive through this one path.
### 6.4 Autosave
### 6.5 Autosave
- Any edit calls `markDirty()`: a 1 s debounce timer; each keystroke restarts
it. On expiry the timer goroutine sends a token on `autosaveChan`; the owner
@@ -245,7 +296,7 @@ Only the visible byte range is shaped and drawn each frame:
retried via `retryChan`. There is no save button; autosave is the only
persistence.
### 6.5 Opening a file
### 6.6 Opening a file
- A browser tap sends the path on `OpenFileChan`. The logic goroutine creates
the `ChunkedBuffer`, dispatches `StatFile` (size guard) and the read +
@@ -312,6 +363,14 @@ Only the visible byte range is shaped and drawn each frame:
(`development_plan.md` Phase 4).
- Dead task types (`ReadChunk`, `SaveState`, `SaveUndo`, …) and unused element
types are candidates for removal in the same round.
- The Android arrow-key/shift workaround in main.go (named `key.Filter`s +
app-side shift tracking, §2.1) compensates for two Gio v0.10 behaviors: the
JNI bridge dropping modifier state, and mobile arrow presses being wrapped
in `input.SystemEvent` for focus navigation. If Gio changes either
behavior (e.g. starts passing meta state), the shift tracking and the named
filters must be re-examined — the workaround would become redundant or
wrong. Re-verify on-device with `adb shell input keyevent 22` (cursor must
move) and `input keycombination 59 22` (selection must extend).
## 11. Performance profiler (default-off, `internal/perf`)
+24 -5
View File
@@ -1,8 +1,8 @@
# Development Plan: reach a lean, usable Android text editor
Status: v6, 2026-08-16 (Phases 0–3 + doc reorg + Phase 6 scroll-perf/clamping
verification + tap-to-position-cursor fix). Written against the **live** repo
`/home/gmp/pad`. v1 (the widget-rebuild plan) is
Status: v7, 2026-08-16 (Phases 0–3 + doc reorg + Phase 6 scroll-perf/clamping
verification + tap-to-position-cursor fix + selection + real-file e2e). Written
against the **live** repo `/home/gmp/pad`. v1 (the widget-rebuild plan) is
superseded — see §12 for why. Doc reorganization (2026-08-16): the over-detailed
docs (`*_implementation_plan.md`, `touch.md`, `element_model.md`,
`layout_rendering.md`, `virtual_scroll_render_optimization.md`,
@@ -23,8 +23,27 @@ refactor); fixed with `tapLocalY`. (2) the `GlyphLayout` byte offsets are
window-relative but the four cursor functions (tap, Home, End, vertical move)
treated them as absolute, so the cursor snapped to the window top; fixed by adding
the `IMEWindowStartByte` window base at each cursor boundary (`glyphBase`). Both
have regression tests. Remaining: real-device swipe/autocorrect sign-off (the
emulator's AOSP/Gboard keyboard is a proxy).
have regression tests.
Phase 8 (2026-08-16/17) added **text selection** (shift+arrow extend; insert/
backspace/delete replace the selection; IME unions its range with the active
selection) with rendering + IME wiring. It also added **real-file e2e tests**
(`internal/test/e2e/real_file_*_test.go`: open/edit/autosave on real on-disk
files, incl. chunk-boundary and multi-byte edits) and found + fixed two real
bugs: (1) `UpdateLineIndexAfterEdit` only shifted offsets — any edit involving
newlines left the line index permanently inconsistent; replaced with
newline-aware `UpdateLineIndexAfterInsert`/`UpdateLineIndexAfterDelete`.
(2) `HandleBackspace`/`HandleDelete` deleted **one byte**, corrupting
multi-byte UTF-8 characters; now rune-granular.
On-device validation (2026-08-17) exposed a **third, platform-level gap**:
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 and shift+arrow was impossible.
Fixed in main.go: explicit named `key.Filter`s for the four arrows (delivers
the press and suppresses the focus jump) plus app-side shift tracking.
Verified end-to-end on the emulator: plain arrows move the caret,
shift+arrow shows a highlight, typing replaces the selection. Remaining:
real-device swipe/autocorrect sign-off (the emulator's AOSP/Gboard keyboard
is a proxy).
## 1. Decision summary (updated)
+10 -2
View File
@@ -52,8 +52,15 @@ elsewhere.
- **Virtualized viewport:** only the visible byte range is shaped and drawn
each frame (typically ~4 KB of a large file), keeping frame cost and shaper
memory constant regardless of file size.
- **Cursor + scroll:** tap to place the cursor, drag/scroll to pan, Home/End
and Page Up/Down on hardware keyboards, arrow keys.
- **Cursor + scroll:** tap to place the cursor, drag/scroll to pan; with a
hardware keyboard, arrow keys, Home/End, and Page Up/Down move the cursor
(verified on the Android emulator; Gio's mobile focus-navigation default
for arrow keys is overridden — see architecture.md §2.1).
- **Text selection:** shift+arrow (hardware keyboard) extends a selection;
insert, backspace, and delete replace the selected text; the IME replaces
a selection when the user types over it. The selection is highlighted in
the editor and pushed to the IME. (Shift state is tracked by the app,
since Gio's Android bridge drops modifier keys — architecture.md §2.1.)
- **Autosave:** every edit restarts a 1 s debounce; on expiry the full content
is written to disk by a worker. Failed writes are retried. This is the only
persistence mechanism.
@@ -147,6 +154,7 @@ recorded here so future rounds don't mistake doc text for behavior:
| File-system watcher | **not implemented** | Browser does not live-refresh; it re-scans on navigation. |
| Alphabetical index sidebar | **not implemented** | `AlphaIndex` element exists but is unused. |
| In-file search, tabs, split view | **not implemented** | — |
| Touch selection (long-press, drag handles) | **not implemented** | Selection is reachable only via hardware-keyboard shift+arrow; touch users can position the caret by tap. |
| Files > 50 MB | **not supported** | `TooLarge` state instead. |
| Desktop / other platforms | **not supported** | Android-first. |