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
+30 -77
View File
@@ -213,6 +213,20 @@ type TextField struct {
// is running (the IME insets dispatches redraw the app), so the keyboard
// could not be dismissed. See TextField.Draw.
ShowIMESeq uint64
// IMEContext is the leading context (up to 10 runes immediately before
// the window start) that the renderer prepends to Value when pushing the
// IME snippet; IMEOffset is the absolute file rune offset where
// IMEContext begins (the pushed snippet's Range.Start). Computed by the
// logic layer at frame-build time; see Renderer.FlushIME and the IME
// fields on EditorState (IMEContext/IMEOffsetRune).
IMEContext string
IMEOffset int
// 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 +245,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,81 +267,28 @@ 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)
}
+136 -5
View File
@@ -110,10 +110,40 @@ 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
// 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 +263,97 @@ func (r *Renderer) pointInHandleBox(p image.Point) bool {
return false
}
func (r *Renderer) FlushIME(gtx layout.Context, tf TextField) {
ctxRunes := utf8.RuneCountInString(tf.IMEContext)
// The snippet is the visible window with up to 10 runes of leading
// context prepended, addressed from the absolute file rune where the
// context begins (tf.IMEOffset): the IME sees the true document
// position, and Android's TextUtils.getCapsMode
// (GioView.getCursorCapsMode) can find real preceding context instead of
// treating the top of the visible window as the start of a sentence.
//
// The snippet is pushed whenever the frame's text differs from the last
// push (window moved, edit applied, file switched). gioui dedupes a
// SnippetCmd against its own cache, so only real changes reach the OS as
// imm.restartInput. After a commit the frame text (the buffer with the
// commit applied) equals what the IME already holds locally, so the
// dedupe naturally suppresses the restart; a fling moves the window and
// re-anchors the IME exactly once per text change. Commit positions
// arriving while a restart is dropped (Gboard during flings) are caught
// by the logic-side drift guard (editor.HandleIMECommit), which snaps a
// small commit to the cursor — the position the IME was last told.
snippet := key.Snippet{
Range: key.Range{
Start: tf.IMEOffset,
End: tf.IMEOffset + ctxRunes + utf8.RuneCountInString(tf.Value),
},
Text: tf.IMEContext + tf.Value,
}
if snippet != r.lastSnippet {
r.lastSnippet = snippet
// The 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.
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.SelectionStart >= 0 && tf.SelectionEnd > tf.SelectionStart {
s, e := tf.SelectionStart, tf.SelectionEnd
if s < 0 {
s = 0
}
if e > len(tf.Value) {
e = len(tf.Value)
}
selStart = tf.IMEOffset + ctxRunes + runeCount(tf.Value, s)
selEnd = tf.IMEOffset + ctxRunes + runeCount(tf.Value, e)
} else {
selStart = -1
selEnd = tf.IMEOffset + ctxRunes + runeCount(tf.Value, tf.CursorPosition)
}
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
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{
@@ -1095,9 +1216,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{