Compare commits
18
Commits
06b1444207
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6bd5588ade | ||
|
|
7a6b130078 | ||
|
|
a9183a0f73 | ||
|
|
9d5c02db03 | ||
|
|
d38a2ee05f | ||
|
|
a83cc1a72f | ||
|
|
51344b9a5b | ||
|
|
cb8ebc003f | ||
|
|
dd9493bdbd | ||
|
|
36b6a86873 | ||
|
|
f54ca2f81a | ||
|
|
4c8a13b779 | ||
|
|
ef54486683 | ||
|
|
e96464ec79 | ||
|
|
4a3ba37075 | ||
|
|
6d3e070c2d | ||
|
|
16740b0de0 | ||
|
|
5e40378072 |
Binary file not shown.
|
After Width: | Height: | Size: 123 KiB |
+65
-7
@@ -112,20 +112,36 @@ func run(w *app.Window) error {
|
||||
// file, cursor, scroll, selection and find bar state. The cmd layer owns
|
||||
// the file (sessionFilePath, per platform); the logic layer owns the
|
||||
// snapshot (editor.SessionState) and calls the saver rate-limited and at
|
||||
// Shutdown. Restoring re-opens the last file straight into the editor.
|
||||
// Shutdown. A session taken on the editor page re-opens the last file
|
||||
// straight into the editor; one taken on the browser page lands back in
|
||||
// the browser at the saved directory.
|
||||
sessPath := sessionFilePath()
|
||||
logic.SetSessionSaver(newSessionSaver(sessPath))
|
||||
if sess, ok := loadSession(sessPath); ok {
|
||||
if sess.InBrowser {
|
||||
log.Printf("restoring session: browser path=%q", sess.BrowserPath)
|
||||
// The saved directory may have vanished (deleted, synced away) or
|
||||
// be unreadable by this app (stat succeeds but the permission bits
|
||||
// deny the read — e.g. /storage/emulated itself, which is
|
||||
// media_rw:media_rw 0750; only /storage/emulated/0 is app-exposed).
|
||||
// Probe with a real directory read — the same operation the
|
||||
// browser's index does — rather than os.Stat, which passes for
|
||||
// unreadable dirs. Fall back to the startup directory otherwise.
|
||||
if _, err := os.ReadDir(sess.BrowserPath); err == nil {
|
||||
logic.BeginBrowserRestore(sess.BrowserPath)
|
||||
}
|
||||
} else {
|
||||
log.Printf("restoring session: file=%s cursor=%d scroll=%v find=%q", sess.File, sess.Cursor, sess.Scroll, sess.FindQuery)
|
||||
logic.BeginRestore(sess)
|
||||
// The find bar's input is a main-owned widget and the input source of
|
||||
// truth: seed it with the restored query so its first frame matches
|
||||
// the logic-side query (an empty widget would forward "" and clear
|
||||
// the restored query).
|
||||
// The find bar's input is a main-owned widget and the input source
|
||||
// of truth: seed it with the restored query so its first frame
|
||||
// matches the logic-side query (an empty widget would forward ""
|
||||
// and clear the restored query).
|
||||
if sess.FindQuery != "" {
|
||||
findEditor.SetText(sess.FindQuery)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clipboard plumbing (architecture.md §6.3): the logic goroutine only
|
||||
// REQUESTS clipboard operations through channels (copy/cut write, paste
|
||||
@@ -355,6 +371,32 @@ func run(w *app.Window) error {
|
||||
})
|
||||
}
|
||||
case key.EditEvent:
|
||||
if focusedID == "editor_text" {
|
||||
// Apply the commit to the pushed snippet model
|
||||
// IMMEDIATELY (see Renderer.ApplyIMECommitToModel):
|
||||
// gioui's EditEvent callback already advanced its
|
||||
// own window state, and without this the op queue
|
||||
// lags it by one commit — every frame event in
|
||||
// the gap regresses the state and sends a
|
||||
// restartInput with pre-commit text per keystroke
|
||||
// (the random-caps bug).
|
||||
renderer.ApplyIMECommitToModel(gtx, k, frame.EditSeq)
|
||||
// The commit range is in absolute file runes (the
|
||||
// coordinate space of the pushed snippet, whose
|
||||
// Range.Start is the context start). The logic maps
|
||||
// it to bytes against the whole buffer — exact
|
||||
// even mid-fling — and applies the drift guard
|
||||
// (see editor.HandleIMECommit).
|
||||
events = append(events, ui.InputEvent{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{
|
||||
StartRune: k.Range.Start,
|
||||
EndRune: k.Range.End,
|
||||
Text: k.Text,
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
events = append(events, ui.InputEvent{
|
||||
Handler: reg.Handler,
|
||||
Data: k,
|
||||
@@ -371,8 +413,22 @@ func run(w *app.Window) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Flush the IME snippet/selection for the focused editor field
|
||||
// (see Renderer.FlushIME): after the key events above were drained
|
||||
// and mirrored into the IME model, and before e.Frame below flushes
|
||||
// the ops to the OS (which is when gioui compares the pushed state
|
||||
// against the IME's own state.
|
||||
if focusedID == "editor_text" {
|
||||
for _, el := range frame.Elems {
|
||||
if tf, ok := el.(ui.TextField); ok && tf.ID() == "editor_text" {
|
||||
renderer.FlushIME(gtx, tf)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
e.Frame(&ops)
|
||||
mu.Unlock()
|
||||
|
||||
if newScale != curScale || newFontScale != curFontScale {
|
||||
logic.ConfigChan() <- editor.ScaleEvent{Scale: newScale, FontScale: newFontScale}
|
||||
}
|
||||
@@ -435,7 +491,9 @@ func newSessionSaver(path string) func(editor.SessionState) {
|
||||
|
||||
// loadSession reads and sanity-checks the relaunch session file (spec §7).
|
||||
// ok=false when there is no session, it is corrupt, or nothing is restorable
|
||||
// — in which case the app starts in the browser as before.
|
||||
// — in which case the app starts in the browser at the startup directory
|
||||
// as before. Browser-page sessions carry no file; an editor-page session
|
||||
// (the pre-InBrowser legacy shape included) needs one.
|
||||
func loadSession(path string) (editor.SessionState, bool) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
@@ -465,7 +523,7 @@ func loadSession(path string) (editor.SessionState, bool) {
|
||||
if s.ScrollSub < 0 {
|
||||
s.ScrollSub = 0
|
||||
}
|
||||
if s.File == "" {
|
||||
if !s.InBrowser && s.File == "" {
|
||||
return editor.SessionState{}, false
|
||||
}
|
||||
return s, true
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
# Pad documentation
|
||||
|
||||
Four documents, kept at the level of *what, why, and invariants* — not
|
||||
Five documents, kept at the level of *what, why, and invariants* — not
|
||||
line-by-line code — so they stay true as the implementation evolves.
|
||||
|
||||
| Doc | What it is |
|
||||
@@ -9,6 +9,7 @@ line-by-line code — so they stay true as the implementation evolves.
|
||||
| [`architecture.md`](./architecture.md) | How it works: single-owner concurrency model, channel topology, Frame handoff contract, ownership rules, editor/browser/render internals. |
|
||||
| [`development_plan.md`](./development_plan.md) | The active plan: completed phases, remaining work, and the on-device observation loop. |
|
||||
| [`release.md`](./release.md) | The release process (`scripts/release.sh`): the gates, the install-to-all-devices policy, and the rule that on-device profiling/testing is diagnostic and needs explicit approval. |
|
||||
| [`ime.md`](./ime.md) | The IME contract: the three text models, the invariants that keep commits landing where they should, stock-gioui structural behaviors (worked around, not patched), log signatures for diagnosing IME desync, and the test layers and what each can catch. |
|
||||
|
||||
## Package inventory
|
||||
|
||||
|
||||
@@ -472,6 +472,14 @@ Only the visible byte range is shaped and drawn each frame:
|
||||
(crash leftovers, plus the legacy deterministic "`.<name>.tmp`" name).
|
||||
Unique temp names make same-file interleaving structurally impossible even
|
||||
if the serialization regressed.
|
||||
- **Post-rename timestamp:** immediately after the rename, `WriteFileAtomic`
|
||||
sets the file's atime/mtime to now (`os.Chtimes`, best-effort). On Android
|
||||
shared storage the FUSE/MediaProvider layer serves the **previous** file's
|
||||
mtime after a rename (its media-scan DB row is not updated on rename), and
|
||||
stat-comparing change detectors (syncthing) then miss the new content
|
||||
until the next full rescan. The explicit utimensat publishes the current
|
||||
mtime and is the update the watcher reacts to immediately; it is also the
|
||||
timestamp contract `TestWriteFileAtomic_PublishesCurrentMtime` pins.
|
||||
- Write failures are tracked per file (`writeFailed`, `retryAttempts`) and
|
||||
retried via `retryChan` (exponential backoff 1 s … 30 s; the timer sends a
|
||||
non-blocking token and the owner re-snapshots at fire time). There is no
|
||||
@@ -536,6 +544,29 @@ Only the visible byte range is shaped and drawn each frame:
|
||||
- The browser renders via `ListView`/`ListItem` elements; rows carry
|
||||
`Interaction` handlers that send channel requests (tap) or mutate state
|
||||
directly when the handler runs on the owner (scroll).
|
||||
- **Live refresh.** While the browser page is on screen the current directory
|
||||
is watched with **inotify** (`dirWatcher`, `internal/editor/dirwatcher.go`):
|
||||
a create / delete / rename / modify / attrib event there — including an
|
||||
inbound sync that changes a file's mtime — re-reads the directory within tens
|
||||
of ms, re-sorted in the *current* sort mode. A slow **backstop rescan** (30 s)
|
||||
covers the rare event the FUSE inotify layer drops; it is the only remaining
|
||||
periodic component and, by the invariant below, emits no frame when nothing
|
||||
changed. The watch is re-pointed whenever the directory changes (a no-op while
|
||||
the path is unchanged) and is closed when the logic goroutine exits. Invariant:
|
||||
**a re-read that finds the directory unchanged rebuilds nothing and emits no
|
||||
frame**, so the event-driven emission contract (§2;
|
||||
`TestNoFramesWhileIdle_Browser`) still holds while the browser idles. A
|
||||
landing (re)index is applied in place: the visible+prefetch pages are
|
||||
repopulated synchronously from the fresh index (no async gap / flicker), the
|
||||
scroll offset is preserved then clamped, and an active search is re-filtered
|
||||
without a scroll jump. Bounded to **one read per directory**: a re-read
|
||||
requested while a read of the same directory is in flight coalesces (skips),
|
||||
and a stale result for a directory the user has since left is dropped rather
|
||||
than clobbering the current view. A failed *refresh* keeps the last good view
|
||||
(the next event or backstop tick retries); a failed *navigation* still recovers
|
||||
to the previous directory. Returning to the browser from the editor triggers
|
||||
one immediate re-read so the list is current on the frame you land back (events
|
||||
that fired while the editor was on screen are no-ops there).
|
||||
|
||||
## 8. Render pipeline (`internal/ui`)
|
||||
|
||||
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
# The IME contract and its failure modes
|
||||
|
||||
What the editor relies on when talking to Android's IME (Gboard), what
|
||||
stock gioui does structurally, and the failure modes observed on device —
|
||||
with their log signatures and the invariants that keep the system safe.
|
||||
This is the map for the next time text lands in the wrong place.
|
||||
|
||||
## The three models
|
||||
|
||||
An IME session involves **three independent copies of the text** that must
|
||||
be kept consistent:
|
||||
|
||||
1. **The file** (logic goroutine, the truth).
|
||||
2. **The pushed snippet** — the 32 KB window around the caret that we push
|
||||
to the IME (`key.SnippetCmd`). All IME commit positions are in *this*
|
||||
coordinate space (absolute file runes, `Range.Start` = window start).
|
||||
3. **Gboard's local model** — Gboard's private copy of the snippet plus its
|
||||
own caret/selection/composition state, which it updates from our pushes
|
||||
*and* from its own bookkeeping of the commits it sends.
|
||||
|
||||
Every bug in this area is a loss of consistency between model 3 and model
|
||||
1. The commit that arrives names a range in model 3; applying it to model 1
|
||||
is only correct if the two still agree.
|
||||
|
||||
## Invariants the code must maintain
|
||||
|
||||
- **Commits map against the whole buffer, never a stale window.**
|
||||
`HandleIMECommit` converts the commit's rune range to bytes with a
|
||||
whole-buffer scan (`runeToByteWhole`), so it stays exact while the
|
||||
visible window moves (a fling in flight). A renderer-side IME model was
|
||||
tried and abandoned: it drifts whenever the render window moves
|
||||
(commit `f54ca2f`).
|
||||
- **The snippet window is hysteresis-gated and decoupled from the render
|
||||
window** (`State.computeIMESnippetWindow`): 32 KB, re-anchored only when
|
||||
the caret comes within 4 KB of an edge. Re-anchoring reaches Gboard as a
|
||||
`restartInput`, which starts a fresh input session that re-derives
|
||||
auto-capitalization — a per-scroll or per-tap re-push is what caused the
|
||||
random mid-word caps (commit `dd9493b`).
|
||||
- **The post-commit caret is `Range.Start + len(text)`**, not
|
||||
`Range.End + len(text)`. Identical for insertions; for a replacement
|
||||
(autocorrect over a selection) the old formula lands `(End−Start)` runes
|
||||
past the inserted text and desynchronizes the IME at the exact moment its
|
||||
model is being updated (commit `51344b9`). The logic side
|
||||
(`applyIMECommitBytes`) and the renderer's immediate push
|
||||
(`ApplyIMECommitToModel`) must compute the *same* caret.
|
||||
- **A legitimate commit is always local**: at the caret, inside the live
|
||||
selection, or a correction a few runes left of the caret. The guard
|
||||
(`HandleIMECommit`, `maxCommitDistance = 1024`) snaps anything else to
|
||||
the caret and arms the resync. A 5-rune autocorrect 19,000 runes from
|
||||
the caret is never legitimate; applying it verbatim clobbers distant
|
||||
text (commit `a83cc1a`).
|
||||
- **Key-event edits desync the IME exactly like a dropped commit — and the
|
||||
IME's next commit is anchored at the pre-edit caret.** Gboard sends
|
||||
Enter as a KEY EVENT, not a commit (the logic's `handleKey(NameReturn)`
|
||||
inserts the `\n`); the IME's model never sees that edit unless a
|
||||
re-syncing snippet push reaches it first, and the push can lose the race
|
||||
— the next commit can arrive in the very same input batch as the key
|
||||
event, so no frame has drawn. While one such edit is pending
|
||||
(`EditorState.imeStaleEditByte`), the guard accepts a small (≤ 2 rune)
|
||||
TEXT commit that ends at or before the edit position (`IME STALE-OK`):
|
||||
everything before the edit is byte-identical in both models, so applying
|
||||
it verbatim is exact (the usual shape is the IME appending to, or
|
||||
correcting, the word it last committed). The pending edit is consumed and
|
||||
a resync is armed. Never relaxed for: empty-text commits (a stale range
|
||||
deletion is how documents get clobbered), commits ending past the edit
|
||||
(the range crosses the shift), or anything without a pending edit
|
||||
(commit `a83cc1a`'s guard stays intact otherwise). The pending edit is
|
||||
set by `noteNonIMEEdit` (Enter, hardware backspace/delete, cut, paste),
|
||||
consumed by the next IME commit or key edit, cleared by a tap.
|
||||
- **A desynchronized IME is healed only by a restart.** See the structural
|
||||
fact below: selection pushes after a commit are deduplicated away, so
|
||||
the *only* mechanism that makes Gboard re-read the truth is a snippet
|
||||
change (`restartInput`). `IMEForceResync` arms on the **first**
|
||||
anomaly, not a streak: the next frame ships the snippet trimmed by one
|
||||
rune (one restart), the following frame ships the full window (one more),
|
||||
then quiet. One-shot, so normal typing never pays for it
|
||||
(commits `cb8ebc0`, `a83cc1a`).
|
||||
- **Pre-commit frames must not flush the IME — and the hold is armed with
|
||||
the drained frame's own seq.** `ApplyIMECommitToModel` updates the pushed
|
||||
model on the drain pass and arms `imeHold` with the **EditSeq of the
|
||||
frame being drained** (it is the pre-commit frame — built before the
|
||||
logic processed the commit — and its snippet would clobber the just-
|
||||
updated model). `FlushIME` skips frames whose EditSeq is at most the
|
||||
armed one and resumes on the next higher; the logic's `HandleIMECommit`
|
||||
always markDirties, so the post-commit frame exists and always advances
|
||||
the seq. The hold is bounded (8 frames) so a stalled logic can never
|
||||
stick the renderer. Two details that are load-bearing: the frame's
|
||||
`ui.TextField.EditSeq` is copied from the state in `EditorLayout` —
|
||||
without it every frame reads 0, `EditSeq <= holdSeq` matches *every*
|
||||
frame, the hold releases only via the 8-frame timeout, and resync pushes
|
||||
(and all IME sync) are silently swallowed (this is why the resync armed
|
||||
by the 2026-09-19 drift-snap never reached Gboard, letting it keep
|
||||
committing against a stale model); and the seq must be the drained
|
||||
frame's, not "the last drawn frame's" — the drained frame is pre-commit
|
||||
even when its seq already differs from earlier ones (a key event landed
|
||||
in between), and arming with the older value releases the hold on the
|
||||
very frame whose snippet is stale.
|
||||
|
||||
## What stock gioui does structurally (worked around, not patched)
|
||||
|
||||
All of the following is stock v0.10.2 behavior. The fixes live entirely in
|
||||
pad; the fork at `~/gioui` carries **diagnostic logging only** (the
|
||||
`PADIME` lines) and can be dropped for stock gioui at any time without
|
||||
behavioral change.
|
||||
|
||||
1. **Post-commit selection pushes are deduplicated away.** The commit
|
||||
callback (`callbacks.EditorReplace`) advances the window's stored
|
||||
`imeState.Selection` *before* the frame's state comparison, so a
|
||||
`SelectionCmd` pushed in the same frame as a commit is "no change" and
|
||||
`imm.updateSelection` is never called. Consequence: after a commit, the
|
||||
IME's caret can only be corrected by a snippet restart. This is why the
|
||||
resync exists and why "just re-push the selection" is not a fix.
|
||||
2. **`restartInput` shadows `updateSelection`.** In
|
||||
`window.EditorStateChanged`, a snippet change takes an early-return
|
||||
branch: the selection update in the same state change is dropped.
|
||||
Gboard re-fetches the selection on restart, so this is harmless — but
|
||||
it means a restart frame is the *only* frame where selection and text
|
||||
are guaranteed to be re-read together.
|
||||
3. **Selection commands are focus-gated.** `keyQueue.setSelection`
|
||||
silently drops a `SelectionCmd` whose tag is not the current key-focus
|
||||
(`req.Tag != state.focus`). A selection push can vanish with no log and
|
||||
no feedback — the IME never acks selections. If taps stop moving
|
||||
Gboard's caret, check focus first.
|
||||
4. **There is no ack anywhere.** Snippet pushes, selection pushes, and
|
||||
commits are fire-and-forget. The system can only *detect* desync
|
||||
indirectly (a commit landing where no text expects it), which is what
|
||||
the drift guard does.
|
||||
|
||||
## Gboard behaviors observed
|
||||
|
||||
- Gboard sends Enter as a **key event** (InputConnection.sendKeyEvent),
|
||||
not a text commit: the app inserts the `\n` via `handleKey(NameReturn)`
|
||||
and the IME's model never learns about it until a re-syncing snippet
|
||||
push (see the key-event-edit invariant above). The emulator's Gboard
|
||||
does the same; its word-appending is milder than the phone's AICore
|
||||
Gboard, so the desync shows as a caret-off-by-one there and as
|
||||
duplicated text on the phone.
|
||||
- Gboard keeps a word selection on its own (a tap near a word selects it)
|
||||
and commits autocorrect as a **replacement over its local selection** —
|
||||
the commit range is then as wide as the word, not a point insertion.
|
||||
- While composing, Gboard re-sends the whole word on every keystroke
|
||||
(`"t"`, `"th"`, `"thi"`, … each replacing the previous), and on
|
||||
backspace it re-sends the shrinking word down to `text=""`. Both are
|
||||
normal; the drift guard must not treat them as anomalies (they are at
|
||||
the caret).
|
||||
- When its local model desynchronizes, Gboard can enter an endless
|
||||
empty-fix-up loop (`text=""`, one commit per ~150 ms) trying to
|
||||
reconcile text that is not in its model. The file is never damaged (the
|
||||
guard snaps each one to the caret); the resync breaks the loop.
|
||||
- The phone's AICore Gboard is stricter/more aggressive than the emulator's
|
||||
Gboard. A flow that is clean on the emulator can still desync on device.
|
||||
|
||||
## Log signatures → diagnosis
|
||||
|
||||
Permanent, low-volume lines (see "Diagnostics"):
|
||||
|
||||
| Signature in logcat | Meaning |
|
||||
|---|---|
|
||||
| `IME TAP … cursor=N winStart=M` | A tap moved the logic cursor (bytes). Compare with the next `IME COMMIT` ranges (runes) — they should be in the same neighborhood (rune ≈ byte − multibyte count, **compute it, don't assume a constant**). |
|
||||
| `IME COMMIT range=[a,b) text=… -> [x,y)` | The logic applied the commit at bytes [x,y). The pre-`->` range is Gboard's coordinate space; the post-`->` range is where it actually landed. |
|
||||
| `IME DRIFT-SNAP … snap to caret + resync` | Anomaly detected: a commit far from the caret/selection (or a stale small commit) was applied at the caret instead. One = a tap/scroll desync just happened; a run = Gboard was looping. | | `IME STALE-OK … staleEdit=N -> apply as-is + resync` | A key-event edit (usually Enter) is pending and the IME's commit was anchored at the pre-edit caret; it was applied at its reported range (byte-identical there) and a resync armed. Expected once per key-edit → keystroke sequence; a run without intervening commits = something is replaying. |
|
||||
| `IME PUSH snippet=[a,b) … (restart)` | We re-anchored the IME window → Gboard restarts its input session. Should be rare: app open, file switch, caret crossing a window margin. Frequent restarts = the hysteresis gate is being defeated (check render-window coupling). |
|
||||
| `IME PUSH sel=[s,e)` | We pushed a caret/selection to Gboard. If a tap does not produce one (or it repeats forever), the selection pipeline is broken upstream (focus gate, dedup, float-noise re-emit). |
|
||||
| `PADIME EditorStateChanged sel A -> B` / `PADIME updateSelection sel=[…]` / `PADIME restartInput` | The gio→Gboard boundary: what actually crossed into Android. If `IME PUSH` shows a value the `PADIME` lines never show, the drop is inside gioui (focus gate / dedup); if `PADIME` shows it and Gboard still misbehaves, the IME ignored it. |
|
||||
|
||||
**Capture the log at incident time.** Logcat rotates fast; the incident
|
||||
that started this document was only reconstructable because the capture
|
||||
happened minutes later.
|
||||
|
||||
## Test layers and what each can catch
|
||||
|
||||
| Layer | What it exercises | Catches |
|
||||
|---|---|---|
|
||||
| e2e harness (`internal/test/e2e`) | Logic + renderer headless; commits injected directly (`HandleIMECommit`) | Commit mapping math, window invariants, guard/resync logic, edit/scroll/selection state. **Never** the IME contract: Gboard is not in the loop. |
|
||||
| Emulator stress loops (`/tmp/loop4.sh`, `/tmp/stress.sh`) | Real app + adb touches, real Gboard | Fling/tap/typing interplay, restart storms, caps regressions. Coarse: no boundary visibility, scenario shape matters (warm-session fling-tap-type was the original shape; it missed the cold-restore → far-scroll → tap → fast-typing shape entirely). |
|
||||
| Full-path scenario (`/tmp/s8.sh`) | Cold open with restored cursor → far scroll → tap into a known word → fast Gboard typing → backspaces; asserts tap position vs commit ranges vs **exact file diff** | The desync class: text landing anywhere but the tap. The byte→rune conversion must be computed from the file, never assumed. |
|
||||
|
||||
Rule: **a bug in the IME boundary is invisible to every layer except the
|
||||
last one.** When IME behavior is touched, run S8.
|
||||
|
||||
## Operational pitfalls hit in these sessions
|
||||
|
||||
- The launcher activity is `pad.pad/org.gioui.GioActivity`, not
|
||||
`.MainActivity`. `am start` failures are silent if stderr is redirected —
|
||||
check the output once, trust it after.
|
||||
- `adb install`/build steps fail with "no adb device" when the emulator is
|
||||
mid-reconnect; the APK may be built but not installed. Verify
|
||||
`dumpsys package … lastUpdateTime` after installs.
|
||||
- The "All files access" settings toggle can be a red herring: `appops
|
||||
set <pkg> MANAGE_EXTERNAL_STORAGE allow` is the reliable grant, and
|
||||
`appops get` output has been observed to lag; `dumpsys appops` is
|
||||
authoritative.
|
||||
- `difflib.SequenceMatcher` on ~1 MB strings is minutes slow; use a linear
|
||||
first-diff scan for test assertions on large files.
|
||||
- Float-equality re-emit is a recurring trap (LastLineY, caret px): any
|
||||
"re-emit when changed" comparison on a float sum needs an epsilon gate,
|
||||
or it spins a loop that re-pushes IME state every frame and starves real
|
||||
work.
|
||||
- When a tap's pixel→text mapping is in question, the `IME TAP` line gives
|
||||
both the local point and the resulting cursor — log both, or the mapping
|
||||
bug is undiagnosable from the outside.
|
||||
|
||||
## Diagnostics currently enabled (temporary)
|
||||
|
||||
- Pad-side, permanent: `IME TAP`, `IME COMMIT`, `IME DRIFT-SNAP`,
|
||||
`IME PUSH snippet/sel/commit-range` (bounded: only on change).
|
||||
- Fork-side, **temporary** (in `~/gioui`, gated by the `replace` in
|
||||
`go.mod`): `PADIME` boundary logs in `GioView.updateSelection`,
|
||||
`GioView.restartInput`, and `window.EditorStateChanged`.
|
||||
|
||||
### Cleanup steps (when informal on-device testing is settled)
|
||||
|
||||
The fork is stock v0.10.2 plus the `PADIME` lines and nothing else
|
||||
(verify first: `git -C ~/gioui diff --stat` must show only
|
||||
`app/GioView.java` and `app/os_android.go`); behavior is identical on
|
||||
stock gioui.
|
||||
|
||||
```sh
|
||||
# 1. Restore the fork to clean v0.10.2
|
||||
git -C ~/gioui checkout -- .
|
||||
git -C ~/gioui diff --stat # must be empty
|
||||
|
||||
# 2. Drop the replace and re-tidy pad against stock gioui
|
||||
cd ~/pad
|
||||
go mod edit -dropreplace gioui.org
|
||||
go mod tidy
|
||||
|
||||
# 3. Verify everything green on stock gioui
|
||||
go build ./...
|
||||
go test -race ./...
|
||||
./scripts/check.sh
|
||||
|
||||
# 4. Rebuild both APKs and smoke-test
|
||||
./scripts/build_emu.sh # install to emulator
|
||||
bash /tmp/s8.sh # full-path scenario must still PASS
|
||||
./scripts/build_phone.sh # install to phone, type + tap once
|
||||
|
||||
# 5. Commit and push the go.mod/go.sum change
|
||||
git add -A && git commit -m "build: drop the temporary gioui diagnostic fork" && git push origin main
|
||||
|
||||
# 6. Remove this cleanup section (and the "temporary" fork-side bullet
|
||||
# above) from ime.md; commit + push.
|
||||
```
|
||||
|
||||
If step 1 shows more than the two diagnostic files, do NOT `checkout --
|
||||
.` blindly: review the diff and keep anything that is a real (non-log)
|
||||
change, porting it upstream or documenting it in this file first.
|
||||
+7
-4
@@ -141,10 +141,13 @@ elsewhere.
|
||||
|
||||
### 2.4 State restoration on relaunch
|
||||
|
||||
- On launch, Pad re-opens the file from the last session and lands straight
|
||||
on the editor page, restoring the cursor, scroll position, live selection,
|
||||
and the find bar (query, open/closed, current match). A relaunch therefore
|
||||
never requires re-browsing to the last file.
|
||||
- On launch, Pad lands exactly where the last session ended. If the app was
|
||||
in the editor, it re-opens the last file straight on the editor page,
|
||||
restoring the cursor, scroll position, live selection, and the find bar
|
||||
(query, open/closed, current match) — a relaunch therefore never requires
|
||||
re-browsing to the last file. If the app was on the browser page, it lands
|
||||
back in the browser at the saved directory (`InBrowser`/`BrowserPath` in
|
||||
the snapshot; a deleted directory falls back to the startup directory).
|
||||
- The scroll position is persisted as the LOGICAL line at the viewport top
|
||||
plus the sub-line remainder (the raw pixel offset is kept too, for
|
||||
pre-line-coordinate session files). The pixel offset alone is not
|
||||
|
||||
@@ -3,15 +3,17 @@ module pad
|
||||
go 1.24.2
|
||||
|
||||
require (
|
||||
gioui.org v0.10.0
|
||||
gioui.org v0.10.2
|
||||
golang.org/x/image v0.26.0
|
||||
golang.org/x/sys v0.39.0
|
||||
)
|
||||
|
||||
require (
|
||||
gioui.org/shader v1.0.8 // indirect
|
||||
gioui.org/shader v1.0.9 // indirect
|
||||
github.com/go-text/typesetting v0.3.4 // indirect
|
||||
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
)
|
||||
|
||||
replace gioui.org => /home/gmp/gioui
|
||||
|
||||
@@ -1,19 +1,12 @@
|
||||
eliasnaur.com/font v0.0.0-20230308162249-dd43949cb42d h1:ARo7NCVvN2NdhLlJE9xAbKweuI9L6UgfTbYb0YwPacY=
|
||||
eliasnaur.com/font v0.0.0-20230308162249-dd43949cb42d/go.mod h1:OYVuxibdk9OSLX8vAqydtRPP87PyTFcT9uH3MlEGBQA=
|
||||
gioui.org v0.9.0 h1:4u7XZwnb5kzQW91Nz/vR0wKD6LdW9CaVF96r3rfy4kc=
|
||||
gioui.org v0.9.0/go.mod h1:CjNig0wAhLt9WZxOPAusgFD8x8IRvqt26LdDBa3Jvao=
|
||||
gioui.org v0.10.0 h1:kV6NKGbEp0JSPLtgoT/xk5dMexVDzvEOErXA40gUxrU=
|
||||
gioui.org v0.10.0/go.mod h1:MZJZsdEPkTBzChdqeE8CiiQhreUQBj43qusDxQNDf7k=
|
||||
gioui.org/cpu v0.0.0-20210808092351-bfe733dd3334/go.mod h1:A8M0Cn5o+vY5LTMlnRoK3O5kG+rH0kWfJjeKd9QpBmQ=
|
||||
gioui.org/shader v1.0.8 h1:6ks0o/A+b0ne7RzEqRZK5f4Gboz2CfG+mVliciy6+qA=
|
||||
gioui.org/shader v1.0.8/go.mod h1:mWdiME581d/kV7/iEhLmUgUK5iZ09XR5XpduXzbePVM=
|
||||
github.com/go-text/typesetting v0.3.0 h1:OWCgYpp8njoxSRpwrdd1bQOxdjOXDj9Rqart9ML4iF4=
|
||||
github.com/go-text/typesetting v0.3.0/go.mod h1:qjZLkhRgOEYMhU9eHBr3AR4sfnGJvOXNLt8yRAySFuY=
|
||||
gioui.org/shader v1.0.9 h1:XxnqIfmClWpN49kizxH2W0JcCFrrEP4q3jZmNYaltbs=
|
||||
gioui.org/shader v1.0.9/go.mod h1:mWdiME581d/kV7/iEhLmUgUK5iZ09XR5XpduXzbePVM=
|
||||
github.com/go-text/typesetting v0.3.4 h1:YYurUOtEb9kGSOz4uE3k4OpBGsp1dDL8+fjCeaFamAU=
|
||||
github.com/go-text/typesetting v0.3.4/go.mod h1:4qZCQphq4KSgGTAeI0uMEkVbROgfah8BuyF5LRYr7XY=
|
||||
github.com/go-text/typesetting-utils v0.0.0-20241103174707-87a29e9e6066 h1:qCuYC+94v2xrb1PoS4NIDe7DGYtLnU2wWiQe9a1B1c0=
|
||||
github.com/go-text/typesetting-utils v0.0.0-20241103174707-87a29e9e6066/go.mod h1:DDxDdQEnB70R8owOx3LVpEFvpMK9eeH1o2r0yZhFI9o=
|
||||
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3 h1:drBZzMgdYPbmyXqOto4YhhJGrFIQCX94FpR4MzTCsos=
|
||||
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o=
|
||||
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM=
|
||||
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8=
|
||||
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0 h1:tMSqXTK+AQdW3LpCbfatHSRPHeW6+2WuxaVQuHftn80=
|
||||
@@ -22,11 +15,7 @@ golang.org/x/image v0.26.0 h1:4XjIFEZWQmCZi6Wv8BoxsDhRU3RVnLX04dToTDAEPlY=
|
||||
golang.org/x/image v0.26.0/go.mod h1:lcxbMFAovzpnJxzXS3nyL83K27tmqtKzIJpctK8YO5c=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -25,6 +28,51 @@ func LoadInitialPages(s *BrowserState) {
|
||||
}
|
||||
}
|
||||
|
||||
// directorySignature is a cheap, order-independent fingerprint of a directory's
|
||||
// real entries (name, size, mtime, isdir), used to tell a no-op periodic
|
||||
// refresh from a real change. The synthetic ".." row is excluded: its mtime is
|
||||
// rebuilt on every pass and would otherwise make the signature differ each time.
|
||||
func directorySignature(entries []Entry) uint64 {
|
||||
names := make([]string, 0, len(entries))
|
||||
byName := make(map[string]Entry, len(entries))
|
||||
for _, e := range entries {
|
||||
if e.Name == ".." {
|
||||
continue
|
||||
}
|
||||
names = append(names, e.Name)
|
||||
byName[e.Name] = e
|
||||
}
|
||||
sort.Strings(names)
|
||||
h := fnv.New64a()
|
||||
fmt.Fprintf(h, "%d\n", len(names))
|
||||
for _, n := range names {
|
||||
e := byName[n]
|
||||
fmt.Fprintf(h, "%s|%d|%d|%v\n", n, e.Size, e.ModTime.UnixNano(), e.IsDir)
|
||||
}
|
||||
return h.Sum64()
|
||||
}
|
||||
|
||||
// replaceVisiblePagesFromIndex drops the current pages and synchronously
|
||||
// reloads the visible+prefetch pages from the (possibly new) SortIndex, so the
|
||||
// frame that carries a fresh index already carries its rows — no async gap and
|
||||
// no flicker on a periodic refresh. Distant pages are dropped and reload from
|
||||
// the fresh index on scroll. Called from the owner goroutine when a directory
|
||||
// (re)index lands (see BrowserManager.handleBuildIndexSuccess).
|
||||
func replaceVisiblePagesFromIndex(s *BrowserState) {
|
||||
if s.SortIndex == nil || s.TotalEntries == 0 {
|
||||
s.Pages = make(map[int]*Page)
|
||||
return
|
||||
}
|
||||
minPage, maxPage := computeVisiblePageRange(s)
|
||||
fresh := make(map[int]*Page, maxPage-minPage+1)
|
||||
for i := minPage; i <= maxPage; i++ {
|
||||
if page := loadPageFromIndex(s, i); page != nil {
|
||||
fresh[i] = page
|
||||
}
|
||||
}
|
||||
s.Pages = fresh
|
||||
}
|
||||
|
||||
// loadPageFromIndex creates a Page from the sorted index at the given page index.
|
||||
// Uses position maps to convert sorted indices to raw indices for entry lookup.
|
||||
// Returns nil if the page index is out of bounds.
|
||||
|
||||
@@ -45,20 +45,15 @@ func TestLazyLoadingLargeDirectory(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for index build result and process it
|
||||
// Wait for index build result and process it. The visible+prefetch pages
|
||||
// are populated synchronously from the fresh index inside HandleResult (no
|
||||
// separate initial LoadPages result is dispatched).
|
||||
res, ok := getResult(15 * time.Second)
|
||||
if !ok {
|
||||
t.Fatal("Timeout waiting for BuildIndex result")
|
||||
}
|
||||
bm.HandleResult(res)
|
||||
|
||||
// Wait for initial page load result and process it
|
||||
res, ok = getResult(15 * time.Second)
|
||||
if !ok {
|
||||
t.Fatal("Timeout waiting for initial LoadPages result")
|
||||
}
|
||||
bm.HandleResult(res)
|
||||
|
||||
// 2. Verify only initial pages loaded (visible + prefetch)
|
||||
if len(state.Pages) == 0 {
|
||||
t.Error("Expected pages to be loaded")
|
||||
@@ -104,8 +99,7 @@ func TestPrefetchOnScroll(t *testing.T) {
|
||||
}
|
||||
|
||||
bm.NavigateTo("/dir")
|
||||
// Process BuildIndex and initial load
|
||||
bm.HandleResult(<-wp.ResultChan())
|
||||
// Process BuildIndex (visible+prefetch pages are populated synchronously).
|
||||
bm.HandleResult(<-wp.ResultChan())
|
||||
|
||||
// Current visible ~page 0. Pages 0, 1, 2 should be loaded.
|
||||
|
||||
+134
-23
@@ -15,6 +15,20 @@ type BrowserManager struct {
|
||||
state *BrowserState
|
||||
workerPool *pool.WorkerPool
|
||||
fs pool.FileSystem
|
||||
// indexInFlightPath is the directory whose BuildIndex read is currently
|
||||
// in flight ("" if none); indexInFlightIsNav records whether that read
|
||||
// was a user navigation (recover-on-failure) or a background refresh
|
||||
// (retry-silently). Both are owner-goroutine-only. Together they keep at
|
||||
// most one read in flight per directory and let a stale, late result be
|
||||
// dropped instead of clobbering the directory the user has since moved to.
|
||||
indexInFlightPath string
|
||||
indexInFlightIsNav bool
|
||||
// lastIndexSignature/lastIndexPath describe the last directory index that
|
||||
// actually changed the view. A refresh whose entries match is a no-op (no
|
||||
// rebuild, no frame), keeping emission event-driven while the browser
|
||||
// idles. Owner-goroutine-only.
|
||||
lastIndexPath string
|
||||
lastIndexSignature uint64
|
||||
}
|
||||
|
||||
func NewBrowserManager(state *BrowserState, wp *pool.WorkerPool, fs pool.FileSystem) (*BrowserManager, error) {
|
||||
@@ -25,6 +39,15 @@ func NewBrowserManager(state *BrowserState, wp *pool.WorkerPool, fs pool.FileSys
|
||||
}, nil
|
||||
}
|
||||
|
||||
// dispatchIndex records an in-flight directory read and sends its task to the
|
||||
// worker pool. isNav marks a user navigation (recover on failure) vs a
|
||||
// background refresh (retry silently on the next tick). Owner-goroutine-only.
|
||||
func (bm *BrowserManager) dispatchIndex(dirPath string, isNav bool) {
|
||||
bm.indexInFlightPath = dirPath
|
||||
bm.indexInFlightIsNav = isNav
|
||||
bm.workerPool.Dispatch(pool.NewBuildIndexTask(dirPath, bm.fs))
|
||||
}
|
||||
|
||||
func (bm *BrowserManager) NavigateTo(dirPath string) {
|
||||
// Save the previous path so we can restore it on navigation failure.
|
||||
bm.state.History = append(bm.state.History, bm.state.CurrentPath)
|
||||
@@ -33,10 +56,38 @@ func (bm *BrowserManager) NavigateTo(dirPath string) {
|
||||
navigateToDirectory(bm.state, dirPath)
|
||||
bm.state.Loading = true
|
||||
|
||||
// Dispatch BuildIndexTask to the worker pool.
|
||||
// In a real app, this would be a task that reads and sorts the directory.
|
||||
task := pool.NewBuildIndexTask(dirPath, bm.fs)
|
||||
bm.workerPool.Dispatch(task)
|
||||
// Re-read the directory; the landing result rebuilds the sorted index and
|
||||
// position maps, so the list and its order always reflect disk.
|
||||
bm.dispatchIndex(dirPath, true)
|
||||
}
|
||||
|
||||
// Load performs the initial directory index for an already-set CurrentPath
|
||||
// (startup). Like a navigation it recovers on failure, but without touching
|
||||
// History. Owner-goroutine-only.
|
||||
func (bm *BrowserManager) Load(dirPath string) {
|
||||
bm.state.CurrentPath = dirPath
|
||||
bm.state.Loading = true
|
||||
bm.dispatchIndex(dirPath, true)
|
||||
}
|
||||
|
||||
// Refresh re-reads the current directory to pick up external changes — files
|
||||
// added, removed, renamed, or mtime-changed (including inbound syncs) — so the
|
||||
// list and its sort order stay live while the browser is on screen. Unlike
|
||||
// NavigateTo it does not touch History or reset the scroll offset, so the
|
||||
// user's position is preserved; the landing result (handleBuildIndexSuccess)
|
||||
// rebuilds the index in place and re-sorts. Bounded to one read per directory:
|
||||
// a refresh while a read of the same directory is in flight is skipped (its
|
||||
// result will refresh the view). Owner-goroutine-only.
|
||||
func (bm *BrowserManager) Refresh(dirPath string) {
|
||||
if dirPath == "" {
|
||||
return
|
||||
}
|
||||
if bm.indexInFlightPath == dirPath {
|
||||
return
|
||||
}
|
||||
bm.state.CurrentPath = dirPath
|
||||
bm.state.Loading = true
|
||||
bm.dispatchIndex(dirPath, false)
|
||||
}
|
||||
|
||||
func (bm *BrowserManager) OnScroll() {
|
||||
@@ -63,28 +114,45 @@ func (bm *BrowserManager) OnScroll() {
|
||||
bm.state.EvictPages()
|
||||
}
|
||||
|
||||
func (bm *BrowserManager) HandleResult(result pool.Result) {
|
||||
// HandleResult applies a completed browser task result to the state. It returns
|
||||
// whether the browser view changed and so a frame should be emitted. A periodic
|
||||
// refresh that finds the directory unchanged returns false, keeping emission
|
||||
// event-driven even while the browser idles.
|
||||
func (bm *BrowserManager) HandleResult(result pool.Result) bool {
|
||||
if !result.IsBrowserResult() {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
switch result.TaskType {
|
||||
case pool.TypeBuildIndex:
|
||||
if result.Success {
|
||||
bm.handleBuildIndexSuccess(result)
|
||||
} else {
|
||||
bm.handleError(result)
|
||||
return bm.handleBuildIndexSuccess(result)
|
||||
}
|
||||
return bm.handleError(result)
|
||||
case pool.TypeLoadPages:
|
||||
if result.Success {
|
||||
bm.handleLoadPagesSuccess(result)
|
||||
} else {
|
||||
bm.handleError(result)
|
||||
return true
|
||||
}
|
||||
return bm.handleError(result)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (bm *BrowserManager) handleBuildIndexSuccess(result pool.Result) bool {
|
||||
// A read of this directory has landed; clear the in-flight marker.
|
||||
if bm.indexInFlightPath == result.DirPath {
|
||||
bm.indexInFlightPath = ""
|
||||
bm.indexInFlightIsNav = false
|
||||
}
|
||||
// A directory we have since left produced a late result (a navigation
|
||||
// overtook it). Drop it so it cannot clobber the current directory's index
|
||||
// and pages. (Production results always carry DirPath; the empty check
|
||||
// keeps hand-built test results without one applying as before.)
|
||||
if result.DirPath != "" && result.DirPath != bm.state.CurrentPath {
|
||||
return false
|
||||
}
|
||||
|
||||
func (bm *BrowserManager) handleBuildIndexSuccess(result pool.Result) {
|
||||
bm.state.Loading = false
|
||||
|
||||
// In the mock implementation, BuildIndexTask returns []types.DirEntry.
|
||||
@@ -116,6 +184,25 @@ func (bm *BrowserManager) handleBuildIndexSuccess(result pool.Result) {
|
||||
})
|
||||
}
|
||||
|
||||
// A refresh of an unchanged directory is a no-op: skip the rebuild and
|
||||
// report "no change" so no frame is emitted (keeps emission event-driven
|
||||
// while the browser idles). The signature covers the real entries only —
|
||||
// name, size, mtime, isdir — and excludes the synthetic ".." row, whose
|
||||
// mtime is rebuilt on every pass and would otherwise always differ.
|
||||
sig := directorySignature(browserEntries)
|
||||
// The no-change fast path assumes the view already shows this content.
|
||||
// A failed navigation's recovery (handleError) breaks that: it resets the
|
||||
// rows (navigateToDirectory zeros TotalEntries/Pages) and re-reads the
|
||||
// previous directory, whose index is unchanged — without this guard the
|
||||
// re-read would take the fast path and the browser would sit on an empty
|
||||
// list forever. A torn-down view always takes the full rebuild below.
|
||||
if bm.state.TotalEntries != 0 &&
|
||||
bm.lastIndexPath == bm.state.CurrentPath && bm.lastIndexSignature == sig {
|
||||
return false
|
||||
}
|
||||
bm.lastIndexPath = bm.state.CurrentPath
|
||||
bm.lastIndexSignature = sig
|
||||
|
||||
// Build the sorted index with position maps
|
||||
bm.state.SortIndex = &DirectoryIndex{
|
||||
Path: bm.state.CurrentPath,
|
||||
@@ -134,8 +221,21 @@ func (bm *BrowserManager) handleBuildIndexSuccess(result pool.Result) {
|
||||
|
||||
bm.state.TotalEntries = len(browserEntries)
|
||||
|
||||
// Trigger initial page load
|
||||
// Refresh the visible rows synchronously from the fresh index so the frame
|
||||
// that carries the new index already carries its rows — no async gap and no
|
||||
// flicker on a periodic refresh. The scroll offset is preserved (a refresh,
|
||||
// not a jump to top) then clamped in case the list shrank; an active search
|
||||
// is re-filtered against the new order without yanking the scroll. Distant
|
||||
// pages are dropped and reload on scroll from the fresh index.
|
||||
replaceVisiblePagesFromIndex(bm.state)
|
||||
if bm.state.Query != "" {
|
||||
prev := bm.state.ScrollOffset
|
||||
recomputeSearchResults(bm.state)
|
||||
bm.state.ScrollOffset = prev
|
||||
}
|
||||
clampScrollOffset(bm.state)
|
||||
bm.OnScroll()
|
||||
return true
|
||||
}
|
||||
|
||||
func (bm *BrowserManager) handleLoadPagesSuccess(result pool.Result) {
|
||||
@@ -152,25 +252,36 @@ func (bm *BrowserManager) handleLoadPagesSuccess(result pool.Result) {
|
||||
}
|
||||
}
|
||||
|
||||
func (bm *BrowserManager) handleError(result pool.Result) {
|
||||
func (bm *BrowserManager) handleError(result pool.Result) bool {
|
||||
fmt.Printf("handleError: TaskType=%d, Error=%v\n", result.TaskType, result.Error)
|
||||
|
||||
// A read of this directory has (failed) landed; clear the in-flight marker.
|
||||
wasNav := bm.indexInFlightIsNav
|
||||
if bm.indexInFlightPath == result.DirPath {
|
||||
bm.indexInFlightPath = ""
|
||||
bm.indexInFlightIsNav = false
|
||||
}
|
||||
bm.state.Loading = false
|
||||
|
||||
// If the failed task was a BuildIndex (directory navigation), restore
|
||||
// the previous path so the user is sent back to where they were.
|
||||
// A failed BACKGROUND REFRESH: keep the current (last good) view and let
|
||||
// the refresh loop retry on its next tick. Do NOT teleport the user or
|
||||
// reset the list over a transient read error. No visible change, no frame.
|
||||
if result.TaskType == pool.TypeBuildIndex && !wasNav {
|
||||
return false
|
||||
}
|
||||
|
||||
// A failed NAVIGATION: restore the previous path so the user is sent back
|
||||
// to where they were.
|
||||
if result.TaskType == pool.TypeBuildIndex && len(bm.state.History) > 0 {
|
||||
prevPath := bm.state.History[len(bm.state.History)-1]
|
||||
bm.state.History = bm.state.History[:len(bm.state.History)-1]
|
||||
bm.state.CurrentPath = prevPath
|
||||
navigateToDirectory(bm.state, prevPath)
|
||||
// Re-dispatch the build index for the previous directory so the
|
||||
// browser renders the old contents again.
|
||||
task := pool.NewBuildIndexTask(prevPath, bm.fs)
|
||||
bm.workerPool.Dispatch(task)
|
||||
return
|
||||
bm.dispatchIndex(prevPath, true)
|
||||
return true
|
||||
}
|
||||
|
||||
// For other errors, just reset the state or log the error.
|
||||
// In production, we'd show a toast or error message.
|
||||
// Anything else: reset the state (or, in production, show a toast).
|
||||
bm.state.Reset()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -9,6 +10,30 @@ import (
|
||||
"pad/internal/io/pool/types"
|
||||
)
|
||||
|
||||
// testDirEntry / testFileInfo are minimal types.DirEntry implementations so a
|
||||
// browser BuildIndex result can be constructed directly (no worker-pool round
|
||||
// trip, which avoids the follow-up LoadPages tasks that a real landing result
|
||||
// triggers via OnScroll).
|
||||
type testDirEntry struct {
|
||||
name string
|
||||
isDir bool
|
||||
size int64
|
||||
mod time.Time
|
||||
}
|
||||
|
||||
func (e testDirEntry) Name() string { return e.name }
|
||||
func (e testDirEntry) IsDir() bool { return e.isDir }
|
||||
func (e testDirEntry) Info() (os.FileInfo, error) { return testFileInfo{e}, nil }
|
||||
|
||||
type testFileInfo struct{ e testDirEntry }
|
||||
|
||||
func (f testFileInfo) Name() string { return f.e.name }
|
||||
func (f testFileInfo) Size() int64 { return f.e.size }
|
||||
func (f testFileInfo) Mode() os.FileMode { return 0o644 }
|
||||
func (f testFileInfo) ModTime() time.Time { return f.e.mod }
|
||||
func (f testFileInfo) IsDir() bool { return f.e.isDir }
|
||||
func (f testFileInfo) Sys() any { return nil }
|
||||
|
||||
// TestNewBrowserManager verifies that a BrowserManager can be constructed
|
||||
// with valid parameters and has correct initial state.
|
||||
func TestNewBrowserManager(t *testing.T) {
|
||||
@@ -121,9 +146,153 @@ func TestHandleResult_BuildIndexSuccess(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleResult_BuildIndexFailure verifies that a failed BuildIndex
|
||||
// result is handled gracefully.
|
||||
func TestHandleResult_BuildIndexFailure(t *testing.T) {
|
||||
// TestHandleResult_BuildIndexRefreshFailure verifies that a failed BACKGROUND
|
||||
// REFRESH keeps the current (last good) view rather than teleporting the user
|
||||
// or resetting the list over a transient read error.
|
||||
func TestHandleResult_BuildIndexRefreshFailure(t *testing.T) {
|
||||
state := NewBrowserState()
|
||||
state.CurrentPath = "/dir"
|
||||
state.TotalEntries = 5
|
||||
state.Pages[0] = NewPage(0, []Entry{{Name: "a.txt"}})
|
||||
fs := mock.NewFileSystem()
|
||||
wp := pool.NewWorkerPool(1)
|
||||
|
||||
bm, err := NewBrowserManager(state, wp, fs)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBrowserManager failed: %v", err)
|
||||
}
|
||||
|
||||
// Model an in-flight background refresh of the current directory (as
|
||||
// BrowserManager.Refresh would), then feed it a failed result.
|
||||
bm.indexInFlightPath = "/dir"
|
||||
bm.indexInFlightIsNav = false
|
||||
result := pool.Result{
|
||||
TaskType: pool.TypeBuildIndex,
|
||||
Success: false,
|
||||
Error: ErrDirNotFound,
|
||||
DirPath: "/dir",
|
||||
}
|
||||
|
||||
bm.HandleResult(result)
|
||||
|
||||
// The view must be preserved: same directory, same pages, no reset.
|
||||
if state.CurrentPath != "/dir" {
|
||||
t.Errorf("CurrentPath = %q after refresh failure, want /dir (view must be kept)", state.CurrentPath)
|
||||
}
|
||||
if len(state.Pages) != 1 {
|
||||
t.Errorf("Pages = %d after refresh failure, want 1 (view must be kept)", len(state.Pages))
|
||||
}
|
||||
if bm.indexInFlightPath != "" {
|
||||
t.Errorf("indexInFlightPath = %q after refresh failure, want cleared", bm.indexInFlightPath)
|
||||
}
|
||||
}
|
||||
|
||||
// waitBrowserResult is a test helper: read one result from the pool's channel
|
||||
// with a deadline, fatal on timeout.
|
||||
func waitBrowserResult(t *testing.T, wp *pool.WorkerPool) pool.Result {
|
||||
t.Helper()
|
||||
select {
|
||||
case res := <-wp.ResultChan():
|
||||
return res
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timeout waiting for browser result")
|
||||
return pool.Result{}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefresh_PicksUpExternalChanges verifies the periodic-refresh contract:
|
||||
// the initial load reports a change; an unchanged refresh reports NO change
|
||||
// (so no frame is emitted while idle) and preserves the scroll offset; and a
|
||||
// refresh after an external add picks up the new file and re-sorts.
|
||||
func TestRefresh_PicksUpExternalChanges(t *testing.T) {
|
||||
t.Parallel()
|
||||
fs := mock.NewFileSystem()
|
||||
fs.AddDir("/Notes", time.Now()) // only used by the OnScroll LoadPages, harmless
|
||||
wp := pool.NewWorkerPool(2)
|
||||
wp.Start()
|
||||
defer wp.Stop()
|
||||
|
||||
state := NewBrowserState()
|
||||
state.CurrentPath = "/Notes"
|
||||
bm, err := NewBrowserManager(state, wp, fs)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBrowserManager failed: %v", err)
|
||||
}
|
||||
|
||||
mod := time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC)
|
||||
buildIndex := func(dirPath string, files ...string) pool.Result {
|
||||
entries := make([]types.DirEntry, 0, len(files))
|
||||
for _, f := range files {
|
||||
entries = append(entries, testDirEntry{name: f, size: 1, mod: mod})
|
||||
}
|
||||
return pool.Result{TaskType: pool.TypeBuildIndex, Success: true, Data: entries, DirPath: dirPath}
|
||||
}
|
||||
|
||||
// Initial load: reports a change.
|
||||
if !bm.HandleResult(buildIndex("/Notes", "a.txt")) {
|
||||
t.Fatal("initial load should report a change")
|
||||
}
|
||||
if state.TotalEntries != 2 { // ".." + a.txt
|
||||
t.Fatalf("TotalEntries = %d after load, want 2", state.TotalEntries)
|
||||
}
|
||||
|
||||
// Unchanged refresh: reports NO change and preserves the scroll offset.
|
||||
state.ScrollOffset = 123
|
||||
if bm.HandleResult(buildIndex("/Notes", "a.txt")) {
|
||||
t.Fatal("unchanged refresh should report no change")
|
||||
}
|
||||
if state.ScrollOffset != 123 {
|
||||
t.Errorf("ScrollOffset = %v after no-op refresh, want 123 (preserved)", state.ScrollOffset)
|
||||
}
|
||||
|
||||
// An external add: the next refresh picks it up and re-sorts.
|
||||
if !bm.HandleResult(buildIndex("/Notes", "a.txt", "b.txt")) {
|
||||
t.Fatal("refresh after external add should report a change")
|
||||
}
|
||||
if state.TotalEntries != 3 { // ".." + a.txt + b.txt
|
||||
t.Fatalf("TotalEntries = %d after add, want 3", state.TotalEntries)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefresh_CoalescesInFlight verifies that a refresh requested while a read
|
||||
// of the same directory is in flight does not dispatch a second read.
|
||||
func TestRefresh_CoalescesInFlight(t *testing.T) {
|
||||
t.Parallel()
|
||||
fs := mock.NewFileSystem()
|
||||
fs.AddDir("/Notes", time.Now())
|
||||
fs.SetDelay(300 * time.Millisecond) // slow the read so we can observe it
|
||||
wp := pool.NewWorkerPool(2)
|
||||
wp.Start()
|
||||
defer wp.Stop()
|
||||
|
||||
state := NewBrowserState()
|
||||
state.CurrentPath = "/Notes"
|
||||
bm, err := NewBrowserManager(state, wp, fs)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBrowserManager failed: %v", err)
|
||||
}
|
||||
|
||||
bm.Load("/Notes") // dispatches one read; it is in flight for ~300ms
|
||||
if bm.indexInFlightPath != "/Notes" {
|
||||
t.Fatalf("expected an in-flight read of /Notes, got %q", bm.indexInFlightPath)
|
||||
}
|
||||
// A refresh while that read is in flight must coalesce (no second read).
|
||||
bm.Refresh("/Notes")
|
||||
if bm.indexInFlightPath != "/Notes" {
|
||||
t.Fatalf("refresh should not replace the in-flight path, got %q", bm.indexInFlightPath)
|
||||
}
|
||||
// Only ONE result should arrive for the coalesced reads.
|
||||
res := waitBrowserResult(t, wp)
|
||||
bm.HandleResult(res)
|
||||
if bm.indexInFlightPath != "" {
|
||||
t.Fatalf("in-flight marker should be cleared after the result, got %q", bm.indexInFlightPath)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleResult_BuildIndexNavFailureRestoresPrevious verifies that a failed
|
||||
// NAVIGATION restores the previous directory (the existing recovery behavior)
|
||||
// instead of leaving the user on a directory that could not be read.
|
||||
func TestHandleResult_BuildIndexNavFailureRestoresPrevious(t *testing.T) {
|
||||
state := NewBrowserState()
|
||||
fs := mock.NewFileSystem()
|
||||
wp := pool.NewWorkerPool(1)
|
||||
@@ -133,18 +302,23 @@ func TestHandleResult_BuildIndexFailure(t *testing.T) {
|
||||
t.Fatalf("NewBrowserManager failed: %v", err)
|
||||
}
|
||||
|
||||
// Simulate a failed BuildIndex result
|
||||
// Model a navigation from "/" to a directory that then fails to read.
|
||||
state.History = append(state.History, "/")
|
||||
state.CurrentPath = "/missing"
|
||||
bm.indexInFlightPath = "/missing"
|
||||
bm.indexInFlightIsNav = true
|
||||
|
||||
result := pool.Result{
|
||||
TaskType: pool.TypeBuildIndex,
|
||||
Success: false,
|
||||
Error: ErrDirNotFound,
|
||||
DirPath: "/missing",
|
||||
}
|
||||
|
||||
bm.HandleResult(result)
|
||||
|
||||
// Should not panic, state should be recoverable
|
||||
if state.CurrentPath != "" {
|
||||
t.Errorf("Expected empty CurrentPath on error, got %q", state.CurrentPath)
|
||||
// The user is sent back to the previous directory.
|
||||
if state.CurrentPath != "/" {
|
||||
t.Errorf("CurrentPath = %q after nav failure, want / (previous dir restored)", state.CurrentPath)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,3 +474,80 @@ func TestHandleResult_UnknownType(t *testing.T) {
|
||||
// Should not panic
|
||||
bm.HandleResult(result)
|
||||
}
|
||||
|
||||
// TestHandleResult_NavigationFailureRecoveryReloads reproduces the empty-list
|
||||
// bug: navigating into an unreadable directory fails, the manager reverts to
|
||||
// the previous path and re-reads it; that re-read finds the directory
|
||||
// UNCHANGED, and the no-change fast path must not skip restoring the rows the
|
||||
// failed navigation's reset wiped — or the browser sits on an empty list
|
||||
// forever (header correct, list dead).
|
||||
func TestHandleResult_NavigationFailureRecoveryReloads(t *testing.T) {
|
||||
state := NewBrowserState()
|
||||
fs := mock.NewFileSystem()
|
||||
wp := pool.NewWorkerPool(1)
|
||||
// Started (unlike the direct-result tests above): the recovery path
|
||||
// dispatches REAL follow-up tasks (BuildIndex, LoadPages), and three of
|
||||
// them would overflow the unstarted pool's high-priority channel.
|
||||
wp.Start()
|
||||
defer wp.Stop()
|
||||
|
||||
bm, err := NewBrowserManager(state, wp, fs)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBrowserManager failed: %v", err)
|
||||
}
|
||||
|
||||
// A FIXED mtime: the two index results must carry byte-identical content
|
||||
// (same directorySignature) so the recovery re-read genuinely hits the
|
||||
// no-change fast path that the bug lived in.
|
||||
fixed := time.Date(2026, 5, 15, 10, 0, 0, 0, time.UTC)
|
||||
entries := func() []types.DirEntry {
|
||||
return []types.DirEntry{
|
||||
testDirEntry{name: "file1.txt", size: 8, mod: fixed},
|
||||
testDirEntry{name: "subdir", isDir: true, mod: fixed},
|
||||
}
|
||||
}
|
||||
indexResult := func(dirPath string) pool.Result {
|
||||
return pool.Result{TaskType: pool.TypeBuildIndex, Success: true, DirPath: dirPath, Data: entries()}
|
||||
}
|
||||
|
||||
// Land in /test/docs with a populated view.
|
||||
state.CurrentPath = "/test/docs"
|
||||
bm.indexInFlightPath = "/test/docs"
|
||||
bm.indexInFlightIsNav = true
|
||||
if !bm.HandleResult(indexResult("/test/docs")) {
|
||||
t.Fatal("initial index did not change the view")
|
||||
}
|
||||
if state.TotalEntries != 3 { // 2 entries + ".."
|
||||
t.Fatalf("TotalEntries = %d, want 3", state.TotalEntries)
|
||||
}
|
||||
|
||||
// The user taps into an unreadable directory (as NavigateTo would set up).
|
||||
state.History = append(state.History, state.CurrentPath)
|
||||
navigateToDirectory(state, "/missing")
|
||||
state.Loading = true
|
||||
bm.indexInFlightPath = "/missing"
|
||||
bm.indexInFlightIsNav = true
|
||||
|
||||
// That read fails: the manager must revert to /test/docs.
|
||||
failed := pool.Result{TaskType: pool.TypeBuildIndex, Success: false, Error: ErrDirNotFound, DirPath: "/missing"}
|
||||
bm.HandleResult(failed)
|
||||
if state.CurrentPath != "/test/docs" {
|
||||
t.Fatalf("CurrentPath = %q, want reverted /test/docs", state.CurrentPath)
|
||||
}
|
||||
if state.TotalEntries != 0 {
|
||||
t.Fatalf("TotalEntries = %d after failed navigation, want 0 (rows reset)", state.TotalEntries)
|
||||
}
|
||||
|
||||
// The recovery re-read of /test/docs lands with the directory unchanged.
|
||||
// This is where the bug lived: the no-change fast path returned early and
|
||||
// the view stayed empty.
|
||||
if !bm.HandleResult(indexResult("/test/docs")) {
|
||||
t.Fatal("recovery re-read reported no view change; the list would stay empty")
|
||||
}
|
||||
if state.TotalEntries != 3 {
|
||||
t.Fatalf("TotalEntries = %d after recovery re-read, want 3", state.TotalEntries)
|
||||
}
|
||||
if page, ok := state.Pages[0]; !ok || page == nil || !page.Loaded {
|
||||
t.Fatal("page 0 not restored after recovery re-read")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -452,10 +452,12 @@ func (cb *ChunkedBuffer) VisibleByteRange(scrollOffset ui.Dp, byteOffset int, vi
|
||||
// released). That is the root cause of the ~1GB "Unknown" memory on large
|
||||
// files.
|
||||
//
|
||||
// Word wrap does not require a separate path: each real line produces at
|
||||
// least one visual line, so shaping viewportHeight/lineHeight real lines
|
||||
// always yields at least as many visual lines as fit in the viewport. The
|
||||
// extra wrapped lines are simply clipped by the renderer.
|
||||
// Word wrap does not require a separate path: the viewport top and bottom
|
||||
// are each expressed in VISUAL-line space and mapped to the logical lines
|
||||
// that contain them (WrapIndex.LineForVisual). Because each logical line
|
||||
// produces at least one visual line, that logical range always covers the
|
||||
// viewport; the fetch is viewport-bounded no matter how many wraps lie
|
||||
// above it, and any spill past the bottom edge is clipped by the renderer.
|
||||
lineH := lineHeight
|
||||
if lineH <= 0 {
|
||||
lineH = EffectiveLineHeight()
|
||||
@@ -564,10 +566,31 @@ func (cb *ChunkedBuffer) visibleByteRangePrecise(scrollOffset ui.Dp, viewportHei
|
||||
// (the legacy no-wrap behavior).
|
||||
v0, _ := scrollDecompose(scrollOffset, lineHeight)
|
||||
startLine = int(v0)
|
||||
if w := cb.WrapIndex; w != nil {
|
||||
startLine = w.LineForVisual(int32(v0))
|
||||
}
|
||||
endLine := int(math.Ceil(float64(scrollOffset+viewportHeight) / float64(lineHeight)))
|
||||
if w := cb.WrapIndex; w != nil {
|
||||
// The window TOP is a visual line (the viewport top): map it to the
|
||||
// logical line that contains it.
|
||||
//
|
||||
// The window BOTTOM must NOT be mapped through the index the same
|
||||
// way: the wrap counts for lines INSIDE the viewport land precisely
|
||||
// while this window is being shaped (their measured layouts feed the
|
||||
// index), so the mapped bottom would oscillate frame to frame as
|
||||
// measurements arrive, resizing the window every frame. Each
|
||||
// resize changes the pushed IME snippet, and gioui turns a snippet
|
||||
// change into a restartInput — a restart on every frame reset the
|
||||
// IME's per-word input session, the source of random mid-word
|
||||
// capitalization.
|
||||
//
|
||||
// Instead use a fixed span of logical lines from the stable top:
|
||||
// each logical line produces at least one visual line, so the
|
||||
// viewport's bottom visual line lies at or above
|
||||
// startLine + (bottomVisual - topVisual); the window always covers
|
||||
// the viewport, over-fetching only by the wrapped lines inside it
|
||||
// (bounded by the viewport height; the renderer clips).
|
||||
bottomVisual := endLine
|
||||
startLine = w.LineForVisual(int32(v0))
|
||||
endLine = startLine + (bottomVisual - int(v0))
|
||||
}
|
||||
|
||||
if startLine < 0 {
|
||||
startLine = 0
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package editor
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// browserWatchMask covers the changes the browser list cares about: a file or
|
||||
// subdirectory appearing (CREATE/MOVED_TO), disappearing (DELETE/MOVED_FROM),
|
||||
// being rewritten (MODIFY), or having its mtime/attributes change (ATTRIB —
|
||||
// this is the signal for an inbound sync that updates a file in place). Any
|
||||
// event in this set is enough to justify a full re-read of the directory.
|
||||
const browserWatchMask = unix.IN_CREATE | unix.IN_DELETE |
|
||||
unix.IN_MOVED_TO | unix.IN_MOVED_FROM |
|
||||
unix.IN_MODIFY | unix.IN_ATTRIB
|
||||
|
||||
// dirWatcher watches a single directory for filesystem changes via inotify and
|
||||
// reports them as coarse "something changed" tokens on its event channel. It
|
||||
// backs the browser's live list: while the browser page is on screen the
|
||||
// current directory is watched, and any event there triggers a re-read (see
|
||||
// Logic.refreshBrowserDir).
|
||||
//
|
||||
// Ownership: only the owner goroutine calls SetDir and Close. The run goroutine
|
||||
// only reads the inotify fd and sends on event. The inotify fd is the single
|
||||
// synchronisation point between them: Close() closes the fd, which unblocks
|
||||
// run()'s blocking Read so the goroutine exits promptly. curDir/curWd are
|
||||
// therefore owner-only (no locking needed).
|
||||
type dirWatcher struct {
|
||||
event chan struct{}
|
||||
fd int
|
||||
curDir string // directory currently watched (owner-only)
|
||||
curWd uint32 // its inotify watch descriptor, for removal on re-point
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
// newDirWatcher initialises an inotify instance and starts the run goroutine
|
||||
// (no directory is watched yet; call SetDir to begin). It returns nil if
|
||||
// inotify is unavailable, in which case the caller's slow backstop rescan is
|
||||
// the only refresh path. The returned watcher must be Closed on shutdown.
|
||||
func newDirWatcher(event chan struct{}) *dirWatcher {
|
||||
fd, err := unix.InotifyInit1(0)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
w := &dirWatcher{event: event, fd: fd}
|
||||
go w.run()
|
||||
return w
|
||||
}
|
||||
|
||||
// SetDir (re)points the watch at dir, removing the previous watch. It is
|
||||
// best-effort: a failure leaves the prior watch in place and is covered by the
|
||||
// slow backstop rescan. Owner-goroutine-only.
|
||||
func (w *dirWatcher) SetDir(dir string) {
|
||||
if w == nil || dir == "" || dir == w.curDir {
|
||||
return
|
||||
}
|
||||
if w.curWd > 0 {
|
||||
unix.InotifyRmWatch(w.fd, w.curWd) // best-effort
|
||||
w.curWd = 0
|
||||
}
|
||||
wd, err := unix.InotifyAddWatch(w.fd, dir, browserWatchMask)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
w.curDir, w.curWd = dir, uint32(wd)
|
||||
}
|
||||
|
||||
// Close stops the watcher: closing the inotify fd unblocks run()'s Read (EBADF)
|
||||
// so the goroutine exits. Safe to call multiple times. Owner-goroutine-only.
|
||||
func (w *dirWatcher) Close() {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
w.closeOnce.Do(func() { unix.Close(w.fd) })
|
||||
}
|
||||
|
||||
// run blocks reading inotify events for the life of the fd. It does not parse
|
||||
// events: any non-empty read means "the watched directory changed", which is all
|
||||
// the browser needs (it re-reads the whole directory and re-sorts). The send is
|
||||
// non-blocking into a buffer-1 channel, so a burst of events coalesces to at
|
||||
// most one pending token — the manager's in-flight marker then bounds the
|
||||
// actual re-reads.
|
||||
func (w *dirWatcher) run() {
|
||||
buf := make([]byte, 16*1024)
|
||||
for {
|
||||
n, err := unix.Read(w.fd, buf)
|
||||
if n > 0 {
|
||||
select {
|
||||
case w.event <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return // fd closed by Close() (EBADF) or an inotify error
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,7 @@ type Frame struct {
|
||||
// poison the WrapIndex for the window's lines. The main goroutine
|
||||
// drops the feedback for such frames.
|
||||
ViewportDegenerate bool
|
||||
|
||||
}
|
||||
|
||||
// frameOf wraps a computed element tree with the current view-state
|
||||
|
||||
@@ -209,17 +209,21 @@ func TestHandleReplaceRange_SwappedBounds(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestHandleReplaceRange_WindowOffset_Chunked verifies the scrolled-viewport
|
||||
// path: the IME snippet is a window that does NOT start at buffer byte 0, so
|
||||
// the EditEvent.Range is window-relative and must be offset by the window
|
||||
// start to address the buffer.
|
||||
// path: the IME snippet starts mid-file, so the EditEvent.Range (absolute
|
||||
// file runes, addressed from IMEOffsetRune) must be mapped through the
|
||||
// leading context and the window to address the buffer.
|
||||
func TestHandleReplaceRange_WindowOffset_Chunked(t *testing.T) {
|
||||
newChunkedState(t, "Hello World, this is a test.", 8)
|
||||
// Simulate a scrolled viewport: layout would have set the visible window
|
||||
// to start at byte 6 ("World, this is a test.").
|
||||
// to start at byte 6 ("World, this is a test."), with no leading context
|
||||
// (all ASCII, so rune offset == byte offset).
|
||||
TheState.Editor.IMEWindowStartByte = 6
|
||||
TheState.Editor.IMEWindowText = "World, this is a test."
|
||||
// Replace runes [0,5) of the window ("World") with "There".
|
||||
HandleReplaceRange(0, 5, "There")
|
||||
TheState.Editor.IMEContext = ""
|
||||
TheState.Editor.IMEContextStartByte = 6
|
||||
TheState.Editor.IMEOffsetRune = 6
|
||||
// The IME reports absolute file runes: "World" is runes [6,11).
|
||||
HandleReplaceRange(6, 11, "There")
|
||||
cb := TheState.Editor.ChunkedBuffer
|
||||
got, err := cb.FullContent()
|
||||
if err != nil {
|
||||
@@ -234,17 +238,110 @@ func TestHandleReplaceRange_WindowOffset_Chunked(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleReplaceRange_WindowOffset_String verifies the same window-relative
|
||||
// logic on the small-file (string) buffer.
|
||||
// TestHandleReplaceRange_WindowOffset_String verifies the same absolute-rune
|
||||
// mapping on the small-file (string) buffer.
|
||||
func TestHandleReplaceRange_WindowOffset_String(t *testing.T) {
|
||||
st := newStringState("Hello World, this is a test.")
|
||||
st.Editor.IMEWindowStartByte = 6
|
||||
st.Editor.IMEWindowText = "World, this is a test."
|
||||
HandleReplaceRange(0, 5, "There")
|
||||
st.Editor.IMEContext = ""
|
||||
st.Editor.IMEContextStartByte = 6
|
||||
st.Editor.IMEOffsetRune = 6
|
||||
HandleReplaceRange(6, 11, "There")
|
||||
if want := "Hello There, this is a test."; st.Editor.Buffer != want {
|
||||
t.Fatalf("windowed replace: got %q, want %q", st.Editor.Buffer, want)
|
||||
}
|
||||
if cp := st.Editor.CursorPosition; cp != 11 {
|
||||
if cp := TheState.Editor.CursorPosition; cp != 11 {
|
||||
t.Fatalf("cursor = %d, want 11", cp)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleReplaceRange_WithContext verifies the leading-context mapping:
|
||||
// the snippet is context+window and the IME's absolute rune offsets may land
|
||||
// inside the context (before the window). The context contains a multi-byte
|
||||
// rune so rune != byte there, which pins the rune->byte walk. A second, fresh
|
||||
// state covers a range that spans the context/window boundary.
|
||||
func TestHandleReplaceRange_WithContext(t *testing.T) {
|
||||
// File "héllo world, this" (18 bytes): h(0) é(1-2) l(3) l(4) o(5)
|
||||
// sp(6) w(7) o(8) r(9) l(10) d(11) ,(12) sp(13) t(14) h(15) i(16) s(17).
|
||||
// Window starts at byte 6 (the space), so window = " world, this"; the
|
||||
// context is the preceding runes "héllo" (5 runes, 6 bytes), starting at
|
||||
// byte 0. The snippet spans absolute runes [0, ...), so IMEOffsetRune=0.
|
||||
st := newStringState("héllo world, this")
|
||||
st.Editor.IMEWindowStartByte = 6
|
||||
st.Editor.IMEWindowText = " world, this"
|
||||
st.Editor.IMEContext = "héllo"
|
||||
st.Editor.IMEContextStartByte = 0
|
||||
st.Editor.IMEOffsetRune = 0
|
||||
// Replace absolute rune [1,2) ("é", bytes 1..3) with "@": inside context.
|
||||
HandleReplaceRange(1, 2, "@")
|
||||
if want := "h@llo world, this"; st.Editor.Buffer != want {
|
||||
t.Fatalf("context replace: got %q, want %q", st.Editor.Buffer, want)
|
||||
}
|
||||
if cp := TheState.Editor.CursorPosition; cp != 2 {
|
||||
t.Fatalf("cursor = %d, want 2", cp)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleReplaceRange_SpansContextWindow verifies a replace range that
|
||||
// straddles the context/window boundary maps correctly through both.
|
||||
func TestHandleReplaceRange_SpansContextWindow(t *testing.T) {
|
||||
st := newStringState("héllo world, this")
|
||||
st.Editor.IMEWindowStartByte = 6
|
||||
st.Editor.IMEWindowText = " world, this"
|
||||
st.Editor.IMEContext = "héllo"
|
||||
st.Editor.IMEContextStartByte = 0
|
||||
st.Editor.IMEOffsetRune = 0
|
||||
// Absolute runes [4,7): rune4='o'(context, byte5) + rune5=sp(window,
|
||||
// byte6) + rune6='w'(window, byte7) -> bytes [5,8) = "o w". Keeping
|
||||
// bytes 0..4 ("héll") and 8+ ("orld, this").
|
||||
HandleReplaceRange(4, 7, "ZZ")
|
||||
if want := "héllZZorld, this"; st.Editor.Buffer != want {
|
||||
t.Fatalf("spanning replace: got %q, want %q", st.Editor.Buffer, want)
|
||||
}
|
||||
if cp := TheState.Editor.CursorPosition; cp != 7 {
|
||||
t.Fatalf("cursor = %d, want 7", cp)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuneAnchorTracking verifies the incremental rune-count cache: it must
|
||||
// follow edits (imeAnchorEdit) and agree with a naive full count after a
|
||||
// sequence of mutations at various positions.
|
||||
func TestRuneAnchorTracking(t *testing.T) {
|
||||
st := newChunkedState(t, "hello wörld, this is a test", 8)
|
||||
check := func(what string) {
|
||||
t.Helper()
|
||||
full, _ := st.Editor.ChunkedBuffer.FullContent()
|
||||
for _, pos := range []int{0, 3, 9, len(full)} {
|
||||
if got, want := st.imeRuneOffsetAt(pos), countRunes(full[:pos]); got != want {
|
||||
t.Fatalf("%s: imeRuneOffsetAt(%d) = %d, want %d", what, pos, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
check("initial")
|
||||
testInsertAt(t, st, 3, "é")
|
||||
check("insert mid")
|
||||
testInsertAt(t, st, int(st.Editor.ChunkedBuffer.FileLen()), "é")
|
||||
check("insert end")
|
||||
testDeleteAt(t, st, 2, 4)
|
||||
check("delete")
|
||||
}
|
||||
|
||||
// testInsertAt inserts text at absolute byte pos on the test state, adjusting
|
||||
// the IME rune anchor the same way the production edit paths do.
|
||||
func testInsertAt(t *testing.T, st *State, pos int, text string) {
|
||||
t.Helper()
|
||||
st.Editor.ChunkedBuffer.Insert(pos, text)
|
||||
st.Editor.ChunkedBuffer.UpdateLineIndexAfterInsert(pos, text)
|
||||
st.Editor.CursorPosition = pos + len(text)
|
||||
imeAnchorEdit(pos, "", text)
|
||||
}
|
||||
|
||||
// testDeleteAt deletes n bytes at absolute byte pos on the test state.
|
||||
func testDeleteAt(t *testing.T, st *State, pos, n int) {
|
||||
t.Helper()
|
||||
del := st.Editor.ChunkedBuffer.Content(pos, pos+n)
|
||||
st.Editor.ChunkedBuffer.Delete(pos, n)
|
||||
st.Editor.ChunkedBuffer.UpdateLineIndexAfterDelete(pos, pos+n)
|
||||
imeAnchorEdit(pos, del, "")
|
||||
}
|
||||
|
||||
+127
-4
@@ -73,6 +73,7 @@ type Logic struct {
|
||||
openFileChan chan string
|
||||
retryChan chan string // auto-save retries
|
||||
autosaveChan chan struct{} // auto-save debounce ticks (timer -> owner)
|
||||
|
||||
// flushSession: one-shot request to persist the session snapshot now
|
||||
// (the OS activity onStop hook, see FlushSession). Buffered 1 so the
|
||||
// requester never blocks, even if an earlier flush is still queued.
|
||||
@@ -93,6 +94,16 @@ type Logic struct {
|
||||
done chan struct{}
|
||||
exitWg sync.WaitGroup
|
||||
saveTimer *time.Timer // auto-save debounce timer; non-nil while pending
|
||||
// Browser live-list (see dirwatcher.go). The primary trigger is inotify:
|
||||
// browserWatcher watches the current browser directory and sends a token on
|
||||
// browserEventChan when it changes (file created/removed/renamed or
|
||||
// mtime-changed, incl. inbound syncs). browserRefreshTimer is a slow
|
||||
// safety-net rescan that covers the rare event the FUSE inotify layer drops.
|
||||
// Both are owner-goroutine-only and funnel into refreshBrowserDir.
|
||||
browserEventChan chan struct{} // inotify: dirWatcher -> owner (buffered 1)
|
||||
browserWatcher *dirWatcher // inotify watch on the current browser dir
|
||||
browserRefreshChan chan struct{} // backstop rescan tick (timer -> owner)
|
||||
browserRefreshTimer *time.Timer // backstop rescan timer; non-nil while pending
|
||||
lastEmit time.Time // time of the last frame emission (profiler cadence)
|
||||
debugCmdC chan string // one-shot debug commands from the cmd-file poller; nil = disabled
|
||||
|
||||
@@ -114,6 +125,10 @@ type Logic struct {
|
||||
// the stat result, and is not a content-arrival signal).
|
||||
restoreScroll ui.Dp
|
||||
restoreScrollArmed bool
|
||||
// restoreArmedAt is when the restore scroll was armed; bounds how long
|
||||
// maybeApplyRestoreScroll may wait for a trustworthy MaxScroll (see
|
||||
// there) before landing best-effort.
|
||||
restoreArmedAt time.Time
|
||||
// restoreScrollLine/restoreScrollSub/restorePinDeadline implement the
|
||||
// restore line-pin (see refreshRestorePin in session.go): the
|
||||
// line-derived scroll offset is only consistent with the all-estimate
|
||||
@@ -183,6 +198,8 @@ func NewLogic(mfs pool.FileSystem, path string, openfunc func(string)) *Logic {
|
||||
openFileChan: make(chan string),
|
||||
retryChan: make(chan string, 1), // Buffered channel
|
||||
autosaveChan: make(chan struct{}),
|
||||
browserEventChan: make(chan struct{}, 1),
|
||||
browserRefreshChan: make(chan struct{}),
|
||||
flushSession: make(chan struct{}, 1),
|
||||
inspectChan: make(chan *inspectReq),
|
||||
writeInFlight: make(map[string]int),
|
||||
@@ -259,9 +276,21 @@ var TheLogic *Logic
|
||||
func (l *Logic) Run() {
|
||||
l.exitWg.Add(1)
|
||||
defer l.exitWg.Done()
|
||||
// Close the inotify watcher on any exit. Run is the owner goroutine, so at
|
||||
// return the watcher is single-threaded and safe to close here (covers both
|
||||
// Shutdown and the test-harness Done+WaitForExit path). The closure reads
|
||||
// browserWatcher at exit time, after emitFrame has created it if the browser
|
||||
// was ever shown.
|
||||
defer func() {
|
||||
if l.browserWatcher != nil {
|
||||
l.browserWatcher.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
// Dispatch initial directory index build on startup
|
||||
l.workerPool.Dispatch(pool.NewBuildIndexTask(l.state.Browser.CurrentPath, l.mockFS))
|
||||
// Dispatch the initial directory index build on startup, routed through the
|
||||
// manager so the in-flight marker is set (a later refresh of the same
|
||||
// directory coalesces, and a late result is dropped once we navigate).
|
||||
l.browserManager.Load(l.state.Browser.CurrentPath)
|
||||
|
||||
// Relaunch restoration (spec §7): re-open the last file if a session
|
||||
// was handed in before Run (BeginRestore). The browser index is still
|
||||
@@ -331,7 +360,12 @@ func (l *Logic) Run() {
|
||||
l.emitFrame()
|
||||
}
|
||||
}
|
||||
if derivedLastLineY != l.state.LastLineY {
|
||||
// Epsilon-gated: the derived value is a float sum of line
|
||||
// heights, and exact-equality re-emit spun a re-emit -> shape ->
|
||||
// re-emit loop whenever the sum landed on a different float
|
||||
// representation frame to frame (each loop iteration re-drew the
|
||||
// editor, re-pushed IME state, and starved real work).
|
||||
if d := derivedLastLineY - l.state.LastLineY; d > 0.5 || d < -0.5 {
|
||||
l.state.LastLineY = derivedLastLineY
|
||||
l.emitFrame()
|
||||
}
|
||||
@@ -362,6 +396,18 @@ func (l *Logic) Run() {
|
||||
// the owner snapshots content and dispatches the write.
|
||||
l.saveTimer = nil
|
||||
l.requestSave(l.state.Editor.Filename)
|
||||
case <-l.browserEventChan:
|
||||
// inotify: the current browser directory changed (an external create,
|
||||
// delete, rename, or mtime change). Re-read it; no-op while the
|
||||
// editor is on screen (the change is picked up on the next return).
|
||||
l.refreshBrowserDir()
|
||||
case <-l.browserRefreshChan:
|
||||
// Slow backstop rescan tick (safety net for a dropped inotify event).
|
||||
// The timer goroutine only sent a token; the owner re-reads the current
|
||||
// directory (bounded) and re-arms. No-op while the editor is on screen.
|
||||
l.browserRefreshTimer = nil
|
||||
l.refreshBrowserDir()
|
||||
l.armBrowserRefresh()
|
||||
case p := <-l.state.pasteChan:
|
||||
// Clipboard content arrived from the main goroutine: insert it
|
||||
// (replacing any live selection, per the selection-aware edit rule).
|
||||
@@ -398,6 +444,17 @@ func (l *Logic) openFile(path string) {
|
||||
cb := NewChunkedBuffer(path, chunkSize, l.mockFS, "")
|
||||
cb.SetWorkerPool(l.workerPool)
|
||||
TheState.Editor.ChunkedBuffer = cb
|
||||
// New file: the previous file's IME rune-count cache and window bookkeeping
|
||||
// are meaningless. Reset the anchor so the next imeRuneOffsetAt recomputes
|
||||
// from scratch (the window/context fields are recomputed by buildFrame).
|
||||
TheState.Editor.imeRuneCacheByte = 0
|
||||
TheState.Editor.imeRuneCacheCount = 0
|
||||
TheState.Editor.imeSnipWS, TheState.Editor.imeSnipWE, TheState.Editor.imeSnipArmed = 0, 0, false
|
||||
TheState.Editor.IMESnippetText = ""
|
||||
TheState.Editor.IMECaretRune, TheState.Editor.IMESelStartRune, TheState.Editor.IMESelEndRune = 0, -1, -1
|
||||
TheState.Editor.IMEContext = ""
|
||||
TheState.Editor.IMEContextStartByte = 0
|
||||
TheState.Editor.IMEOffsetRune = 0
|
||||
|
||||
// Dispatch stat task to get file size
|
||||
l.workerPool.Dispatch(pool.NewStatFileTask(path, l.mockFS))
|
||||
@@ -411,6 +468,19 @@ func (l *Logic) emitFrame() {
|
||||
// Relaunch snapshot (spec §7): persist when the state has changed and
|
||||
// the rate limit elapsed (tiny JSON file, see session.go).
|
||||
l.saveSessionIfChanged()
|
||||
// While the browser is on screen, keep its directory fresh so external
|
||||
// adds/removes/renames/mtime changes (incl. inbound syncs) appear live, in
|
||||
// the current sort order. Point the inotify watch at the current directory
|
||||
// (created on first use; re-pointed on navigation, a no-op while the path is
|
||||
// unchanged) and arm the slow backstop rescan. Runs on every browser frame,
|
||||
// covering startup, back-from-editor, and sort toggle.
|
||||
if l.state.page == BrowserPage {
|
||||
if l.browserWatcher == nil {
|
||||
l.browserWatcher = newDirWatcher(l.browserEventChan)
|
||||
}
|
||||
l.browserWatcher.SetDir(l.state.Browser.CurrentPath)
|
||||
l.armBrowserRefresh()
|
||||
}
|
||||
elems := l.state.layout(l.browserManager)
|
||||
// Relaunch restore (spec §7): land the armed restore scroll AFTER the
|
||||
// layout pass above (it refreshed MaxScroll for the current viewport and
|
||||
@@ -655,10 +725,52 @@ func (l *Logic) markDirty() {
|
||||
})
|
||||
}
|
||||
|
||||
// browserBackstopInterval is how often the visible browser directory is
|
||||
// re-read as a SLOW safety net while the browser page is on screen. The primary
|
||||
// trigger is inotify (browserWatcher, see dirwatcher.go), which re-reads within
|
||||
// ~tens of ms of a real change; this rescan only covers the rare event the FUSE
|
||||
// inotify layer drops. One directory read per interval is a single ReadDir plus
|
||||
// a per-entry stat; the manager's in-flight marker keeps it to one read at a
|
||||
// time, and its change-detection emits no frame when nothing changed.
|
||||
const browserBackstopInterval = 30 * time.Second
|
||||
|
||||
// refreshBrowserDir re-reads the current browser directory (bounded to one in
|
||||
// flight by the manager). Triggered by either an inotify event
|
||||
// (browserEventChan) or the slow backstop tick (browserRefreshChan). No-op
|
||||
// while the editor is on screen — there is no list to keep fresh there.
|
||||
func (l *Logic) refreshBrowserDir() {
|
||||
if l.state.page != BrowserPage {
|
||||
return
|
||||
}
|
||||
l.browserManager.Refresh(l.state.Browser.CurrentPath)
|
||||
}
|
||||
|
||||
// armBrowserRefresh starts (or leaves running) the slow backstop rescan timer.
|
||||
// Idempotent: at most one timer at a time. The timer goroutine only sends a
|
||||
// token on browserRefreshChan; the owner does the re-read. The send is
|
||||
// non-blocking so the timer goroutine can never block, even after the logic
|
||||
// loop has exited (the token is then simply dropped). Owner-goroutine-only.
|
||||
func (l *Logic) armBrowserRefresh() {
|
||||
if l.browserRefreshTimer != nil {
|
||||
return
|
||||
}
|
||||
l.browserRefreshTimer = time.AfterFunc(browserBackstopInterval, func() {
|
||||
select {
|
||||
case l.browserRefreshChan <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// handleWorkerResult processes results from the worker pool.
|
||||
func (l *Logic) handleWorkerResult(res pool.Result) {
|
||||
// A browser result re-emits only when it actually changed the view; a
|
||||
// periodic refresh of an unchanged directory is dropped here, keeping
|
||||
// emission event-driven while the browser idles. Other results always
|
||||
// re-emit.
|
||||
emit := true
|
||||
if res.IsBrowserResult() {
|
||||
l.browserManager.HandleResult(res)
|
||||
emit = l.browserManager.HandleResult(res)
|
||||
} else if res.TaskType == pool.TypeReadFile {
|
||||
if res.Success {
|
||||
if content, ok := res.Data.([]byte); ok {
|
||||
@@ -713,11 +825,20 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
|
||||
|
||||
if res.Success {
|
||||
if chunk, ok := res.Data.([]byte); ok {
|
||||
// A full-file load (SetContent) may have finished while this
|
||||
// lazy chunk read was in flight; its resident chunks are the
|
||||
// authoritative content and must not be clobbered by a stale
|
||||
// lazy result (which can also be a short read). Applying it
|
||||
// would truncate/shift the chunk and move every byte offset
|
||||
// after it — taps and IME commits landing at the wrong
|
||||
// position (text corruption).
|
||||
if !cb.fullyLoaded {
|
||||
for len(cb.chunks) <= res.ChunkIdx {
|
||||
cb.chunks = append(cb.chunks, nil)
|
||||
}
|
||||
cb.chunks[res.ChunkIdx] = chunk
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.Printf("Logic: ReadChunkTask failed for %s chunk %d: %v", res.FilePath, res.ChunkIdx, res.Error)
|
||||
}
|
||||
@@ -824,8 +945,10 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
|
||||
l.state.Editor.applySearchResult(res)
|
||||
}
|
||||
}
|
||||
if emit {
|
||||
l.emitFrame()
|
||||
}
|
||||
}
|
||||
|
||||
// State returns the current state.
|
||||
func (l *Logic) State() *State {
|
||||
|
||||
@@ -72,7 +72,7 @@ func TestSelectionMenu_FollowsTextAcrossScroll(t *testing.T) {
|
||||
// The menu sits ABOVE the anchor's line: lineTop(line 5) = reg.Y + 5*lh
|
||||
// (reg.Y = 32: the top bar is margin-free, the anchor's visual line
|
||||
// index is 5).
|
||||
wantY0 := ui.Dp(32) + ui.Dp(5*lh) - menuH - 8
|
||||
wantY0 := TopBarHeight + ui.Dp(5*lh) - menuH - 8
|
||||
if !dpeq(y0, wantY0) {
|
||||
t.Fatalf("initial menu Y = %v, want %v (above the anchor line)", y0, wantY0)
|
||||
}
|
||||
@@ -109,19 +109,20 @@ func TestSelectionMenu_ClampsWhenTextLeavesView(t *testing.T) {
|
||||
}
|
||||
yTop := e.MenuRect.Y // above line 5
|
||||
|
||||
// Scroll 10 lines: line 5 is 5 lines ABOVE the viewport top. Both ends
|
||||
// Scroll 11 lines: line 5 is 6 lines ABOVE the viewport top. Both ends
|
||||
// of the selection stay inside the shaped window (small file = whole
|
||||
// buffer) so the menu tracks: the preferred above-placement overflows
|
||||
// (the line is off-screen top) and the menu flips below the line, which
|
||||
// lands just under the window top (lineTop + lh + handleDropDp + 8).
|
||||
TheState.ScrollOffset = ui.Dp(10 * lh)
|
||||
// overflows the window top too (lineTop + lh + handleDropDp + 8 = 0 < 8)
|
||||
// and clamps to it.
|
||||
TheState.ScrollOffset = ui.Dp(11 * lh)
|
||||
EditorLayout(ui.Dp(1000), ui.Dp(2000), false)
|
||||
|
||||
if !e.MenuVisible {
|
||||
t.Fatal("menu hidden, but the selection is still in the shaped window")
|
||||
}
|
||||
// Below-placement: lineTop(32) + 5*lh - 10*lh + lh + handleDropDp + 8
|
||||
// = 6.8 < 8, so the menu clamps to the window top.
|
||||
// Below-placement: lineTop(TopBarHeight) + 5*lh - 11*lh + lh + handleDropDp + 8
|
||||
// = 0 < 8, so the menu clamps to the window top.
|
||||
if got := e.MenuRect.Y; !dpeq(got, 8) {
|
||||
t.Fatalf("menu Y = %v, want 8 (below-placement clamped to the window top)", got)
|
||||
}
|
||||
@@ -171,9 +172,10 @@ func TestSelectionMenu_FlipsBelowOnFirstLine(t *testing.T) {
|
||||
if !e.MenuVisible {
|
||||
t.Fatal("menu not shown")
|
||||
}
|
||||
// Line 0 top = reg.Y = 32; above would be 32-52-8 = -28 < 8, so the menu
|
||||
// flips below the selection HANDLES: line bottom + handleDropDp + 8.
|
||||
wantY := ui.Dp(32) + EffectiveLineHeight() + ui.Dp(handleDropDp) + 8
|
||||
// Line 0 top = reg.Y = TopBarHeight; above would be TopBarHeight-52-8 =
|
||||
// -18 < 8, so the menu flips below the selection HANDLES: line bottom +
|
||||
// handleDropDp + 8.
|
||||
wantY := TopBarHeight + EffectiveLineHeight() + ui.Dp(handleDropDp) + 8
|
||||
if !dpeq(e.MenuRect.Y, wantY) {
|
||||
t.Fatalf("menu Y = %v, want %v (flipped below the first line, clear of the handles)", e.MenuRect.Y, wantY)
|
||||
}
|
||||
@@ -220,7 +222,7 @@ func TestSelectionMenu_AnchorsToStableEnd(t *testing.T) {
|
||||
t.Fatal("menu not shown")
|
||||
}
|
||||
// Above line 3 (the stable start), NOT above line 5 (the moving end).
|
||||
wantY := ui.Dp(32) + ui.Dp(3*lh) - menuH - 8
|
||||
wantY := TopBarHeight + ui.Dp(3*lh) - menuH - 8
|
||||
if !dpeq(e.MenuRect.Y, wantY) {
|
||||
t.Fatalf("menu Y = %v, want %v (above the selection's TOP line)", e.MenuRect.Y, wantY)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// State restoration on relaunch (spec §7).
|
||||
//
|
||||
// The restorable state is a small snapshot (SessionState) the logic
|
||||
// goroutine takes on demand: the last opened file, the cursor byte offset,
|
||||
// goroutine takes on demand: which page the app was on, and, on the editor
|
||||
// page, the last opened file, the cursor byte offset,
|
||||
// the editor scroll offset, the live selection, and the find bar (query,
|
||||
// open/closed, current match). The search RESULTS themselves are not part
|
||||
// of the snapshot: on relaunch they are regenerated by re-scanning the
|
||||
@@ -65,6 +66,14 @@ type SessionState struct {
|
||||
FindCurByte int // start byte of the current find match (-1 = none)
|
||||
// AppFontScale is the app-local pinch font scale (0 = default 1.0).
|
||||
AppFontScale float64
|
||||
// InBrowser records that the app was sitting on the BROWSER page when
|
||||
// the snapshot was taken: the relaunch must land back in the browser at
|
||||
// BrowserPath instead of re-opening the last file in the editor. The
|
||||
// flag (not "File == "") disambiguates from pre-flag session files, whose
|
||||
// absence of the key unmarshals to false and restores the editor as
|
||||
// before. When true, File is "" and the editor-side fields are stale.
|
||||
InBrowser bool
|
||||
BrowserPath string
|
||||
}
|
||||
|
||||
// SetSessionSaver registers the callback that persists snapshots (the cmd
|
||||
@@ -115,8 +124,20 @@ func (l *Logic) SnapshotSession() SessionState {
|
||||
// Dp discriminator used on restore).
|
||||
scrollSub = r0 / float64(lh)
|
||||
}
|
||||
inBrowser := l.state.page == BrowserPage
|
||||
file := e.Filename
|
||||
if inBrowser {
|
||||
// Nothing to restore in the editor: leaving the last file in File
|
||||
// would let a reader that ignores InBrowser re-open it, and the
|
||||
// editor->browser transition is then also an urgent save (File
|
||||
// change), so the "back in the browser" state hits disk immediately
|
||||
// instead of waiting out the rate limit.
|
||||
file = ""
|
||||
}
|
||||
return SessionState{
|
||||
File: e.Filename,
|
||||
File: file,
|
||||
InBrowser: inBrowser,
|
||||
BrowserPath: l.state.Browser.CurrentPath,
|
||||
Cursor: cur,
|
||||
Scroll: float64(s.ScrollOffset),
|
||||
ScrollLine: scrollLine,
|
||||
@@ -237,6 +258,9 @@ func (l *Logic) BeginRestore(s SessionState) {
|
||||
// struct).
|
||||
l.restoreScroll = ui.Dp(s.Scroll)
|
||||
l.restoreScrollArmed = s.Scroll > 0
|
||||
if l.restoreScrollArmed {
|
||||
l.restoreArmedAt = time.Now()
|
||||
}
|
||||
// The app-local font scale lands immediately, BEFORE any layout: the
|
||||
// restore's line-based offset math reads it through EffectiveLineHeight.
|
||||
if as := s.AppFontScale; as > 0 {
|
||||
@@ -254,6 +278,18 @@ func (l *Logic) BeginRestore(s SessionState) {
|
||||
l.emitFrame() // show the editor page now; the content loads async
|
||||
}
|
||||
|
||||
// BeginBrowserRestore makes a relaunch land in the browser at dirPath
|
||||
// instead of the startup directory (see SessionState.InBrowser). It is
|
||||
// synchronous: the directory is dispatched for its index by Run, which reads
|
||||
// CurrentPath, so it must be called after NewLogic and before Run (the cmd
|
||||
// layer does both before starting the logic goroutine). An empty dirPath
|
||||
// keeps the startup directory.
|
||||
func (l *Logic) BeginBrowserRestore(dirPath string) {
|
||||
if dirPath != "" {
|
||||
l.state.Browser.CurrentPath = dirPath
|
||||
}
|
||||
}
|
||||
|
||||
// abortRestore ends a restore without landing it (the user opened another
|
||||
// file, the read failed, or the file is too large): clears the pending
|
||||
// snapshot so session saving resumes (see saveSessionIfChanged). The editor
|
||||
@@ -293,6 +329,19 @@ func (l *Logic) maybeApplyRestoreScroll() bool {
|
||||
if l.state.Page() != EditorPage || !l.restoreContentLanded {
|
||||
return false
|
||||
}
|
||||
// The clamp below needs a trustworthy MaxScroll. For a chunked buffer it
|
||||
// is measured from the line index (or the large pre-index estimate) and
|
||||
// is valid as soon as the content has landed. For a string buffer it
|
||||
// derives from the shaper's last baseline, which is still 0 until the
|
||||
// first non-empty frame has shaped — applying now would clamp the
|
||||
// offset to 0 and the scroll position would be silently lost. Wait for
|
||||
// that frame (its feedback triggers the emitFrame that re-runs this);
|
||||
// a deadline covers content that never produces a baseline (empty or
|
||||
// newlines-only), which lands best-effort.
|
||||
if l.state.Editor.ChunkedBuffer == nil && l.state.LastLineY <= 0 &&
|
||||
time.Since(l.restoreArmedAt) < restoreScrollArmTimeout {
|
||||
return false
|
||||
}
|
||||
// Re-derive the offset from the persisted logical line (see the
|
||||
// SessionState doc): the snapshot's pixel offset mapped to its position
|
||||
// only while the saving session's WrapIndex was valid. On relaunch the
|
||||
@@ -338,6 +387,7 @@ func (l *Logic) maybeApplyRestoreScroll() bool {
|
||||
}
|
||||
l.state.ScrollOffset = l.restoreScroll
|
||||
l.restoreScrollArmed = false
|
||||
log.Printf("RESTORE scroll off=%.1f line=%d maxScroll=%.1f", l.restoreScroll, s.ScrollLine, l.state.MaxScroll)
|
||||
// The snapshot has fully landed (cursor/selection/find with the
|
||||
// content, scroll now): lift the save suppression.
|
||||
l.session = SessionState{}
|
||||
@@ -348,6 +398,13 @@ func (l *Logic) maybeApplyRestoreScroll() bool {
|
||||
// the restored window has either settled or the user has moved on.
|
||||
const restorePinTimeout = 2 * time.Second
|
||||
|
||||
// restoreScrollArmTimeout bounds how long maybeApplyRestoreScroll may wait
|
||||
// for a trustworthy MaxScroll before landing the offset best-effort (see
|
||||
// the guard there). Shaping a real file completes in well under this; it
|
||||
// exists so degenerate content (empty, newlines-only) cannot leave the
|
||||
// restore armed forever.
|
||||
const restoreScrollArmTimeout = 2 * time.Second
|
||||
|
||||
// releaseRestorePin clears the restore line-pin (user or search took over
|
||||
// the viewport). Must be called on the logic goroutine.
|
||||
func (l *Logic) releaseRestorePin() {
|
||||
|
||||
+514
-81
@@ -83,12 +83,75 @@ type EditorState struct {
|
||||
// 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
|
||||
// viewport start. The IME snippet is the window, so an EditEvent.Range is
|
||||
// relative to the window and must be offset by this to address the buffer.
|
||||
// viewport start. HandleReplaceRange uses it to convert IME offsets to
|
||||
// absolute file offsets.
|
||||
IMEWindowStartByte int
|
||||
// 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.
|
||||
// It is set during layout.
|
||||
IMEWindowText string
|
||||
// IMEContext is up to 10 runes immediately before IMEWindowStartByte. It
|
||||
// is prepended to the window when the snippet is pushed to the IME, so the
|
||||
// IME always sees real text preceding the caret — auto-cap must never
|
||||
// treat the top of the visible window as the start of a sentence.
|
||||
IMEContext string
|
||||
// IMEContextStartByte is the absolute byte offset where IMEContext begins
|
||||
// (IMEWindowStartByte - len(IMEContext)).
|
||||
IMEContextStartByte int
|
||||
// IMEOffsetRune is the rune count of file[0:IMEContextStartByte): the
|
||||
// absolute file rune offset where the pushed snippet starts (its
|
||||
// Range.Start). A non-zero value tells the IME the window sits
|
||||
// mid-document, keeping its sentence/word-boundary logic honest. IME edit
|
||||
// ranges are addressed from this offset (see imeRuneToByte).
|
||||
IMEOffsetRune int
|
||||
// imeRuneCache{Byte,Count} memoizes "rune count of [0, Byte)" so
|
||||
// IMEOffsetRune stays O(delta) while the window scrolls; edits adjust it
|
||||
// (imeAnchorEdit) and a file switch resets it to (0,0).
|
||||
imeRuneCacheByte int
|
||||
imeRuneCacheCount int
|
||||
|
||||
// IME snippet window (byte offsets, hysteresis-gated — see
|
||||
// computeIMESnippetWindow). Decoupled from the render window: the render
|
||||
// window follows the viewport (keyboard show/hide resizes it), while the
|
||||
// IME snippet must be STABLE so a tap that re-centers the render window
|
||||
// does not re-push the snippet. A snippet re-push reaches Gboard as
|
||||
// imm.restartInput, which starts a fresh input session and capitalizes
|
||||
// the first committed character even mid-word. The snippet re-anchors
|
||||
// only when the caret leaves the window margins.
|
||||
imeSnipWS int
|
||||
imeSnipWE int
|
||||
imeSnipArmed bool
|
||||
IMESnippetText string
|
||||
IMESnippetStartRune int
|
||||
IMESnippetEndRune int
|
||||
IMECaretRune int
|
||||
IMESelStartRune int
|
||||
IMESelEndRune int
|
||||
// IMEForceResync asks the next frame to re-push the snippet trimmed by
|
||||
// one rune (a forced restartInput): an anomalous commit (drift-snapped
|
||||
// or distant — see HandleIMECommit) means the IME's local text is
|
||||
// desynchronized from ours, and it may keep re-sending the same fix in
|
||||
// a loop (observed on the phone: an endless stream of empty commits).
|
||||
// A selection push cannot heal this (it is deduplicated away after
|
||||
// commits); only a restart makes the IME re-fetch the real text and
|
||||
// selection around the caret. Set by HandleIMECommit on the first
|
||||
// anomaly and by noteNonIMEEdit (a key-event edit desyncs the IME just
|
||||
// as surely as a dropped commit does), consumed by the next frame
|
||||
// (EditorLayout).
|
||||
IMEForceResync bool
|
||||
// imeStaleEditByte is the byte position of one content edit the IME did
|
||||
// NOT make (a key-event edit: Enter, hardware backspace/delete, cut,
|
||||
// paste) that its local model is missing: the IME still addresses the
|
||||
// caret as it was before that edit, and its next commit is anchored
|
||||
// there (observed on device: Gboard sent Enter as a key event, the
|
||||
// logic inserted the \n, and the very next keystroke committed against
|
||||
// the pre-Enter caret, which the drift guard misread as a desync and
|
||||
// snap-duplicated). -1 = no pending edit (the models agree). While set,
|
||||
// the drift guard accepts one small TEXT commit that ends at or before
|
||||
// the edit position — everything before it is byte-identical in both
|
||||
// models, so applying it verbatim is exact (see HandleIMECommit). Any
|
||||
// later IME commit or non-IME edit consumes it; a tap clears it (the
|
||||
// tap's selection push / re-anchor re-reads the truth).
|
||||
imeStaleEditByte int
|
||||
// EditSeq counts content edits (incremented by markDirty). The shaped
|
||||
// glyph layout arriving via layoutChan is only applied to the WrapIndex
|
||||
// when its EditSeq matches, so a layout shaped before an edit can never
|
||||
@@ -686,6 +749,12 @@ func HandleBrowserScroll(data any) {
|
||||
func GoToBrowser(data any) {
|
||||
if TheLogic != nil {
|
||||
TheLogic.FlushAll()
|
||||
// Re-read the current directory now (don't wait for the first periodic
|
||||
// tick) so the list is current the moment we land back: files may have
|
||||
// been added/removed/renamed, or an inbound sync may have changed them,
|
||||
// while we were in the editor. The periodic refresh keeps it fresh
|
||||
// afterwards (see Logic.armBrowserRefresh).
|
||||
TheLogic.browserManager.Refresh(TheLogic.state.Browser.CurrentPath)
|
||||
}
|
||||
TheState.Editor.findClose()
|
||||
TheState.page = BrowserPage
|
||||
@@ -943,6 +1012,7 @@ func deleteRange(start, end int) {
|
||||
if end <= start {
|
||||
return
|
||||
}
|
||||
del := TheState.fileContent(start, end)
|
||||
if buf := TheState.Editor.ChunkedBuffer; buf != nil {
|
||||
buf.Delete(start, end-start)
|
||||
buf.UpdateLineIndexAfterDelete(start, end)
|
||||
@@ -950,6 +1020,7 @@ func deleteRange(start, end int) {
|
||||
str := TheState.Editor.Buffer
|
||||
TheState.Editor.Buffer = str[:start] + str[end:]
|
||||
}
|
||||
imeAnchorEdit(start, del, "")
|
||||
TheState.Editor.findEdit(start, end, 0)
|
||||
}
|
||||
|
||||
@@ -1677,6 +1748,7 @@ func handleMenuCut() {
|
||||
return
|
||||
}
|
||||
TheState.clipboardSetChan <- text
|
||||
noteNonIMEEdit(e.SelectionStart)
|
||||
deleteRange(e.SelectionStart, e.SelectionEnd)
|
||||
markDirty()
|
||||
e.CursorPosition = e.SelectionStart
|
||||
@@ -1930,6 +2002,7 @@ func utf8AdvanceWidth(seg string) int {
|
||||
func HandleDelete() {
|
||||
e := &TheState.Editor
|
||||
if selActive() {
|
||||
noteNonIMEEdit(e.SelectionStart)
|
||||
deleteRange(e.SelectionStart, e.SelectionEnd)
|
||||
e.CursorPosition = e.SelectionStart
|
||||
ClearSelection()
|
||||
@@ -1941,8 +2014,10 @@ func HandleDelete() {
|
||||
if buf != nil {
|
||||
seg := buf.Content(pos, pos+4)
|
||||
if w := utf8AdvanceWidth(seg); w > 0 {
|
||||
noteNonIMEEdit(pos)
|
||||
buf.Delete(pos, w)
|
||||
buf.UpdateLineIndexAfterDelete(pos, pos+w)
|
||||
imeAnchorEdit(pos, seg[:w], "")
|
||||
e.findEdit(pos, pos+w, 0)
|
||||
markDirty()
|
||||
}
|
||||
@@ -1958,7 +2033,11 @@ func HandleDelete() {
|
||||
end = pos + 4
|
||||
}
|
||||
w := utf8AdvanceWidth(str[pos:end])
|
||||
if w > 0 {
|
||||
noteNonIMEEdit(pos)
|
||||
}
|
||||
TheState.Editor.Buffer = str[:pos] + str[pos+w:]
|
||||
imeAnchorEdit(pos, str[pos:pos+w], "")
|
||||
e.findEdit(pos, pos+w, 0)
|
||||
markDirty()
|
||||
}
|
||||
@@ -1970,11 +2049,17 @@ func HandleInsert(s string) {
|
||||
// copy, or the writes below are lost.
|
||||
e := &TheState.Editor
|
||||
pos := e.CursorPosition
|
||||
if selActive() {
|
||||
replacing := selActive()
|
||||
if replacing {
|
||||
pos = e.SelectionStart
|
||||
deleteRange(e.SelectionStart, e.SelectionEnd)
|
||||
ClearSelection()
|
||||
}
|
||||
if s != "" || replacing {
|
||||
// A key-event/paste edit the IME did not make: desync bookkeeping
|
||||
// (see noteNonIMEEdit).
|
||||
noteNonIMEEdit(pos)
|
||||
}
|
||||
buf := e.ChunkedBuffer
|
||||
if buf != nil {
|
||||
buf.Insert(pos, s)
|
||||
@@ -1984,6 +2069,7 @@ func HandleInsert(s string) {
|
||||
str := e.Buffer
|
||||
e.Buffer = str[:pos] + s + str[pos:]
|
||||
}
|
||||
imeAnchorEdit(pos, "", s)
|
||||
e.findEdit(pos, pos, len(s))
|
||||
e.CursorPosition = pos + len(s)
|
||||
markDirty()
|
||||
@@ -1994,6 +2080,7 @@ func HandleInsert(s string) {
|
||||
func HandleBackspace() {
|
||||
e := &TheState.Editor
|
||||
if selActive() {
|
||||
noteNonIMEEdit(e.SelectionStart)
|
||||
deleteRange(e.SelectionStart, e.SelectionEnd)
|
||||
e.CursorPosition = e.SelectionStart
|
||||
ClearSelection()
|
||||
@@ -2011,8 +2098,12 @@ func HandleBackspace() {
|
||||
segStart = 0
|
||||
}
|
||||
w := utf8BackspaceWidth(buf.Content(segStart, pos))
|
||||
if w > 0 {
|
||||
noteNonIMEEdit(pos - w)
|
||||
}
|
||||
buf.Delete(pos-w, w)
|
||||
buf.UpdateLineIndexAfterDelete(pos-w, pos)
|
||||
imeAnchorEdit(pos-w, buf.Content(pos-w, pos), "")
|
||||
TheState.Editor.CursorPosition = pos - w
|
||||
e.findEdit(pos-w, pos, 0)
|
||||
markDirty()
|
||||
@@ -2025,7 +2116,11 @@ func HandleBackspace() {
|
||||
segStart = 0
|
||||
}
|
||||
w := utf8BackspaceWidth(str[segStart:pos])
|
||||
if w > 0 {
|
||||
noteNonIMEEdit(pos - w)
|
||||
}
|
||||
TheState.Editor.Buffer = str[:pos-w] + str[pos:]
|
||||
imeAnchorEdit(pos-w, str[pos-w:pos], "")
|
||||
TheState.Editor.CursorPosition = pos - w
|
||||
e.findEdit(pos-w, pos, 0)
|
||||
markDirty()
|
||||
@@ -2052,17 +2147,222 @@ func runeIndexToByteStr(s string, n int) int {
|
||||
return len(s)
|
||||
}
|
||||
|
||||
// HandleReplaceRange replaces the text in the rune range [startRune, endRune)
|
||||
// with text and places the cursor at the end of the inserted text.
|
||||
// countRunes counts the runes in s.
|
||||
func countRunes(s string) int {
|
||||
n := 0
|
||||
for i := 0; i < len(s); {
|
||||
_, w := utf8.DecodeRuneInString(s[i:])
|
||||
i += w
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// fileContent returns file[lo:hi) from the active buffer (chunked or small).
|
||||
func (s *State) fileContent(lo, hi int) string {
|
||||
e := &s.Editor
|
||||
if e.ChunkedBuffer != nil {
|
||||
return e.ChunkedBuffer.Content(lo, hi)
|
||||
}
|
||||
if lo < 0 {
|
||||
lo = 0
|
||||
}
|
||||
if hi > len(e.Buffer) {
|
||||
hi = len(e.Buffer)
|
||||
}
|
||||
if lo > hi {
|
||||
lo = hi
|
||||
}
|
||||
return e.Buffer[lo:hi]
|
||||
}
|
||||
|
||||
// bufferLen is the active buffer length in bytes.
|
||||
func (s *State) bufferLen() int {
|
||||
if e := &s.Editor; e.ChunkedBuffer != nil {
|
||||
return int(e.ChunkedBuffer.FileLen())
|
||||
}
|
||||
return len(s.Editor.Buffer)
|
||||
}
|
||||
|
||||
// imeRuneOffsetAt returns the rune count of the file prefix [0, bytePos).
|
||||
// It scans only the delta from the cached anchor (imeRuneCacheByte/Count), so
|
||||
// repeated calls with a slowly moving byte position (scrolling while typing)
|
||||
// are O(delta); a large jump (file switch, long scroll) does one full scan
|
||||
// and then anchors again. Must be called on the logic goroutine (owner).
|
||||
// computeIMESnippetWindow maintains the hysteresis-gated IME snippet window
|
||||
// (see the imeSnip* fields) and fills IMESnippetText / IMESnippet*Rune /
|
||||
// IMECaretRune / IMESel* for the renderer to push. Must run on the logic
|
||||
// goroutine during layout.
|
||||
//
|
||||
// The window is [32 KB] around the caret and re-anchors only when the caret
|
||||
// is within [4 KB] of an edge (a screenful of flings stays inside, so
|
||||
// fling-tap-type does not restart the IME session; only a genuinely distant
|
||||
// tap or file switch re-anchors). Consequences:
|
||||
// - typing inside the window never re-anchors (the frame's snippet text
|
||||
// changes by the commit, which ApplyIMECommitToModel has already pushed
|
||||
// - FlushIME dedupes and no restartInput is sent per keystroke);
|
||||
// - a tap/caret move within the margins does not re-anchor: Gboard keeps
|
||||
// its input session, so the first character after a tap is lowercase
|
||||
// even mid-word (a render-window snippet re-anchored on every viewport
|
||||
// change, resetting Gboard to a fresh session that caps the first
|
||||
// character);
|
||||
// - scrolls (flings) do not move the caret, so they never re-anchor: the
|
||||
// IME stays anchored to the caret even while it is off-screen, which is
|
||||
// what commit targeting needs.
|
||||
//
|
||||
// Edits shift the byte window silently (the text is re-read fresh every
|
||||
// frame); the drift self-corrects at the next re-anchor.
|
||||
func (s *State) computeIMESnippetWindow() {
|
||||
const snipSize, snipMargin = 32768, 4096
|
||||
caret := s.Editor.CursorPosition
|
||||
if s.Editor.imeSnipArmed {
|
||||
if caret < s.Editor.imeSnipWS+snipMargin || caret > s.Editor.imeSnipWE-snipMargin {
|
||||
s.Editor.imeSnipArmed = false
|
||||
}
|
||||
}
|
||||
if !s.Editor.imeSnipArmed {
|
||||
ws := caret - snipSize/2
|
||||
if ws < 0 {
|
||||
ws = 0
|
||||
}
|
||||
s.Editor.imeSnipWS = ws
|
||||
s.Editor.imeSnipWE = ws + snipSize
|
||||
s.Editor.imeSnipArmed = true
|
||||
}
|
||||
if end := int(s.fileLenNow()); end > 0 && s.Editor.imeSnipWE > end {
|
||||
s.Editor.imeSnipWE = end
|
||||
}
|
||||
text := s.fileContent(s.Editor.imeSnipWS, s.Editor.imeSnipWE)
|
||||
startRune := s.imeRuneOffsetAt(s.Editor.imeSnipWS)
|
||||
s.Editor.IMESnippetText = text
|
||||
s.Editor.IMESnippetStartRune = startRune
|
||||
s.Editor.IMESnippetEndRune = startRune + utf8.RuneCountInString(text)
|
||||
s.Editor.IMECaretRune = s.imeRuneOffsetAt(caret)
|
||||
if selActive() {
|
||||
ss, se := s.Editor.SelectionStart, s.Editor.SelectionEnd
|
||||
if ss < s.Editor.imeSnipWS {
|
||||
ss = s.Editor.imeSnipWS
|
||||
}
|
||||
if se > s.Editor.imeSnipWE {
|
||||
se = s.Editor.imeSnipWE
|
||||
}
|
||||
r0 := s.imeRuneOffsetAt(ss)
|
||||
s.Editor.IMESelStartRune = r0
|
||||
s.Editor.IMESelEndRune = r0 + utf8.RuneCountInString(s.fileContent(ss, se))
|
||||
} else {
|
||||
s.Editor.IMESelStartRune = -1
|
||||
s.Editor.IMESelEndRune = -1
|
||||
}
|
||||
}
|
||||
|
||||
// imeSelectionRuneRange returns the live selection in absolute file runes,
|
||||
// or (-1, -1) when there is none. Used by the anomalous-commit guard to
|
||||
// allow commits inside a user selection anywhere.
|
||||
func imeSelectionRuneRange() (int, int) {
|
||||
if !selActive() {
|
||||
return -1, -1
|
||||
}
|
||||
e := &TheState.Editor
|
||||
r0 := TheState.imeRuneOffsetAt(e.SelectionStart)
|
||||
r1 := r0 + utf8.RuneCountInString(TheState.fileContent(e.SelectionStart, e.SelectionEnd))
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// fileLenNow returns the current content length (chunked or string buffer).
|
||||
func (s *State) fileLenNow() int64 {
|
||||
if cb := s.Editor.ChunkedBuffer; cb != nil {
|
||||
return cb.fileLen
|
||||
}
|
||||
return int64(len(s.Editor.Buffer))
|
||||
}
|
||||
|
||||
func (s *State) imeRuneOffsetAt(bytePos int) int {
|
||||
e := &s.Editor
|
||||
fileLen := s.bufferLen()
|
||||
if bytePos > fileLen {
|
||||
bytePos = fileLen
|
||||
}
|
||||
if e.imeRuneCacheByte > fileLen {
|
||||
e.imeRuneCacheByte, e.imeRuneCacheCount = 0, 0
|
||||
}
|
||||
if bytePos == e.imeRuneCacheByte {
|
||||
return e.imeRuneCacheCount
|
||||
}
|
||||
delta := bytePos - e.imeRuneCacheByte
|
||||
const maxDelta = 256 * 1024
|
||||
if delta > maxDelta || delta < -maxDelta {
|
||||
n := countRunes(s.fileContent(0, bytePos))
|
||||
e.imeRuneCacheByte, e.imeRuneCacheCount = bytePos, n
|
||||
return n
|
||||
}
|
||||
lo, hi := e.imeRuneCacheByte, bytePos
|
||||
if hi < lo {
|
||||
lo, hi = hi, lo
|
||||
}
|
||||
n := e.imeRuneCacheCount
|
||||
if delta > 0 {
|
||||
n += countRunes(s.fileContent(lo, hi))
|
||||
} else {
|
||||
n -= countRunes(s.fileContent(lo, hi))
|
||||
}
|
||||
e.imeRuneCacheByte, e.imeRuneCacheCount = bytePos, n
|
||||
return n
|
||||
}
|
||||
|
||||
// imeAnchorEdit adjusts the IME rune-count cache after a buffer mutation at
|
||||
// absolute byte position editByte that removed delText and inserted insText.
|
||||
// An edit at or after the cached position does not change the rune count of
|
||||
// [0, cacheByte), so only edits strictly before it move the anchor.
|
||||
func imeAnchorEdit(editByte int, delText, insText string) {
|
||||
e := &TheState.Editor
|
||||
if editByte < e.imeRuneCacheByte {
|
||||
e.imeRuneCacheByte += len(insText) - len(delText)
|
||||
e.imeRuneCacheCount += countRunes(insText) - countRunes(delText)
|
||||
}
|
||||
}
|
||||
|
||||
// runeToByteWhole maps an absolute file rune offset (the IME's coordinate
|
||||
// space, in which the pushed snippet starts at IMEOffsetRune) to an absolute
|
||||
// buffer byte offset by scanning the WHOLE active buffer, in 8 KiB steps.
|
||||
// Unlike a window-relative mapping it does not depend on the visible window,
|
||||
// so it stays exact while the window moves (a fling in flight): scrolling
|
||||
// moves the window, not the buffer. One pass over the file is ~1-2 ms for a
|
||||
// 1 MB file — negligible next to the disk save a commit triggers.
|
||||
func runeToByteWhole(runePos int) int {
|
||||
if runePos <= 0 {
|
||||
return 0
|
||||
}
|
||||
total, off, fileLen := 0, 0, TheState.bufferLen()
|
||||
const step = 8 * 1024
|
||||
for off < fileLen {
|
||||
hi := off + step
|
||||
if hi > fileLen {
|
||||
hi = fileLen
|
||||
}
|
||||
n := countRunes(TheState.fileContent(off, hi))
|
||||
if total+n >= runePos {
|
||||
return off + runeIndexToByteStr(TheState.fileContent(off, hi), runePos-total)
|
||||
}
|
||||
total += n
|
||||
off = hi
|
||||
}
|
||||
return fileLen
|
||||
}
|
||||
|
||||
// HandleReplaceRange replaces the text in the rune range [startRune,
|
||||
// endRune) with text and places the cursor at the end of the inserted text.
|
||||
//
|
||||
// This implements the IME replacement contract (key.EditEvent.Range): a swipe
|
||||
// or autocorrect commit replaces the selected region instead of blindly
|
||||
// inserting at the cursor, so the old text is removed (no duplication). It
|
||||
// also covers plain inserts (start==end) and range deletes (text == "").
|
||||
//
|
||||
// startRune/endRune are RUNE indices (the IME's text model), while the buffer
|
||||
// is byte-based, so they are converted to byte offsets first. Must be called
|
||||
// on the logic goroutine (owner).
|
||||
// startRune/endRune are ABSOLUTE file rune offsets (the IME's coordinate
|
||||
// space, in which the pushed snippet starts at IMEOffsetRune), while the
|
||||
// buffer is byte-based, so they are converted to absolute byte offsets first
|
||||
// (runeToByteWhole, against the whole buffer). Used by the test harness
|
||||
// (editor.HandleKeyDown with a key.EditEvent); the real app routes commits
|
||||
// through HandleIMECommit. Must be called on the logic goroutine (owner).
|
||||
func HandleReplaceRange(startRune, endRune int, text string) {
|
||||
// A too-large file is not editable: ignore IME commits.
|
||||
if TheState.Editor.TooLarge {
|
||||
@@ -2071,89 +2371,178 @@ func HandleReplaceRange(startRune, endRune int, text string) {
|
||||
if startRune > endRune {
|
||||
startRune, endRune = endRune, startRune
|
||||
}
|
||||
// The IME snippet is the visible window (IMEWindowText), so startRune/
|
||||
// endRune are relative to that window. Resolve them to window-byte
|
||||
// offsets, then add the window's absolute start to address the buffer.
|
||||
// For small (string) files the window is the whole buffer (start 0), so
|
||||
// this reduces to absolute addressing. If IMEWindowText is empty (tests
|
||||
// that never run layout), fall back to the whole buffer as the window.
|
||||
windowStart := TheState.Editor.IMEWindowStartByte
|
||||
windowText := TheState.Editor.IMEWindowText
|
||||
if windowText == "" {
|
||||
windowStart = 0
|
||||
if cb := TheState.Editor.ChunkedBuffer; cb != nil {
|
||||
windowText, _ = cb.FullContent()
|
||||
} else {
|
||||
windowText = TheState.Editor.Buffer
|
||||
applyIMECommitBytes(runeToByteWhole(startRune), runeToByteWhole(endRune), text)
|
||||
}
|
||||
|
||||
// IMECommit is an IME commit whose range is in ABSOLUTE FILE RUNES — the
|
||||
// coordinate space of the pushed snippet, whose Range.Start is IMEOffsetRune
|
||||
// (see editorLayout). The logic maps it to bytes against the whole buffer
|
||||
// (runeToByteWhole), so it stays exact while the visible window moves
|
||||
// (a fling in flight): scrolling moves the window, not the buffer.
|
||||
type IMECommit struct {
|
||||
StartRune int
|
||||
EndRune int
|
||||
Text string
|
||||
}
|
||||
|
||||
// noteNonIMEEdit marks a content edit that the IME did not make: the IME's
|
||||
// local model is missing it, so until a re-syncing snippet push reaches the
|
||||
// IME (the next drawn frame, see IMEForceResync) the IME still addresses the
|
||||
// caret as it was before the edit. Arm the resync now, and remember the edit
|
||||
// position so the drift guard can accept the one commit the IME is about to
|
||||
// send against its stale caret instead of snap-duplicating it. pos is the
|
||||
// edit's byte position (before the mutation). Must be called on the logic
|
||||
// goroutine (owner), only when the edit actually changes content.
|
||||
func noteNonIMEEdit(pos int) {
|
||||
e := &TheState.Editor
|
||||
e.imeStaleEditByte = pos
|
||||
e.IMEForceResync = true
|
||||
}
|
||||
|
||||
// HandleIMECommit applies an IME commit from the real app (cmd/pad/main.go
|
||||
// routes editor_text key.EditEvents here; the test harness uses
|
||||
// HandleReplaceRange). In addition to the whole-buffer mapping it applies
|
||||
// the drift guard: Android's IME contract (InputConnection) says commit
|
||||
// positions are relative to the text the IME last received; if a
|
||||
// restartInput is dropped (observed with Gboard during flings), the IME's
|
||||
// text is stale and its reported position is in the stale text's
|
||||
// coordinates. A small commit (range ≤ 2 runes) is always anchored at the
|
||||
// caret the IME was last told about — an insertion is [c,c), a composing
|
||||
// replacement [c-1,c). If the reported range ends elsewhere, the IME's text
|
||||
// is stale: snap the commit to the cursor, the only position it cannot
|
||||
// drift from. Must be called on the logic goroutine (owner).
|
||||
func HandleIMECommit(data any) {
|
||||
c, ok := data.(IMECommit)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// A too-large file is not editable: ignore IME commits.
|
||||
if TheState.Editor.TooLarge {
|
||||
return
|
||||
}
|
||||
startRune, endRune := c.StartRune, c.EndRune
|
||||
if startRune > endRune {
|
||||
startRune, endRune = endRune, startRune
|
||||
}
|
||||
// Anomalous-commit guard. A legitimate IME commit is always local: at
|
||||
// the caret (a typed char, a composing word), inside the live
|
||||
// selection, or a correction of the word just typed (a few runes left
|
||||
// of the caret). Anything else means the IME's local text has
|
||||
// desynchronized from ours — its reported range addresses text that is
|
||||
// not where we think it is. Applying it verbatim clobbers distant text
|
||||
// (observed on the phone: a 5-rune autocorrect 19,000 runes from the
|
||||
// caret); the only safe action is to apply it at the caret and force a
|
||||
// re-syncing snippet re-push on the next frame (see IMEForceResync): a
|
||||
// desynced IME is healed only by a restart (a selection push is
|
||||
// deduplicated away after commits — see Renderer.FlushIME), so the
|
||||
// resync is armed on the FIRST anomaly, not after a streak.
|
||||
const maxCommitDistance = 1024
|
||||
caretRune := TheState.imeRuneOffsetAt(TheState.Editor.CursorPosition)
|
||||
selStartRune, selEndRune := imeSelectionRuneRange()
|
||||
anomalous := endRune-startRune <= 2 && endRune != caretRune
|
||||
if anomalous && c.Text != "" {
|
||||
// Stale-caret tolerance (see imeStaleEditByte): a key-event edit
|
||||
// (Enter, backspace, paste, cut) moved our buffer and caret without
|
||||
// going through the IME, and the updated snippet may not have reached
|
||||
// it yet — the commit can arrive in the very same input batch, so no
|
||||
// frame has drawn. The IME's model still matches ours everywhere
|
||||
// BEFORE the edit position and it still addresses the pre-edit caret,
|
||||
// so a small TEXT commit ending at or before the edit position applies
|
||||
// verbatim against identical text (the usual shape: the IME appending
|
||||
// to, or correcting, the word it last committed). A range deletion
|
||||
// (empty text) is never tolerated: deleting at a range the IME sees
|
||||
// but we no longer have there is how documents get clobbered. The
|
||||
// pending edit is consumed and a resync is armed: after the verbatim
|
||||
// apply the IME's model is still missing our key edit, and the next
|
||||
// frame's forced restart heals it.
|
||||
if e := TheState.Editor.imeStaleEditByte; e >= 0 && endRune <= TheState.imeRuneOffsetAt(e) {
|
||||
log.Printf("IME STALE-OK range=[%d,%d) text=%q caret=%d staleEdit=%d -> apply as-is + resync", startRune, endRune, c.Text, caretRune, e)
|
||||
anomalous = false
|
||||
TheState.Editor.imeStaleEditByte = -1
|
||||
TheState.Editor.IMEForceResync = true
|
||||
}
|
||||
}
|
||||
absStart := windowStart + runeIndexToByteStr(windowText, startRune)
|
||||
absEnd := windowStart + runeIndexToByteStr(windowText, endRune)
|
||||
if !anomalous && c.Text != "" {
|
||||
// The commit must be near the caret, or inside the live selection
|
||||
// (a replacement of a user selection, wherever it is).
|
||||
lo := caretRune - maxCommitDistance
|
||||
hi := caretRune + maxCommitDistance
|
||||
if selStartRune >= 0 {
|
||||
if selStartRune < lo {
|
||||
lo = selStartRune
|
||||
}
|
||||
if selEndRune > hi {
|
||||
hi = selEndRune
|
||||
}
|
||||
}
|
||||
if startRune > hi || endRune < lo {
|
||||
anomalous = true
|
||||
}
|
||||
}
|
||||
if anomalous {
|
||||
log.Printf("IME DRIFT-SNAP range=[%d,%d) text=%q caret=%d -> snap to caret + resync", startRune, endRune, c.Text, caretRune)
|
||||
startRune, endRune = caretRune, caretRune
|
||||
TheState.Editor.IMEForceResync = true
|
||||
}
|
||||
absStart, absEnd := runeToByteWhole(startRune), runeToByteWhole(endRune)
|
||||
log.Printf("IME COMMIT range=[%d,%d) text=%q -> [%d,%d)", startRune, endRune, c.Text, absStart, absEnd)
|
||||
applyIMECommitBytes(absStart, absEnd, c.Text)
|
||||
}
|
||||
|
||||
// applyIMECommitBytes replaces [startByte, endByte) with text and places the
|
||||
// cursor at the end of the inserted text. Both byte addresses are absolute
|
||||
// file offsets. Shared by HandleReplaceRange (rune-translated) and
|
||||
// HandleIMECommit (model-translated). Must run on the logic goroutine.
|
||||
func applyIMECommitBytes(startByte, endByte int, text string) {
|
||||
// The IME made (or, drift-snapped, was snapped to) this edit, so its
|
||||
// local model accounts for it: no key-edit is pending anymore.
|
||||
TheState.Editor.imeStaleEditByte = -1
|
||||
if startByte > endByte {
|
||||
startByte, endByte = endByte, startByte
|
||||
}
|
||||
// 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 startByte > TheState.Editor.SelectionStart {
|
||||
startByte = TheState.Editor.SelectionStart
|
||||
}
|
||||
if absEnd < TheState.Editor.SelectionEnd {
|
||||
absEnd = TheState.Editor.SelectionEnd
|
||||
if endByte < TheState.Editor.SelectionEnd {
|
||||
endByte = 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)
|
||||
}
|
||||
// Capture the deleted text (before the mutation) for the rune-anchor.
|
||||
delText := TheState.fileContent(startByte, endByte)
|
||||
|
||||
var newCursor int
|
||||
if buf := TheState.Editor.ChunkedBuffer; buf != nil {
|
||||
if absEnd > absStart {
|
||||
buf.Delete(absStart, absEnd-absStart)
|
||||
if endByte > startByte {
|
||||
buf.Delete(startByte, endByte-startByte)
|
||||
}
|
||||
buf.Insert(absStart, text)
|
||||
if absEnd > absStart {
|
||||
buf.UpdateLineIndexAfterDelete(absStart, absEnd)
|
||||
buf.Insert(startByte, text)
|
||||
if endByte > startByte {
|
||||
buf.UpdateLineIndexAfterDelete(startByte, endByte)
|
||||
}
|
||||
buf.UpdateLineIndexAfterInsert(absStart, text)
|
||||
newCursor = absStart + len(text)
|
||||
buf.UpdateLineIndexAfterInsert(startByte, text)
|
||||
newCursor = startByte + len(text)
|
||||
} else {
|
||||
s := TheState.Editor.Buffer
|
||||
if absEnd > absStart {
|
||||
s = s[:absStart] + s[absEnd:]
|
||||
if endByte > startByte {
|
||||
s = s[:startByte] + s[endByte:]
|
||||
}
|
||||
TheState.Editor.Buffer = s[:absStart] + text + s[absStart:]
|
||||
newCursor = absStart + len(text)
|
||||
TheState.Editor.Buffer = s[:startByte] + text + s[startByte:]
|
||||
newCursor = startByte + len(text)
|
||||
}
|
||||
TheState.Editor.findEdit(absStart, absEnd, len(text))
|
||||
imeAnchorEdit(startByte, delText, text)
|
||||
TheState.Editor.findEdit(startByte, endByte, 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 {
|
||||
dbgBuf = dbgBuf[:40]
|
||||
}
|
||||
fmt.Printf("IME DEBUG -> newCursor=%d buffer=%q\n", newCursor, dbgBuf)
|
||||
}
|
||||
markDirty()
|
||||
}
|
||||
|
||||
// imeDebugLog enables verbose per-commit IME logging. Keep false in normal
|
||||
// use; enable when debugging IME commit/cursor sync on device.
|
||||
const imeDebugLog = false
|
||||
|
||||
// currentEditorText returns the current editor buffer contents (full for
|
||||
// chunked files). Used only for debug logging.
|
||||
func currentEditorText() string {
|
||||
if cb := TheState.Editor.ChunkedBuffer; cb != nil {
|
||||
s, _ := cb.FullContent()
|
||||
return s
|
||||
}
|
||||
return TheState.Editor.Buffer
|
||||
}
|
||||
|
||||
func markDirty() {
|
||||
// Every content edit funnels through here, so EditSeq is the universal
|
||||
// "content changed" token (the WrapIndex layout-correlation gate uses it).
|
||||
@@ -2170,6 +2559,15 @@ func markDirty() {
|
||||
// (which shrinks the text area to make room) both use it.
|
||||
const FindBarHeight = ui.Dp(40)
|
||||
|
||||
// TopBarHeight is the editor top bar's height (buildFindBar hangs off it
|
||||
// too); TopBarIconSize is that bar's icon size — both ~30% larger than the
|
||||
// old 32dp/24dp pair so the back/search icons are a comfortable tap
|
||||
// target. The find bar keeps the smaller ui.IconSize.
|
||||
const (
|
||||
TopBarHeight = ui.Dp(42)
|
||||
TopBarIconSize = ui.Dp(31)
|
||||
)
|
||||
|
||||
// buildFindBar lays out the in-file search bar: [input][counter][prev][next]
|
||||
// [clear-X], full screen width, directly below the margin-free top bar (the
|
||||
// bars merge, so this one does too; inner content keeps the margin). The
|
||||
@@ -2180,7 +2578,7 @@ func buildFindBar(screenWidth ui.Dp) ui.Element {
|
||||
margin := ui.Dp(10)
|
||||
gap := ui.Dp(8)
|
||||
h := FindBarHeight
|
||||
topY := ui.Dp(32) // top bar height (see EditorLayout)
|
||||
topY := TopBarHeight // top bar height (see EditorLayout)
|
||||
|
||||
// Right-hand button column: prev, next, clear (X).
|
||||
iconW := ui.IconSize
|
||||
@@ -2229,7 +2627,7 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
|
||||
statusBarRegion := ui.Region{
|
||||
X: 0, Y: 0,
|
||||
W: screenWidth,
|
||||
H: ui.Dp(32),
|
||||
H: TopBarHeight,
|
||||
}
|
||||
statusBarW := statusBarRegion.W
|
||||
filename := TheState.Editor.Filename
|
||||
@@ -2240,10 +2638,10 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
|
||||
statusBarRegion,
|
||||
ui.Color{R: 230, G: 230, B: 230, A: 255},
|
||||
[]ui.Element{
|
||||
ui.NewIcon("back", ui.Region{X: margin, Y: ui.Dp(4), W: ui.IconSize, H: ui.IconSize}, 0,
|
||||
ui.NewIcon("back", ui.Region{X: margin, Y: ui.Dp(5), W: TopBarIconSize, H: TopBarIconSize}, 0,
|
||||
[]ui.Interaction{{Gesture: ui.Tap, Handler: GoToBrowser}}),
|
||||
ui.NewLabel(filename, 14, ui.Region{X: ui.Dp(32) + margin, Y: ui.Dp(6), W: statusBarW - ui.Dp(32) - margin - ui.IconSize - ui.Dp(8), H: ui.Dp(20)}, ui.AlignStart, "", nil),
|
||||
ui.NewIcon("search", ui.Region{X: screenWidth - margin - ui.IconSize, Y: ui.Dp(4), W: ui.IconSize, H: ui.IconSize}, 0,
|
||||
ui.NewLabel(filename, 14, ui.Region{X: margin + TopBarIconSize + ui.Dp(8), Y: ui.Dp(11), W: statusBarW - margin - TopBarIconSize - ui.Dp(8) - margin - TopBarIconSize, H: ui.Dp(20)}, ui.AlignStart, "", nil),
|
||||
ui.NewIcon("search", ui.Region{X: screenWidth - margin - TopBarIconSize, Y: ui.Dp(5), W: TopBarIconSize, H: TopBarIconSize}, 0,
|
||||
[]ui.Interaction{{Gesture: ui.Tap, Handler: ToggleFind}}),
|
||||
},
|
||||
)
|
||||
@@ -2285,9 +2683,9 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
|
||||
bottomBarRegion,
|
||||
ui.Color{R: 230, G: 230, B: 230, A: 255},
|
||||
[]ui.Element{
|
||||
ui.NewLabel(statusText, 12, ui.Region{X: margin, Y: ui.Dp(2), W: bottomBarW - margin, H: ui.Dp(20)}, ui.AlignStart, "", nil),
|
||||
ui.NewLabel(cursorPosText, 12, ui.Region{X: 0, Y: ui.Dp(2), W: bottomBarW, H: ui.Dp(20)}, ui.AlignCenter, "", nil),
|
||||
ui.NewLabel(wrapText, 12, ui.Region{X: 0, Y: ui.Dp(2), W: bottomBarW - margin, H: ui.Dp(20)}, ui.AlignEnd, "wrap", []ui.Interaction{
|
||||
ui.NewLabel(statusText, 12, ui.Region{X: margin, Y: ui.Dp(5), W: bottomBarW - margin, H: ui.Dp(20)}, ui.AlignStart, "", nil),
|
||||
ui.NewLabel(cursorPosText, 12, ui.Region{X: 0, Y: ui.Dp(5), W: bottomBarW, H: ui.Dp(20)}, ui.AlignCenter, "", nil),
|
||||
ui.NewLabel(wrapText, 12, ui.Region{X: 0, Y: ui.Dp(5), W: bottomBarW - margin, H: ui.Dp(20)}, ui.AlignEnd, "wrap", []ui.Interaction{
|
||||
{Gesture: ui.Tap, Handler: ToggleWordWrap},
|
||||
}),
|
||||
},
|
||||
@@ -2415,7 +2813,6 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
|
||||
// range [start, end) so a tall viewport is filled (a fixed 2000-byte
|
||||
// window could leave the lower rows blank).
|
||||
visibleContent = cb.Content(start, end)
|
||||
|
||||
// Adjust cursor position to be relative to visibleContent. It may be
|
||||
// NEGATIVE (the cursor's line scrolled above the window) or exceed
|
||||
// len(visibleContent) (scrolled below): the renderer treats an
|
||||
@@ -2466,12 +2863,14 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
|
||||
TheState.VisibleStart = start
|
||||
TheState.VisibleEnd = end
|
||||
|
||||
// Record the visible window for IME: the snippet is this window, so an
|
||||
// EditEvent.Range (relative to the window) is offset by IMEWindowStartByte
|
||||
// to address the buffer. start is 0 for small (string) files, so the
|
||||
// window is the whole buffer there.
|
||||
// Record the visible window for IME: the snippet pushed to the IME is
|
||||
// the leading context plus this window, addressed from IMEOffsetRune (the
|
||||
// absolute file rune offset where the context begins). start is 0 for
|
||||
// small (string) files, so the window is the whole buffer there and there
|
||||
// is no leading context. See imeRuneToByte / Renderer.FlushIME.
|
||||
TheState.Editor.IMEWindowStartByte = start
|
||||
TheState.Editor.IMEWindowText = visibleContent
|
||||
TheState.computeIMESnippetWindow()
|
||||
// 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
|
||||
@@ -2556,6 +2955,26 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
|
||||
{Gesture: ui.Pinch, Handler: HandleFontPinch},
|
||||
},
|
||||
)
|
||||
// Lead the IME snippet with up to 10 runes before the window and address
|
||||
// it from its true file position (see imeLeadingContext / IMEOffsetRune
|
||||
// above and Renderer.FlushIME): this is what stops the keyboard from
|
||||
// auto-capitalizing mid-sentence at the top of the visible window.
|
||||
editorElem.IMESnippetText = TheState.Editor.IMESnippetText
|
||||
editorElem.IMESnippetStartRune = TheState.Editor.IMESnippetStartRune
|
||||
editorElem.IMESnippetEndRune = TheState.Editor.IMESnippetEndRune
|
||||
editorElem.IMECaretRune = TheState.Editor.IMECaretRune
|
||||
editorElem.IMESelStartRune = TheState.Editor.IMESelStartRune
|
||||
editorElem.IMESelEndRune = TheState.Editor.IMESelEndRune
|
||||
editorElem.IMEForceResync = TheState.Editor.IMEForceResync
|
||||
TheState.Editor.IMEForceResync = false
|
||||
// EditSeq (the content-edit counter at frame-build time) is what the
|
||||
// renderer's IME hold compares against: a pre-commit frame carries the
|
||||
// seq the hold was armed with, a post-commit frame a newer one (which
|
||||
// releases the hold). Without it every frame reads 0 and the hold can
|
||||
// only time out, swallowing the resync pushes it is meant to protect
|
||||
// against regressions from (see Renderer.FlushIME).
|
||||
editorElem.EditSeq = TheState.Editor.EditSeq
|
||||
editorElem.WindowStartByte = start
|
||||
// While the find bar is open, key focus belongs to the main-owned
|
||||
// "find_bar" widget.Editor: the editor stops its per-frame IME sync, and
|
||||
// regaining "editor_text" focus re-issues key.FocusCmd on close (see
|
||||
@@ -2759,8 +3178,14 @@ func tapLocalY(ptY, regionTopY ui.Dp) float64 {
|
||||
// clears any selection.
|
||||
func SetCursorFromPoint(x, y float64) {
|
||||
ClearSelection()
|
||||
// A tap re-reads the truth: the selection push (and any snippet
|
||||
// re-anchor) that follows re-synchronizes the IME, so a pending
|
||||
// key-edit can no longer describe its model.
|
||||
TheState.Editor.imeStaleEditByte = -1
|
||||
if pos, ok := textPosFromLocalPoint(x, y); ok {
|
||||
TheState.Editor.CursorPosition = pos
|
||||
log.Printf("IME TAP local=(%.0f,%.0f) cursor=%d winStart=%d offsetRune=%d",
|
||||
x, y, pos, TheState.Editor.IMEWindowStartByte, TheState.Editor.IMEOffsetRune)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2865,8 +3290,16 @@ func textPosOnLineAtX(visualLine int, x float64) (int, bool) {
|
||||
if visualLine < len(layout.VisualLineStarts) {
|
||||
return base + layout.VisualLineStarts[visualLine], true
|
||||
}
|
||||
// No line start recorded for this line (finger beyond the content):
|
||||
// clamp to the last non-empty line.
|
||||
// No line start recorded for this line (finger below the last line):
|
||||
// the insertion point there is the end of the visible window — what
|
||||
// the phantom trailing-line start used to provide (the shaper no
|
||||
// longer records one at the window end; see the VisualLineStarts
|
||||
// capture in drawWrappedText). A layout with NO line starts at all
|
||||
// (degenerate/synthetic) has no window end to point at: clamp to
|
||||
// the last non-empty line instead.
|
||||
if len(layout.VisualLineStarts) > 0 {
|
||||
return base + len(TheState.Editor.IMEWindowText), true
|
||||
}
|
||||
for i := len(groups) - 1; i >= 0; i-- {
|
||||
if len(groups[i].indices) > 0 {
|
||||
visualLine = i
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package real
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"pad/internal/io/pool/types"
|
||||
)
|
||||
@@ -63,11 +65,23 @@ func (fs *RealFileSystem) ReadFileAt(path string, offset, size int) ([]byte, err
|
||||
}
|
||||
defer f.Close()
|
||||
buf := make([]byte, size)
|
||||
n, err := f.ReadAt(buf, int64(offset))
|
||||
if err != nil && err != io.EOF {
|
||||
// ReadAt may return a SHORT read with a nil or io.EOF error (POSIX
|
||||
// allows it; the Android FUSE layer does it), so loop until the whole
|
||||
// range is read or the file truly ends. A silently short result would
|
||||
// truncate a chunk and shift every byte offset after it — taps and IME
|
||||
// commits would then land at the wrong buffer position (text corruption).
|
||||
total := 0
|
||||
for total < size {
|
||||
n, err := f.ReadAt(buf[total:], int64(offset)+int64(total))
|
||||
total += n
|
||||
if err != nil {
|
||||
if err == io.EOF || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
break
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return buf[:n], nil
|
||||
}
|
||||
return buf[:total], nil
|
||||
}
|
||||
|
||||
func (fs *RealFileSystem) WriteFile(path string, content []byte) error {
|
||||
@@ -109,6 +123,23 @@ func (fs *RealFileSystem) WriteFileAtomic(path string, content []byte) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// The Android shared-storage layer (FUSE backed by MediaProvider
|
||||
// metadata) re-serves the PREVIOUS file's mtime after a rename: its
|
||||
// media-scan DB row for the path is not updated when the staging file
|
||||
// is renamed into place (logcat: "Database update failed while
|
||||
// renaming"). Change detectors that combine inotify events with a
|
||||
// stat compare (syncthing) then treat the new content as unmodified
|
||||
// and skip it until the next full rescan — up to an hour of "edited
|
||||
// but not synced" on a phone. Setting the timestamps explicitly after
|
||||
// the rename publishes the current mtime through the FUSE layer, and
|
||||
// the timestamp update is the event the watcher acts on immediately
|
||||
// (verified on device: a plain rename's mtime is reverted to the old
|
||||
// file's, while utimensat sticks and triggers the sync at once).
|
||||
if err := os.Chtimes(fullPath, time.Now(), time.Now()); err != nil {
|
||||
// The content is already safely in place; the timestamps are a
|
||||
// best-effort hint for external change detectors, not data.
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func randomPayload(t *testing.T, seed int64, size int) []byte {
|
||||
@@ -209,4 +210,41 @@ func TestWriteFileAtomic_StaleTempFileIsConsumed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteFileAtomic_PublishesCurrentMtime pins the timestamp contract:
|
||||
// after a successful write the file's mtime is current, and a subsequent
|
||||
// write ADVANCES it. On Android shared storage a bare rename can leave the
|
||||
// PREVIOUS file's mtime visible through the FUSE layer (the MediaProvider
|
||||
// metadata row is not updated on rename), which makes stat-based change
|
||||
// detectors (syncthing) treat the new content as unmodified until the next
|
||||
// full rescan. WriteFileAtomic's post-rename Chtimes is what publishes the
|
||||
// current mtime; if that line is ever removed, this test documents what the
|
||||
// phone then experiences (it cannot reproduce the clobber itself on ext4).
|
||||
func TestWriteFileAtomic_PublishesCurrentMtime(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
fs := NewRealFileSystem(d)
|
||||
if err := fs.WriteFileAtomic("/m.txt", []byte("v1")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := os.Stat(filepath.Join(d, "m.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if delta := time.Since(first.ModTime()); delta > 30*time.Second || delta < 0 {
|
||||
t.Fatalf("first write mtime not current: %v (delta %v)", first.ModTime(), delta)
|
||||
}
|
||||
// Cross a whole-second boundary: filesystems with 1 s mtime granularity
|
||||
// (Android FUSE) must still show an advance.
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
if err := fs.WriteFileAtomic("/m.txt", []byte("v2, longer content")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := os.Stat(filepath.Join(d, "m.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !second.ModTime().After(first.ModTime()) {
|
||||
t.Fatalf("mtime did not advance after rewrite: first=%v second=%v (Android FUSE would report the stale mtime and syncthing would never see the change)", first.ModTime(), second.ModTime())
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int) string { return strconv.Itoa(n) }
|
||||
|
||||
@@ -108,10 +108,10 @@ func TestRealFile_FindBarAndNavigation(t *testing.T) {
|
||||
t.Fatalf("focus %q, want find_bar", focus)
|
||||
}
|
||||
// The text area must shrink from the top while the find bar is open so
|
||||
// the first line is not covered: region top = top bar (32) + FindBarHeight.
|
||||
// the first line is not covered: region top = TopBarHeight + FindBarHeight.
|
||||
reg, _ := h.Inspect(func(st *editor.State) any { return st.EditorRegion })
|
||||
if got := reg.(ui.Region); got.Y != ui.Dp(32)+editor.FindBarHeight {
|
||||
t.Fatalf("editor region top %d, want %d (find bar must not cover text)", int(got.Y), int(ui.Dp(32)+editor.FindBarHeight))
|
||||
if got := reg.(ui.Region); got.Y != editor.TopBarHeight+editor.FindBarHeight {
|
||||
t.Fatalf("editor region top %d, want %d (find bar must not cover text)", int(got.Y), int(editor.TopBarHeight+editor.FindBarHeight))
|
||||
}
|
||||
// The editor field reports UNFOCUSED while the find bar is open (the
|
||||
// renderer hides its caret for unfocused fields; main hands key focus to
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package e2e_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gioui.org/io/key"
|
||||
"pad/internal/editor"
|
||||
"pad/internal/test/e2e"
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
// incidentContent is the file from the 2026-09-19 phone incident: "test"
|
||||
// plus five newlines (9 bytes). The tap target is byte 6 (the start of
|
||||
// line 3), exactly where the user tapped.
|
||||
const incidentContent = "test\n\n\n\n\n"
|
||||
|
||||
func setCursor(t *testing.T, h *e2e.Harness, pos int) {
|
||||
t.Helper()
|
||||
if err := h.WithState(func(st *editor.State) {
|
||||
st.Editor.CursorPosition = pos
|
||||
}); err != nil {
|
||||
t.Fatalf("set cursor: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// contentAfter sends the input batch (nil = none) and waits until the buffer
|
||||
// content reaches want; the logic goroutine applies the events
|
||||
// asynchronously, so a read straight after SendInput is a race.
|
||||
func contentAfter(t *testing.T, h *e2e.Harness, events []ui.InputEvent, want string) string {
|
||||
t.Helper()
|
||||
if events != nil {
|
||||
h.SendInput(events)
|
||||
}
|
||||
for i := 0; i < 300; i++ {
|
||||
c, err := h.FullContent()
|
||||
if err != nil {
|
||||
t.Fatalf("FullContent: %v", err)
|
||||
}
|
||||
if c == want {
|
||||
return c
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("buffer did not reach %q", want)
|
||||
return ""
|
||||
}
|
||||
|
||||
// TestIMECommitAfterEnterKeySameBatch is the exact phone incident: tap at
|
||||
// byte 6, type "a" (Gboard autocaps and commits [6,6)→"A"), press Enter
|
||||
// (Gboard sends it as a KEY EVENT, not a commit — the logic inserts "\n"
|
||||
// and the caret moves to 8, but Gboard's local model still lacks it), then
|
||||
// type "a" (Gboard, one edit behind, commits the word append [6,7)→"Aa"
|
||||
// against the pre-Enter caret). The key event and the append commit arrive
|
||||
// in the same input batch, so no frame has drawn between them.
|
||||
//
|
||||
// The append must be applied at its reported range — everything before the
|
||||
// pending key edit is byte-identical in both models — instead of being
|
||||
// drift-snapped to the new caret and duplicated (the incident produced
|
||||
// "test\n\nA\nAaAa\n\n\n").
|
||||
func TestIMECommitAfterEnterKeySameBatch(t *testing.T) {
|
||||
h, _ := realFileHarness(t, "test.txt", incidentContent)
|
||||
defer h.Cleanup()
|
||||
setCursor(t, h, 6)
|
||||
|
||||
// "a" typed with autocap: one clean IME commit.
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{StartRune: 6, EndRune: 6, Text: "A"},
|
||||
}}, "test\n\nA\n\n\n")
|
||||
|
||||
// Enter (key event) and the stale-model word append in ONE batch: the
|
||||
// logic processes the "\n" first, so when the append is guarded the
|
||||
// caret is already at 8 while the commit ends at 7. "A" must be replaced
|
||||
// by "Aa" in place and the Enter newline survive after it.
|
||||
contentAfter(t, h, []ui.InputEvent{
|
||||
{Handler: editor.HandleKeyDown, Data: ui.KeyEvent{Name: key.NameReturn}},
|
||||
{Handler: editor.HandleIMECommit, Data: editor.IMECommit{StartRune: 6, EndRune: 7, Text: "Aa"}},
|
||||
}, "test\n\nAa\n\n\n\n")
|
||||
|
||||
if pos, _ := h.CursorPosition(); pos != 8 {
|
||||
t.Errorf("cursor: got %d want 8 (end of the replaced word)", pos)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIMECommitAfterEnterKeyNextBatch is the same incident with the append
|
||||
// commit arriving in a LATER input batch than the Enter: a frame was
|
||||
// emitted for the Enter, but the resyncing snippet push only lands on the
|
||||
// next drawn frame, and the IME's commit can beat it. The pending key edit
|
||||
// must still be honored.
|
||||
func TestIMECommitAfterEnterKeyNextBatch(t *testing.T) {
|
||||
h, _ := realFileHarness(t, "test.txt", incidentContent)
|
||||
defer h.Cleanup()
|
||||
setCursor(t, h, 6)
|
||||
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{StartRune: 6, EndRune: 6, Text: "A"},
|
||||
}}, "test\n\nA\n\n\n")
|
||||
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleKeyDown,
|
||||
Data: ui.KeyEvent{Name: key.NameReturn},
|
||||
}}, "test\n\nA\n\n\n\n")
|
||||
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{StartRune: 6, EndRune: 7, Text: "Aa"},
|
||||
}}, "test\n\nAa\n\n\n\n")
|
||||
}
|
||||
|
||||
// TestIMEEmptyCommitStillSnappedWithPendingEdit: a pending key edit does
|
||||
// NOT relax the guard for range deletions (empty text). Deleting at a range
|
||||
// the IME sees but the app no longer expects there is how documents get
|
||||
// clobbered; such commits must still snap to the caret (a no-op there).
|
||||
func TestIMEEmptyCommitStillSnappedWithPendingEdit(t *testing.T) {
|
||||
h, _ := realFileHarness(t, "test.txt", incidentContent)
|
||||
defer h.Cleanup()
|
||||
setCursor(t, h, 6)
|
||||
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{StartRune: 6, EndRune: 6, Text: "A"},
|
||||
}}, "test\n\nA\n\n\n")
|
||||
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleKeyDown,
|
||||
Data: ui.KeyEvent{Name: key.NameReturn},
|
||||
}}, "test\n\nA\n\n\n\n")
|
||||
|
||||
// Gboard's stale model still shows "A" at [6,7) and asks to delete it.
|
||||
// The commit must snap to the caret (a no-op there), so the "A"
|
||||
// survives. The content is unchanged by a correct snap, so poll for
|
||||
// quiescence (a new frame after the input) before asserting.
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{StartRune: 6, EndRune: 7, Text: ""},
|
||||
}}, "test\n\nA\n\n\n\n")
|
||||
before := h.FrameCount()
|
||||
for h.FrameCount() == before {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if c, _ := h.FullContent(); c != "test\n\nA\n\n\n\n" {
|
||||
t.Fatalf("empty commit must snap to the caret (no-op), got %q", c)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIMECommitPastPendingEditStillSnapped: a commit that ends PAST the
|
||||
// pending key edit addresses text the IME's model does not have (it is
|
||||
// shifted by the edit), so it is still anomalous and snaps to the caret.
|
||||
func TestIMECommitPastPendingEditStillSnapped(t *testing.T) {
|
||||
h, _ := realFileHarness(t, "test.txt", incidentContent)
|
||||
defer h.Cleanup()
|
||||
setCursor(t, h, 6)
|
||||
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{StartRune: 6, EndRune: 6, Text: "A"},
|
||||
}}, "test\n\nA\n\n\n")
|
||||
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleKeyDown,
|
||||
Data: ui.KeyEvent{Name: key.NameReturn},
|
||||
}}, "test\n\nA\n\n\n\n")
|
||||
|
||||
// Ends at 9, past the pending edit at 7: the range crosses the edit, so
|
||||
// the file content there is NOT what the IME sees. Snap to the caret
|
||||
// (8): "x" lands at 8, not 9.
|
||||
contentAfter(t, h, []ui.InputEvent{{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{StartRune: 9, EndRune: 9, Text: "x"},
|
||||
}}, "test\n\nA\nx\n\n\n")
|
||||
}
|
||||
@@ -172,9 +172,13 @@ func TestRealFile_Fuzz_EditSaveReload(t *testing.T) {
|
||||
type win struct {
|
||||
Start int
|
||||
Text string
|
||||
CtxStart int
|
||||
Context string
|
||||
OffsetRune int
|
||||
}
|
||||
raw, err := h.Inspect(func(st *editor.State) any {
|
||||
return win{st.Editor.IMEWindowStartByte, st.Editor.IMEWindowText}
|
||||
return win{st.Editor.IMEWindowStartByte, st.Editor.IMEWindowText,
|
||||
st.Editor.IMEContextStartByte, st.Editor.IMEContext, st.Editor.IMEOffsetRune}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("batch %d op %d: inspect: %v", batch, j, err)
|
||||
@@ -191,17 +195,39 @@ func TestRealFile_Fuzz_EditSaveReload(t *testing.T) {
|
||||
batch, j, w.Start, len(w.Text),
|
||||
compactMismatch(w.Text, model[w.Start:min(len(model), w.Start+len(w.Text))]))
|
||||
}
|
||||
wr := countRunes(w.Text)
|
||||
ra := rng.Intn(wr + 1)
|
||||
rb := ra + rng.Intn(wr-ra+1)
|
||||
// Context consistency: it is the slice immediately before the
|
||||
// window, and the snippet's Range.Start is the rune offset of
|
||||
// the context start.
|
||||
if len(w.Context) > 0 {
|
||||
if w.CtxStart+len(w.Context) != w.Start ||
|
||||
w.Context != model[w.CtxStart:w.CtxStart+len(w.Context)] {
|
||||
t.Fatalf("batch %d op %d: IME context desync: ctxStart=%d", batch, j, w.CtxStart)
|
||||
}
|
||||
}
|
||||
if w.OffsetRune != countRunes(model[:w.CtxStart]) {
|
||||
t.Fatalf("batch %d op %d: IME offset desync: got=%d want=%d", batch, j, w.OffsetRune, countRunes(model[:w.CtxStart]))
|
||||
}
|
||||
// The real IME reports ABSOLUTE file runes: the pushed snippet
|
||||
// (context+window) starts at OffsetRune, so a snippet-local
|
||||
// range [sa,sb) is absolute [OffsetRune+sa, OffsetRune+sb).
|
||||
ctxRunes := countRunes(w.Context)
|
||||
total := ctxRunes + countRunes(w.Text)
|
||||
sa := rng.Intn(total + 1)
|
||||
sb := sa + rng.Intn(total-sa+1)
|
||||
absByte := func(snipRune int) int {
|
||||
if snipRune <= ctxRunes {
|
||||
return w.CtxStart + runeToByte(w.Context, snipRune)
|
||||
}
|
||||
return w.Start + runeToByte(w.Text, snipRune-ctxRunes)
|
||||
}
|
||||
text := randomFuzzText(rng, 0, 12)
|
||||
if err := h.WithState(func(st *editor.State) {
|
||||
editor.HandleReplaceRange(ra, rb, text)
|
||||
editor.HandleReplaceRange(w.OffsetRune+sa, w.OffsetRune+sb, text)
|
||||
}); err != nil {
|
||||
t.Fatalf("batch %d op %d: replace: %v", batch, j, err)
|
||||
}
|
||||
bs := w.Start + runeToByte(w.Text, ra)
|
||||
be := w.Start + runeToByte(w.Text, rb)
|
||||
bs := absByte(sa)
|
||||
be := absByte(sb)
|
||||
model = model[:bs] + text + model[be:]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
package e2e_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gioui.org/io/key"
|
||||
"pad/internal/editor"
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
// largeFileContent generates a deterministic ~1.6 MB text file: 40,000 lines
|
||||
// of ~40 unique ASCII bytes each, with a multibyte rune ("é", "中") sprinkled
|
||||
// through every 500th line so rune offsets and byte offsets genuinely differ.
|
||||
// Generating in-test (t.TempDir, via realFileHarness) keeps the repository
|
||||
// small while still exercising the >500 KB chunked/IME path the same way a
|
||||
// real multi-hundred-kb note would.
|
||||
func largeFileContent(lines int) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < lines; i++ {
|
||||
b.WriteString(fmt.Sprintf("large file line %05d pad", i))
|
||||
if i%500 == 0 {
|
||||
b.WriteString(" é 中")
|
||||
}
|
||||
b.WriteString(strings.Repeat(string(rune('a'+i%26)), 12))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// TestRealFile_LargeFile_IMECommits pins IME commit correctness on a large
|
||||
// (~1.6 MB, well over the 500 KB threshold that the on-device "needs a
|
||||
// gioui fork" claim referred to) file:
|
||||
//
|
||||
// - the IME window invariants (window text, leading context, absolute
|
||||
// rune offset) hold for a window deep in the file;
|
||||
// - a replacement commit (a selection, as a swipe/autocorrect would send)
|
||||
// lands exactly in the scrolled window and nowhere else;
|
||||
// - an insert commit (empty range at the caret, a plain typed char) in a
|
||||
// second, deeper window lands exactly at the caret.
|
||||
//
|
||||
// The full-content comparison after each commit catches the classic
|
||||
// corruption mode (the commit mapped through a stale/zero window start and
|
||||
// clobbering text near the top of the file).
|
||||
func TestRealFile_LargeFile_IMECommits(t *testing.T) {
|
||||
const (
|
||||
lines = 40000
|
||||
scrollLn = 20000 // scroll deep into the file
|
||||
editLn = 20008 // comfortably inside the ~18-line viewport window
|
||||
)
|
||||
model := largeFileContent(lines)
|
||||
h, path := realFileHarness(t, "large.txt", model)
|
||||
defer h.Cleanup()
|
||||
|
||||
h.SendConfig(780, 400)
|
||||
if _, err := h.WaitForFrame(5 * time.Second); err != nil {
|
||||
t.Fatalf("wait for frame: %v", err)
|
||||
}
|
||||
|
||||
// Scroll deep (5 dp into the line: avoid the float32/float64 line-pitch
|
||||
// boundary fragility, see TestRealFile_WindowSelectionAtScroll) and put a
|
||||
// selection on line editLn, 6 bytes into its filler.
|
||||
selStart := byteOffsetOfLine(t, model, editLn) + 31
|
||||
selEnd := selStart + 6
|
||||
if err := h.WithState(func(st *editor.State) {
|
||||
st.ScrollOffset = ui.Dp(16.8*scrollLn + 5)
|
||||
st.Editor.SelectionStart = selStart
|
||||
st.Editor.SelectionEnd = selEnd
|
||||
st.Editor.CursorPosition = selEnd
|
||||
}); err != nil {
|
||||
t.Fatalf("WithState: %v", err)
|
||||
}
|
||||
prev := h.FrameCount()
|
||||
h.SendConfig(780, 400)
|
||||
if _, err := h.WaitForFrameCount(prev+1, 5*time.Second); err != nil {
|
||||
t.Fatalf("wait for scrolled frame: %v", err)
|
||||
}
|
||||
|
||||
// 1) IME window invariants for a window deep in a large file.
|
||||
var win struct {
|
||||
Start int
|
||||
Text string
|
||||
Snip string
|
||||
}
|
||||
v, err := h.Inspect(func(st *editor.State) any {
|
||||
e := &st.Editor
|
||||
return struct {
|
||||
Start int
|
||||
Text string
|
||||
Snip string
|
||||
}{e.IMEWindowStartByte, e.IMEWindowText, e.IMESnippetText}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Inspect: %v", err)
|
||||
}
|
||||
win = v.(struct {
|
||||
Start int
|
||||
Text string
|
||||
Snip string
|
||||
})
|
||||
if want := model[win.Start : win.Start+len(win.Text)]; win.Text != want {
|
||||
t.Fatalf("IME window text desync at start=%d", win.Start)
|
||||
}
|
||||
// The IME snippet is a hysteresis window around the caret (see
|
||||
// State.computeIMESnippetWindow); it must always be a fresh slice of
|
||||
// the model.
|
||||
if i := strings.Index(model, win.Snip); i < 0 {
|
||||
t.Fatalf("IME snippet not a slice of the model: %q", win.Snip[:min(40, len(win.Snip))])
|
||||
}
|
||||
|
||||
// 2) Replacement commit: absolute file runes (the coordinate space the
|
||||
// real IME uses; the multibyte sprinkles make runes != bytes).
|
||||
absStart := utf8.RuneCountInString(model[:selStart])
|
||||
absEnd := utf8.RuneCountInString(model[:selEnd])
|
||||
wantModel := model[:selStart] + "ZZ" + model[selEnd:]
|
||||
h.SendInput([]ui.InputEvent{{
|
||||
Handler: editor.HandleKeyDown,
|
||||
Data: key.EditEvent{
|
||||
Range: key.Range{Start: absStart, End: absEnd},
|
||||
Text: "ZZ",
|
||||
},
|
||||
}})
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
got, err := h.FullContent()
|
||||
if err != nil {
|
||||
t.Fatalf("FullContent: %v", err)
|
||||
}
|
||||
if got != wantModel {
|
||||
t.Fatalf("after replacement commit: content differs (first diff at %d)", firstDiff(wantModel, got))
|
||||
}
|
||||
|
||||
// 3) Insert commit in a deeper window: caret-only (empty range), the
|
||||
// plain "typed a character" case.
|
||||
deepLn := 30000
|
||||
caret := byteOffsetOfLine(t, wantModel, deepLn) + 20
|
||||
if err := h.WithState(func(st *editor.State) {
|
||||
st.ScrollOffset = ui.Dp(16.8*float64(deepLn) + 5)
|
||||
st.Editor.SelectionStart = -1
|
||||
st.Editor.SelectionEnd = -1
|
||||
st.Editor.CursorPosition = caret
|
||||
}); err != nil {
|
||||
t.Fatalf("WithState: %v", err)
|
||||
}
|
||||
prev = h.FrameCount()
|
||||
h.SendConfig(780, 400)
|
||||
if _, err := h.WaitForFrameCount(prev+1, 5*time.Second); err != nil {
|
||||
t.Fatalf("wait for second scrolled frame: %v", err)
|
||||
}
|
||||
absCaret := utf8.RuneCountInString(wantModel[:caret])
|
||||
wantModel2 := wantModel[:caret] + "Q" + wantModel[caret:]
|
||||
h.SendInput([]ui.InputEvent{{
|
||||
Handler: editor.HandleKeyDown,
|
||||
Data: key.EditEvent{
|
||||
Range: key.Range{Start: absCaret, End: absCaret},
|
||||
Text: "Q",
|
||||
},
|
||||
}})
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
got, err = h.FullContent()
|
||||
if err != nil {
|
||||
t.Fatalf("FullContent: %v", err)
|
||||
}
|
||||
if got != wantModel2 {
|
||||
t.Fatalf("after insert commit: content differs (first diff at %d)", firstDiff(wantModel2, got))
|
||||
}
|
||||
if cp, err := h.Inspect(func(st *editor.State) any { return st.Editor.CursorPosition }); err != nil {
|
||||
t.Fatalf("Inspect: %v", err)
|
||||
} else if cp.(int) != caret+1 {
|
||||
t.Fatalf("cursor = %d, want %d", cp.(int), caret+1)
|
||||
}
|
||||
|
||||
// 4) Persistence: the on-disk file matches the in-memory content.
|
||||
if err := h.Flush(); err != nil {
|
||||
t.Fatalf("flush: %v", err)
|
||||
}
|
||||
if disk := readDisk(t, path); disk != wantModel2 {
|
||||
t.Fatalf("disk content differs from in-memory (first diff at %d)", firstDiff(wantModel2, disk))
|
||||
}
|
||||
}
|
||||
|
||||
// byteOffsetOfLine returns the absolute byte offset of the start of line n
|
||||
// (0-indexed) in model. The generated lines are unique, so a plain index of
|
||||
// the line prefix is unambiguous.
|
||||
func byteOffsetOfLine(t *testing.T, model string, n int) int {
|
||||
t.Helper()
|
||||
prefix := fmt.Sprintf("large file line %05d", n)
|
||||
i := strings.Index(model, prefix)
|
||||
if i < 0 {
|
||||
t.Fatalf("line %d not found", n)
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// firstDiff returns the byte offset of the first difference between a and b
|
||||
// (min(len) when they are a common prefix), for useful failure messages.
|
||||
func firstDiff(a, b string) int {
|
||||
n := len(a)
|
||||
if len(b) < n {
|
||||
n = len(b)
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
if a[i] != b[i] {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// TestRealFile_IMEForceResync pins the desync recovery: the first
|
||||
// anomalous IME commit (a drift-snapped small commit, a distant commit —
|
||||
// the phone autocorrect that landed 19,000 runes from the caret — or an
|
||||
// empty fix-up) arms a forced re-syncing snippet re-push on the very next
|
||||
// frame (a desynced IME is healed only by a restart; a selection push is
|
||||
// deduplicated away after commits). A normal commit never arms it.
|
||||
func TestRealFile_IMEForceResync(t *testing.T) {
|
||||
model := largeFileContent(4000)
|
||||
h, _ := realFileHarness(t, "resync.txt", model)
|
||||
defer h.Cleanup()
|
||||
|
||||
h.SendConfig(780, 400)
|
||||
if _, err := h.WaitForFrame(5 * time.Second); err != nil {
|
||||
t.Fatalf("wait for frame: %v", err)
|
||||
}
|
||||
|
||||
const caretByte = 10000
|
||||
caretRune := utf8.RuneCountInString(model[:caretByte])
|
||||
if err := h.WithState(func(st *editor.State) {
|
||||
st.Editor.CursorPosition = caretByte
|
||||
}); err != nil {
|
||||
t.Fatalf("WithState: %v", err)
|
||||
}
|
||||
|
||||
commit := func(start, end int, text string) {
|
||||
h.SendInput([]ui.InputEvent{{
|
||||
Handler: editor.HandleIMECommit,
|
||||
Data: editor.IMECommit{StartRune: start, EndRune: end, Text: text},
|
||||
}})
|
||||
// The logic applies commits asynchronously; wait for the resulting
|
||||
// frame before asserting on the derived state.
|
||||
prev := h.FrameCount()
|
||||
if _, err := h.WaitForFrameCount(prev+1, 5*time.Second); err != nil {
|
||||
t.Fatalf("wait for commit frame: %v", err)
|
||||
}
|
||||
}
|
||||
forceInLatestFrame := func() bool {
|
||||
frames := h.GetFrames()
|
||||
if len(frames) == 0 {
|
||||
t.Fatal("no frames")
|
||||
}
|
||||
for _, el := range frames[len(frames)-1] {
|
||||
if tf, ok := el.(ui.TextField); ok && tf.ID() == "editor_text" {
|
||||
return tf.IMEForceResync
|
||||
}
|
||||
}
|
||||
t.Fatal("no editor_text element in latest frame")
|
||||
return false
|
||||
}
|
||||
|
||||
// A normal commit at the caret arms nothing.
|
||||
commit(caretRune, caretRune, "q")
|
||||
if forceInLatestFrame() {
|
||||
t.Fatal("resync armed by a normal commit")
|
||||
}
|
||||
|
||||
// A small drifted commit (Gboard fix-up at a stale position): the frame
|
||||
// emitted by that commit carries the resync flag.
|
||||
commit(caretRune+5, caretRune+5, "")
|
||||
if !forceInLatestFrame() {
|
||||
t.Fatal("resync not armed after a drift-snapped commit")
|
||||
}
|
||||
|
||||
// One-shot: a later frame carries no flag.
|
||||
prev := h.FrameCount()
|
||||
h.SendConfig(780, 400)
|
||||
if _, err := h.WaitForFrameCount(prev+1, 5*time.Second); err != nil {
|
||||
t.Fatalf("wait for frame: %v", err)
|
||||
}
|
||||
if forceInLatestFrame() {
|
||||
t.Fatal("resync flag not one-shot")
|
||||
}
|
||||
|
||||
// A distant replacement commit (width > 2: the autocorrect class that
|
||||
// the old guard let through) is snapped to the caret and arms the
|
||||
// resync.
|
||||
commit(caretRune+20000, caretRune+20005, "silly")
|
||||
if !forceInLatestFrame() {
|
||||
t.Fatal("resync not armed after a distant commit")
|
||||
}
|
||||
|
||||
// The distant commit must have landed at the caret, not at 20000:
|
||||
// the caret advances by exactly the inserted text length.
|
||||
var cur int
|
||||
if err := h.WithState(func(st *editor.State) {
|
||||
cur = st.Editor.CursorPosition
|
||||
}); err != nil {
|
||||
t.Fatalf("WithState: %v", err)
|
||||
}
|
||||
// "q" (1) + "silly" (5) inserted at the original caret.
|
||||
if want := caretByte + 6; cur != want {
|
||||
t.Fatalf("cursor = %d, want %d (distant commit must land at the caret)", cur, want)
|
||||
}
|
||||
}
|
||||
@@ -137,9 +137,11 @@ func TestRealFile_IMECommitAtScroll(t *testing.T) {
|
||||
t.Fatalf("wait for frame: %v", err)
|
||||
}
|
||||
|
||||
// The selection (absolute) and the matching window-relative EditEvent
|
||||
// range: the IME reports offsets relative to the pushed snippet, which
|
||||
// is the visible window.
|
||||
// The selection (absolute) and the matching EditEvent range: the IME
|
||||
// reports offsets in absolute file runes (the coordinate space of the
|
||||
// pushed snippet, which now starts at the leading context's true file
|
||||
// position). The content is ASCII, so rune == byte and the range is just
|
||||
// the absolute byte offsets.
|
||||
selStart := editLn*lineLen + 5
|
||||
selEnd := editLn*lineLen + 11
|
||||
// Scroll 5 dp into line 10 (see TestRealFile_WindowSelectionAtScroll for
|
||||
@@ -159,12 +161,14 @@ func TestRealFile_IMECommitAtScroll(t *testing.T) {
|
||||
}
|
||||
|
||||
// Typing replaces the selection: "ZZ" over the 6 selected filler chars
|
||||
// (in-line offsets [5,11)) on line 12. The pre-fix code (windowStart=0)
|
||||
// applied this at byte 47 — line 2 — corrupting the file.
|
||||
// (in-line offsets [5,11)) on line 12. The commit range is in absolute
|
||||
// file runes (== bytes here). The pre-fix code (windowStart=0, no
|
||||
// leading context) applied a mis-mapped range near the top of the file,
|
||||
// corrupting it.
|
||||
h.SendInput([]ui.InputEvent{{
|
||||
Handler: editor.HandleKeyDown,
|
||||
Data: key.EditEvent{
|
||||
Range: key.Range{Start: selStart - scrollLn*lineLen, End: selEnd - scrollLn*lineLen},
|
||||
Range: key.Range{Start: selStart, End: selEnd},
|
||||
Text: "ZZ",
|
||||
},
|
||||
}})
|
||||
|
||||
@@ -503,7 +503,18 @@ func TestRestore_ScrollSurvivesWrapState(t *testing.T) {
|
||||
h1.Run()
|
||||
h1.SendConfig(780, 1688)
|
||||
h1.SendScale(2.0)
|
||||
defer h1.Cleanup()
|
||||
// The harness runs against the package globals (TheState/TheLogic), so
|
||||
// only ONE harness may be alive at a time: h1 is stopped (not deferred)
|
||||
// as soon as its snapshot is in hand, before h2's NewLogic overwrites
|
||||
// the globals out from under h1's still-running goroutines.
|
||||
h1Cleaned := false
|
||||
cleanup1 := func() {
|
||||
if !h1Cleaned {
|
||||
h1Cleaned = true
|
||||
h1.Cleanup()
|
||||
}
|
||||
}
|
||||
defer cleanup1()
|
||||
|
||||
if err := h1.WithState(func(st *editor.State) { editor.OpenFile("/wrap.txt") }); err != nil {
|
||||
t.Fatalf("OpenFile: %v", err)
|
||||
@@ -563,6 +574,9 @@ got:
|
||||
t.Errorf("snapshot ScrollSub = %v, want ~0", snap.ScrollSub)
|
||||
}
|
||||
|
||||
// h1's job is done: stop it before h2 overwrites the package globals.
|
||||
cleanup1()
|
||||
|
||||
// Second session (the relaunch): the WrapIndex is fresh, every count the
|
||||
// estimate (1). The restore must land on logical line 200, not on visual
|
||||
// line 500 mapped 1:1 (which would be line 500, far deeper).
|
||||
@@ -833,3 +847,55 @@ drainDone:
|
||||
t.Fatal("timed out: selection appearance was not saved immediately (urgent path)")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRestore_BrowserPageSession covers the relaunch bug where a session
|
||||
// ended on the browser page still re-opened the last edited file: a
|
||||
// snapshot taken on the browser page must mark InBrowser (with the browser
|
||||
// directory and no file), and a relaunch handed that snapshot must land
|
||||
// back in the browser at the saved directory.
|
||||
func TestRestore_BrowserPageSession(t *testing.T) {
|
||||
// Snapshot on the browser page.
|
||||
h := e2e.NewHarnessWithDefaults()
|
||||
defer h.Cleanup()
|
||||
if err := h.WithState(func(st *editor.State) {
|
||||
st.Browser.CurrentPath = "/Documents/Work"
|
||||
}); err != nil {
|
||||
t.Fatalf("WithState: %v", err)
|
||||
}
|
||||
v, err := h.Inspect(func(st *editor.State) any {
|
||||
return h.Logic().SnapshotSession()
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Inspect: %v", err)
|
||||
}
|
||||
sess := v.(editor.SessionState)
|
||||
if !sess.InBrowser {
|
||||
t.Fatalf("browser-page snapshot: InBrowser = false, want true: %+v", sess)
|
||||
}
|
||||
if sess.File != "" {
|
||||
t.Errorf("browser-page snapshot: File = %q, want \"\"", sess.File)
|
||||
}
|
||||
if sess.BrowserPath != "/Documents/Work" {
|
||||
t.Errorf("browser-page snapshot: BrowserPath = %q, want \"/Documents/Work\"", sess.BrowserPath)
|
||||
}
|
||||
|
||||
// Relaunch with that session: land in the browser at the saved dir.
|
||||
h2 := e2e.NewHarness()
|
||||
defer h2.Cleanup()
|
||||
h2.Logic().BeginBrowserRestore(sess.BrowserPath)
|
||||
h2.Run()
|
||||
h2.SendConfig(780, 1688)
|
||||
h2.SendScale(2.0)
|
||||
if _, err := e2e.WaitForNewFrame(h2, 0, 5*time.Second); err != nil {
|
||||
t.Fatalf("timeout waiting for frames: %v", err)
|
||||
}
|
||||
v, err = h2.Inspect(func(st *editor.State) any {
|
||||
return st.Page() == editor.BrowserPage && st.Browser.CurrentPath == sess.BrowserPath
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Inspect: %v", err)
|
||||
}
|
||||
if !v.(bool) {
|
||||
t.Fatal("relaunch with a browser session did not land on the browser page at the saved directory")
|
||||
}
|
||||
}
|
||||
|
||||
+40
-94
@@ -213,6 +213,30 @@ type TextField struct {
|
||||
// is running (the IME insets dispatches redraw the app), so the keyboard
|
||||
// could not be dismissed. See TextField.Draw.
|
||||
ShowIMESeq uint64
|
||||
// IME snippet (hysteresis window around the caret — see
|
||||
// State.computeIMESnippetWindow): IMESnippetText is the pushed text,
|
||||
// IMESnippet{Start,End}Rune its absolute file rune range, IMECaretRune
|
||||
// the caret's absolute rune, and IMESel*Rune the live selection's rune
|
||||
// range (-1/-1 when no selection).
|
||||
IMESnippetText string
|
||||
IMESnippetStartRune int
|
||||
IMESnippetEndRune int
|
||||
IMECaretRune int
|
||||
IMESelStartRune int
|
||||
IMESelEndRune int
|
||||
// IMEForceResync: re-push the snippet trimmed by one rune this frame
|
||||
// (a forced restartInput that heals a desynchronized IME; see
|
||||
// EditorState.IMEForceResync).
|
||||
IMEForceResync bool
|
||||
// EditSeq is the buffer edit sequence at frame-build time (0 for
|
||||
// non-editor fields); the renderer uses it to detect the frame that
|
||||
// carries an IME commit's result (see Renderer.imeHold).
|
||||
EditSeq uint64
|
||||
// WindowStartByte is the absolute file byte offset where Value (the
|
||||
// visible window) begins; -1/0 for whole-buffer fields. Used by the
|
||||
// renderer's IME model to translate snippet positions back to file bytes
|
||||
// (see Renderer.ModelTranslate).
|
||||
WindowStartByte int
|
||||
}
|
||||
|
||||
func (tf TextField) Type() string { return "textfield" }
|
||||
@@ -231,14 +255,6 @@ func (tf TextField) String() string {
|
||||
// and draws display lines inline — one LayoutString call, no double-shaping.
|
||||
func (tf TextField) Draw(gtx layout.Context, r *Renderer) {
|
||||
if tf.Focused {
|
||||
// (Re-)gained focus for this field (or a different field than the one the
|
||||
// dedup state currently tracks): force a fresh snippet/selection push so
|
||||
// the IME starts from a known state.
|
||||
if r.lastIMEField != tf.id || !r.lastWasFocused {
|
||||
r.lastSnippet = key.Snippet{}
|
||||
r.lastSelStart = -1
|
||||
r.lastSelCaret = -1
|
||||
}
|
||||
r.lastIMEField = tf.id
|
||||
r.lastWasFocused = true
|
||||
// Issue key.FocusCmd only on a focus transition (see
|
||||
@@ -261,102 +277,32 @@ func (tf TextField) Draw(gtx layout.Context, r *Renderer) {
|
||||
r.lastIMEShowSeq = tf.ShowIMESeq
|
||||
gtx.Execute(key.SoftKeyboardCmd{Show: true})
|
||||
}
|
||||
// IME wiring. The visible window (tf.Value) is pushed as the snippet
|
||||
// with Range {0, len}, so the IME treats the window as the document and
|
||||
// reports EditEvent.Range window-relative. This lets swipe/autocorrect
|
||||
// operate on the visible text without shipping the whole file to the IME.
|
||||
//
|
||||
// Item 4: tell the IME this is a text field (enables the text keyboard,
|
||||
// Tell the IME this is a text field (enables the text keyboard,
|
||||
// autocorrect, and suggestions).
|
||||
key.InputHintOp{Tag: tf.id, Hint: key.HintText}.Add(gtx.Ops)
|
||||
// Item 2: push the snippet (the visible window) for swipe/autocorrect,
|
||||
// but only when it changed. Re-pushing an unchanged snippet every frame
|
||||
// resets the IME's composition/cursor, which desyncs fast commits (see
|
||||
// widget.Editor's updateSnippet dedup).
|
||||
snippet := key.Snippet{
|
||||
Range: key.Range{Start: 0, End: runeCount(tf.Value, len(tf.Value))},
|
||||
Text: tf.Value,
|
||||
}
|
||||
if snippet != r.lastSnippet {
|
||||
r.lastSnippet = snippet
|
||||
gtx.Execute(key.SnippetCmd{Tag: tf.id, Snippet: snippet})
|
||||
}
|
||||
// Item 1: sync the caret/selection so the IME's selection matches.
|
||||
// Window-relative rune indices (tf.CursorPosition and the selection
|
||||
// bounds are byte offsets into tf.Value). With a selection, push the
|
||||
// full range so the IME highlights it and a commit replaces it (the
|
||||
// logic side unions the commit range with the selection, so the
|
||||
// replacement is deterministic regardless of what the IME reports).
|
||||
// Push only when the (start, end) pair changes, so a static selection
|
||||
// does not reset the IME every frame.
|
||||
var selStart, selEnd int
|
||||
if tf.SelectionStart >= 0 && tf.SelectionEnd > tf.SelectionStart {
|
||||
// Clamp to the window (the element may be built from a window that
|
||||
// does not fully contain the selection).
|
||||
s := tf.SelectionStart
|
||||
if s < 0 {
|
||||
s = 0
|
||||
}
|
||||
e := tf.SelectionEnd
|
||||
if e > len(tf.Value) {
|
||||
e = len(tf.Value)
|
||||
}
|
||||
selStart = runeCount(tf.Value, s)
|
||||
selEnd = runeCount(tf.Value, e)
|
||||
} else {
|
||||
selStart = -1
|
||||
selEnd = runeCount(tf.Value, tf.CursorPosition)
|
||||
}
|
||||
if selStart != r.lastSelStart || selEnd != r.lastSelCaret {
|
||||
// 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{}})
|
||||
}
|
||||
}
|
||||
// The IME snippet and selection are NOT pushed here. They are pushed
|
||||
// by Renderer.FlushIME, which the main loop calls after this frame's
|
||||
// key events were drained (and mirrored into the renderer's IME model)
|
||||
// and before the ops are flushed to the OS. Pushing the snippet from
|
||||
// Draw runs before the logic has applied the frame's IME edit, so the
|
||||
// commit frame would push the pre-edit text; gioui then sees the
|
||||
// mismatch with the IME's own post-commit snippet and calls
|
||||
// imm.restartInput() — resetting the keyboard's auto-cap state (the
|
||||
// random mid-word capitals) on every keystroke. See FlushIME.
|
||||
} else if r.lastIMEField == tf.id {
|
||||
// This (previously-focused) field lost focus: forget it so the next focus
|
||||
// pushes a fresh snippet/selection. Resetting lastIMEShowSeq makes the
|
||||
// next focus re-raise the keyboard even without a fresh pulse.
|
||||
// This (previously-focused) field lost focus: forget it so the next
|
||||
// focus pushes a fresh snippet/selection. Resetting lastIMEShowSeq
|
||||
// makes the next focus re-raise the keyboard even without a fresh
|
||||
// pulse; resetting lastSnippet makes the next focus re-push the
|
||||
// snippet even if the text is unchanged.
|
||||
r.lastIMEField = ""
|
||||
r.lastWasFocused = false
|
||||
r.lastSnippet = key.Snippet{}
|
||||
r.lastSelStart = -1
|
||||
r.lastSelCaret = -1
|
||||
r.lastIMEShowSeq = 0
|
||||
r.lastSnippet = key.Snippet{}
|
||||
}
|
||||
r.drawWrappedText(gtx, tf.Value, tf.region, tf.WordWrap, tf.WrapWidth, tf.ScrollOffset, tf.CursorPosition, tf.SelectionStart, tf.SelectionEnd, tf.CaretDrag, tf.MatchRanges, tf.CurrentMatch, tf.Focused)
|
||||
}
|
||||
|
||||
// runeCount returns the number of UTF-8 runes in s[:bytePos] (bytePos is a
|
||||
// byte offset, clamped to len(s)). A rune starts at an ASCII byte (<0x80) or a
|
||||
// multi-byte lead byte (>=0xC0); 0x80-0xBF are continuation bytes.
|
||||
func runeCount(s string, bytePos int) int {
|
||||
if bytePos > len(s) {
|
||||
bytePos = len(s)
|
||||
}
|
||||
n := 0
|
||||
for i := 0; i < bytePos; i++ {
|
||||
b := s[i]
|
||||
if b < 0x80 || b >= 0xC0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// NewTextField creates a visible multiline TextField.
|
||||
func NewTextField(id string, value string, region Region, wordWrap bool, wrapWidth Dp, scrollOffset Dp, cursorPos int, selStart, selEnd int, interactions []Interaction) TextField {
|
||||
return TextField{
|
||||
|
||||
@@ -5,7 +5,7 @@ const (
|
||||
StatusBarLineHeight = Dp(24)
|
||||
StatusBarFilenameLine = Dp(24)
|
||||
StatusBarIconsLine = Dp(24)
|
||||
BottomBarHeight = Dp(24)
|
||||
BottomBarHeight = Dp(31) // ~30% taller than the old 24dp: the bar's only tap target (the wrap toggle) is a text label, so the bar doubles as its hit area
|
||||
IconSize = Dp(24)
|
||||
IconGap = Dp(36)
|
||||
Padding = Dp(8)
|
||||
|
||||
+272
-5
@@ -24,6 +24,7 @@ import (
|
||||
"gioui.org/unit"
|
||||
"gioui.org/widget"
|
||||
"golang.org/x/image/math/fixed"
|
||||
"log"
|
||||
)
|
||||
|
||||
// maxInt32 is a large value used as MaxWidth for single-line text layout.
|
||||
@@ -110,10 +111,55 @@ type Renderer struct {
|
||||
lastIMEField string
|
||||
lastWasFocused bool
|
||||
lastSnippet key.Snippet
|
||||
lastSelStart int // window-relative rune index of last-pushed selection start; -1 = no selection
|
||||
lastSelCaret int // window-relative rune index of last-pushed selection end/caret
|
||||
|
||||
lastSelStart int // absolute rune index of last-pushed selection start; -1 = no selection
|
||||
lastSelCaret int // absolute rune index of last-pushed selection end/caret
|
||||
lastIMEShowSeq uint64 // last ShowIMESeq value that issued SoftKeyboardCmd{Show:true}
|
||||
|
||||
// IME model (main-owned, persistent across frames). The renderer keeps a
|
||||
// local copy of the snippet the IME currently holds and updates it in
|
||||
// place as IME edits arrive (ApplyIMEEdit / ApplyIMEKey, called from the
|
||||
// key-event drain), so the snippet pushed each frame (FlushIME) is
|
||||
// byte-identical to the IME's own post-commit snippet. Gioui calls
|
||||
// imm.restartInput() whenever the pushed snippet differs from the IME's
|
||||
// internal state (app/os_android.go EditorStateChanged); a restart makes
|
||||
// the keyboard (Gboard) re-derive its auto-cap state from scratch, which
|
||||
// is the root cause of the random mid-word capitals. The model is flushed
|
||||
// AFTER the key events of the frame were drained and BEFORE e.Frame
|
||||
// flushes the ops, so the commit frame pushes the post-edit text instead
|
||||
// of the pre-edit frame text (which is what desynced the old push-from-
|
||||
// Draw path and restarted the IME on every keystroke).
|
||||
|
||||
// Caret geometry drawn during the most recent frame, in view-local
|
||||
// pixels (imeCaretPos is the caret/baseline intersection, per key.Caret).
|
||||
// FlushIME attaches it to the pushed SelectionCmd: gioui only calls
|
||||
// GioView.updateCaret (-> imm.updateCursorAnchorInfo, the update that
|
||||
// actually reaches the IME and makes Gboard re-evaluate its auto-cap
|
||||
// state) when the SelectionCmd's Caret changes. A zero caret never
|
||||
// changes, so Gboard never saw a caret move and kept its stale
|
||||
// auto-shift after the caret jumped (e.g. from a line start, where
|
||||
// caps are legitimately on, to mid-word).
|
||||
// lastIMECaretPos is the caret last shipped in a SelectionCmd.
|
||||
imeCaretPos f32.Point
|
||||
imeCaretAscent float32
|
||||
imeCaretDescent float32
|
||||
lastIMECaretPos f32.Point
|
||||
|
||||
// imeHold: a commit was applied to the pushed model (see
|
||||
// ApplyIMECommitToModel) but the logic's post-commit frame has not been
|
||||
// drawn yet. The frame being drained is pre-commit (it was built before
|
||||
// the logic processed the commit); its snippet would clobber the model
|
||||
// with the stale text, regressing gioui's editor state and causing a
|
||||
// restart per keystroke. The hold is armed with the drained frame's
|
||||
// EditSeq: while the hold is active, FlushIME skips a frame whose
|
||||
// EditSeq is at most the armed one (the drained frame, and any no-op
|
||||
// frame repeating the seq) and resumes on the next higher one. The
|
||||
// logic's HandleIMECommit markDirties the buffer, so the post-commit
|
||||
// frame always advances it.
|
||||
imeHoldActive bool
|
||||
imeHoldEditSeq uint64
|
||||
imeHoldFrames int
|
||||
|
||||
// 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
|
||||
@@ -233,6 +279,199 @@ func (r *Renderer) pointInHandleBox(p image.Point) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// ApplyIMECommitToModel applies a drained IME commit to the pushed snippet
|
||||
// model and re-pushes it IMMEDIATELY, on the drain pass. This is required
|
||||
// because gioui's EditEvent callback applies the same commit to its own
|
||||
// window state (w.imeState) directly, bypassing the op queue; the op-queue
|
||||
// state then lags w.imeState by exactly this commit, and gioui's
|
||||
// per-frame comparison (updateState) sees the mismatch as a SNIPPET
|
||||
// REGRESSION — it rolls the state back and sends a restartInput with the
|
||||
// PRE-commit text on every single keystroke. Gboard resets its per-word
|
||||
// input session on that restart (and it never queries the app for
|
||||
// context), which is the source of the random mid-word capitalization.
|
||||
// Pushing the post-commit snippet here makes the op queue match w.imeState
|
||||
// before the next frame: the comparison is a no-op, no restart is sent,
|
||||
// and Gboard's session (auto-shift, composition) survives the keystroke.
|
||||
// The logic goroutine applies the same commit to the buffer asynchronously;
|
||||
// when its frame arrives, FlushIME sees the snippet unchanged (already
|
||||
// pushed) and does nothing. If the logic SNAPS the commit to a different
|
||||
// position (drift guard), the post-commit frame's snippet differs from the
|
||||
// model and one resyncing restart is pushed then — correct.
|
||||
// frameEditSeq is the EditSeq of the frame the commit was drained from
|
||||
// (the pre-commit frame); it arms the hold (see the imeHold field).
|
||||
func (r *Renderer) ApplyIMECommitToModel(gtx layout.Context, ev key.EditEvent, frameEditSeq uint64) {
|
||||
sn := r.lastSnippet
|
||||
local := ev.Range.Start - sn.Range.Start
|
||||
total := utf8.RuneCountInString(sn.Text)
|
||||
if local < 0 || local > total || ev.Range.End-sn.Range.Start > total {
|
||||
return // commit outside the pushed window; the next frame resyncs
|
||||
}
|
||||
// Replace [local, local+repl) runes with ev.Text (repl is the commit's
|
||||
// own replaced span — 0 for a plain insertion).
|
||||
rs := []rune(sn.Text)
|
||||
repl := ev.Range.End - ev.Range.Start
|
||||
newRs := make([]rune, 0, len(rs)+len([]rune(ev.Text)))
|
||||
newRs = append(newRs, rs[:local]...)
|
||||
newRs = append(newRs, []rune(ev.Text)...)
|
||||
if local+repl < len(rs) {
|
||||
newRs = append(newRs, rs[local+repl:]...)
|
||||
}
|
||||
newSnip := key.Snippet{
|
||||
Range: key.Range{
|
||||
Start: sn.Range.Start,
|
||||
End: sn.Range.End + len([]rune(ev.Text)) - repl,
|
||||
},
|
||||
Text: string(newRs),
|
||||
}
|
||||
r.lastSnippet = newSnip
|
||||
gtx.Execute(key.SnippetCmd{Tag: "editor_text", Snippet: newSnip})
|
||||
// The caret is at the end of the inserted text: push the selection so
|
||||
// the op queue's selection matches w.imeState (the EditEvent's Replace
|
||||
// moved it there). The px caret position is the current one (the next
|
||||
// frame corrects it); gioui's updateCaret is cosmetic for the IME.
|
||||
// Hold the pre-commit frame(s) out of FlushIME until the post-commit
|
||||
// frame arrives (they would clobber the model just pushed). Arm with
|
||||
// the drained frame's own EditSeq: it is the seq of the last
|
||||
// pre-commit frame, and the post-commit frame's seq is strictly higher
|
||||
// (the logic's HandleIMECommit markDirties the buffer).
|
||||
r.imeHoldActive = true
|
||||
r.imeHoldEditSeq = frameEditSeq
|
||||
r.imeHoldFrames = 0
|
||||
// The post-commit caret is at the END of the inserted text, which
|
||||
// starts at Range.Start: for an insertion (Start == End) that is
|
||||
// Range.End + len, but for a replacement (a swipe/autocorrect over a
|
||||
// selection) it is Range.Start + len — Range.End + len would land
|
||||
// (End-Start) runes past the inserted text and desynchronize the IME's
|
||||
// caret from ours (observed on the phone: a 4-rune replacement left
|
||||
// every subsequent commit 4 runes ahead of the caret).
|
||||
caret := ev.Range.Start + utf8.RuneCountInString(ev.Text)
|
||||
log.Printf("IME PUSH commit-range=[%d,%d) text=%q -> sel caret=%d", ev.Range.Start, ev.Range.End, ev.Text, caret)
|
||||
r.lastSelStart, r.lastSelCaret = -1, caret
|
||||
r.lastIMECaretPos = r.imeCaretPos
|
||||
gtx.Execute(key.SelectionCmd{
|
||||
Tag: "editor_text",
|
||||
Range: key.Range{Start: caret, End: caret},
|
||||
Caret: key.Caret{
|
||||
Pos: r.imeCaretPos,
|
||||
Ascent: r.imeCaretAscent,
|
||||
Descent: r.imeCaretDescent,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Renderer) FlushIME(gtx layout.Context, tf TextField) {
|
||||
// An IME commit is in flight (see ApplyIMECommitToModel): a pre-commit
|
||||
// frame must not push its stale snippet and regress gioui's state.
|
||||
if r.imeHoldActive {
|
||||
if tf.EditSeq <= r.imeHoldEditSeq {
|
||||
// Bounded so a commit whose post-commit frame never arrives
|
||||
// (logic stall) cannot stick the hold: after a few frames
|
||||
// resume normal flushing.
|
||||
if r.imeHoldFrames++; r.imeHoldFrames > 8 {
|
||||
r.imeHoldActive = false
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
r.imeHoldActive = false
|
||||
}
|
||||
// The snippet is the hysteresis window around the caret (see
|
||||
// State.computeIMESnippetWindow), shipped precomputed by the logic:
|
||||
// stable across render-window moves (keyboard show/hide, tap
|
||||
// re-centering, scrolls), so those events do NOT re-push the snippet —
|
||||
// a re-push reaches Gboard as imm.restartInput, which starts a fresh
|
||||
// input session that capitalizes the first committed character even
|
||||
// mid-word. It re-anchors only when the caret leaves the window
|
||||
// margins (far tap, fling past the window, file switch), and on edits
|
||||
// (whose text ApplyIMECommitToModel has already pushed, so the frame's
|
||||
// copy dedupes away).
|
||||
snippet := key.Snippet{
|
||||
Range: key.Range{
|
||||
Start: tf.IMESnippetStartRune,
|
||||
End: tf.IMESnippetEndRune,
|
||||
},
|
||||
Text: tf.IMESnippetText,
|
||||
}
|
||||
if tf.IMEForceResync && utf8.RuneCountInString(tf.IMESnippetText) > 2 {
|
||||
// The IME's local text has desynchronized (several consecutive
|
||||
// drift-snapped or empty commits — see EditorState.IMEForceResync)
|
||||
// and it keeps re-sending the same fix in a loop. Pushing the
|
||||
// window trimmed by one rune forces a snippet change (and thus a
|
||||
// restartInput): the IME re-fetches the real text and selection
|
||||
// around the caret and its model converges. The next frame pushes
|
||||
// the full window again (one more restart), then everything is
|
||||
// quiet again.
|
||||
rs := []rune(tf.IMESnippetText)
|
||||
snippet = key.Snippet{
|
||||
Range: key.Range{
|
||||
Start: tf.IMESnippetStartRune + 1,
|
||||
End: tf.IMESnippetEndRune,
|
||||
},
|
||||
Text: string(rs[1:]),
|
||||
}
|
||||
}
|
||||
if snippet != r.lastSnippet {
|
||||
r.lastSnippet = snippet
|
||||
// A snippet change resets the IME's selection: force the selection
|
||||
// re-push below so the caret is re-anchored in the new text in the
|
||||
// same frame. (A drained IME commit is applied to the model BEFORE
|
||||
// this runs — see ApplyIMECommitToModel — so a normal keystroke
|
||||
// never reaches this branch; it is the re-anchoring path: scroll,
|
||||
// tap, file switch, snapped commit, external edit.)
|
||||
log.Printf("IME PUSH snippet=[%d,%d) len=%d (restart)", snippet.Range.Start, snippet.Range.End, utf8.RuneCountInString(snippet.Text))
|
||||
r.lastSelStart, r.lastSelCaret = -1, -1
|
||||
gtx.Execute(key.SnippetCmd{Tag: tf.id, Snippet: snippet})
|
||||
}
|
||||
// Push the caret/selection (deduped) in absolute file runes, the same
|
||||
// coordinate space as the snippet (see widget.Editor's updateIMEState).
|
||||
var selStart, selEnd int
|
||||
if tf.IMESelStartRune >= 0 && tf.IMESelEndRune > tf.IMESelStartRune {
|
||||
selStart, selEnd = tf.IMESelStartRune, tf.IMESelEndRune
|
||||
} else {
|
||||
selStart = -1
|
||||
selEnd = tf.IMECaretRune
|
||||
}
|
||||
selectionJumped := selStart != r.lastSelStart || selEnd != r.lastSelCaret
|
||||
caretMoved := r.imeCaretPos != r.lastIMECaretPos
|
||||
if selectionJumped || caretMoved {
|
||||
// Skip while a selection/caret handle drag is in flight (see
|
||||
// Renderer.selDragActive): a mid-gesture updateSelection makes the
|
||||
// IME's selection jump and aborts the gesture. key.SelDragActive is
|
||||
// stale here (renderer-owned), so use the renderer's own flag.
|
||||
if !r.selDragActive {
|
||||
r.lastSelStart = selStart
|
||||
r.lastSelCaret = selEnd
|
||||
r.lastIMECaretPos = r.imeCaretPos
|
||||
log.Printf("IME PUSH sel=[%d,%d)", selStart, selEnd)
|
||||
rng := key.Range{Start: selStart, End: selEnd}
|
||||
if selStart < 0 {
|
||||
rng = key.Range{Start: selEnd, End: selEnd}
|
||||
}
|
||||
// The SelectionCmd must reach the IME on every caret jump: it is
|
||||
// the signal (GioView.updateSelection -> imm.updateSelection,
|
||||
// delivered as onUpdateSelection) that makes Gboard re-derive
|
||||
// its auto-shift state from the new position — mid-word: off;
|
||||
// line/sentence start: on. It must NOT be shadowed by a snippet
|
||||
// push in the same frame: a snippet change makes gioui's
|
||||
// EditorStateChanged take the restartInput branch instead (which
|
||||
// Gboard does not use to re-derive caps), so a caret jump with an
|
||||
// unchanged snippet is exactly the case that works.
|
||||
// The Caret field carries the real position (view-local px, Pos
|
||||
// on the baseline) so gioui also fires updateCaret
|
||||
// (imm.updateCursorAnchorInfo) for the jump.
|
||||
gtx.Execute(key.SelectionCmd{
|
||||
Tag: tf.id,
|
||||
Range: rng,
|
||||
Caret: key.Caret{
|
||||
Pos: r.imeCaretPos,
|
||||
Ascent: r.imeCaretAscent,
|
||||
Descent: r.imeCaretDescent,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// New creates a new Renderer.
|
||||
func New(th Theme, shp *text.Shaper) *Renderer {
|
||||
r := &Renderer{
|
||||
@@ -1037,10 +1276,28 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
|
||||
flushLine()
|
||||
if g.Flags&text.FlagLineBreak != 0 {
|
||||
lineCount++
|
||||
// Record the next visual line's start ONLY when a real line
|
||||
// follows the break: a real "\n" cluster (zero width, one
|
||||
// rune — including the final one of a newline-terminated
|
||||
// file, whose trailing empty line is real) or a soft wrap
|
||||
// with content after it. The shaper ALSO flags the last
|
||||
// visible glyph of a final line without a trailing newline,
|
||||
// and the synthetic end-of-text glyph after a trailing
|
||||
// newline: both sit at len(str) with no line after them.
|
||||
// Recording them creates a phantom visual line: taps below
|
||||
// the content map onto it (harmless — it returns the EOF
|
||||
// byte), but CaretPoint resolves the caret through it and
|
||||
// draws the caret on that phantom line — one line BELOW
|
||||
// where the typed text lands, so the letter appeared a line
|
||||
// above the cursor.
|
||||
isRealNewline := g.Advance == 0 && g.Runes > 0
|
||||
softWrap := g.Advance != 0 && byteOffset < len(str)
|
||||
if isRealNewline || softWrap {
|
||||
layout.VisualLineStarts = append(layout.VisualLineStarts, byteOffset)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(line) > 0 {
|
||||
flushLine()
|
||||
lineCount++
|
||||
@@ -1095,9 +1352,19 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
|
||||
// byte and len(str) is the window's last insertion point.
|
||||
if focused && 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
|
||||
caretX, caretY := caretPoint(cursorPos) // y is the line's baseline, region-relative
|
||||
cursorX := reg.X + caretX
|
||||
cursorY := reg.Y - scrollOffset + caretY - ascent
|
||||
|
||||
// Save the caret geometry (view-local px; Pos on the baseline) for
|
||||
// FlushIME's SelectionCmd so the IME is told where the caret moved.
|
||||
// See imeCaretPos.
|
||||
r.imeCaretPos = f32.Point{
|
||||
X: float32(r.toPx(cursorX)),
|
||||
Y: float32(r.toPx(reg.Y - scrollOffset + caretY)),
|
||||
}
|
||||
r.imeCaretAscent = float32(r.toPx(ascent))
|
||||
r.imeCaretDescent = float32(r.toPx(lineH - ascent))
|
||||
|
||||
// Draw the cursor (thin vertical bar)
|
||||
cursorRegion := Region{
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate cmd/pad/appicon.png, the Pad app icon.
|
||||
|
||||
Design: a soft, light cream pillow on a dark ink field, with "P_" (the
|
||||
underscore standing in for the text cursor) embroidered on it in slate
|
||||
thread. gogio picks appicon.png up automatically from the main package
|
||||
(cmd/pad) and builds the Android mipmap/adaptive-icon set and the iOS
|
||||
icon set from it.
|
||||
|
||||
Usage: scripts/make_icon.py
|
||||
Requires: python3 with PIL.
|
||||
"""
|
||||
import pathlib
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
||||
|
||||
SIZE = 1024
|
||||
INK = (32, 38, 50) # background
|
||||
PILLOW = (243, 231, 211) # base fabric
|
||||
PILLOW_LIT = (252, 246, 234)
|
||||
PILLOW_RIM = (206, 187, 158)
|
||||
THREAD = (92, 104, 134) # embroidered slate thread
|
||||
THREAD_DARK = (58, 67, 92)
|
||||
|
||||
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"
|
||||
|
||||
|
||||
def rrect_mask(w, h, r):
|
||||
m = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(m).rounded_rectangle([0, 0, w - 1, h - 1], radius=r, fill=255)
|
||||
return m
|
||||
|
||||
|
||||
def main() -> None:
|
||||
img = Image.new("RGB", (SIZE, SIZE), INK)
|
||||
|
||||
# --- pillow geometry (kept inside the adaptive-icon safe zone) ---
|
||||
pw, ph, pr = 672, 612, 195 # pillow size + corner radius
|
||||
px0, py0 = (SIZE - pw) // 2, (SIZE - ph) // 2 + 6
|
||||
|
||||
# --- soft drop shadow (slightly below, so light comes from above) ---
|
||||
shadow = Image.new("L", (SIZE, SIZE), 0)
|
||||
d = ImageDraw.Draw(shadow)
|
||||
d.rounded_rectangle([px0 + 16, py0 + 30, px0 + pw - 16, py0 + ph + 36],
|
||||
radius=pr + 10, fill=120)
|
||||
shadow = shadow.filter(ImageFilter.GaussianBlur(42))
|
||||
img = Image.composite(Image.new("RGB", (SIZE, SIZE), (18, 21, 29)), img,
|
||||
shadow)
|
||||
|
||||
# --- pillow body: plump radial shading ---
|
||||
base = Image.new("RGB", (SIZE, SIZE), INK)
|
||||
base.paste(Image.new("RGB", (pw, ph), PILLOW), (px0, py0))
|
||||
sharp = rrect_mask(pw, ph, pr)
|
||||
inner = sharp.filter(ImageFilter.GaussianBlur(pr * 0.8))
|
||||
lit = Image.new("RGB", (pw, ph), PILLOW_LIT)
|
||||
rim = Image.new("RGB", (pw, ph), PILLOW_RIM)
|
||||
base.paste(lit, (px0, py0), inner) # bright center
|
||||
rim_mask = Image.composite(Image.new("L", (pw, ph), 0), sharp,
|
||||
inner) # edge only
|
||||
rim_mask = rim_mask.point(lambda v: min(255, v * 2))
|
||||
base.paste(rim, (px0, py0), rim_mask) # shaded edge
|
||||
|
||||
# top sheen: an out-of-focus light patch
|
||||
sheen = Image.new("L", (SIZE, SIZE), 0)
|
||||
d = ImageDraw.Draw(sheen)
|
||||
d.ellipse([px0 + 110, py0 + 30, px0 + pw - 110, py0 + ph // 2 + 40],
|
||||
fill=80)
|
||||
sheen = sheen.filter(ImageFilter.GaussianBlur(75))
|
||||
base = Image.composite(Image.new("RGB", (SIZE, SIZE), PILLOW_LIT),
|
||||
base, sheen)
|
||||
|
||||
# corner dimples: soft darkening where a puffed pillow pinches
|
||||
for cx, cy in [
|
||||
(px0 + pr - 20, py0 + pr - 20), (px0 + pw - pr + 20, py0 + pr - 20),
|
||||
(px0 + pr - 20, py0 + ph - pr + 20),
|
||||
(px0 + pw - pr + 20, py0 + ph - pr + 20),
|
||||
]:
|
||||
dip = Image.new("L", (SIZE, SIZE), 0)
|
||||
ImageDraw.Draw(dip).ellipse([cx - 70, cy - 70, cx + 70, cy + 70],
|
||||
fill=55)
|
||||
dip = dip.filter(ImageFilter.GaussianBlur(30))
|
||||
base = Image.composite(
|
||||
Image.blend(base, Image.new("RGB", (SIZE, SIZE),
|
||||
(214, 196, 168)), 0.5),
|
||||
base, dip)
|
||||
|
||||
# --- dashed seam line, like a quilted pillow ---
|
||||
# Sample the rounded-rect path finely, then draw dash segments along it.
|
||||
m = 44 # margin from the pillow edge
|
||||
r = pr - m # corner radius of the seam
|
||||
import math as _m
|
||||
# Corners clockwise: center, angle start -> end (screen coords, y down).
|
||||
# Each arc is followed by the straight side to the next arc's start.
|
||||
arcs = [
|
||||
(m + r, m + r, _m.pi, 1.5 * _m.pi), # top-left
|
||||
(pw - m - r, m + r, 1.5 * _m.pi, 2 * _m.pi), # top-right
|
||||
(pw - m - r, ph - m - r, 0, 0.5 * _m.pi), # bottom-right
|
||||
(m + r, ph - m - r, 0.5 * _m.pi, _m.pi), # bottom-left
|
||||
]
|
||||
samples = []
|
||||
for i, (cx, cy, a0, a1) in enumerate(arcs):
|
||||
nx, ny, na0, _ = arcs[(i + 1) % 4]
|
||||
n = max(2, int(abs(a1 - a0) * r // 3))
|
||||
for k in range(n + 1):
|
||||
a = a0 + (a1 - a0) * k / n
|
||||
samples.append((cx + r * _m.cos(a), cy + r * _m.sin(a)))
|
||||
# straight side from this arc's end to the next arc's start
|
||||
end = (nx + r * _m.cos(na0), ny + r * _m.sin(na0))
|
||||
last = samples[-1]
|
||||
n = max(2, int(_m.hypot(end[0] - last[0], end[1] - last[1]) // 3))
|
||||
for k in range(1, n + 1):
|
||||
samples.append((last[0] + (end[0] - last[0]) * k / n,
|
||||
last[1] + (end[1] - last[1]) * k / n))
|
||||
# cumulative arc length
|
||||
cum = [0.0]
|
||||
for i in range(1, len(samples)):
|
||||
cum.append(cum[-1] + _m.hypot(samples[i][0] - samples[i - 1][0],
|
||||
samples[i][1] - samples[i - 1][1]))
|
||||
total = cum[-1]
|
||||
dash, gap = 26.0, 18.0
|
||||
seam_ring = Image.new("L", (pw, ph), 0)
|
||||
d = ImageDraw.Draw(seam_ring)
|
||||
s0 = 0.0
|
||||
while s0 < total:
|
||||
s1 = min(s0 + dash, total)
|
||||
pts = [(x, y) for (x, y), c in zip(samples, cum) if s0 <= c <= s1]
|
||||
if len(pts) > 1:
|
||||
d.line(pts, fill=255, width=9, joint="curve")
|
||||
s0 += dash + gap
|
||||
seam_ring = seam_ring.filter(ImageFilter.GaussianBlur(1.2))
|
||||
seam = seam_ring
|
||||
seam_full = Image.new("L", (SIZE, SIZE), 0)
|
||||
seam_full.paste(seam, (px0, py0))
|
||||
seam_col = Image.new("RGB", (SIZE, SIZE), (203, 183, 154))
|
||||
base = Image.composite(seam_col, base, seam_full)
|
||||
|
||||
# composite pillow onto background via its sharp mask
|
||||
full_sharp = Image.new("L", (SIZE, SIZE), 0)
|
||||
full_sharp.paste(sharp, (px0, py0))
|
||||
img.paste(base, (0, 0), full_sharp)
|
||||
|
||||
# --- embroidered "P_" ---
|
||||
# Center the CAP of the P on the pillow (optical center); the
|
||||
# underscore hangs below the baseline like a cursor on the next line.
|
||||
font = ImageFont.truetype(FONT, 300)
|
||||
# Drawing "P" at (x, y) puts its cap top at y + pb[1]; center the cap
|
||||
# on the pillow, keep the whole "P_" string on the same baseline.
|
||||
probe = ImageDraw.Draw(img)
|
||||
pb = probe.textbbox((0, 0), "P", font=font)
|
||||
cb_h = pb[3] - pb[1] # cap height
|
||||
ty = SIZE // 2 - cb_h // 2 - pb[1]
|
||||
tb = probe.textbbox((0, 0), "P_", font=font)
|
||||
tw, th = tb[2] - tb[0], tb[3] - tb[1]
|
||||
tx = (SIZE - tw) // 2 - tb[0]
|
||||
|
||||
# stitch texture: fine diagonal thread lines, tiled
|
||||
tile = 6
|
||||
pat = Image.new("L", (tile, tile), 160)
|
||||
ImageDraw.Draw(pat).line([(0, tile - 1), (tile - 1, 0)], fill=255,
|
||||
width=1)
|
||||
pat = pat.filter(ImageFilter.GaussianBlur(0.5))
|
||||
mw, mh = tw + 40, tb[3] + 80
|
||||
stitch = pat.resize((mw, mh), Image.NEAREST)
|
||||
|
||||
# text mask in local coords
|
||||
# local (0,0) == the absolute drawing origin (tx, ty); paste happens at
|
||||
# (tx-20, ty-20), so text goes at (20 - tb[0], 20).
|
||||
mask = Image.new("L", (mw, mh), 0)
|
||||
ImageDraw.Draw(mask).text((20 - tb[0], 20), "P_", font=font,
|
||||
fill=255)
|
||||
|
||||
# drop shadow of the stitches on the fabric (thread sits on top of it)
|
||||
sh = mask.filter(ImageFilter.GaussianBlur(5))
|
||||
sh_full = Image.new("L", (SIZE, SIZE), 0)
|
||||
sh_full.paste(sh, (tx - 20, ty - 20 + 7))
|
||||
img = Image.composite(Image.new("RGB", (SIZE, SIZE), (182, 164, 140)),
|
||||
img, sh_full)
|
||||
|
||||
# thread color modulated by the stitch pattern (subtle per-stitch depth)
|
||||
stitch_full = Image.new("L", (SIZE, SIZE), 0)
|
||||
stitch_full.paste(stitch, (tx - 20, ty - 20))
|
||||
mod = Image.composite(Image.new("RGB", (SIZE, SIZE), THREAD_DARK),
|
||||
Image.new("RGB", (SIZE, SIZE), THREAD),
|
||||
stitch_full)
|
||||
mask_full = Image.new("L", (SIZE, SIZE), 0)
|
||||
mask_full.paste(mask, (tx - 20, ty - 20))
|
||||
img = Image.composite(mod, img, mask_full)
|
||||
|
||||
out = pathlib.Path(__file__).resolve().parent.parent / "cmd" / "pad" / "appicon.png"
|
||||
img.save(out)
|
||||
print(f"wrote {out} ({SIZE}x{SIZE})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user