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
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="touch.inject">
<uses-permission android:name="android.permission.INJECT_EVENTS"/>
<application>
<service android:name=".Injector" android:exported="true"/>
<receiver android:name=".Injector$ScriptReceiver" android:exported="true"/>
</application>
</manifest>
+223
View File
@@ -0,0 +1,223 @@
package touch.inject;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Multi-touch gesture injector for the Pad emulator.
*
* Runs as a privileged system app (/system/priv-app) so that the
* signature|privileged INJECT_EVENTS permission is granted; it then injects
* real MotionEvents through InputManager — the exact path a physical touch
* screen takes — which is what the adb `input` applet cannot do (it has no
* multi-touch support).
*
* Usage:
* adb shell am startservice -n touch.inject/.Injector -e script "SCRIPT"
*
* SCRIPT is a whitespace-separated sequence of:
* down <finger> <x> <y> finger (1-based) touches at (x,y) px
* move <finger> <x> <y> finger moves to (x,y) px
* up <finger> finger lifts
* wait <ms> pause
*
* Progress is logged to logcat under the "TouchInject" tag.
*/
public class Injector extends Service {
public static final String TAG = "TouchInject";
/** Shell-triggerable entry point: works even while the app is stopped
* (the shell can broadcast to an explicit component).
* KNOWN FLAKE: the process is "cached" while the thread runs and the
* 1.5GB emulator OOM-killed it once mid-script (during a 200ms wait),
* losing the final UP. Service routing is NOT an alternative — Android
* 12+ blocks background startService from a receiver, and the AVD's
* locked bootloader blocks the system-app escalation. The harness
* therefore verifies "=== done" in logcat after every script and
* re-runs on failure; scripts should stay short. */
public static class ScriptReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String script = intent.getStringExtra("script");
if (script == null) {
return;
}
InputManager im = (InputManager)
context.getSystemService(Context.INPUT_SERVICE);
new Thread(() -> execute(im, script), "TouchInject").start();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String script = intent != null ? intent.getStringExtra("script") : null;
if (script == null) {
stopSelf();
return START_NOT_STICKY;
}
InputManager im = (InputManager) getSystemService(INPUT_SERVICE);
new Thread(() -> execute(im, script), "TouchInject").start();
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private static void execute(InputManager im, String script) {
Log.i(TAG, "=== script: " + script);
// finger number (1-based) -> [x, y]; insertion order = pointer index.
LinkedHashMap<Integer, float[]> fingers = new LinkedHashMap<>();
long downTime = 0;
String[] toks = script.split("\\s+");
int i = 0;
while (i < toks.length) {
String cmd = toks[i++];
try {
switch (cmd) {
case "down": {
int f = Integer.parseInt(toks[i++]);
float x = Float.parseFloat(toks[i++]);
float y = Float.parseFloat(toks[i++]);
int action = fingers.isEmpty()
? MotionEvent.ACTION_DOWN
: MotionEvent.ACTION_POINTER_DOWN;
int idx = fingers.size();
fingers.put(f, new float[]{x, y});
inject(im, action, idx, fingers, downTime);
if (downTime == 0) {
downTime = SystemClock.uptimeMillis();
}
break;
}
case "move": {
int f = Integer.parseInt(toks[i++]);
float x = Float.parseFloat(toks[i++]);
float y = Float.parseFloat(toks[i++]);
float[] p = fingers.get(f);
if (p == null) {
Log.w(TAG, "move of unknown finger " + f + " (skipped)");
break;
}
p[0] = x;
p[1] = y;
// Generic ACTION_MOVE for all moves (1 or N pointers):
// InputFlinger accepts it and GioView treats every
// pointer as a MOVE.
inject(im, MotionEvent.ACTION_MOVE, 0, fingers, downTime);
break;
}
case "up": {
int f = Integer.parseInt(toks[i++]);
if (!fingers.containsKey(f)) {
Log.w(TAG, "up of unknown finger " + f + " (skipped)");
break;
}
boolean last = fingers.size() == 1;
int action = last
? MotionEvent.ACTION_UP
: MotionEvent.ACTION_POINTER_UP;
int idx = indexOf(fingers, f);
// The lifted pointer must still be part of the event.
inject(im, action, idx, fingers, downTime);
fingers.remove(f);
if (fingers.isEmpty()) {
downTime = 0;
}
break;
}
case "wait": {
int ms = Integer.parseInt(toks[i++]);
Thread.sleep(ms);
break;
}
default:
Log.e(TAG, "unknown command: " + cmd);
}
} catch (Exception e) {
Log.e(TAG, "script error at '" + cmd + "': " + e);
break;
}
}
Log.i(TAG, "=== done");
}
private static int indexOf(LinkedHashMap<Integer, float[]> m, int f) {
int idx = 0;
for (Integer k : m.keySet()) {
if (k == f) {
return idx;
}
idx++;
}
return 0;
}
// INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT. The SDK stub jar omits the
// constant (and injectInputEvent itself), so both go through reflection;
// the method is a public API at runtime on the device.
private static final int INJECT_WAIT_FOR_RESULT = 1;
private static void inject(InputManager im, int action, int actionIndex,
Map<Integer, float[]> fingers, long downTime) {
int n = fingers.size();
int[] ids = new int[n];
MotionEvent.PointerCoords[] coords = new MotionEvent.PointerCoords[n];
int j = 0;
for (Map.Entry<Integer, float[]> e : fingers.entrySet()) {
ids[j] = e.getKey() - 1; // pointer id (0-based)
MotionEvent.PointerCoords c = new MotionEvent.PointerCoords();
c.x = e.getValue()[0];
c.y = e.getValue()[1];
c.pressure = 1f;
c.size = 1f;
// TOOL_TYPE_FINGER. The compile-time android.jar lacks
// PointerCoords.setToolType, but the device runtime (API 24+)
// has it, so call it reflectively.
try {
java.lang.reflect.Method stt = MotionEvent.PointerCoords.class
.getMethod("setToolType", int.class);
stt.invoke(c, 1);
} catch (Exception ignored) {
}
coords[j] = c;
j++;
}
long now = SystemClock.uptimeMillis();
int fullAction = action == MotionEvent.ACTION_MOVE
? action
: action | (actionIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT);
MotionEvent ev = MotionEvent.obtain(downTime, now, fullAction, n, ids, coords,
0 /*edgeFlags*/, 1f /*xPrecision*/, 1f /*yPrecision*/,
0 /*metaState*/, 0 /*deviceId*/,
0x4000003 /*SOURCE_TOUCH|SOURCE_CLASS_MASK*/, 0 /*displayId*/);
boolean ok = doInject(im, ev);
Log.i(TAG, String.format("inject action=%d idx=%d n=%d ids=%s ok=%b",
action, actionIndex, n, java.util.Arrays.toString(ids), ok));
ev.recycle();
}
private static boolean doInject(InputManager im, MotionEvent ev) {
try {
java.lang.reflect.Method m = InputManager.class.getMethod(
"injectInputEvent", android.view.InputEvent.class, int.class);
Object r = m.invoke(im, ev, INJECT_WAIT_FOR_RESULT);
return r instanceof Boolean && (Boolean) r;
} catch (Exception e) {
Throwable c = e.getCause() != null ? e.getCause() : e;
Log.e(TAG, "injectInputEvent failed: " + c);
return false;
}
}
}
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# Builds touchinject.apk (a privileged multi-touch gesture injector) from
# Injector.java using the local Android SDK. The APK must be installed under
# /system/priv-app for the INJECT_EVENTS (signature|privileged) permission to
# be granted — see the bottom of this file.
set -euo pipefail
cd "$(dirname "$0")"
SDK=/home/gmp/android-sdk
BT="$SDK/build-tools/35.0.0"
PLAT="$SDK/platforms/android-35/android.jar"
rm -rf build
mkdir -p build/classes
javac -nowarn -source 1.8 -target 1.8 -classpath "$PLAT" -d build/classes Injector.java
"$BT/d8" --release --min-api 24 --lib "$PLAT" --output build build/classes/touch/inject/*.class
# aapt2 resolves the android: namespace against the framework resource
# table, which is shipped inside android.jar (resources.arsc).
"$BT/aapt2" link --manifest AndroidManifest.xml -I "$PLAT" \
--min-sdk-version 24 --target-sdk-version 35 -o build/base.apk
cp build/base.apk build/touchinject-unsigned.apk
jar uf build/touchinject-unsigned.apk -C build classes.dex
if [ ! -f build/ts.jks ]; then
keytool -genkeypair -keystore build/ts.jks -storepass android -keypass android \
-alias ts -dname "CN=TouchInject, OU=Dev" -keyalg RSA -keysize 2048 -validity 10000
fi
"$BT/apksigner" sign --ks build/ts.jks --ks-pass pass:android --key-pass pass:android \
--out touchinject.apk build/touchinject-unsigned.apk
"$BT/apksigner" verify --print-certs touchinject.apk | head -1
echo "=== DONE: $(pwd)/touchinject.apk"
# --- Install as a privileged system app (emulator, rooted) ---------------
# SER=emulator-5554
# adb -s $SER root && adb -s $SER remount
# adb -s $SER shell mkdir -p /system/priv-app/TouchInject
# adb -s $SER push touchinject.apk /system/priv-app/TouchInject/TouchInject.apk
# adb -s $SER shell chmod 644 /system/priv-app/TouchInject/TouchInject.apk
# adb -s $SER reboot # permission grant is evaluated at install/boot
# adb -s $SER wait-for-device && adb -s $SER shell 'while [ -z $(getprop sys.boot_completed) ]; do sleep 1; done'
# adb -s $SER shell dumpsys package touch.inject | grep -A2 INJECT_EVENTS # granted=true
#
# --- Inject a gesture ------------------------------------------------------
# adb -s $SER shell am startservice -n touch.inject/.Injector \
# -e script "down 1 400 1000 wait 100 down 2 700 1200 wait 100 \
# move 1 380 980 move 2 720 1220 wait 50 \
# move 1 340 940 move 2 760 1260 wait 50 up 1 up 2"
# adb -s $SER logcat -d -s TouchInject
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env bash
# Pinch e2e test harness for the Pad emulator (aosp_atd AVD).
#
# The platform-signed touch.inject app (real MotionEvents through
# InputManager — the only multi-touch path that works in the emulator)
# drives the renderer's pinch probe; each gesture below is ONE script in
# ONE process (the injector's finger map is per-process).
#
# KNOWN FLAKES (both verified, both handled below):
# 1. The injector process is "cached" while its script thread runs and the
# 1.5 GB emulator OOM-kills it mid-script occasionally — the script
# never reaches "=== done". ti() checks logcat for the done line and
# re-runs (a re-run starts a fresh gesture; a stuck pointer from a
# half-run is replaced by the next ACTION_DOWN).
# 2. The app is on-demand-rendering at ~1 fps: a burst of moves within
# one frame's drain does not scroll (single-frame delta pattern).
# Scroll tests therefore space the moves >= 40 ms apart — which is
# also what a real finger produces over several frames.
#
# READING RESULTS: AppFontScale in the session file is the reliable pinch
# signal. Scroll in the session is NOT (the restore re-derives it from the
# pinned line anchor); for scroll tests compare the before/after
# screenshots instead.
SER=emulator-5554
export ANDROID_SERIAL=$SER
ti() {
local script="$1"
for attempt in 1 2 3; do
adb logcat -c 2>/dev/null
adb shell 'am broadcast -n "touch.inject/.Injector$ScriptReceiver" --es script "'"$script"'"' >/dev/null 2>&1
sleep 4
if adb shell logcat -d 2>/dev/null | grep -aq "TouchInject: === done"; then
return 0
fi
echo " (injection incomplete, attempt $attempt — retrying)"
done
echo " !! injection failed after 3 attempts"
return 1
}
# ensure Pad is in the foreground (the ATD launcher intermittently holds
# focus after a cold start; a backgrounded app receives no touch)
fg() {
for i in 1 2 3 4 5; do
FOC=$(adb shell 'dumpsys window | grep mCurrentFocus')
case "$FOC" in *pad.pad*) return 0;; esac
adb shell am start -n pad.pad/org.gioui.GioActivity >/dev/null 2>&1
sleep 8
done
echo " !! Pad never gained focus: $FOC"
return 1
}
dbg() { adb shell "echo '$1' > /sdcard/PadPerf/cmd"; sleep 1.5; }
shot() { adb exec-out screencap -p > "$1"; }
# force-stop (flushes the session), print it, relaunch + reopen the file
measure() {
adb shell am force-stop pad.pad
sleep 4
echo "session: $(adb shell cat /sdcard/Pad/session.json 2>/dev/null)"
adb shell am start -n pad.pad/org.gioui.GioActivity >/dev/null 2>&1
sleep 4
}
case "$1" in
t1) # single-finger scroll must NEVER change the font (device regression)
echo "=== T1: single-finger scroll (font must not change) ==="
fg || exit 1
shot /tmp/t1_before.png
S="down 1 720 1400 wait 80"
for y in 1320 1240 1160 1080 1000 920 840 760 680 600 520 440 360 280 200; do
S="$S move 1 720 $y wait 40"
done
S="$S wait 100 up 1"
ti "$S"
sleep 2
shot /tmp/t1_after.png # compare to before: content moved, same font size
measure
;;
t2) # two-finger pinch-out: font must scale, center anchored
echo "=== T2: two-finger pinch-out (font must grow) ==="
fg || exit 1
shot /tmp/t2_before.png
S="down 1 570 1200 wait 40 down 2 870 1200 wait 60"
for i in 1 2 3 4 5 6 7 8; do
x1=$((570 - i*37)); x2=$((870 + i*37))
S="$S move 1 $x1 1200 move 2 $x2 1200 wait 50"
done
S="$S wait 150 up 1 up 2"
ti "$S"
sleep 1
shot /tmp/t2_after.png
measure
;;
t3) # palm-first: the resting finger lands FIRST, the pinch pair is the
# two that move — the palm must never enter the distance
echo "=== T3: palm-first three fingers (pinch pair = the two movers) ==="
fg || exit 1
shot /tmp/t3_before.png
S="down 1 720 400 wait 100 down 2 570 1200 wait 60 down 3 870 1200 wait 150"
for i in 1 2 3 4 5 6 7 8; do
x2=$((570 - i*37)); x3=$((870 + i*37))
S="$S move 2 $x2 1200 move 3 $x3 1200 wait 50"
done
S="$S wait 150 up 2 up 3 wait 50 up 1"
ti "$S"
sleep 1
shot /tmp/t3_after.png
measure
;;
t4) # lift one finger mid-pinch: survivor must SCROLL, not zoom
echo "=== T4: lift finger mid-pinch (survivor scrolls, no more zoom) ==="
fg || exit 1
shot /tmp/t4_before.png
S="down 1 570 1200 wait 40 down 2 870 1200 wait 60 move 1 533 1200 move 2 907 1200 wait 80 up 2 wait 80"
for y in 1280 1360 1440 1520 1600 1680 1760 1840 1920 2000; do
S="$S move 1 533 $y wait 40" # survivor (finger 1) keeps its own x
done
S="$S wait 100 up 1"
ti "$S"
sleep 1
shot /tmp/t4_after.png # compare to before: content scrolled, font frozen
measure
;;
reset) # back to a known state (one command per file — no pipes)
dbg "fontsize 1"; dbg "top"
;;
*) echo "usage: $0 t1|t2|t3|t4|reset" ;;
esac