IME: fix random mid-word capitalization (stable snippet window + commit in-flight handling)

Gboard capitalizes the first character of a fresh input session and
derives its word context from the text it holds locally; it never
queries the app for context while typing. The editor was resetting that
session on essentially every event, so Gboard re-anchored to a fresh
session mid-word and caps went random:

- The pushed snippet WAS the render window. Any viewport change (keyboard
  show/hide animation, tap re-centering, scroll) changed the snippet, and
  gioui turns every snippet change into imm.restartInput — a full IME
  session reset. The snippet is now a hysteresis window around the caret
  (32 KB, re-anchor only when the caret is within 4 KB of an edge),
  decoupled from the render window: typing, taps within range, keyboard
  animation and flings never re-push it.
- gioui's EditEvent callback applies the commit to its own window state
  directly, so the op queue lags it by one commit; any frame event in
  the gap regressed the state and sent a restartInput with pre-commit
  text per keystroke. The drained commit is now applied to the pushed
  model immediately (Renderer.ApplyIMECommitToModel), and a short hold
  keeps stale pre-commit frames out of FlushIME until the logic's
  post-commit frame arrives.
- The layout feedback loop re-emitted on exact float equality of the
  derived last-line Y, spinning a re-emit -> shape -> re-emit loop
  (float-sum noise) that re-drew the editor and re-pushed IME state;
  gate it with a 0.5 dp epsilon.
- The render window bottom mapped through the WrapIndex whose
  in-viewport counts land while this very window is being shaped: the
  bottom oscillated frame to frame, resizing the window (and the old
  snippet) every frame. Use a fixed line span from the stable top
  instead (each logical line yields >= 1 visual line, so the viewport is
  always covered).

Result: zero snippet re-pushes during typing or flings (one re-anchor at
a far tap/file switch); emulator typing tests show all-lowercase
mid-word commits ('thaaaaaaaae', 'vapoaaaaaaaar') and the stress suite
(7 scenarios) passes clean with contiguous insertions only.
This commit is contained in:
gmp
2026-09-13 17:00:49 -04:00
parent 36b6a86873
commit dd9493bdbd
7 changed files with 309 additions and 149 deletions
+21 -8
View File
@@ -568,15 +568,28 @@ func (cb *ChunkedBuffer) visibleByteRangePrecise(scrollOffset ui.Dp, viewportHei
startLine = int(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 is still in VISUAL space: it is the visual line at the
// viewport bottom, so map it to the logical line that contains it,
// exactly like the top. Using the raw visual number as a logical
// index over-fetched the window by every wrapped line above the
// viewport — an over-fetch that grows without bound with scroll
// depth, so shaping/drawing (and therefore scroll responsiveness)
// degraded the further down the file you were.
endLine = w.LineForVisual(int32(endLine))
endLine = startLine + (bottomVisual - int(v0))
}
if startLine < 0 {
+10 -2
View File
@@ -356,7 +356,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()
}
@@ -440,6 +445,9 @@ func (l *Logic) openFile(path string) {
// 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
@@ -762,7 +770,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)))
+99 -36
View File
@@ -108,6 +108,24 @@ type EditorState struct {
// (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
// 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
@@ -2095,21 +2113,6 @@ func countRunes(s string) int {
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
@@ -2136,26 +2139,85 @@ func (s *State) bufferLen() int {
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).
// 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
}
}
// 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()
@@ -2353,7 +2415,6 @@ func applyIMECommitBytes(startByte, endByte int, text string) {
markDirty()
}
func markDirty() {
// Every content edit funnels through here, so EditSeq is the universal
// "content changed" token (the WrapIndex layout-correlation gate uses it).
@@ -2681,9 +2742,7 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
// 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)
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
@@ -2772,8 +2831,12 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
// 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.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.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