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:
+15
-26
@@ -213,20 +213,26 @@ 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
|
||||
// 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
|
||||
// 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" }
|
||||
@@ -293,23 +299,6 @@ func (tf TextField) Draw(gtx layout.Context, r *Renderer) {
|
||||
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{
|
||||
|
||||
+121
-36
@@ -110,6 +110,7 @@ type Renderer struct {
|
||||
lastIMEField string
|
||||
lastWasFocused bool
|
||||
lastSnippet key.Snippet
|
||||
|
||||
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}
|
||||
@@ -128,7 +129,6 @@ type Renderer struct {
|
||||
// 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
|
||||
@@ -144,6 +144,20 @@ type Renderer struct {
|
||||
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(s) drawn in the gap are pre-commit; their
|
||||
// snippets would clobber the model with the stale text, regressing
|
||||
// gioui's editor state and causing a restart per keystroke. While the
|
||||
// hold is active, FlushIME skips a frame whose EditSeq equals the
|
||||
// pre-commit sequence and resumes on the next one.
|
||||
imeHoldActive bool
|
||||
imeHoldEditSeq uint64
|
||||
imeHoldFrames int
|
||||
// lastEditSeq: the EditSeq of the last editor frame drawn (the
|
||||
// pre-commit sequence when an IME commit is in flight).
|
||||
lastEditSeq int64
|
||||
|
||||
// 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
|
||||
@@ -263,56 +277,127 @@ 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.
|
||||
func (r *Renderer) ApplyIMECommitToModel(gtx layout.Context, ev key.EditEvent) {
|
||||
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).
|
||||
r.imeHoldActive = true
|
||||
r.imeHoldEditSeq = uint64(r.lastEditSeq)
|
||||
r.imeHoldFrames = 0
|
||||
caret := ev.Range.End + utf8.RuneCountInString(ev.Text)
|
||||
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) {
|
||||
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.
|
||||
// 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 no-op commit (no EditSeq advance) 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
|
||||
}
|
||||
if tf.EditSeq > 0 {
|
||||
r.lastEditSeq = int64(tf.EditSeq)
|
||||
}
|
||||
// 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.IMEOffset,
|
||||
End: tf.IMEOffset + ctxRunes + utf8.RuneCountInString(tf.Value),
|
||||
Start: tf.IMESnippetStartRune,
|
||||
End: tf.IMESnippetEndRune,
|
||||
},
|
||||
Text: tf.IMEContext + tf.Value,
|
||||
Text: tf.IMESnippetText,
|
||||
}
|
||||
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.
|
||||
// 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.)
|
||||
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)
|
||||
if tf.IMESelStartRune >= 0 && tf.IMESelEndRune > tf.IMESelStartRune {
|
||||
selStart, selEnd = tf.IMESelStartRune, tf.IMESelEndRune
|
||||
} else {
|
||||
selStart = -1
|
||||
selEnd = tf.IMEOffset + ctxRunes + runeCount(tf.Value, tf.CursorPosition)
|
||||
selEnd = tf.IMECaretRune
|
||||
}
|
||||
selectionJumped := selStart != r.lastSelStart || selEnd != r.lastSelCaret
|
||||
caretMoved := r.imeCaretPos != r.lastIMECaretPos
|
||||
|
||||
Reference in New Issue
Block a user