IME: map commits against the whole buffer; drop the renderer-side model

The renderer kept a mirror of the pushed IME snippet (the 'IME model')
to translate commit positions, but it transiently desynced from the
buffer on fling/tap sequences (observed as a few-byte mapping drift on
both the x86_64 emulator and the ARM phone), corrupting text. The model
string also sat on the main goroutine next to the JNI render path,
where the app observed states that were impossible for Go memory
(string contents changing between reads microseconds apart), pointing
at corruption in the native bridge layer.

Restructure along the lines of the Android InputConnection contract
and Gio's own reference editor (widget/editor.go):

- Commits carry absolute file runes (the pushed snippet's coordinate
  space) straight to the logic goroutine, which maps them to bytes
  against the WHOLE buffer (runeToByteWhole, an 8 KiB-step scan).
  Scrolling moves the window, not the buffer, so the mapping is exact
  mid-fling by construction — no mirror to desync.
- Drift guard in HandleIMECommit: a small commit (range <= 2 runes)
  is always anchored at the caret the IME was last told about; if the
  IME reports it ending elsewhere, its snippet text is stale (a
  dropped restartInput, as Gboard does during flings) and its
  position is in the stale text's coordinates — snap the commit to
  the cursor, the only position it cannot drift from.
- FlushIME simplifies to: push the snippet when the frame's
  (context+window) text differs from the last push (gioui dedupes
  against its own cache), force the selection re-push in the same
  frame. After a commit the frame text equals what the IME already
  holds locally, so the restart is naturally suppressed; a fling
  re-anchors the IME once per text change.
- Remove the renderer model (adoptFrame/ModelTranslate/
  ApplyIMEEdit/ApplyIMEKey/IMECaret), the IME freeze/settle
  machinery (IMEFrozen, markIMEScrollActive, imeSettleChan), and the
  window-relative imeRuneToByte.

Also fixed along the way (both found while chasing the corruption):

- real.ReadFileAt: loop over short reads. A single ReadAt on Android
  FUSE can return a short read, silently truncating a chunk and
  shifting every byte offset after it.
- logic: a late lazy-chunk result no longer clobbers a buffer that
  SetContent has already fully loaded.
- e2e: large-file IME test (1.6 MB file, fling + commit).
- app icon (scripts/make_icon.py + cmd/pad/appicon.png) so gogio
  builds the mipmap/adaptive icon set.

Verified: go vet + staticcheck, go test -race (all packages), and the
emulator scenario loop (open moby excerpt, fling to mid-file, tap,
type 'a', byte-compare the saved file) 75/75 clean.
This commit is contained in:
gmp
2026-09-13 11:57:38 -04:00
parent 4c8a13b779
commit f54ca2f81a
15 changed files with 1096 additions and 188 deletions
+1
View File
@@ -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
+107 -10
View File
@@ -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, "")
}
+22 -4
View File
@@ -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.
@@ -434,6 +435,14 @@ 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.IMEContext = ""
TheState.Editor.IMEContextStartByte = 0
TheState.Editor.IMEOffsetRune = 0
// Dispatch stat task to get file size
l.workerPool.Dispatch(pool.NewStatFileTask(path, l.mockFS))
@@ -753,7 +762,7 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
} else if res.TaskType == pool.TypeReadFile {
if res.Success {
if content, ok := res.Data.([]byte); ok {
if l.state.Editor.ChunkedBuffer != nil {
if l.state.Editor.ChunkedBuffer != nil {
// Full-load the in-range file: set the whole content (split into
// resident chunks). No lazy load, so no stale-disk re-read.
l.state.Editor.ChunkedBuffer.SetFileSize(int64(len(content)))
@@ -804,10 +813,19 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
if res.Success {
if chunk, ok := res.Data.([]byte); ok {
for len(cb.chunks) <= res.ChunkIdx {
cb.chunks = append(cb.chunks, nil)
// 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
}
cb.chunks[res.ChunkIdx] = chunk
}
} else {
log.Printf("Logic: ReadChunkTask failed for %s chunk %d: %v", res.FilePath, res.ChunkIdx, res.Error)
+275 -69
View File
@@ -83,12 +83,31 @@ 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
// 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
@@ -949,6 +968,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)
@@ -956,6 +976,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)
}
@@ -1949,6 +1970,7 @@ func HandleDelete() {
if w := utf8AdvanceWidth(seg); w > 0 {
buf.Delete(pos, w)
buf.UpdateLineIndexAfterDelete(pos, pos+w)
imeAnchorEdit(pos, seg[:w], "")
e.findEdit(pos, pos+w, 0)
markDirty()
}
@@ -1965,6 +1987,7 @@ func HandleDelete() {
}
w := utf8AdvanceWidth(str[pos:end])
TheState.Editor.Buffer = str[:pos] + str[pos+w:]
imeAnchorEdit(pos, str[pos:pos+w], "")
e.findEdit(pos, pos+w, 0)
markDirty()
}
@@ -1990,6 +2013,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()
@@ -2019,6 +2043,7 @@ func HandleBackspace() {
w := utf8BackspaceWidth(buf.Content(segStart, pos))
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()
@@ -2032,6 +2057,7 @@ func HandleBackspace() {
}
w := utf8BackspaceWidth(str[segStart:pos])
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()
@@ -2058,17 +2084,165 @@ 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
}
// lastRunesStart returns the byte offset where the last n runes of s begin
// (0 if s has fewer than n runes). It stops at rune boundaries, so the result
// never splits a UTF-8 sequence.
func lastRunesStart(s string, n int) int {
start := len(s)
for i := 0; i < n && start > 0; i++ {
start--
// Walk back over continuation bytes (0x80-0xBF) to the lead byte.
for start > 0 && s[start]&0xC0 == 0x80 {
start--
}
}
return start
}
// 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)
}
// imeLeadingContext returns up to 10 runes immediately before byte position
// start in the active buffer ("" at file start, or for too-large files). At
// most 64 bytes are scanned (10 runes * 4 bytes + margin).
func imeLeadingContext(start int) string {
if start <= 0 || TheState.Editor.TooLarge {
return ""
}
a := start - 64
if a < 0 {
a = 0
}
span := TheState.fileContent(a, start)
return span[lastRunesStart(span, 10):]
}
// 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).
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 {
@@ -2077,88 +2251,108 @@ 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
}
// 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
}
if endRune-startRune <= 2 {
caretRune := TheState.imeRuneOffsetAt(TheState.Editor.CursorPosition)
if endRune != caretRune {
log.Printf("IME DRIFT-SNAP range=[%d,%d) caret=%d -> snap to caret", startRune, endRune, caretRune)
startRune, endRune = caretRune, caretRune
}
}
absStart := windowStart + runeIndexToByteStr(windowText, startRune)
absEnd := windowStart + runeIndexToByteStr(windowText, endRune)
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) {
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
@@ -2430,7 +2624,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
@@ -2481,12 +2674,16 @@ 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.Editor.IMEContext = imeLeadingContext(start)
TheState.Editor.IMEContextStartByte = start - len(TheState.Editor.IMEContext)
TheState.Editor.IMEOffsetRune = TheState.imeRuneOffsetAt(TheState.Editor.IMEContextStartByte)
// 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
@@ -2571,6 +2768,13 @@ 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.IMEContext = TheState.Editor.IMEContext
editorElem.IMEOffset = TheState.Editor.IMEOffsetRune
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
@@ -2776,6 +2980,8 @@ func SetCursorFromPoint(x, y float64) {
ClearSelection()
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)
}
}