Pinch-to-font-size (continuous, content-point pinned) + IME-open scroll fix

Two feature bodies accumulated in the working tree:

1. Pinch to change the app font size, continuously (no snapping):
   - internal/ui/pinch_tracker.go: logic-free touch state machine.
     Two-mover formation (the resting palm can land first or last;
     movement is the only signal valid for both), pair = the mover
     pair whose distance changed most, baseline = press distance
     (formDist), lazy pending releases, survivor-scroll forwarding
     after a pair break. Robust to ~1 fps frames: a whole pinch can
     land in one drain (formDist/brokeFactor/lazy releases).
   - render.go: pinch probe (raw pointer events) + grab lifecycle so
     the pair is exclusive (scroll sees nothing of the pair) and the
     survivor's finger keeps working as a scroll after the pinch.
   - state.go/logic.go/session.go/frame.go: app-local float font
     scale, content-point pin (buffer byte + offset from baseline,
     not a layout point, so rewrap keeps the same character under
     the center), restore/font pins, session persistence.
   - pinch_test.go, pinch_font_test.go, tag_identity_test.go,
     real_draw_probe_test.go: unit + real-Renderer/real-Router tests.

2. Soft keyboard must not shift content:
   - Root cause: gioui.org/app calls Router.RevealFocus on any frame
     the viewport shrinks (IME open under adjustResize) and
     synthesizes a pointer.Scroll nudge aimed at the focused field's
     stale pre-resize bounds; gesture.Scroll consumed it -> a 32 dp
     content jump.
   - Fix: main.go flags the shrink frame; render.go drains that one
     synthetic scroll for the gesture's tag before Update (scroll-
     range clamping cannot work: the router UNIONs ranges across
     frames). Finger scroll (pointer.Drag) and the flinger are
     untouched. reveal_focus_drain_test.go reproduces RevealFocus at
     the router level and verifies the drain + zero delta.

Also: tools/touchinject (platform-signed emulator multi-touch
injection harness + e2e script, adb has no two-finger input),
docs (spec 2.2 + development_plan 18-20), .gitignore, gofmt.
This commit is contained in:
gmp
2026-08-23 09:00:51 -04:00
parent 0f1b6e6290
commit 180fa966c8
23 changed files with 3302 additions and 45 deletions
+17
View File
@@ -111,6 +111,23 @@ There are TWO independent scale factors, not one:
(window start, sub-line remainder, tap mapping, scroll clamp, caret,
handles, highlight). Change it and the line pitch on screen changes
(57 px/line at 1.3× vs 44 px/line at 1.0× on this AVD).
- **App-local pinch font scale** (a third factor, in-app only): a two-finger
pinch in the editor multiplies a continuous float32 scale (1.0 default,
clamped 0.5–3.0, never rounded) on top of the two factors above; the
rendered line pitch is `16.8 × fontScale × appFontScale` dp. The logic
side folds it into `EffectiveLineHeight()` (system × app) and the
renderer multiplies the editor's sp size by it. The pinch CENTER is the
anchor: the logic captures the **content point** there (the glyph byte +
offset from its baseline, with a line/fragment/sub-line fallback) and
re-anchors it under every newly shaped layout — including the re-wrap a
few frames after the font change — so the character under the fingers
holds still, not merely its (rewrap-moved) visual line. It is persisted in
the relaunch session (`AppFontScale`), and
the session's `ScrollSub` is stored as a *fraction* of the line height so
scroll restore is font-independent. Test hook: `scripts/emu.sh cmd pinch
<F>` (relative, anchored at the editor region center) / `fontsize <F>`
(absolute, top-anchored) drive the same `HandleFontPinch` path a real
pinch delivers.
On-device verification notes:
+295
View File
@@ -1048,3 +1048,298 @@ Verified on device: with the exclusion active, horizontal drags from the
left-edge start handle no longer trigger `startBackNavigation`
(`dumpsys window` shows the exclusion region; logcat shows zero
back-gesture previews).
## 18. Pinch-to-change-font-size, continuous (2026-08-22)
A two-finger pinch in the editor now changes the app's font size smoothly,
without snapping to whole points. The app-local scale is a float32
(default 1.0, clamped 0.5–3.0) layered on top of the system user font
setting; it is never rounded anywhere in the pipeline.
**Renderer (`internal/ui`).** Gio v0.10 has no two-finger pinch primitive,
so the Renderer owns a probe event tag clipped to the editor text region
(next to the long-press probe). It tracks the active pointers across frames
(window-px positions keyed by pointer ID) and emits one relative factor per
frame — `pinchDist(cur)/pinchDist(prev)` — as `ui.FontPinchEvent` to the
editor's new `ui.Pinch` interaction handler. `pinchDist` (two lowest-ID
pointers) is a pure function, unit-tested. While a pinch is active, scroll
emission is suppressed so the first finger does not drag the text.
`drawWrappedText` multiplies the editor's sp size by the frame's
`AppFontScale` (main goroutine feeds it via `SetAppFontScale` before
Draw); ascent/line-height/highlight/caret/handles all follow because they
derive from the same size.
**Logic (`internal/editor`).** `State.appFontScale` + `HandleFontPinch`
(multiply by the per-frame factor and clamp). The anchor is the pinch
CENTER, not the viewport top — and it is a **content point**, not a layout
point: `State.captureContentPin` names the glyph under the midpoint (the
ABSOLUTE buffer byte — the layout's `ByteOffsets` are window-relative, so
the capture adds `IMEWindowStartByte` — plus the point's offset from that
glyph's baseline), captured under the pre-change layout. A rewrap moves
the *text* of a visual line (the same fragment index holds different bytes
after the rewrap), so pinning (line, fragment) would leave a different
character at the center; naming the byte does not. The offset is applied
in two phases: (1) immediately, `rescaleScrollAnchored` rescales `S + m`
about the center (continuous, valid until rewrap lands); (2) on **every
newly shaped layout at the current scale** — the re-shape after the font
change and the rewrap corrections that follow it — `refineContentPin`
recomputes the offset from the pinned byte's fresh baseline:
`S' = vk·lh + Y + Dy − m`, where `vk = VisualsBefore(WindowStartLine)` is
the window's FIRST visual line (the window top sits at content `vk·lh`,
NOT `floor(S/lh)·lh` — a different line whenever the viewport top lands
mid-way through a wrapped logical line) and `Y` is the byte's baseline in
the fresh layout (located by its absolute byte, window start from
`LayoutFeedback.WindowStartByte`). That lands the byte exactly on the
center and is a fixed point when the layout already agrees (no drift, no
oscillation). Two stale-data traps had to be closed: the scale change
**invalidates the last shaped layout** (`invalidateShapedLayout`) —
otherwise the next frame computes its window start with the OLD line
height and the NEW rescaled offset, a window ~10k lines off — and
`refreshFontPin` skips feedback shaped at a different scale (during a
pinch every frame changes the scale, so all but the latest feedback are
stale). While armed (2 s, refreshed by feedback) the pin rides every
frame; a (line, fragment, sub-line) anchor (`captureFontPin`/`applyFontPin`)
stands in for points off any glyph; an edit (EditSeq mismatch), a scroll,
or the timeout disarms it. `SetAppFontScale` (the `fontsize` debug
command) keeps the top-anchored behavior (no fingers to center on) and
invalidates the stale layout too. `EffectiveLineHeight()` is now system ×
app; every geometry consumer (window start, tap mapping, scroll clamp,
restore) was already routed through it. `Frame.AppFontScale` carries the
value to the renderer; `LayoutFeedback.ScrollOffset` carries the shaped
scroll back (used by the fallback path and diagnostics).
**Persistence.** The session snapshot gains `AppFontScale`, and
`ScrollSub` is now stored as a *fraction* of the line height (font-
independent; legacy Dp values > 1 are converted on restore).
**Testing.** `pinch_font_test.go` (continuous product of small factors,
clamp at both ends, center-anchor invariance, glyph hit-testing, content-
pin capture, the refine keeping the pinned BYTE on the center across a
rewrap that moves it to another fragment, the fixed-point property, the
(line, fragment) fallback, fragment clamp on pinch-out, bad-data no-op),
`pinch_test.go` (pinchDist/pinchMid geometry,
factor-series telescoping). On the emulator
(`scripts/emu.sh cmd pinch <F>` / `fontsize <F>` — one-shot commands that
drive the same `HandleFontPinch` path a real pinch delivers, since adb has
no two-finger input; `pinch` anchors at the editor-region center): five
×1.05 steps produced line pitches 44→46→49→51→54→56 px (autocorrelation-
measured) — continuous, no whole-point snapping; on a 40k-line wrapped
file scrolled to the middle, a pinch in/out cycle (×1.5 → ×0.75 →
×1.125) exercised the rewrap in BOTH directions (1→2 and 2→1 fragments
per line) and the pin converged to a fixed point within 2–3 layout-
feedback frames at every step, keeping the captured BYTE's line on the
region center (verified against the app's own geometry, not the pixels);
the ground-truth tap test (tap a line, type a marker, read the file)
passed at a 1.125× scale after two rewrapping pinches; `fontsize` keeps
the top anchor across a 1→2 rewrap; font scale, file, cursor and scroll
all survive a full restart; 0.5/3.0 clamps hold; one-finger scroll is
unaffected (and takes over the viewport, disarming the pin).
**Bugs found by the emulator round (both would have passed the unit
suite).** (1) `GlyphLayout.ByteOffsets` are window-relative, not absolute:
capturing the pin's byte without adding the window start made the pin
chase a moving offset and never converge. (2) The scale change left the
old `GlyphLayout` in place; the next frame computed its window start with
the OLD line height and the NEW rescaled offset — a window ~10k lines
from the viewport (visible as a ~1000-line jump). Fixed by
`invalidateShapedLayout()` on every scale change.
**Bug found by the on-device round (the emulator round could never have
found it — adb has no two-finger input, and the debug `pinch` command
bypasses the probe entirely).** On the phone a real two-finger pinch did
nothing. On-device logcat (probe event logs + per-frame event counts)
showed the scroll gesture receiving every finger move while both probe
tags received zero events. Root cause: the probes were declared as
`struct{}` fields of the Renderer. The unnamed fieldless `struct{}` is a
SINGLE canonical Go type, so `pressProbe`, `pinchProbe` (and a
diagnostic third) were the SAME tag value. Gio's router keys handlers by
tag value, so all three `event.Op` registrations collapsed into one
handler; the press probe's drain (which runs first in `CheckGestures`)
consumed every event for that tag and the pinch probe was structurally
starved. Fixed by giving each probe its own named type
(`pressProbeTag`, `pinchProbeTag`), with a regression test
(`TestProbeTagIdentity`) asserting the tags remain distinct map keys, and
`TestRealDrawOpsProbeHit`, which runs the real `Renderer.Draw` op stream
through a real `input.Router` and asserts the probe tags receive the
pointer press. Verified on the Pixel 9 Pro: 927 probe events across a
multi-pinch session, 137 per-frame factors emitted and applied (net
scale 1.70×, font visibly enlarged), scroll suppressed mid-pinch,
anchor held.
## 19. Pinch tracker: explicit pair, two-mover formation, slow frames (2026-08-23)
The §18 probe design ("two lowest-ID pointers") was replaced by an explicit
pair state machine (`internal/ui/pinch_tracker.go`, pure and unit-tested;
the renderer's `consumePinchProbe` is now a thin adapter that feeds events,
executes the tracker's grabs, and emits its factor). Four on-device failure
modes drove the rewrite, plus a whole class of slow-frame bugs only visible
on the ~1 fps emulator:
1. **Single-finger scroll changed the font** — the pair was re-derived from
whatever pointers happened to be present, so a scroll finger got paired
with a stale pointer and its drags became "pinch".
2. **Scroll-down enlarged the font** — same root: the scroll finger's
distance to a stale second pointer grows as it moves.
3. **Two fingers produced a sudden zoom before the pinch** — the baseline
(`prevDist`) survived from the previous pinch, so a new pinch 2.5× wider
emitted 2.5× on its first frame.
4. **Pinch-out stopped and became a scroll** — the pair was not explicit;
once a finger moved past the scroll slop the router handed the pointer
to the scroll gesture and the "pair" silently switched composition.
**Explicit, stable pair + grabs.** When the pair forms, the adapter issues
`pointer.GrabCmd` for BOTH fingers (exclusive delivery to the probe:
releases arrive even off-clip, and scroll/click are dropped with a Cancel —
so the pair can never be stolen mid-gesture, failure mode 4). The pair's
composition and its baseline are never re-derived from ambient pointers.
`factor()` = current pair distance / previous frame's distance, one factor
per frame (the Android driver replays historical samples — several drags per
frame — so the font sees one factor per frame, not per sample). A sanity
clamp drops factors outside 0.1–10 and advances the baseline, so a
teleporting pointer (ID-reuse noise) cannot jump the font. When a pair
finger lifts, the other becomes the **survivor**: it stays grabbed (Gio
v0.10 has no release-grab) and its drags are forwarded as a plain scroll
delta (`survivorScroll`), so the finger is not dead. A second finger that
returns re-forms the pair with a fresh baseline.
**Formation requires TWO MOVING fingers — and nothing else.** The dominant
real-world case is a palm edge already down when the two pinch fingers
land; a static rule about "which finger is the palm" (the oldest? the
newest? the still one?) cannot survive both palm-first and palm-last hand
lands. Movement is the only signal that works for both: while 2–3 fresh
fingers are down the tracker is *pending*; the pair forms — at `factor()`
time, after the whole frame's events, never per-event (per-event locking
in the first mover pair seen would pair a finger with a drifting palm) —
when two pending fingers have each moved more than `pinchMoveEps` (10 px)
from where they pressed, and it is the mover pair whose **distance**
changed most (a drifting palm's distance to a finger changes little; a
pinch's does). A lone mover is a scroll, never a pair; a unison movement
(a two-finger slide) leaves the distance unchanged and forms nothing.
Consequences verified: a resting (pruned, >300 ms) or still palm can never
enter the distance; the three fresh-fingers case pairs the pinch fingers;
the re-form candidate (a finger landing on a survivor) must also move
before it becomes the pair.
**Baseline = the PRESS distance.** Any spread that happened before the pair
starts is owed, not lost: the formation frame emits `d_current /
d_press`, and a pinch that breaks before its first `factor()` settles the
same owed factor at the break.
**Slow frames (the ~1 fps emulator batches a whole gesture into one
drain).** (a) *Born-and-dead in one frame*: presses, drags and BOTH
releases in one drain — pending releases are held **lazy** (`released`
map) until `factor()`: the pair forms at the fingers' final positions,
then breaks there (no survivor when both released), settling the owed
factor. (b) *Pair broke mid-frame*: `brokeFactor`/`brokeMid` are settled
at the break (against `prevDist`, or the press distance when fresh) and
emitted by the subsequent `factor()` call, which would otherwise see
`on==false` and drop the frame's movement.
**Emulator multi-touch injection.** adb has no two-finger input, so the
failure modes could not be tested end-to-end until `tools/touchinject`: a
platform-signed (AOSP test key, `INJECT_EVENTS` granted) toy app whose
broadcast receiver injects a scripted `MotionEvent` stream
(`down/move/up/wait`, display px) through
`InputManager.injectInputEvent` — `/dev/uhid` is a dead end (no kernel
module in the image). Two known flakes, both documented in the harness:
the receiver process is "cached" and the 1.5 GB emulator OOM-kills it
mid-script occasionally (the harness verifies `=== done` in logcat and
re-runs; service routing is blocked by Android 12+ background-start
restrictions, and the AVD's locked bootloader blocks the system-app
escalation); and burst drags (all moves within one frame's drain) do not
scroll — the app is on-demand-rendering at ~1 fps, so scroll tests space
the moves ~80 ms apart, which also matches what a real finger produces
over several frames.
**End-to-end results (real injected MotionEvents, big wrapped file).**
Single-finger drag: zero factors, scale unchanged (font), content scrolls.
Two-finger pinch-out 300→596 px: exactly one factor 596/300 = 1.98667,
font ~2×. Palm-first three fingers (palm resting and still, pinch fingers
landing 80/120 ms later): pair is the two pinch fingers — the factor
tracks the pinch, the palm never enters the distance. Lift one finger
mid-pinch: the factor stream stops at the lift (font frozen), the
survivor's 600 px drag scrolls the content 600/3.5 = 171.4 dp. The
one-frame leak at formation (the pair's own drags of the formation frame
still reach scroll, since the grabs commit next frame) is bounded by the
scroll slop — the deliberate cost of not grabbing on press, which would
kill single-finger scrolls.
**Testing.** `pinch_test.go` now covers: factor-series telescoping
(baseline = press distance), single-finger never scales, resting/stale
palm excluded, extra finger during an active pinch ignored, fresh baseline
per pinch, sanity clamp, the three slow-frame shapes (full pinch in one
frame, stationary born-dead, born-and-dead), palm-first three fingers,
and survivor scroll + re-form (candidate must move).
`real_draw_probe_test.go` runs the real `Renderer.Draw` op stream through
a real `input.Router`: press frame (pending, nothing), formation frame
(grabs + owed factor, one-frame scroll leak), post-formation frames (scroll
sees nothing of the pair), off-clip survival, release via the grab,
survivor scroll forwarding, re-form.
## 20. IME open: content must not shift (2026-08-23)
**Bug.** With the soft keyboard open (adjustResize), the editor content
jumped up by exactly 32 dp (112 px) every time the keyboard appeared.
Top-anchored layout keeps the window start line put when only the
viewport height changes, so the shift was not our layout: KBW
instrumentation of every `ScrollOffset` writer showed
`HandleScroll` receiving a single +112 px delta at the resize frame.
**Root cause (Gio, not the app).** `gioui.org/app` `window.go`, on every
frame whose viewport *shrank*, calls `Router.RevealFocus(viewport)` —
"scroll the focused widget into view". For a text editor the focused
field's registered bounds (stale — from the pre-resize, taller frame)
extend below the new viewport, so RevealFocus synthesizes a
`pointer.Scroll` event (`Source: Touch`, position (0,0), Y = the nudge)
delivered to the focused field's scroll handler. `gesture.Scroll`
consumes it like any wheel scroll → `HandleScroll` → the 32 dp jump.
The event is invisible to the app: it never enters the pointer queue
(no `MotionEvent` on the Android side), it is manufactured by the router
during `processEvent(frameEvent)`, before the app's frame handler runs.
Reproduced at the router level: `RevealFocus` on a shrunken viewport
queues exactly one scroll event for the gesture's tag.
**Why not the obvious fixes.**
- Zeroing the scroll *range* on the shrink frame does nothing: the router
UNIONs scroll ranges into the handler's filter across frames
(`pointerFilter.Add`/`Merge`), so the historical max can never shrink
back to zero — the clamp stays at ±∞ forever.
- Patching `app/window.go` to drop the shrink→RevealFocus call would mean
shipping a forked gioui (the build constraint is clean v0.10.0).
- `adjustNothing` removes the resize but hides the cursor line under the
keyboard.
**Fix (app-side, two files).**
- `cmd/pad/main.go`: on each `FrameEvent`, detect a shrink
(`e.Size` smaller than the previous frame's) and set
`renderer.ZeroWheelScroll` for that one frame.
- `internal/ui/render.go` (`CheckGestures`): when flagged, drain
`pointer.Scroll` events for the editor scroll gesture's tag
(`q.Event(pointer.Filter{Target: reg.scroll, Kinds: pointer.Scroll})`)
before `gesture.Scroll.Update` consumes anything. Only the synthesized
nudge matches: finger scroll is `pointer.Drag`, inertia is the
flinger, and on a phone there is no trackpad wheel. Normal frames are
untouched.
**Verification.**
- `reveal_focus_drain_test.go`: real `input.Router` + real
`Renderer.Draw` ops; the focused field (KeyDown interaction required —
it records the `event.Op` tag reference, and a per-frame
`key.FocusFilter` consumer marks the handler focusable, else the key
queue clears the focus each frame), shrunken viewport, `RevealFocus` →
exactly one synthetic scroll queued for the gesture tag; the drain
terminates and `gesture.Scroll.Update` then returns 0.
- Emulator E2E (real injected taps, keyboard really opens, window
2560→1527 px): pre-fix the scroll gesture emitted delta=112 on the
shrink frame and a screenshot cross-correlation showed a 112 px content
shift; post-fix the drain consumes the event, the gesture delta is 0,
and the cross-correlation shift is 0 (corr 0.987). The perf-CSV
(ScrollDP per logic frame) shows no 32 dp step when the keyboard opens
on the final build.
**Notes.** The `aosp_atd` emulator later started ANR-ing Pad on first
frame — the ANR trace shows the main thread in
`GioView.onFrameCallback` → `glDeleteBuffers` → gfxstream guest →
`madvise` (91 s system time): the emulated GPU's buffer-free path,
unrelated to input handling. Final verification therefore used a small
file (fast first frame) plus the router-level test.
+28
View File
@@ -60,6 +60,34 @@ elsewhere.
hardware keyboard, arrow keys, Home/End, and Page Up/Down move the cursor
(verified on the Android emulator; Gio's mobile focus-navigation default
for arrow keys is overridden — see architecture.md §2.1).
- **Soft keyboard does not shift content:** opening or closing the IME
resizes the window (adjustResize); the editor is top-anchored, so the
visible text stays put. Gio's window otherwise synthesizes a scroll-to-
focus nudge on any frame the viewport shrinks (RevealFocus, aimed at the
focused field's stale pre-resize bounds), which would shift the content
up; the app drains that one synthetic scroll on the shrink frame
(development_plan.md §20).
- **Pinch to change font size:** a two-finger pinch inside the editor text
changes the app's font size continuously — the rendered size tracks the
inter-finger distance with no snapping to whole points (the scale is a
float32 multiplied by the per-frame distance ratio, clamped to 0.5×–3.0×
of the 14sp base). It is an *app-local* scale layered on top of the
system user font setting. The CONTENT UNDER THE PINCH CENTER STAYS
FIXED: the logic captures the **content point** under the finger
midpoint — the glyph byte and the point's offset from that glyph's
baseline — and re-derives the scroll offset to keep that point on the
center. A content point, not a layout point: when the font change
re-wraps a line, a *visual* line's text moves (fragment 2 of the new
wrap is different text), so pinning (line, fragment) would leave a
different character at the center. The pin therefore names the
character itself (byte + baseline offset) and re-anchors it under every
newly shaped layout — the re-wrap included — which is what keeps the
character under the fingers through the rewrap. (A (line, fragment,
sub-line) anchor stands in as fallback for points off any glyph.)
Single-finger scroll is suppressed mid-pinch (the pinch owns the two
fingers) and takes over the viewport on the first scroll after the
pinch. The scale is part of the relaunch session (§2.4) and survives
restarts.
- **Text selection:** two input paths. **Touch** (the Android-native model):
long-press selects the word under the finger (on a blank spot it places the
caret and offers a paste-only menu); double-tap selects the word; the