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
+18
View File
@@ -900,6 +900,11 @@ const (
// The renderer registers the underlying gesture.Drag ops itself (it owns
// the handle geometry); this interaction just delivers the logic handler.
SelDrag
// Pinch is a two-finger pinch inside the element's text region. The
// renderer owns the probe (it needs raw two-pointer geometry that no
// single gesture primitive in Gio v0.10 provides); this interaction just
// delivers the logic handler, which receives FontPinchEvent.
Pinch
)
// Interaction pairs a gesture type with a handler function.
@@ -950,6 +955,19 @@ type SelectionDragEvent struct {
// SelectionDragEnd is emitted when a selection/caret drag is released.
type SelectionDragEnd struct{}
// FontPinchEvent carries one frame's relative two-finger pinch factor
// (current inter-finger distance / previous frame's distance, both in px).
// The logic applies it as a multiplier to the app-local font scale; the
// value is a plain float32 ratio with no rounding, so the font size is
// continuous, never snapped to whole points. Center is the pinch midpoint
// (the average of the two fingers) in app-local window Dp — the same space
// as Point; the logic anchors the content under this point so it stays put
// while the font scales.
type FontPinchEvent struct {
Scale float32
Center Point
}
// MenuItem is one button in the selection menu.
// X/Y/W/H are relative to the Menu region.
type MenuItem struct {
+510
View File
@@ -0,0 +1,510 @@
package ui
import (
"math"
"testing"
"time"
"gioui.org/f32"
"gioui.org/io/pointer"
)
// pev builds a synthetic pointer event. Time is explicit: the Android driver
// supplies it per event and the freshness window runs on it.
func pev(kind pointer.Kind, id pointer.ID, x, y float32, at time.Duration) pointer.Event {
return pointer.Event{Kind: kind, PointerID: id, Position: f32.Point{X: x, Y: y}, Time: at}
}
// ms/s are time helpers so test timelines read as intended (a bare integer
// constant is nanoseconds — the first draft's "2000ms" was 2µs).
func ms(n int) time.Duration { return time.Duration(n) * time.Millisecond }
func s(n int) time.Duration { return time.Duration(n) * time.Second }
// runFrame feeds a batch of events (one frame's drain) through the tracker
// and returns the frame's factor, the grabs it asked for, and the
// survivor-finger scroll, mirroring consumePinchProbe.
func runFrame(t *pinchTracker, evts ...pointer.Event) (f float32, mid f32.Point, ok bool, grabs []pointer.ID, scroll int) {
for _, e := range evts {
if s := t.step(e); len(s.grabs) > 0 {
grabs = append(grabs, s.grabs...)
}
}
f, mid, ok, g2 := t.factor()
grabs = append(grabs, g2...)
scroll = t.survivorScroll()
return
}
// approx reports whether a and b are within 1e-3.
func approx(a, b float64) bool { return math.Abs(a-b) < 1e-3 }
// A clean two-finger pinch: the pair forms when BOTH fingers move (the
// two-mover rule), owes the spread that happened by then (baseline = press
// distance), then one factor per frame whose product telescopes to the total
// distance ratio — the property that makes the font track the fingers.
func TestTrackerPinchFactorSeries(t *testing.T) {
var tr pinchTracker
// Frame 1: both fingers down 200px apart. Pending: no pair, no grabs,
// no factor (a press alone is not a pinch).
_, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1),
)
if ok || len(grabs) != 0 {
t.Fatalf("press-only frame: ok=%v grabs=%v want nothing", ok, grabs)
}
// Frames 2-4: the pair spreads 200 -> 240 -> 300 -> 250. Frame 2 is the
// formation: both fingers moved 20px (movers), grabs issued, and the
// owed factor is measured against the PRESS distance (200).
f2, _, ok2, g2, _ := runFrame(&tr,
pev(pointer.Drag, 0, 80, 100, 10),
pev(pointer.Drag, 1, 320, 100, 11),
)
if !ok2 || !approx(float64(f2), 240.0/200) {
t.Fatalf("f2=%v ok=%v want %v", f2, ok2, 240/200)
}
if len(g2) != 2 {
t.Fatalf("formation frame must grab both fingers, got %v", g2)
}
f3, mid3, ok3, _, _ := runFrame(&tr,
pev(pointer.Drag, 0, 50, 100, 20),
pev(pointer.Drag, 1, 350, 100, 21),
)
if !ok3 || !approx(float64(f3), 300.0/240) {
t.Fatalf("f3=%v ok=%v want %v", f3, ok3, 300/240)
}
if mid3 != (f32.Point{X: 200, Y: 100}) {
t.Fatalf("mid3=%v want (200,100)", mid3)
}
f4, _, ok4, _, _ := runFrame(&tr,
pev(pointer.Drag, 0, 125, 100, 30),
pev(pointer.Drag, 1, 375, 100, 31),
)
if !ok4 || !approx(float64(f4), 250.0/300) {
t.Fatalf("f4=%v ok=%v want %v", f4, ok4, 250.0/300)
}
total := f2 * f3 * f4
if !approx(float64(total), 250.0/200) {
t.Fatalf("product=%v want total ratio %v", total, 250/200)
}
}
// A single finger — press, hold, long scroll — must never produce a factor
// or a grab. This is the device regression "one-finger scroll changes the
// font": the old code paired the scroll finger with whatever stale pointer
// was in the map.
func TestTrackerSingleFingerNeverScales(t *testing.T) {
var tr pinchTracker
// A pinch earlier in the session...
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1),
)
runFrame(&tr,
pev(pointer.Drag, 0, 80, 100, 10),
pev(pointer.Drag, 1, 320, 100, 11),
)
runFrame(&tr,
pev(pointer.Release, 0, 80, 100, 20),
pev(pointer.Release, 1, 320, 100, 21),
)
// ...now a single finger scrolls for many frames.
for i := 0; i < 20; i++ {
y := float32(400 - i*20)
_, _, ok, grabs, scroll := runFrame(&tr,
pev(pointer.Drag, 5, 200, y, time.Duration(100+i*10)))
if ok || len(grabs) != 0 || scroll != 0 {
t.Fatalf("frame %d: single finger produced factor ok=%v grabs=%v scroll=%v",
i, ok, grabs, scroll)
}
}
// Fresh pointer IDs (Android resets them after full release) — still nothing.
_, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Press, 0, 200, 500, 500),
)
if ok || len(grabs) != 0 {
t.Fatalf("fresh single finger: ok=%v grabs=%v", ok, grabs)
}
for i := 0; i < 10; i++ {
_, _, ok, grabs, _ = runFrame(&tr,
pev(pointer.Drag, 0, 200, float32(500-i*15), time.Duration(510+i*10)))
if ok || len(grabs) != 0 {
t.Fatalf("scroll frame %d: ok=%v grabs=%v", i, ok, grabs)
}
}
}
// Device regression "sudden dramatic zoom before pinching": a finger that
// has been RESTING (palm edge, parked pinky) must not be paired with a new
// one. The freshness window prunes it; the pair forms only from fresh
// fingers.
func TestTrackerRestingFingerNotPaired(t *testing.T) {
var tr pinchTracker
// Palm rests at t=0.
_, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Press, 3, 600, 800, 0))
if ok || len(grabs) != 0 {
t.Fatal("one resting finger must not pinch")
}
// At t=2s the thumb lands: the palm is stale (>300ms) and pruned.
_, _, ok, grabs, _ = runFrame(&tr,
pev(pointer.Press, 0, 100, 100, s(2)),
pev(pointer.Drag, 3, 605, 800, s(2)+ms(1)), // palm still there, drifting
)
if ok || len(grabs) != 0 {
t.Fatalf("resting palm + new finger must not form a pair (ok=%v grabs=%v)", ok, grabs)
}
// At t=2.1s the index lands: two fresh fingers -> pending (formation
// waits for a third finger or the first movement; the palm is stale).
_, _, _, grabs, _ = runFrame(&tr,
pev(pointer.Press, 1, 300, 100, s(2)+ms(100)))
if len(grabs) != 0 {
t.Fatalf("pending pair must not grab yet, grabs=%v", grabs)
}
// The palm keeps drifting and the pair starts moving: the pair is
// (thumb, index) and its distance is unaffected by the palm.
f, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Drag, 3, 640, 810, s(2)+ms(200)), // palm moves (pruned, ignored)
pev(pointer.Drag, 0, 80, 100, s(2)+ms(201)),
pev(pointer.Drag, 1, 320, 100, s(2)+ms(202)),
)
if len(grabs) != 2 {
t.Fatalf("thumb+index must form the pair on movement, grabs=%v", grabs)
}
if !ok || !approx(float64(f), 240.0/200) {
t.Fatalf("f=%v ok=%v want %v (palm must not enter the distance)", f, ok, 240/200)
}
}
// Device regression "pinch dies and becomes scroll": the pair must survive
// finger movement past the scroll slop. In the router this is guaranteed by
// the grabs (scroll is dropped from the pair's path); here we assert the
// state machine keeps emitting factors for a pair that moves a lot, and
// ignores drags of pointers that are not the pair.
func TestTrackerPinchSurvivesLargeMoves(t *testing.T) {
var tr pinchTracker
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1))
// Big outward moves (far past the ~30px scroll slop), 5 frames.
want := []float32{1.5, 1.4, 1.3, 1.2, 1.1}
d := 200.0
for i := 0; i < 5; i++ {
d *= float64(want[i])
half := d / 2
_, _, ok, _, _ := runFrame(&tr,
pev(pointer.Drag, 0, 200-float32(half), 100, time.Duration(10+i*10)),
pev(pointer.Drag, 1, 200+float32(half), 100, time.Duration(11+i*10)),
)
if !ok {
t.Fatalf("frame %d: factor stopped (pinch died)", i)
}
}
}
// Lifting one finger of the pair: no more factors (the pair is gone), the
// survivor's drags come out as scroll (forwarded), and returning a second
// finger re-forms the pair with a fresh baseline.
func TestTrackerSurvivorScrollAndReform(t *testing.T) {
var tr pinchTracker
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1))
// Pinch in a bit.
runFrame(&tr,
pev(pointer.Drag, 0, 80, 100, 10),
pev(pointer.Drag, 1, 320, 100, 11))
// Finger 0 lifts. Finger 1 survives.
_, _, ok, _, _ := runFrame(&tr,
pev(pointer.Release, 0, 80, 100, 20))
if ok {
t.Fatal("broken pair must not emit a factor")
}
// The survivor scrolls: 40px up over two frames -> +40, +25.
_, _, _, _, scroll := runFrame(&tr,
pev(pointer.Drag, 1, 320, 60, 30))
if scroll != 40 {
t.Fatalf("survivor scroll=%d want 40", scroll)
}
_, _, _, _, scroll = runFrame(&tr,
pev(pointer.Drag, 1, 320, 35, 40))
if scroll != 25 {
t.Fatalf("survivor scroll=%d want 25", scroll)
}
// A second finger returns: CANDIDATE for a re-form; the pair re-forms
// only when the new finger MOVES (two-mover rule — a palm resting on
// the survivor is not a pinch).
_, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Press, 2, 50, 35, 50))
if ok || len(grabs) != 0 {
t.Fatalf("candidate press must not re-form yet (ok=%v grabs=%v)", ok, grabs)
}
f, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Drag, 1, 320, 35, 60),
pev(pointer.Drag, 2, 30, 35, 61)) // 20px from press: a real second finger
if len(grabs) != 1 || grabs[0] != 2 {
t.Fatalf("re-form grabs=%v want [2] (only the new finger)", grabs)
}
// Baseline = the distance at the candidate's PRESS (270 = 320-50); the
// spread to 290 by re-form time is owed, not lost.
if !ok || !approx(float64(f), 290.0/270) {
t.Fatalf("post-reform f=%v ok=%v want %v", f, ok, 290/270)
}
// Survivor lifts: fully idle again.
_, _, ok, _, scroll = runFrame(&tr,
pev(pointer.Release, 1, 320, 35, 70))
if ok || scroll != 0 {
t.Fatal("idle state must emit nothing")
}
}
// Device regression "dramatic zoom before the pinch starts": a NEW pinch
// must never emit a factor on its formation frame, even if the previous
// pinch ended at a very different distance (stale baseline).
func TestTrackerFreshBaselineEachPinch(t *testing.T) {
var tr pinchTracker
// Pinch A at ~200px.
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1))
runFrame(&tr,
pev(pointer.Release, 0, 100, 100, 10),
pev(pointer.Release, 1, 300, 100, 11))
// Pinch B starts 500px apart (the fingers landed far apart). The old
// code would have emitted 500/200 = 2.5x on the first frame.
_, _, ok, _, _ := runFrame(&tr,
pev(pointer.Press, 0, 0, 100, 100),
pev(pointer.Press, 1, 500, 100, 101))
if ok {
t.Fatal("second pinch's formation frame must not emit a factor (stale baseline)")
}
f, _, ok, _, _ := runFrame(&tr,
pev(pointer.Drag, 0, -20, 100, 110),
pev(pointer.Drag, 1, 520, 100, 111))
if !ok || !approx(float64(f), 540.0/500) {
t.Fatalf("f=%v ok=%v want %v (baseline = this pinch's own start)", f, ok, 540/500)
}
}
// A third finger landing DURING an active pinch is ignored (palm rest): the
// pair is fixed, its distance is untouched, and no extra grabs are issued.
func TestTrackerExtraFingerDuringPinchIgnored(t *testing.T) {
var tr pinchTracker
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1))
// Palm lands and sits.
_, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Press, 4, 700, 900, 10))
if ok || len(grabs) != 0 {
t.Fatalf("extra finger during pinch: ok=%v grabs=%v", ok, grabs)
}
// Palm drifts a bit; the two pinch fingers move (forming the pair); the
// palm is not in the pair and its distance is untouched.
f, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Drag, 4, 710, 910, 20), // 14px: a mover, but its distance to the fingers changes little
pev(pointer.Drag, 0, 80, 100, 21),
pev(pointer.Drag, 1, 320, 100, 22))
if len(grabs) != 2 {
t.Fatalf("pinch fingers must form the pair, grabs=%v", grabs)
}
if !ok || !approx(float64(f), 240.0/200) {
t.Fatalf("f=%v ok=%v want %v", f, ok, 240/200)
}
// Palm lifts: still nothing.
_, _, ok, _, _ = runFrame(&tr,
pev(pointer.Release, 4, 750, 950, 30))
if ok {
t.Fatal("palm release must not emit a factor")
}
}
// A global cancel (app switch) breaks the pair with no survivor.
func TestTrackerCancelBreaksPair(t *testing.T) {
var tr pinchTracker
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1))
runFrame(&tr,
pev(pointer.Drag, 0, 80, 100, 10),
pev(pointer.Drag, 1, 320, 100, 11))
// App switch: cancels for both pointers.
_, _, ok, _, scroll := runFrame(&tr,
pev(pointer.Cancel, 0, 0, 0, 20),
pev(pointer.Cancel, 1, 0, 0, 21))
if ok || scroll != 0 {
t.Fatal("cancel must break the pair cleanly")
}
// The cancelled drags must not resurrect anything.
_, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Drag, 0, 70, 100, 30))
if ok || len(grabs) != 0 {
t.Fatal("post-cancel drags must be inert")
}
}
// A finger that leaves the region pre-pinch is no longer a candidate:
// press-leave-press must not form a pair.
func TestTrackerLeaveCancelsCandidate(t *testing.T) {
var tr pinchTracker
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0))
runFrame(&tr,
pev(pointer.Drag, 0, 500, 1500, 10), // leaves the region
pev(pointer.Leave, 0, 500, 1500, 11))
_, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Press, 1, 300, 100, 20))
if ok || len(grabs) != 0 {
t.Fatalf("leaving finger must not pair with a new one (ok=%v grabs=%v)", ok, grabs)
}
}
// A pair broken by one finger lifting, then the survivor lifting too: the
// state must be fully idle (a later single-finger scroll emits nothing).
func TestTrackerFullyIdleAfterSurvivorLift(t *testing.T) {
var tr pinchTracker
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1))
runFrame(&tr,
pev(pointer.Release, 0, 100, 100, 10))
runFrame(&tr,
pev(pointer.Drag, 1, 300, 60, 20)) // survivor scrolls
runFrame(&tr,
pev(pointer.Release, 1, 300, 60, 30))
for i := 0; i < 5; i++ {
_, _, ok, grabs, scroll := runFrame(&tr,
pev(pointer.Drag, 1, 300, float32(60-i*20), time.Duration(40+i*10)))
if ok || len(grabs) != 0 || scroll != 0 {
t.Fatalf("frame %d: not idle (ok=%v grabs=%v scroll=%v)", i, ok, grabs, scroll)
}
}
}
// The sanity clamp: a factor outside 0.1..10 (teleporting pair) is dropped
// and the baseline advances, so one bad frame cannot jump the font.
func TestTrackerSanityClamp(t *testing.T) {
var tr pinchTracker
runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1))
// Teleport: finger 0 jumps 3000px (ID-reuse noise) while finger 1 moves
// 20px: both are movers, the pair forms, distance 200 -> 2800, factor
// 14x — must be dropped, baseline advanced.
f, _, ok, _, _ := runFrame(&tr,
pev(pointer.Drag, 0, 3100, 100, ms(10)),
pev(pointer.Drag, 1, 320, 100, ms(11)))
if ok {
t.Fatalf("implausible factor emitted: %v", f)
}
// Next frame is sane relative to the NEW baseline (2800px).
f, _, ok, _, _ = runFrame(&tr,
pev(pointer.Drag, 0, 3050, 100, ms(20)),
pev(pointer.Drag, 1, 325, 100, ms(21)))
if !ok || !approx(float64(f), 2725.0/2780) {
t.Fatalf("f=%v ok=%v want %v", f, ok, 2725.0/2780)
}
}
// A slow frame: the whole pinch (formation + spread + both releases) can
// arrive in ONE frame's drain (the Android driver replays historical samples
// and a low frame rate batches events). The factors must still be owed:
// the formation-frame movement relative to the formation distance, and the
// final movement settled when the pair breaks.
func TestTrackerSlowFrameFullPinch(t *testing.T) {
var tr pinchTracker
// Frame 1: both Presses (200px apart) and drags out to 300px, all in
// one drain. The pair forms at 200 and moved to 300 this frame:
// factor 300/200 owed.
f, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1),
pev(pointer.Drag, 0, 50, 100, 2),
pev(pointer.Drag, 1, 350, 100, 3))
if !ok || !approx(float64(f), 300.0/200) {
t.Fatalf("f1=%v ok=%v want %v (formation-frame movement is owed)", f, ok, 300.0/200)
}
if len(grabs) != 2 {
t.Fatalf("grabs=%v want 2", grabs)
}
// Frame 2: spread to 400px, then both fingers lift — same drain. The
// 400/300 factor must be settled at the break, not lost.
f, _, ok, _, _ = runFrame(&tr,
pev(pointer.Drag, 0, 0, 100, 10),
pev(pointer.Drag, 1, 400, 100, 11),
pev(pointer.Release, 0, 0, 100, 12),
pev(pointer.Release, 1, 400, 100, 13))
if !ok || !approx(float64(f), 400.0/300) {
t.Fatalf("f2=%v ok=%v want %v (break settles the owed factor)", f, ok, 400.0/300)
}
// Fully idle after the break.
if _, _, ok, _, scroll := runFrame(&tr,
pev(pointer.Drag, 1, 400, 80, 20)); ok || scroll != 0 {
t.Fatal("tracker must be idle after both releases")
}
}
// A stationary pair that forms and then breaks without moving owes nothing.
func TestTrackerSlowFrameNoMovement(t *testing.T) {
var tr pinchTracker
if _, _, ok, _, _ := runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1),
pev(pointer.Release, 0, 100, 100, 2),
pev(pointer.Release, 1, 300, 100, 3)); ok {
t.Fatal("stationary pair that breaks must not emit a factor")
}
}
// The worst case (a ~1fps emulator frame): the ENTIRE pinch — formation,
// spread, and both releases — lands in one frame's drain. The owed factor
// is settled at the break against the formation distance.
func TestTrackerBornAndDeadInOneFrame(t *testing.T) {
var tr pinchTracker
f, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Press, 0, 100, 100, 0),
pev(pointer.Press, 1, 300, 100, 1),
pev(pointer.Drag, 0, 0, 100, 2),
pev(pointer.Drag, 1, 400, 100, 3),
pev(pointer.Release, 0, 0, 100, 4),
pev(pointer.Release, 1, 400, 100, 5))
if !ok || !approx(float64(f), 400.0/200) {
t.Fatalf("f=%v ok=%v want %v", f, ok, 400.0/200)
}
if len(grabs) != 2 {
t.Fatalf("grabs=%v want 2", grabs)
}
if _, _, ok, _, _ := runFrame(&tr,
pev(pointer.Drag, 1, 400, 80, 10)); ok {
t.Fatal("idle tracker must not emit")
}
}
// Palm-first three-finger: the palm edge is resting and still, then the two
// pinch fingers land (all within the freshness window). The pair must be the
// two NEWEST fingers — the pinch pair — not the palm.
func TestTrackerPalmFirstThreeFingers(t *testing.T) {
var tr pinchTracker
// Palm rests at t=0 (still), pinch fingers land 80/120ms later.
// Pending: no pair yet (movement decides).
_, _, _, grabs, _ := runFrame(&tr,
pev(pointer.Press, 3, 720, 400, 0),
pev(pointer.Press, 0, 570, 1200, ms(80)),
pev(pointer.Press, 1, 870, 1200, ms(120)))
if len(grabs) != 0 {
t.Fatalf("pending: no grabs yet, got %v", grabs)
}
// The pinch spreads 300 -> 596 while the palm stays put: the two MOVERS
// (the pinch fingers) form the pair, and the factor must track the
// pinch pair — not the palm.
f, _, ok, grabs, _ := runFrame(&tr,
pev(pointer.Drag, 0, 422, 1200, ms(200)),
pev(pointer.Drag, 1, 1018, 1200, ms(201)),
pev(pointer.Drag, 3, 720, 400, ms(202))) // palm still
if len(grabs) != 2 || (grabs[0] != 0 && grabs[0] != 1) || (grabs[1] != 0 && grabs[1] != 1) {
t.Fatalf("pair must be the two pinch fingers, grabs=%v", grabs)
}
if !ok || !approx(float64(f), 596.0/300) {
t.Fatalf("f=%v ok=%v want %v (palm must not enter the distance)", f, ok, 596.0/300)
}
}
+470
View File
@@ -0,0 +1,470 @@
package ui
import (
"math"
"time"
"gioui.org/f32"
"gioui.org/io/pointer"
)
// pinchFreshWindow is how recently BOTH pair fingers must have pressed for a
// pinch to start. A finger that has been resting (palm edge, pinky parked on
// the screen) is not a pinch candidate; without this window a resting third
// finger could be paired with a new one and the font would follow a
// single-finger scroll.
const pinchFreshWindow = 300 * time.Millisecond
// pinchMoveEps is how far (window px, from the press position) a pending
// finger must travel to count as "moving" for pair formation. It filters
// touch jitter while still registering an intentional pinch start quickly.
const pinchMoveEps = 10.0
// Pair formation requires TWO MOVING fingers, and nothing else. A pinch is
// two fingers moving apart (or together); a scroll is one finger moving;
// a resting palm is a finger that never moves. No static rule about which
// finger is "the palm" (first? last? still?) survives 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": it forms the
// pair the moment two of them have moved more than pinchMoveEps from where
// they pressed (the pair = those two). A lone mover is a scroll, never a
// pinch, and cannot form a pair; the pending state cancels on any release
// that leaves fewer than two fingers.
// pinchTracker is the pure state machine for the editor's two-finger pinch
// (font scaling). It is independent of the Gio input router so the whole
// gesture — including the failure modes found on device (pair switching,
// stale baselines, scroll-grab starvation) — is unit-testable with synthetic
// pointer-event sequences.
//
// Design: the pair is EXPLICIT and stable. When two fresh fingers are down
// inside the region, they are named as the pair and the adapter issues
// pointer.GrabCmds for both (exclusive event delivery: releases always
// arrive, even off-clip, and scroll/click are dropped with a Cancel). The
// per-frame factor is current pair distance / previous frame's pair
// distance. Neither the pair's composition nor its baseline is ever
// re-derived from whatever pointers happen to be present — that re-derivation
// (two lowest IDs + stale prevDist) is what made single-finger scrolls scale
// the font on the phone.
type pinchTracker struct {
// Pre-pinch ("pending"): fresh fingers down in the region, no pair yet.
// The pair forms when TWO of them have moved more than pinchMoveEps
// from where they pressed (see the comment above the constants).
observed map[pointer.ID]f32.Point
observedAt map[pointer.ID]time.Duration
// Position each pending finger had when it PRESSED: the formation
// baseline (formDist) is the press distance, so a pinch that has
// already spread by the time the pair starts owes that spread; and the
// displacement from here is the "mover" measurement.
pressPos map[pointer.ID]f32.Point
// Pending fingers that released in the CURRENT frame's drain, held lazy
// until factor() (which forms the pair — and may break it again — at
// the fingers' final positions). A normal active-pair release breaks
// immediately in step(); this map is only for releases that arrive
// while the pair is still pending.
released map[pointer.ID]bool
// Reform candidate: after a pair broke, the survivor is still grabbed
// and a NEW finger has landed. The pair re-forms (survivor + new) only
// when the new finger moves (pinchMoveEps) — the same two-mover rule;
// a palm landing on the survivor is not a pinch. reformPos is where
// the candidate PRESSED (the mover reference).
reformID pointer.ID
reformPos f32.Point
reformBase float32 // pair distance at the candidate's press
reformHave bool
// The active (grabbed) pair.
pair [2]pointer.ID
pos [2]f32.Point
on bool
prevDist float32
// The pair's distance at the moment of (re)formation: the distance of
// the two press positions. The Android driver replays
// historical samples, so drags of the forming pair can land in the same
// frame as the pair's formation; movement relative to the formation
// distance is real and owed.
formDist float32
// Set on the pair's formation frame (start or re-form): the baseline
// is being established, so factor() emits nothing unless the pair
// moved from its formation positions this frame.
fresh bool
// The pair broke (a finger lifted) during the current frame's drain.
// factor() runs AFTER the drain, so on a slow frame the pair's drags
// and the breaking release arrive together and the frame's factor
// would be lost (on==false by the time factor() runs). The factor is
// settled here instead.
brokeFactor float32
brokeMid f32.Point
// A pair finger was released while the other is still down (still
// grabbed by the probe; Gio v0.10 has no release-grab). The survivor's
// drags are forwarded as scroll so the finger is not dead.
survOn bool
survID pointer.ID
survPos f32.Point
// Accumulated survivor scroll for the current frame (window px,
// gesture.Scroll convention: positive = content scrolls up).
survScroll int
}
// pinchStep is the outcome of one pointer event.
type pinchStep struct {
// Grabs the adapter must issue (pointer.GrabCmd per ID). Only the
// survivor re-form path emits grabs per event; initial pair formation
// is decided in factor() (after the whole frame's events).
grabs []pointer.ID
}
// step feeds one pointer event into the tracker. The per-frame factor is not
// part of the step result: the adapter calls factor() once after draining
// the frame's events, because the Android driver replays historical samples
// (several drags per frame) and the font must see one factor per frame.
func (t *pinchTracker) step(pe pointer.Event) pinchStep {
var s pinchStep
id := pe.PointerID
switch pe.Kind {
case pointer.Press:
switch {
case t.on:
// Extra finger during an active pinch (palm rest, third
// finger): ignore — the pair is fixed.
case t.survOn && t.reformHave && id == t.reformID:
// The reform candidate lifted before moving: not a pinch.
t.reformHave = false
case t.survOn:
// A new finger lands while the survivor is down: CANDIDATE for
// a re-form; it must MOVE to become the pair (the same two-mover
// rule — a palm resting on the survivor is not a pinch). The
// formation baseline is the distance at this PRESS (any spread
// by re-form time is owed).
t.reformID = id
t.reformPos = pe.Position
t.reformBase = pairDist(t.survPos, pe.Position)
t.reformHave = true
default:
if t.observed == nil {
t.observed = make(map[pointer.ID]f32.Point)
t.observedAt = make(map[pointer.ID]time.Duration)
t.pressPos = make(map[pointer.ID]f32.Point)
}
t.observed[id] = pe.Position
t.observedAt[id] = pe.Time
t.pressPos[id] = pe.Position
// Prune stale fingers (resting palm/pinky); a pruned palm is
// out of the game entirely.
t.pruneStale(pe.Time)
// (Two or more fingers down is the PENDING state; the pair
// forms only when two of them are movers, decided in factor().)
}
case pointer.Drag:
switch {
case t.on:
if i := t.pairIndex(id); i >= 0 {
t.pos[i] = pe.Position
}
case t.survOn && id == t.survID:
t.survScroll += int(t.survPos.Y - pe.Position.Y)
t.survPos = pe.Position
case t.survOn && t.reformHave && id == t.reformID:
// The reform candidate moves: if it clears the epsilon from
// where it pressed it is a real second finger — re-form the
// pair (survivor + new).
dx, dy := pe.Position.X-t.reformPos.X, pe.Position.Y-t.reformPos.Y
if dx*dx+dy*dy > pinchMoveEps*pinchMoveEps {
t.pair = [2]pointer.ID{t.survID, id}
t.pos = [2]f32.Point{t.survPos, pe.Position}
t.survOn = false
t.reformHave = false
t.on = true
t.fresh = true
t.formDist = t.reformBase
s.grabs = []pointer.ID{id} // survivor already grabbed
}
default:
if _, ok := t.pressPos[id]; ok {
t.observed[id] = pe.Position
// Formation is NOT decided here: a per-event decision would
// lock in the first mover pair seen (e.g. (finger, drifting
// palm)) before the second pinch finger's drag lands in the
// same drain. factor() decides, after the full frame.
}
}
case pointer.Release, pointer.Cancel:
switch {
case t.on:
if i := t.pairIndex(id); i >= 0 {
t.breakPair(i)
}
case t.survOn && id == t.survID:
// The survivor lifts too: fully idle (the candidate, if any,
// was a lone finger — never a pair).
t.survOn = false
t.reformHave = false
default:
// Pending finger goes up: held LAZY until factor() — on a slow
// frame the whole pinch (drags AND releases) can land in one
// drain, and the pair must form at the fingers' final positions
// before the break settles the owed factor.
if _, ok := t.observed[id]; ok {
t.markReleased(id)
}
}
case pointer.Leave:
// Only meaningful pre-pinch: a finger that leaves the editor
// region is no longer a pinch candidate. (A grabbed pair finger
// keeps delivering through the grab; its Leave is ignored.)
if t.survOn && t.reformHave && id == t.reformID {
t.reformHave = false
} else if t.observed != nil {
if _, ok := t.observed[id]; ok {
t.markReleased(id)
}
}
}
return s
}
// breakPair settles the frame's owed factor (if any) and breaks the pair.
// The surviving finger stays grabbed by the probe (no release-grab in v0.10)
// and becomes the survivor — UNLESS it too released in this same drain
// (slow frame: a born-and-dead pair), in which case the tracker goes fully
// idle. Settling here (before factor() runs) is what keeps the factor on a
// frame where the drags and the breaking release arrive together.
func (t *pinchTracker) breakPair(i int) {
base := t.prevDist
if base == 0 && t.fresh {
base = t.formDist
}
if d := pairDist(t.pos[0], t.pos[1]); d > 0 && base > 0 && d != base {
if f := d / base; f >= 0.1 && f <= 10 {
t.brokeFactor = f
t.brokeMid = pairMid(t.pos[0], t.pos[1])
}
}
t.on = false
t.prevDist = 0
other := 1 - i
if !t.released[t.pair[other]] {
t.survOn = true
t.survID = t.pair[other]
t.survPos = t.pos[other]
}
}
// markReleased lazily records a pending finger's release (see the Release
// case). Cleared by factor() after it has formed (and possibly broken) the
// pair.
func (t *pinchTracker) markReleased(id pointer.ID) {
if t.released == nil {
t.released = make(map[pointer.ID]bool)
}
t.released[id] = true
}
// dropObserved removes a pending finger for good.
func (t *pinchTracker) dropObserved(id pointer.ID) {
if t.observed == nil {
return
}
delete(t.observed, id)
delete(t.observedAt, id)
delete(t.pressPos, id)
delete(t.released, id)
}
// movers returns the pending fingers that moved more than pinchMoveEps from
// where they pressed, most-displaced first.
func (t *pinchTracker) movers() []pointer.ID {
type dm struct {
id pointer.ID
d float64
}
var list []dm
for id, pp := range t.pressPos {
dx := float64(t.observed[id].X - pp.X)
dy := float64(t.observed[id].Y - pp.Y)
if d := math.Sqrt(dx*dx + dy*dy); d > pinchMoveEps {
list = append(list, dm{id, d})
}
}
for i := 0; i < len(list); i++ {
for j := i + 1; j < len(list); j++ {
if list[j].d > list[i].d {
list[i], list[j] = list[j], list[i]
}
}
}
out := make([]pointer.ID, 0, len(list))
for _, e := range list {
out = append(out, e.id)
}
return out
}
// tryFormPair forms the pair from the pending fingers if at least TWO are
// movers (two moving fingers = a pinch; one = a scroll, never a pair). Of
// the mover pairs, the one whose DISTANCE changed most wins: a pinch's pair
// distance changes, while a drifting palm's distance to a finger changes
// little. A mover pair whose distance does not change (fingers moving in
// unison) is a slide, not a pinch. Returns the IDs to grab, or nil when no
// pair forms.
func (t *pinchTracker) tryFormPairAny() []pointer.ID {
m := t.movers()
if len(m) < 2 {
return nil
}
bestA, bestB := m[0], m[1]
bestChange := -1.0
for i := 0; i < len(m); i++ {
for j := i + 1; j < len(m); j++ {
a, b := m[i], m[j]
now := float64(pairDist(t.observed[a], t.observed[b]))
press := float64(pairDist(t.pressPos[a], t.pressPos[b]))
if chg := math.Abs(now - press); chg > bestChange {
bestChange = chg
bestA, bestB = a, b
}
}
}
if bestChange <= pinchMoveEps {
return nil // unison movement: a slide, not a pinch
}
a, b := bestA, bestB
t.pair = [2]pointer.ID{a, b}
t.pos = [2]f32.Point{t.observed[a], t.observed[b]}
t.on = true
t.fresh = true
// Baseline = the PRESS distance of the pair: any spread that happened
// before the pair started is owed, not lost.
t.formDist = pairDist(t.pressPos[a], t.pressPos[b])
t.observed = nil
t.observedAt = nil
t.pressPos = nil
return []pointer.ID{a, b}
}
// pairIndex returns 0/1 if id is a member of the active pair, else -1.
func (t *pinchTracker) pairIndex(id pointer.ID) int {
if !t.on {
return -1
}
if t.pair[0] == id {
return 0
}
if t.pair[1] == id {
return 1
}
return -1
}
// pruneStale drops observed fingers that pressed more than
// pinchFreshWindow before now.
func (t *pinchTracker) pruneStale(now time.Duration) {
for id, at := range t.observedAt {
if now-at > pinchFreshWindow {
delete(t.observed, id)
delete(t.observedAt, id)
delete(t.pressPos, id)
}
}
}
// factor returns the current frame's relative pinch scale and the pair
// midpoint (window px), or ok=false when no factor applies (no active pair,
// first frame of a pinch, or an implausible jump). It must be called once
// per frame, after all of the frame's events have been stepped.
func (t *pinchTracker) factor() (f float32, mid f32.Point, ok bool, grabs []pointer.ID) {
// Pending pair formation is decided HERE, after the whole frame's
// events (not per event): a per-event decision would lock in the first
// mover pair seen — e.g. (finger, drifting palm) — before the second
// pinch finger's drag lands in the same drain.
if !t.on && !t.survOn && t.observed != nil {
if g := t.tryFormPairAny(); g != nil {
grabs = g
// Slow frame: a pair member may have released in this same
// drain (the release arrived while the pair was still pending):
// break it now at the fingers' final positions.
for i, id := range t.pair {
if t.released[id] {
t.breakPair(i)
break
}
}
}
}
// Pending fingers that released this frame are dropped for good.
if t.released != nil {
for id := range t.released {
t.dropObserved(id)
}
t.released = nil
}
if !t.on {
// The pair broke during this frame's drain: emit the settled
// factor (on a slow frame the drags and the breaking release can
// arrive together, and factor() runs only after the drain).
if t.brokeFactor > 0 {
f, mid, ok = t.brokeFactor, t.brokeMid, true
t.brokeFactor = 0
t.brokeMid = f32.Point{}
}
return f, mid, ok, grabs
}
d := pairDist(t.pos[0], t.pos[1])
if t.fresh {
// Formation frame: establish the baseline. Emit only if the pair
// already moved from its formation positions this frame (the
// Android driver replays historical samples, so drags can batch
// with the formation Press).
t.fresh = false
t.prevDist = d
if t.formDist > 0 && d != t.formDist {
f = d / t.formDist
if f < 0.1 || f > 10 {
return 0, f32.Point{}, false, grabs
}
return f, pairMid(t.pos[0], t.pos[1]), true, grabs
}
return 0, f32.Point{}, false, grabs
}
if t.prevDist > 0 && d > 0 && d != t.prevDist {
// No-movement guard: a stationary pair emits nothing (an f=1.0
// factor would churn the font pin's re-layout for no change).
f = d / t.prevDist
// Sanitize: a real pinch moves millimeters between frames; a
// factor this far off 1 is noise, not a finger.
if f < 0.1 || f > 10 {
t.prevDist = d
return 0, f32.Point{}, false, grabs
}
t.prevDist = d
return f, pairMid(t.pos[0], t.pos[1]), true, grabs
}
t.prevDist = d
return 0, f32.Point{}, false, grabs
}
// survivorScroll returns and resets the frame's accumulated survivor-finger
// scroll (window px, gesture.Scroll convention: positive = content scrolls
// up).
func (t *pinchTracker) survivorScroll() int {
d := t.survScroll
t.survScroll = 0
return d
}
// reset clears all state (the editor left the screen).
func (t *pinchTracker) reset() {
*t = pinchTracker{}
}
// pairDist is the distance between two pair points (window px).
func pairDist(a, b f32.Point) float32 {
dx, dy := a.X-b.X, a.Y-b.Y
return float32(math.Sqrt(float64(dx*dx + dy*dy)))
}
// pairMid is the midpoint of two pair points (window px).
func pairMid(a, b f32.Point) f32.Point {
return f32.Point{X: (a.X + b.X) / 2, Y: (a.Y + b.Y) / 2}
}
+281
View File
@@ -0,0 +1,281 @@
package ui
// Definitive host test: run the app's REAL Renderer.Draw op stream (a
// realistic editor frame: status bar, editor TextField, bottom bar) through
// the real input.Router with the app's per-frame protocol (drain before
// commit), queue a touch press inside the editor text, and check which tags
// receive it: the scroll tag (known-good on the phone) as control, plus the
// pressProbe/pinchProbe tags (dead on the phone).
import (
"image"
"testing"
"time"
"gioui.org/f32"
"gioui.org/font/gofont"
"gioui.org/io/event"
"gioui.org/io/input"
"gioui.org/io/pointer"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/text"
"gioui.org/unit"
)
func TestRealDrawOpsProbeHit(t *testing.T) {
shp := text.NewShaper(text.WithCollection(gofont.Collection()))
r := New(Theme{FontSize: 14}, shp)
noop := func(any) {}
const (
wW = 411
wH = 914
)
editorRegion := Region{X: 10, Y: 52, W: wW - 20, H: 700}
editor := NewTextField("editor_text", "hello world\nsecond line\nthird line", editorRegion, true, editorRegion.W, 0, 5, -1, -1, []Interaction{
{Gesture: Scroll, Handler: noop},
{Gesture: Tap, Handler: noop},
{Gesture: Pinch, Handler: noop},
})
editor.Focused = true
editor.ShowIMESeq = 7
statusBar := NewContainer(Region{X: 0, Y: 0, W: wW, H: 52}, Color{R: 240, G: 240, B: 240, A: 255}, []Element{
NewLabel("←", 16, Region{X: 5, Y: 5, W: 40, H: 42}, AlignStart, "back_id", nil),
NewLabel("/storage/emulated/0/Notes/test.txt", 14, Region{X: 50, Y: 5, W: 300, H: 42}, AlignStart, "path_id", nil),
})
bottomBar := NewContainer(Region{X: 0, Y: wH - 40, W: wW, H: 40}, Color{R: 240, G: 240, B: 240, A: 255}, []Element{
NewLabel("Saved", 14, Region{X: 5, Y: wH - 35, W: 100, H: 30}, AlignStart, "saved_id", nil),
})
elems := []Element{statusBar, editor, bottomBar}
m := unit.Metric{PxPerDp: 1, PxPerSp: 1}
gtxFor := func(ops *op.Ops) layout.Context {
return layout.Context{
Ops: ops,
Metric: m,
Constraints: layout.Constraints{Min: image.Point{}, Max: image.Point{X: wW, Y: wH}},
}
}
var rtr input.Router
probeK := pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel
pinchF := pointer.Filter{Target: event.Tag(r.pinchProbe), Kinds: probeK}
pressF := pointer.Filter{Target: event.Tag(r.pressProbe), Kinds: probeK}
// Frame 1: record the real app ops and commit.
{
var ops op.Ops
r.Draw(gtxFor(&ops), elems, 1.0)
if _, ok := r.scrolls["editor_text"]; !ok {
t.Fatal("scroll reg not created for editor_text")
}
scroll := r.scrolls["editor_text"].scroll
t.Logf("scroll tag = %p", scroll)
// Pre-merge filters (app calls Event every frame; first call here).
rtr.Source().Event(pinchF)
rtr.Source().Event(pressF)
rtr.Source().Event(pointer.Filter{Target: scroll, Kinds: probeK})
rtr.Frame(&ops)
}
// A touch press lands in the editor text region.
pos := f32.Pt(100, 100)
rtr.Queue(pointer.Event{Kind: pointer.Press, Source: pointer.Touch, Position: pos})
t.Logf("queued press at %v", pos)
// Frame 2: draw again, then drain (app protocol: consume before commit).
{
var ops op.Ops
r.Draw(gtxFor(&ops), elems, 1.0)
drain := func(name string, f pointer.Filter) {
for {
e, ok := rtr.Source().Event(f)
if !ok {
break
}
if pe, ok := e.(pointer.Event); ok {
t.Logf("frame2: %-12s got kind=%v pos=%v", name, pe.Kind, pe.Position)
}
}
}
drain("pressProbe", pressF)
drain("pinchProbe", pinchF)
drain("scroll", pointer.Filter{Target: r.scrolls["editor_text"].scroll, Kinds: probeK})
rtr.Frame(&ops)
}
}
// TestRealDrawPinchGrabLifecycle runs the REAL app frame loop (draw ops ->
// CheckGestures -> commit) through the real input.Router with a real
// two-finger pinch and verifies the grab semantics that fix the on-device
// jank: the pair is tracked exclusively (the probe keeps getting drags even
// off-clip, scroll gets nothing), a factor is emitted per moved frame, a
// release breaks the pair, and the survivor finger's drags come out as plain
// scroll (forwarded), so the finger is not dead after a pinch.
func TestRealDrawPinchGrabLifecycle(t *testing.T) {
shp := text.NewShaper(text.WithCollection(gofont.Collection()))
r := New(Theme{FontSize: 14}, shp)
var pinchEvents []any
var scrollEvents []any
editor := NewTextField("editor_text", "hello world\nsecond line\nthird line",
Region{X: 10, Y: 52, W: 391, H: 700}, true, 391, 0, 5, -1, -1, []Interaction{
{Gesture: Scroll, Handler: func(d any) { scrollEvents = append(scrollEvents, d) }},
{Gesture: Tap, Handler: func(any) {}},
{Gesture: Pinch, Handler: func(d any) { pinchEvents = append(pinchEvents, d) }},
})
editor.Focused = true
elems := []Element{editor}
m := unit.Metric{PxPerDp: 1, PxPerSp: 1}
gtxFor := func(ops *op.Ops) layout.Context {
return layout.Context{
Ops: ops,
Metric: m,
Constraints: layout.Constraints{Min: image.Point{}, Max: image.Point{X: 411, Y: 914}},
}
}
var rtr input.Router
var prevOps op.Ops
havePrev := false
// ptEv builds a router-queueable pointer event. "Drag" is written as
// Move: the router only accepts Press/Move/Release/Cancel/Scroll and
// converts a pressed pointer's Move into a Drag before delivery.
ptEv := func(kind pointer.Kind, id pointer.ID, x, y float32, at time.Duration) pointer.Event {
if kind == pointer.Drag {
kind = pointer.Move
}
return pointer.Event{Kind: kind, Source: pointer.Touch, PointerID: id, Position: f32.Point{X: x, Y: y}, Time: at}
}
// runFrame mirrors the app's loop: commit the previous frame's ops
// (w.Event), queue this frame's pointer events, draw, CheckGestures.
// It also observes what the SCROLL tag receives this frame (drained
// before CheckGestures so the observation is lossless).
runFrame := func(evts ...pointer.Event) (events []InputEvent, scrollKinds []pointer.Kind) {
if havePrev {
rtr.Frame(&prevOps)
}
for _, e := range evts {
rtr.Queue(e)
}
var ops op.Ops
r.Draw(gtxFor(&ops), elems, 1.0)
for {
e, ok := rtr.Source().Event(pointer.Filter{
Target: r.scrolls["editor_text"].scroll,
Kinds: pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel,
})
if !ok {
break
}
if pe, ok := e.(pointer.Event); ok {
scrollKinds = append(scrollKinds, pe.Kind)
}
}
events = r.CheckGestures(rtr.Source(), m)
// The app's main loop dispatches each event to its logic handler;
// mirror that so the capture handlers see them.
for _, e := range events {
e.Handler(e.Data)
}
prevOps, havePrev = ops, true
return events, scrollKinds
}
// Setup frame: register the ops.
runFrame()
hasKind := func(kinds []pointer.Kind, k pointer.Kind) bool {
for _, x := range kinds {
if x == k {
return true
}
}
return false
}
// Two fingers press 200px apart inside the editor text. Pending: no
// pair yet (the pair forms when BOTH move), no pinch events, no grabs.
_, scrollKinds := runFrame(
ptEv(pointer.Press, 0, 100, 100, time.Millisecond),
ptEv(pointer.Press, 1, 300, 100, 2*time.Millisecond))
if len(pinchEvents) != 0 {
t.Fatalf("press frame emitted a pinch event: %v", pinchEvents)
}
if hasKind(scrollKinds, pointer.Drag) {
t.Fatalf("scroll saw a drag on the press frame: %v", scrollKinds)
}
// The pair spreads 200 -> 240: this is the FORMATION frame — both
// fingers moved (the two-mover rule), the pair forms and the grabs are
// issued. One factor (1.2) is owed against the press distance. The
// pair's drags of THIS frame still reach scroll (the grabs commit on
// the next frame): a one-frame leak bounded by the scroll slop — the
// cost of not grabbing on press (which would kill single-finger
// scrolls). From the NEXT frame on, scroll must see nothing of the pair.
runFrame(
ptEv(pointer.Drag, 0, 80, 100, 10*time.Millisecond),
ptEv(pointer.Drag, 1, 320, 100, 11*time.Millisecond))
if len(pinchEvents) != 1 {
t.Fatalf("formation frame: pinch events=%d want 1 (%v)", len(pinchEvents), pinchEvents)
}
fpe, ok := pinchEvents[0].(FontPinchEvent)
if !ok || fpe.Scale < 1.19 || fpe.Scale > 1.21 {
t.Fatalf("scale=%v want ~1.2", pinchEvents[0])
}
// The pair keeps spreading: from here the grabs are active and SCROLL
// sees no drag of the pair (a Cancel for the dropped press may arrive).
_, scrollKinds = runFrame(
ptEv(pointer.Drag, 0, 50, 100, 15*time.Millisecond),
ptEv(pointer.Drag, 1, 350, 100, 16*time.Millisecond))
if len(pinchEvents) != 2 {
t.Fatalf("mid-pinch frame: pinch events=%d want 2 (%v)", len(pinchEvents), pinchEvents)
}
if hasKind(scrollKinds, pointer.Drag) {
t.Fatalf("scroll saw the pair's drags after formation: %v (grab failed)", scrollKinds)
}
// Finger 0 drags FAR OUTSIDE the editor region: the grab keeps it
// delivering to the probe (no stale pointer, no lost release).
_, scrollKinds = runFrame(
ptEv(pointer.Drag, 0, 2, 890, 20*time.Millisecond), // off-clip
ptEv(pointer.Drag, 1, 330, 100, 21*time.Millisecond))
if len(pinchEvents) != 3 {
t.Fatalf("off-clip frame: pinch events=%d want 3 (pair must survive off-clip)", len(pinchEvents))
}
if hasKind(scrollKinds, pointer.Drag) {
t.Fatalf("scroll saw the off-clip drag: %v", scrollKinds)
}
// Finger 0 lifts (off-clip): the release still arrives via the grab.
// The pair breaks; no pinch event.
before := len(pinchEvents)
runFrame(ptEv(pointer.Release, 0, 2, 890, 30*time.Millisecond))
if len(pinchEvents) != before {
t.Fatal("broken pair emitted a pinch event")
}
// The survivor (finger 1) scrolls 30px up: forwarded as a plain scroll
// delta to the editor's scroll handler — the finger is not dead.
scrollBefore := len(scrollEvents)
runFrame(ptEv(pointer.Drag, 1, 330, 70, 40*time.Millisecond))
if len(scrollEvents) != scrollBefore+1 {
t.Fatalf("survivor scroll not forwarded: events=%d want %d", len(scrollEvents), scrollBefore+1)
}
if d, ok := scrollEvents[scrollBefore].(int); !ok || d != 30 {
t.Fatalf("survivor delta=%v want 30 (px, scroll-up positive)", scrollEvents[scrollBefore])
}
// A second finger returns: candidate for a re-form (no event on the
// press); it must MOVE to become the pair (two-mover rule).
runFrame(ptEv(pointer.Press, 2, 50, 70, 50*time.Millisecond))
before = len(pinchEvents)
runFrame(
ptEv(pointer.Drag, 1, 340, 70, 60*time.Millisecond),
ptEv(pointer.Drag, 2, 30, 70, 61*time.Millisecond)) // 20px from press
if len(pinchEvents) != before+1 {
t.Fatalf("re-formed pair: pinch events=%d want %d", len(pinchEvents), before+1)
}
}
+174 -8
View File
@@ -62,6 +62,17 @@ type scrollReg struct {
handler func(any)
}
// Probe tags for the raw-pointer probes (long-press, pinch). Each probe
// needs its OWN named type: the unnamed fieldless struct{} is a single
// canonical Go type, so distinct `struct{}` fields are the SAME value.
// Gio's router keys handlers by the tag value, so two `struct{}` probes
// collapse into one handler and whichever probe drains first (the press
// probe, which is consumed before the pinch probe) consumes every event,
// starving the other — this is why pinch received nothing on device while
// long-press appeared to work.
type pressProbeTag struct{}
type pinchProbeTag struct{}
// Renderer consumes a slice of elements and draws them.
//
// The Renderer is owned by the main goroutine. It is the home of any state
@@ -80,6 +91,17 @@ type Renderer struct {
lastLineY Dp // last line baseline offset from text origin, in Dp (derived from GlyphLayout)
glyphLayout GlyphLayout // captured per-glyph layout from last drawWrappedText
// ZeroWheelScroll, set by main on a frame whose window size shrank, makes
// CheckGestures drain any pointer.Scroll events queued for the editor's
// scroll gesture before consuming gestures. Gio's window calls RevealFocus
// on any frame the viewport shrinks (e.g. the IME opening under
// adjustResize) and synthesizes a pointer.Scroll nudge to bring the focused
// field's (stale, pre-resize) bounds into view; consumed by gesture.Scroll
// that nudge shifts the editor content. The drain kills only the
// synthesized event: finger scroll (pointer.Drag) and the flinger are
// untouched, and normal frames consume pointer.Scroll as before.
ZeroWheelScroll bool
// IME dedup (main-owned, persistent across frames). Re-pushing an unchanged
// snippet or selection every frame resets the IME's composition and caret,
// which desyncs fast commits; push only on change, as widget.Editor does in
@@ -114,12 +136,40 @@ type Renderer struct {
// scroll/drag then, not a press). longPressID gates the long-press to the
// editor's click reg (browser rows etc. don't long-press). ppLast is in
// f32.Point because pointer.Event.Position is window-space f32.
pressProbe struct{}
pressProbe pressProbeTag
ppLast f32.Point
ppActive bool
ppMoved bool
longPressID string
// Pinch-to-change-font-size (editor text region). Gio v0.10 has no
// two-finger pinch primitive: pinchProbe is a raw event tag inside the
// editor clip, and pinchT (pinch_tracker.go) is the gesture's state
// machine. When two fresh fingers are down the tracker names them as an
// EXPLICIT pair and the adapter grabs both (pointer.GrabCmd): exclusive
// event delivery (releases always arrive, even off-clip; scroll/click
// are dropped with a Cancel, which also stops the first finger dragging
// the text mid-pinch). The per-frame factor is the pair-distance ratio
// (FontPinchEvent to pinchHandler). The pair is never re-derived from
// whatever pointers happen to be present: that re-derivation (two
// lowest IDs) let a resting third finger pair with a live one and made
// single-finger scrolls scale the font on the phone. When one pair
// finger lifts, the survivor stays grabbed (v0.10 has no release-grab)
// and its drags are forwarded as scroll via pinchScrollHandler. State
// is dropped when the editor leaves the screen (see Draw).
pinchProbe pinchProbeTag
pinchT pinchTracker
pinchHandler func(any)
pinchScrollHandler func(any)
pinchProbeOn bool
// appFontScale is the app-local font-size multiplier (pinch zoom;
// 1.0 = default, 0 = not set yet). The main goroutine feeds it from the
// frame's snapshot via SetAppFontScale before Draw; drawWrappedText
// multiplies the editor font size by it. The system user font scale is
// separate and already folded into gtx.Metric/gtx.Sp.
appFontScale float32
// Selection / caret drag handles (0 = start, 1 = end, 2 = body, 3 = caret
// handle). Registered clipped in drawWrappedText only while a selection or
// caret handle is visible; a gesture.Drag grabs the pointer once movement
@@ -155,6 +205,17 @@ type Renderer struct {
gestureExclusions [][4]int
}
// SetAppFontScale sets the app-local font-size multiplier for subsequent
// draw passes (1.0 = default; <= 0 is treated as 1). Main-goroutine-only;
// call before Draw (see appFontScale).
func (r *Renderer) SetAppFontScale(v float32) {
if v > 0 {
r.appFontScale = v
} else {
r.appFontScale = 1
}
}
// GestureExclusions returns the handle grab boxes collected for the last
// frame (see gestureExclusions).
func (r *Renderer) GestureExclusions() [][4]int { return r.gestureExclusions }
@@ -238,6 +299,12 @@ func (r *Renderer) toDp(px Px) Dp {
func (r *Renderer) Draw(gtx layout.Context, elems []Element, scale float32) {
r.scale = scale
r.focusSeenThisFrame = false // per-frame reset for FocusCmd dedup
if !r.pinchProbeOn {
// No editor text in the previous frame: drop all pinch state so a
// later pinch starts clean.
r.pinchT.reset()
}
r.pinchProbeOn = false
// Gio sets constraints to layout.Exact(windowSize), so Min==Max. Use (0,0) as Min.
winW := gtx.Constraints.Max.X
winH := gtx.Constraints.Max.Y
@@ -343,6 +410,12 @@ func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
// Long-press motion probe first: it must see the press/drag events before
// the click loop decides about a long press.
r.consumePressProbe(q)
// Pinch probe: drain the raw pointer events, grab/release the pair,
// and emit the frame's scale factor and any survivor-finger scroll.
// Runs before the click/scroll loops so the pinch is applied in the
// same input batch that carried the finger moves, and the pair's
// grabs are queued ahead of any competing scroll grab.
events = append(events, r.consumePinchProbe(q)...)
for id, reg := range r.clicks {
// Drain every queued event for this gesture in this frame.
// gesture.Click returns one event per Update call, but on Android a
@@ -467,9 +540,25 @@ func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
// gesture.Scroll.Update returns scroll delta in pixels.
// ScrollY range: Min = -scrollOffset (remaining above), Max = large (content height unknown yet).
// With Min==Max==0, clampSplit consumes zero scroll.
// Update runs unconditionally (it keeps the gesture's flinger state
// healthy). Emission is suppressed while a pinch owns the pair: the
// pair is grabbed (scroll is dropped from its path) once the grabs
// commit, and this guard covers the one-frame window before that.
if r.ZeroWheelScroll {
// RevealFocus (see ZeroWheelScroll) queued a synthetic
// pointer.Scroll on this shrink frame; consume it here so the
// gesture never sees it. Scroll-range clamping is no use: the
// router UNIONs ranges across frames and the historical max
// can never shrink back to zero.
for {
if _, ok := q.Event(pointer.Filter{Target: reg.scroll, Kinds: pointer.Scroll}); !ok {
break
}
}
}
delta := reg.scroll.Update(m, q, time.Now(), gesture.Vertical,
pointer.ScrollRange{}, pointer.ScrollRange{Min: -(1 << 30), Max: 1 << 30})
if delta != 0 {
if delta != 0 && !r.pinchT.on {
events = append(events, InputEvent{
Handler: reg.handler,
Data: delta,
@@ -480,11 +569,63 @@ func (r *Renderer) CheckGestures(q input.Source, m unit.Metric) []InputEvent {
return events
}
// consumePinchProbe drains the pinch probe's raw pointer events into the
// tracker, issues the pair's grabs, and returns this frame's events: the
// scale factor (when the active pair moved) and the survivor finger's
// forwarded scroll (when a pair broke with one finger still down).
func (r *Renderer) consumePinchProbe(q input.Source) []InputEvent {
var events []InputEvent
for {
evt, ok := q.Event(pointer.Filter{Target: r.pinchProbe, Kinds: pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel | pointer.Leave})
if !ok {
break
}
pe, ok := evt.(pointer.Event)
if !ok {
continue
}
if s := r.pinchT.step(pe); len(s.grabs) > 0 {
for _, id := range s.grabs {
q.Execute(pointer.GrabCmd{Tag: r.pinchProbe, ID: id})
}
}
}
// The tracker may have formed the pair during factor() (after the full
// frame's events); issue those grabs now. Either way they commit
// before any scroll grab queued later in this frame (FIFO command
// queue), so the pair wins the race even if a finger is already past
// the scroll slop.
f, mid, ok, grabs := r.pinchT.factor()
for _, id := range grabs {
q.Execute(pointer.GrabCmd{Tag: r.pinchProbe, ID: id})
}
if ok && r.pinchHandler != nil {
events = append(events, InputEvent{
Handler: r.pinchHandler,
Data: FontPinchEvent{
Scale: f,
Center: Point{X: r.toDp(Px(mid.X)), Y: r.toDp(Px(mid.Y))},
},
})
}
if d := r.pinchT.survivorScroll(); d != 0 && r.pinchScrollHandler != nil {
events = append(events, InputEvent{
Handler: r.pinchScrollHandler,
Data: d,
})
}
return events
}
// consumePressProbe drains the raw pointer events of the long-press probe
// and updates ppLast/ppMoved. It runs before the click loop each frame.
// Leave ends the pending press: a finger that drifts off the editor region
// must not keep a long press armed (its release would never come to the
// probe if it was grabbed by scroll, so without this the timer could fire
// for a finger that is long gone).
func (r *Renderer) consumePressProbe(q input.Source) {
for {
evt, ok := q.Event(pointer.Filter{Target: r.pressProbe, Kinds: pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel})
evt, ok := q.Event(pointer.Filter{Target: r.pressProbe, Kinds: pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel | pointer.Leave})
if !ok {
return
}
@@ -505,7 +646,7 @@ func (r *Renderer) consumePressProbe(q input.Source) {
}
}
r.ppLast = pe.Position
case pointer.Release, pointer.Cancel:
case pointer.Release, pointer.Cancel, pointer.Leave:
r.ppMoved = false
r.ppActive = false
}
@@ -595,6 +736,18 @@ func (r *Renderer) drawElement(gtx layout.Context, e Element) {
// clipped in drawWrappedText where the handle geometry is known.
r.registerInteraction(interactive.ID(), interaction, gtx)
}
if interaction.Gesture == Pinch {
// The renderer owns the probe (raw two-pointer geometry);
// this records the logic handlers. The scroll handler is
// the survivor-finger's forwarding target: after a pinch
// breaks with one finger still down, that finger stays
// grabbed by the probe (v0.10 has no release-grab), so its
// drags are emitted as plain scroll deltas.
r.pinchHandler = interaction.Handler
if reg, ok := r.scrolls[interactive.ID()]; ok {
r.pinchScrollHandler = reg.handler
}
}
}
}
e.Draw(gtx, r)
@@ -783,19 +936,28 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
}
r.gestureExclusions = nil // rebuilt from this frame's handle boxes
// App-local font-size multiplier (pinch zoom; SetAppFontScale keeps it
// > 0). It multiplies the sp font size directly, so the value is a
// continuous float — no rounding to whole points anywhere.
appScale := r.appFontScale
if appScale <= 0 {
appScale = 1
}
size := float32(r.theme.FontSize) * appScale
// Fixed line height based on font size, not glyph metrics.
lineHeightSp := unit.Sp(float32(r.theme.FontSize) * LineHeightScale)
lineHeightSp := unit.Sp(size * LineHeightScale)
// User font-size setting (sp per dp). The shaper draws baselines at
// Sp(...) physical px, so the RENDERED line pitch in density-dp is
// lineHeightSp × fontScale. Every dp-space value below (line height,
// ascent) uses the scaled form so caret/handles/highlight follow the
// drawn glyphs; the logic side tracks the same factor via
// EffectiveLineHeight (ScaleEvent.FontScale).
// EffectiveLineHeight (ScaleEvent.FontScale × app font scale).
fontScale := float32(1)
if gtx.Metric.PxPerDp > 0 && gtx.Metric.PxPerSp > 0 {
fontScale = gtx.Metric.PxPerSp / gtx.Metric.PxPerDp
}
ascent := Dp(float32(r.theme.FontSize) * fontScale)
ascent := Dp(size * fontScale)
lineH := Dp(float32(lineHeightSp) * fontScale)
// Wrap disabled: shape with unlimited width so lines extend past the
// region (clipped by textClip below) instead of wrapping.
@@ -804,7 +966,7 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
maxWidthPx = int(r.toPx(wrapWidth))
}
params := text.Parameters{
PxPerEm: fixed.I(gtx.Sp(r.theme.FontSize)),
PxPerEm: fixed.I(gtx.Sp(unit.Sp(size))),
MinWidth: 0,
MaxWidth: maxWidthPx,
MaxLines: 0, // unlimited - wrap at MaxWidth
@@ -952,6 +1114,10 @@ func (r *Renderer) drawWrappedText(gtx layout.Context, str string, reg Region, w
// inside the editor region.
r.selDragsOn = [4]bool{}
event.Op(gtx.Ops, r.pressProbe)
// Pinch probe: same clip as the press probe, so a pinch only registers
// when both fingers' presses/moves land in the editor text region.
event.Op(gtx.Ops, r.pinchProbe)
r.pinchProbeOn = true
r.longPressID = "editor_text"
if r.selDragHandler != nil && (selStart >= 0 && selEnd > selStart || caretDrag) {
// handleAt mirrors the cursor computation above: window-relative byte
+133
View File
@@ -0,0 +1,133 @@
package ui
import (
"image"
"testing"
"time"
"gioui.org/font/gofont"
"gioui.org/gesture"
"gioui.org/io/event"
"gioui.org/io/input"
"gioui.org/io/key"
"gioui.org/io/pointer"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/text"
"gioui.org/unit"
)
// TestRevealFocusDrainTermination reproduces the IME-open scenario at the
// router level: the focused editor field has registered (stale, taller)
// bounds, the window's viewport shrinks, and the framework calls
// Router.RevealFocus which synthesizes a pointer.Scroll for the focused
// field's scroll handler. The app's shrink-frame fix (Renderer
// ZeroWheelScroll) drains pointer.Scroll events for the gesture's tag before
// gesture.Scroll.Update consumes them. This test verifies:
// 1. RevealFocus really does queue a scroll event for the gesture tag,
// 2. the drain loop terminates (bounded iteration count),
// 3. after the drain, gesture.Scroll.Update returns 0 (content does not
// move), and
// 4. on a normal (non-shrink) frame the drain is not needed and the
// gesture consumes whatever scroll it would have consumed anyway.
func TestRevealFocusDrainTermination(t *testing.T) {
shp := text.NewShaper(text.WithCollection(gofont.Collection()))
r := New(Theme{FontSize: 14}, shp)
noop := func(any) {}
const (
wW = 411
wH = 914
)
editorRegion := Region{X: 10, Y: 52, W: wW - 20, H: wH - 92}
// KeyDown is required: it is what makes drawElement record the
// event.Op reference for the tag, without which the key queue clears
// the FocusCmd target ("tag has no event.Op references").
editor := NewTextField("editor_text", "hello world\nsecond line\nthird line", editorRegion, true, editorRegion.W, 0, 5, -1, -1, []Interaction{
{Gesture: Scroll, Handler: noop},
{Gesture: KeyDown, Handler: noop},
})
editor.Focused = true
elems := []Element{editor}
m := unit.Metric{PxPerDp: 1, PxPerSp: 1}
var rtr input.Router
gtxFor := func(ops *op.Ops) layout.Context {
return layout.Context{
Ops: ops,
Metric: m,
Source: rtr.Source(),
Constraints: layout.Constraints{Min: image.Point{}, Max: image.Point{X: wW, Y: wH}},
}
}
// The app consumes a key.FocusFilter for the focused field every frame
// (main.go); that is what marks the handler focusable so keyQueue.Frame
// keeps the focus across frames.
drainFocus := func(q input.Source) {
for {
if _, ok := q.Event(key.FocusFilter{Target: event.Tag("editor_text")}); !ok {
break
}
}
}
// Frame 1: register handlers, focus the field (Draw issues the FocusCmd).
{
var ops op.Ops
gtx := gtxFor(&ops)
r.Draw(gtx, elems, 1.0)
drainFocus(gtx.Source)
rtr.Frame(&ops)
}
scroll := r.scrolls["editor_text"].scroll
t.Logf("focused(editor_text) after frame1: %v", rtr.Source().Focused(event.Tag("editor_text")))
// Frame 2: the app consumes gestures every frame; gesture.Scroll.Update
// registers the Scroll kind in the handler's filter, which Router.Deliver
// (used by RevealFocus/ScrollFocus) requires to match.
{
var ops op.Ops
gtx := gtxFor(&ops)
r.Draw(gtx, elems, 1.0)
drainFocus(gtx.Source)
_ = scroll.Update(m, gtx.Source, time.Now(), gesture.Vertical,
pointer.ScrollRange{}, pointer.ScrollRange{Min: -(1 << 30), Max: 1 << 30})
rtr.Frame(&ops)
}
// Simulate the keyboard opening: the framework shrinks the viewport and
// calls RevealFocus with the new (smaller) viewport.
shrunk := image.Rectangle{Min: image.Point{}, Max: image.Point{X: wW, Y: wH - 400}}
rtr.RevealFocus(shrunk)
// The app's shrink-frame fix: drain pointer.Scroll for the gesture tag.
q := rtr.Source()
drained := 0
for {
evt, ok := q.Event(pointer.Filter{Target: scroll, Kinds: pointer.Scroll})
if !ok {
break
}
drained++
if pe, ok := evt.(pointer.Event); ok {
t.Logf("drained synthetic scroll: %+v", pe.Scroll)
}
if drained > 10 {
t.Fatalf("drain loop did not terminate within 10 iterations")
}
}
if drained == 0 {
t.Fatalf("RevealFocus did not queue a scroll event for the scroll gesture tag")
}
// The gesture must now see no scroll (content stays put).
var ops op.Ops
r.Draw(gtxFor(&ops), elems, 1.0)
delta := scroll.Update(m, q, time.Now(), gesture.Vertical,
pointer.ScrollRange{}, pointer.ScrollRange{Min: -(1 << 30), Max: 1 << 30})
if delta != 0 {
t.Fatalf("gesture consumed %d px of scroll after drain; content would shift", delta)
}
rtr.Frame(&ops)
}
+29
View File
@@ -0,0 +1,29 @@
package ui
import (
"testing"
"gioui.org/font/gofont"
"gioui.org/text"
)
// Regression test for the pinch-on-device bug: the probes were declared as
// `struct{}` fields. The unnamed fieldless struct{} is a single canonical Go
// type, so all three probes were the SAME tag value and Gio's router merged
// them into one handler — the press probe (drained first) consumed every
// event and the pinch probe was starved. Each probe now has its own named
// type and must be a distinct map key.
func TestProbeTagIdentity(t *testing.T) {
r := New(Theme{FontSize: 14}, text.NewShaper(text.WithCollection(gofont.Collection())))
m := map[interface{}]int{}
m[r.pressProbe] = 1
m[r.pinchProbe] = 2
t.Logf("distinct probe tag keys: %d", len(m))
if len(m) != 2 {
t.Fatalf("probe tags must be distinct values, got %d distinct keys", len(m))
}
var a, b interface{} = r.pressProbe, r.pinchProbe
if a == b {
t.Fatal("pressProbe and pinchProbe must not be equal interface values")
}
}
+5
View File
@@ -91,6 +91,11 @@ type LayoutFeedback struct {
WindowStartByte int // absolute byte offset of the window's first byte
WindowStartLine int // logical line the window starts at (-1: none)
EditSeq uint64 // editor content-edit counter at frame time
// ScrollOffset is the editor scroll offset (Dp) the frame this layout
// was shaped from carried. The logic needs it to express layout positions
// (window-relative) in content coordinates: the window top is the
// shaped scroll's sub-line remainder above the region top.
ScrollOffset Dp
}
type GlyphLayout struct {