From e44d5c91f3a91af2f13ffb9c9aab74889865b613 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 01:12:23 +0000 Subject: [PATCH 1/2] Converter: tolerate bundled copies of JDK internals that HotSpot's module system refuses An APK that bundles classes extending JDK-internal ones (com.sun.*, sun.*, jdk.internal.*) made the conversion fail fatally on 135 classes, although ART would only fail them if reached. The decision logic moves to Linkage.java and now also defers 'cannot access class X (in module M) because module M does not export ...' and 'cannot inherit from final class X' unless X is an Android framework class. Adds dex_linkage with HotSpot's wording and cases that must stay fatal. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01PJPA3yakkwfTojo9mNCzmA --- tests/java/CMakeLists.txt | 3 + .../java/converter_linkage/LinkageCheck.java | 75 +++++++++++++++++++ tests/java/converter_linkage_test.py | 20 +++++ tools/dex/rewriter/ApkCache.java | 25 +------ tools/dex/rewriter/Linkage.java | 62 +++++++++++++++ 5 files changed, 161 insertions(+), 24 deletions(-) create mode 100644 tests/java/converter_linkage/LinkageCheck.java create mode 100644 tests/java/converter_linkage_test.py create mode 100644 tools/dex/rewriter/Linkage.java diff --git a/tests/java/CMakeLists.txt b/tests/java/CMakeLists.txt index 455a7e8..6743080 100644 --- a/tests/java/CMakeLists.txt +++ b/tests/java/CMakeLists.txt @@ -55,6 +55,9 @@ if(TARGET venture-framework) # R8's superclass-constructor calls on a new-instance (Open Brush, Unity's UnityPlayer). add_test(NAME dex_super_init COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/super_init_test.py") set_tests_properties(dex_super_init PROPERTIES TIMEOUT 120) + # Which converter verification failures are deferred linkage and which stop an app from starting. + add_test(NAME dex_linkage COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/converter_linkage_test.py") + set_tests_properties(dex_linkage PROPERTIES TIMEOUT 120) # Several JVM fixtures take ~16 s even on an idle host. Assertions in the # fixtures test behavior; this bound only catches a stalled suite. diff --git a/tests/java/converter_linkage/LinkageCheck.java b/tests/java/converter_linkage/LinkageCheck.java new file mode 100644 index 0000000..4eea672 --- /dev/null +++ b/tests/java/converter_linkage/LinkageCheck.java @@ -0,0 +1,75 @@ +package com.venture.dex; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** Which verification failures stop an app from starting (Linkage.deferred). The messages are + * HotSpot's own wording, taken from a converted APK that bundles copies of the JDK's internals. */ +public final class LinkageCheck { + static int failures; + static final Set FRAMEWORK = Set.of("android/view/View", "android/app/Activity"); + + static Map failure(String stage, String kind, String detail) { + Map f = new HashMap<>(); + f.put("stage", stage); + f.put("kind", kind); + f.put("detail", detail); + f.put("class", "app.Example"); + return f; + } + + static void check(boolean expected, String what, Map f) { + boolean actual = Linkage.deferred(f, FRAMEWORK); + if (actual != expected) { + failures++; + System.out.println("FAIL: " + what + ": expected " + (expected ? "deferred" : "fatal") + ", got " + (actual ? "deferred" : "fatal")); + } + } + + public static void main(String[] args) { + String hs = "hotspot"; + String iae = "java.lang.IllegalAccessError"; + // Deferred: they fail only when reached, as on ART. + check(true, "missing framework method", failure("framework-member", "java.lang.NoSuchMethodError", "android/view/View.foo()V")); + check(true, "missing frame hierarchy", failure("frames", null, "missing frame hierarchy: app/Missing")); + check(true, "app class in java.* package", failure(hs, "java.lang.SecurityException", "Prohibited package name: java.awt")); + check(true, "missing class", failure(hs, "java.lang.NoClassDefFoundError", "app/Gone")); + check(true, "class that does not verify", failure(hs, "java.lang.VerifyError", "Bad type on operand stack")); + check(true, "package-private super in another app package", + failure(hs, iae, "class app.a.Child cannot access its superclass app.b.Stub")); + check(true, "super in a JDK package the module does not export (java.base)", + failure(hs, iae, "superclass access check failed: class com.sun.net.ssl.internal.www.protocol.https.Handler (in unnamed module @0x5955568) " + + "cannot access class sun.net.www.protocol.https.Handler (in module java.base) because module java.base does not export " + + "sun.net.www.protocol.https to unnamed module @0x5955568")); + check(true, "interface in a JDK package the module does not export (java.xml)", + failure(hs, iae, "superinterface check failed: class com.sun.org.apache.bcel.internal.generic.InstructionComparator$1 (in unnamed module @0x5955568) " + + "cannot access class com.sun.org.apache.bcel.internal.generic.InstructionComparator (in module java.xml) because module java.xml " + + "does not export com.sun.org.apache.bcel.internal.generic to unnamed module @0x5955568")); + check(true, "subclass of a JDK class that is final here", + failure(hs, "java.lang.IncompatibleClassChangeError", "class sun.java2d.pipe.Region$ImmutableRegion cannot inherit from final class sun.java2d.pipe.Region")); + + // Fatal: these are Venture's own gaps or real defects. + check(false, "inaccessible framework superclass (old wording)", + failure(hs, iae, "class app.Child cannot access its superclass android.view.View")); + check(false, "inaccessible framework class (module wording)", + failure(hs, iae, "superclass access check failed: class app.Child (in unnamed module @0x1) cannot access class android.app.Activity " + + "(in module x) because module x does not export android.app to unnamed module @0x1")); + check(false, "framework class that is final here", + failure(hs, "java.lang.IncompatibleClassChangeError", "class app.Child cannot inherit from final class android.view.View")); + check(false, "other class-change error", + failure(hs, "java.lang.IncompatibleClassChangeError", "Class app.A does not implement the requested interface app.B")); + check(false, "other access error", + failure(hs, iae, "class app.A tried to access private method 'void app.B.hidden()'")); + check(false, "other security error", + failure(hs, "java.lang.SecurityException", "signer information does not match signer information of other classes in the same package")); + check(false, "frames failure that is not a missing hierarchy", failure("frames", null, "inconsistent stackmap frames at app/A.run")); + check(false, "unknown stage", failure("pipeline", null, "boom")); + + if (failures != 0) { + System.out.println(failures + " check(s) failed"); + System.exit(1); + } + System.out.println("linkage checks passed"); + } +} diff --git a/tests/java/converter_linkage_test.py b/tests/java/converter_linkage_test.py new file mode 100644 index 0000000..1e3f840 --- /dev/null +++ b/tests/java/converter_linkage_test.py @@ -0,0 +1,20 @@ +"""Which converter verification failures stop an app from starting: compiles the production rewriter and +runs tests/java/converter_linkage/LinkageCheck.java against its deferred-linkage rules.""" +from pathlib import Path +import os +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tools/dex")) +from convert_apk import build_tools, java_path, java_tool + +FIXTURE = ROOT / "tests/java/converter_linkage" + +with tempfile.TemporaryDirectory(prefix="venture-linkage-") as directory: + tools = java_path(build_tools()) + checks = Path(directory) / "classes" + subprocess.run([java_tool("javac"), "-encoding", "UTF-8", "--release", "21", "-cp", tools, "-d", str(checks), + str(FIXTURE / "LinkageCheck.java")], check=True) + subprocess.run([java_tool("java"), "-cp", os.pathsep.join([tools, str(checks)]), "com.venture.dex.LinkageCheck"], check=True) diff --git a/tools/dex/rewriter/ApkCache.java b/tools/dex/rewriter/ApkCache.java index 98e8bc4..2192aea 100644 --- a/tools/dex/rewriter/ApkCache.java +++ b/tools/dex/rewriter/ApkCache.java @@ -330,8 +330,6 @@ static Map.Entry> convertLocked(Path apk, String pkg, return publish(work, context, report); } - static final Pattern INACCESSIBLE_SUPER = Pattern.compile("cannot access its (?:abstract )?super(?:class|interface) (\\S+)"); - static Set classNames(List jars) throws IOException { Set names = new HashSet<>(); for (Path jar : jars) @@ -345,28 +343,7 @@ static Set classNames(List jars) throws IOException { } static boolean deferredLinkage(Map f, Set frameworkClasses) { - // A missing framework method or field fails only the call that reaches it, as on ART. - if ("framework-member".equals(f.get("stage"))) return true; - if ("frames".equals(f.get("stage"))) return str(f, "detail").contains("missing frame hierarchy:"); - if ("hotspot".equals(f.get("stage"))) { - // A class that does not verify fails when it is reached, as ART - // fails a method when it runs; bundled SDK code a VR game never - // reaches must not stop the game. - Object kind = f.get("kind"); - // HotSpot refuses app classes in java.* packages, which ART loads; - // Stremio's libVLC bundles Blu-ray menu classes in java.awt and java.io. - if ("java.lang.SecurityException".equals(kind)) return str(f, "detail").startsWith("Prohibited package name:"); - // ART links a class when it is first used and fails it then. An app class that cannot - // access another app class (Alcove's media-compat classes extend a package-private - // Stub in another package) is the app's own; an inaccessible framework class is ours. - if ("java.lang.IllegalAccessError".equals(kind)) { - Matcher m = INACCESSIBLE_SUPER.matcher(str(f, "detail")); - return m.find() && !frameworkClasses.contains(m.group(1).replace('.', '/')); - } - return "java.lang.NoClassDefFoundError".equals(kind) || "java.lang.ClassNotFoundException".equals(kind) - || "java.lang.VerifyError".equals(kind); - } - return false; + return Linkage.deferred(f, frameworkClasses); } static void declarations(List failures, String label, Set expected, Set actual) { diff --git a/tools/dex/rewriter/Linkage.java b/tools/dex/rewriter/Linkage.java new file mode 100644 index 0000000..3d12587 --- /dev/null +++ b/tools/dex/rewriter/Linkage.java @@ -0,0 +1,62 @@ +package com.venture.dex; + +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Which verification failures of a converted APK are deferred linkage: they fail only when the + * class or method is reached, as on ART, so they must not stop the app from starting. */ +final class Linkage { + private Linkage() {} + + static final Pattern INACCESSIBLE_SUPER = Pattern.compile("cannot access its (?:abstract )?super(?:class|interface) (\\S+)"); + // HotSpot's module system refuses an app class that extends or implements a class in a package + // its JDK module does not export. A library that bundles a copy of the JDK's own internals + // (a Blu-ray player's java.awt peers, an XML stack's com.sun classes) has such classes. ART has no + // modules and loads a class only when it is used, so they never fail unless the app reaches them. + static final Pattern UNEXPORTED_SUPER = Pattern.compile( + "cannot access class (\\S+) \\(in module \\S+\\) because module \\S+ does not export"); + // The same bundled copies can subclass a JDK class that is final in this JDK. + static final Pattern FINAL_SUPER = Pattern.compile("cannot inherit from final class (\\S+)"); + + static boolean deferred(Map f, Set frameworkClasses) { + // A missing framework method or field fails only the call that reaches it, as on ART. + if ("framework-member".equals(f.get("stage"))) return true; + if ("frames".equals(f.get("stage"))) return str(f, "detail").contains("missing frame hierarchy:"); + if ("hotspot".equals(f.get("stage"))) { + // A class that does not verify fails when it is reached, as ART + // fails a method when it runs; bundled SDK code a VR game never + // reaches must not stop the game. + Object kind = f.get("kind"); + String detail = str(f, "detail"); + // HotSpot refuses app classes in java.* packages, which ART loads; + // Stremio's libVLC bundles Blu-ray menu classes in java.awt and java.io. + if ("java.lang.SecurityException".equals(kind)) return detail.startsWith("Prohibited package name:"); + // ART links a class when it is first used and fails it then. An app class that cannot + // access another app class (Alcove's media-compat classes extend a package-private + // Stub in another package) is the app's own; an inaccessible framework class is ours. + if ("java.lang.IllegalAccessError".equals(kind)) { + Matcher m = INACCESSIBLE_SUPER.matcher(detail); + boolean found = m.find(); + if (!found) { + m = UNEXPORTED_SUPER.matcher(detail); + found = m.find(); + } + return found && !frameworkClasses.contains(m.group(1).replace('.', '/')); + } + if ("java.lang.IncompatibleClassChangeError".equals(kind)) { + Matcher m = FINAL_SUPER.matcher(detail); + return m.find() && !frameworkClasses.contains(m.group(1).replace('.', '/')); + } + return "java.lang.NoClassDefFoundError".equals(kind) || "java.lang.ClassNotFoundException".equals(kind) + || "java.lang.VerifyError".equals(kind); + } + return false; + } + + private static String str(Map map, String key) { + Object value = map.get(key); + return value == null ? "" : value.toString(); + } +} From 2dd82a35b1ecf536c2ac4a74f03194b7be1c4a3e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:54:44 +0000 Subject: [PATCH 2/2] Framework: add android.view.GestureDetector The class and its listener interfaces were missing, so an app that builds touch handling into its views stopped on NoClassDefFoundError at startup. Taps, scrolls, flings, double taps and long presses follow the first pointer; context clicks are not reported. Adds framework_gesture_detector. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01PJPA3yakkwfTojo9mNCzmA --- .../android/view/GestureDetector.java | 368 ++++++++++++++++++ tests/java/CMakeLists.txt | 5 +- tests/java/GestureDetectorTest.java | 161 ++++++++ 3 files changed, 533 insertions(+), 1 deletion(-) create mode 100644 src/runtime/java/framework/android/view/GestureDetector.java create mode 100644 tests/java/GestureDetectorTest.java diff --git a/src/runtime/java/framework/android/view/GestureDetector.java b/src/runtime/java/framework/android/view/GestureDetector.java new file mode 100644 index 0000000..311e5b0 --- /dev/null +++ b/src/runtime/java/framework/android/view/GestureDetector.java @@ -0,0 +1,368 @@ +package android.view; + +import android.content.Context; +import android.os.Handler; +import android.os.Looper; + +/** + * Recognizes taps, double taps, long presses, scrolls and flings in a stream of single-pointer touch + * events and reports them to listeners, with the public API of android.view.GestureDetector. + * + *

Timing and distances come from {@link ViewConfiguration}. Two simplifications: a gesture follows + * the first pointer only (a second finger ends tap recognition), and context clicks (a stylus or + * mouse button press) are not reported, because {@link MotionEvent} has no button actions here. + * A PC VR session produces no touch input; this exists so apps that build touch handling into their + * views, such as video players, load and run. + */ +public class GestureDetector { + /** Notified of the gestures: touch down, press, tap, scroll, long press and fling. */ + public interface OnGestureListener { + boolean onDown(MotionEvent e); + void onShowPress(MotionEvent e); + boolean onSingleTapUp(MotionEvent e); + boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY); + void onLongPress(MotionEvent e); + boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); + } + + /** Notified of double taps and of single taps that are not the first half of a double tap. */ + public interface OnDoubleTapListener { + boolean onSingleTapConfirmed(MotionEvent e); + boolean onDoubleTap(MotionEvent e); + boolean onDoubleTapEvent(MotionEvent e); + } + + /** Notified of context clicks. */ + public interface OnContextClickListener { + boolean onContextClick(MotionEvent e); + } + + /** All three listeners with empty implementations, to override only what is needed. */ + public static class SimpleOnGestureListener + implements OnGestureListener, OnDoubleTapListener, OnContextClickListener { + public boolean onSingleTapUp(MotionEvent e) { + return false; + } + public void onLongPress(MotionEvent e) {} + public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { + return false; + } + public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { + return false; + } + public void onShowPress(MotionEvent e) {} + public boolean onDown(MotionEvent e) { + return false; + } + public boolean onDoubleTap(MotionEvent e) { + return false; + } + public boolean onDoubleTapEvent(MotionEvent e) { + return false; + } + public boolean onSingleTapConfirmed(MotionEvent e) { + return false; + } + public boolean onContextClick(MotionEvent e) { + return false; + } + } + + // A second tap closer in time than this is a bounce, not a double tap. + private static final int DOUBLE_TAP_MIN_TIME = 40; + // Velocity is taken over the touch samples of this many milliseconds. + private static final long VELOCITY_WINDOW = 100; + private static final int MAX_SAMPLES = 8; + + private final OnGestureListener listener; + private OnDoubleTapListener doubleTapListener; + private OnContextClickListener contextClickListener; + private final Handler handler; + private final int touchSlopSquare; + private final int biggerTouchSlopSquare; + private final int doubleTapSlopSquare; + private final int minimumFlingVelocity; + private final int maximumFlingVelocity; + + private boolean longpressEnabled = true; + private boolean stillDown; + private boolean inLongPress; + private boolean alwaysInTapRegion; + private boolean alwaysInBiggerTapRegion; + private boolean deferConfirmSingleTap; + private boolean doubleTapping; + private boolean pendingTapConfirm; + private boolean ignoreNextUp; + private MotionEvent currentDown; + private MotionEvent previousUp; + private float downX, downY, lastX, lastY; + private final long[] sampleTime = new long[MAX_SAMPLES]; + private final float[] sampleX = new float[MAX_SAMPLES]; + private final float[] sampleY = new float[MAX_SAMPLES]; + private int sampleCount; + + private final Runnable showPress = new Runnable() { + public void run() { + if (currentDown != null) listener.onShowPress(currentDown); + } + }; + private final Runnable longPress = new Runnable() { + public void run() { + if (currentDown == null) return; + handler.removeCallbacks(confirmTap); + pendingTapConfirm = false; + deferConfirmSingleTap = false; + inLongPress = true; + listener.onLongPress(currentDown); + } + }; + private final Runnable confirmTap = new Runnable() { + public void run() { + pendingTapConfirm = false; + if (doubleTapListener == null) return; + if (!stillDown) doubleTapListener.onSingleTapConfirmed(currentDown); + else deferConfirmSingleTap = true; + } + }; + + /** A detector for events from the calling thread, with default touch distances. */ + public GestureDetector(OnGestureListener listener) { + this(null, listener, null); + } + + public GestureDetector(OnGestureListener listener, Handler handler) { + this(null, listener, handler); + } + + public GestureDetector(Context context, OnGestureListener listener) { + this(context, listener, null); + } + + public GestureDetector(Context context, OnGestureListener listener, Handler handler) { + if (listener == null) throw new NullPointerException("OnGestureListener must not be null"); + this.listener = listener; + if (listener instanceof OnDoubleTapListener) setOnDoubleTapListener((OnDoubleTapListener) listener); + if (listener instanceof OnContextClickListener) setContextClickListener((OnContextClickListener) listener); + if (handler != null) { + this.handler = handler; + } else { + Looper looper = Looper.myLooper() != null ? Looper.myLooper() : Looper.getMainLooper(); + this.handler = new Handler(looper); + } + ViewConfiguration configuration = context != null ? ViewConfiguration.get(context) : new ViewConfiguration(); + int slop = configuration.getScaledTouchSlop(); + int doubleTapSlop = configuration.getScaledDoubleTapSlop(); + minimumFlingVelocity = configuration.getScaledMinimumFlingVelocity(); + maximumFlingVelocity = configuration.getScaledMaximumFlingVelocity(); + touchSlopSquare = slop * slop; + // The region within which a second tap may still pair with the first: 2.5 times the touch slop. + int bigger = Math.round(slop * 2.5f); + biggerTouchSlopSquare = bigger * bigger; + doubleTapSlopSquare = doubleTapSlop * doubleTapSlop; + } + + public void setOnDoubleTapListener(OnDoubleTapListener listener) { + doubleTapListener = listener; + } + + public void setContextClickListener(OnContextClickListener listener) { + contextClickListener = listener; + } + + /** Whether a held touch is reported as a long press (on by default). */ + public void setIsLongpressEnabled(boolean enabled) { + longpressEnabled = enabled; + } + + public boolean isLongpressEnabled() { + return longpressEnabled; + } + + /** Feeds a touch event; true if a listener handled it. */ + public boolean onTouchEvent(MotionEvent ev) { + final int action = ev.getActionMasked(); + final float x = ev.getX(); + final float y = ev.getY(); + boolean handled = false; + switch (action) { + case MotionEvent.ACTION_POINTER_DOWN: + case MotionEvent.ACTION_POINTER_UP: + // A second finger is not a tap or a one-finger scroll. + alwaysInTapRegion = false; + alwaysInBiggerTapRegion = false; + cancelTimers(); + break; + case MotionEvent.ACTION_DOWN: { + if (doubleTapListener != null) { + boolean hadTapMessage = pendingTapConfirm; + if (hadTapMessage) { + handler.removeCallbacks(confirmTap); + pendingTapConfirm = false; + } + if (currentDown != null && previousUp != null && hadTapMessage + && isConsideredDoubleTap(currentDown, previousUp, ev)) { + doubleTapping = true; + handled |= doubleTapListener.onDoubleTap(currentDown); + handled |= doubleTapListener.onDoubleTapEvent(ev); + } else { + handler.postDelayed(confirmTap, ViewConfiguration.getDoubleTapTimeout()); + pendingTapConfirm = true; + } + } + downX = lastX = x; + downY = lastY = y; + currentDown = copy(ev); + alwaysInTapRegion = true; + alwaysInBiggerTapRegion = true; + stillDown = true; + inLongPress = false; + deferConfirmSingleTap = false; + sampleCount = 0; + addSample(ev); + if (longpressEnabled) { + handler.removeCallbacks(longPress); + handler.postDelayed(longPress, + ViewConfiguration.getTapTimeout() + ViewConfiguration.getLongPressTimeout()); + } + handler.removeCallbacks(showPress); + handler.postDelayed(showPress, ViewConfiguration.getTapTimeout()); + handled |= listener.onDown(ev); + break; + } + case MotionEvent.ACTION_MOVE: { + if (inLongPress) break; + addSample(ev); + final float scrollX = lastX - x; + final float scrollY = lastY - y; + if (doubleTapping) { + handled |= doubleTapListener.onDoubleTapEvent(ev); + } else if (alwaysInTapRegion) { + final int deltaX = (int) (x - downX); + final int deltaY = (int) (y - downY); + final int distance = deltaX * deltaX + deltaY * deltaY; + if (distance > touchSlopSquare) { + handled = listener.onScroll(currentDown, ev, scrollX, scrollY); + lastX = x; + lastY = y; + alwaysInTapRegion = false; + cancelTimers(); + } + if (distance > biggerTouchSlopSquare) alwaysInBiggerTapRegion = false; + } else if (Math.abs(scrollX) >= 1 || Math.abs(scrollY) >= 1) { + handled = listener.onScroll(currentDown, ev, scrollX, scrollY); + lastX = x; + lastY = y; + } + break; + } + case MotionEvent.ACTION_UP: { + stillDown = false; + MotionEvent currentUp = copy(ev); + if (doubleTapping) { + handled |= doubleTapListener.onDoubleTapEvent(ev); + } else if (inLongPress) { + handler.removeCallbacks(confirmTap); + pendingTapConfirm = false; + inLongPress = false; + } else if (alwaysInTapRegion && !ignoreNextUp) { + handled = listener.onSingleTapUp(ev); + if (deferConfirmSingleTap && doubleTapListener != null) doubleTapListener.onSingleTapConfirmed(ev); + } else if (!ignoreNextUp) { + addSample(ev); + float[] velocity = velocity(); + if (Math.abs(velocity[1]) > minimumFlingVelocity || Math.abs(velocity[0]) > minimumFlingVelocity) + handled = listener.onFling(currentDown, ev, velocity[0], velocity[1]); + } + if (previousUp != null) previousUp.recycle(); + previousUp = currentUp; + doubleTapping = false; + deferConfirmSingleTap = false; + ignoreNextUp = false; + cancelTimers(false); + break; + } + case MotionEvent.ACTION_CANCEL: + cancel(); + break; + default: + break; + } + return handled; + } + + /** Feeds a generic (non-touch) motion event; context clicks are not reported, so always false. */ + public boolean onGenericMotionEvent(MotionEvent ev) { + return false; + } + + private boolean isConsideredDoubleTap(MotionEvent firstDown, MotionEvent firstUp, MotionEvent secondDown) { + if (!alwaysInBiggerTapRegion) return false; + final long deltaTime = secondDown.getEventTime() - firstUp.getEventTime(); + if (deltaTime > ViewConfiguration.getDoubleTapTimeout() || deltaTime < DOUBLE_TAP_MIN_TIME) return false; + int deltaX = (int) firstDown.getX() - (int) secondDown.getX(); + int deltaY = (int) firstDown.getY() - (int) secondDown.getY(); + return deltaX * deltaX + deltaY * deltaY < doubleTapSlopSquare; + } + + private void cancelTimers() { + cancelTimers(true); + } + + private void cancelTimers(boolean includeTap) { + handler.removeCallbacks(showPress); + handler.removeCallbacks(longPress); + if (includeTap) { + handler.removeCallbacks(confirmTap); + pendingTapConfirm = false; + } + deferConfirmSingleTap = false; + } + + private void cancel() { + cancelTimers(); + sampleCount = 0; + doubleTapping = false; + stillDown = false; + alwaysInTapRegion = false; + alwaysInBiggerTapRegion = false; + deferConfirmSingleTap = false; + if (inLongPress) inLongPress = false; + } + + // The first pointer's position as a single-pointer event of its own. + private static MotionEvent copy(MotionEvent e) { + return MotionEvent.obtain(e.getDownTime(), e.getEventTime(), e.getActionMasked(), e.getX(), e.getY(), + e.getMetaState()); + } + + private void addSample(MotionEvent e) { + if (sampleCount == MAX_SAMPLES) { + System.arraycopy(sampleTime, 1, sampleTime, 0, MAX_SAMPLES - 1); + System.arraycopy(sampleX, 1, sampleX, 0, MAX_SAMPLES - 1); + System.arraycopy(sampleY, 1, sampleY, 0, MAX_SAMPLES - 1); + sampleCount--; + } + sampleTime[sampleCount] = e.getEventTime(); + sampleX[sampleCount] = e.getX(); + sampleY[sampleCount] = e.getY(); + sampleCount++; + } + + // Pixels per second over the recent samples, limited to the maximum fling velocity. + private float[] velocity() { + float[] out = new float[2]; + if (sampleCount < 2) return out; + int last = sampleCount - 1; + int first = last; + while (first > 0 && sampleTime[last] - sampleTime[first - 1] <= VELOCITY_WINDOW) first--; + long elapsed = sampleTime[last] - sampleTime[first]; + if (elapsed <= 0) return out; + out[0] = clamp((sampleX[last] - sampleX[first]) * 1000f / elapsed); + out[1] = clamp((sampleY[last] - sampleY[first]) * 1000f / elapsed); + return out; + } + + private float clamp(float velocity) { + return Math.max(-maximumFlingVelocity, Math.min(maximumFlingVelocity, velocity)); + } +} diff --git a/tests/java/CMakeLists.txt b/tests/java/CMakeLists.txt index 6743080..11c0682 100644 --- a/tests/java/CMakeLists.txt +++ b/tests/java/CMakeLists.txt @@ -25,8 +25,9 @@ if(TARGET venture-framework) "${CMAKE_CURRENT_SOURCE_DIR}/DownloadManagerTest.java" "${CMAKE_CURRENT_SOURCE_DIR}/AndroidKeyStoreTest.java" "${CMAKE_CURRENT_SOURCE_DIR}/InstrumentationProbe.java" + "${CMAKE_CURRENT_SOURCE_DIR}/GestureDetectorTest.java" DEPENDS "${VENTURE_FRAMEWORK_JAR}" FrameworkTest.java AbiProfileTest.java VMStackTest.java ProcessExitTest.java ProcessCommandsTest.java - ColdRestartTest.java LifecycleTest.java LocalServicesTest.java PreferencesTest.java AssetReadTraceTest.java RecordingHost.java TestNatives.java GraphicsTest.java ThermalTest.java MenuQuitTest.java SQLiteTest.java WebkitTest.java DownloadManagerTest.java AndroidKeyStoreTest.java InstrumentationProbe.java VERBATIM) + ColdRestartTest.java LifecycleTest.java LocalServicesTest.java PreferencesTest.java AssetReadTraceTest.java RecordingHost.java TestNatives.java GraphicsTest.java ThermalTest.java MenuQuitTest.java SQLiteTest.java WebkitTest.java DownloadManagerTest.java AndroidKeyStoreTest.java InstrumentationProbe.java GestureDetectorTest.java VERBATIM) add_custom_target(venture_framework_tests ALL DEPENDS "${framework_test_classes}/FrameworkTest.class") if(WIN32) set(framework_classpath "${VENTURE_FRAMEWORK_JAR}\;${framework_test_classes}") @@ -43,6 +44,8 @@ if(TARGET venture-framework) set_tests_properties(framework_webkit PROPERTIES TIMEOUT 30) add_test(NAME framework_download_manager COMMAND "${VENTURE_JAVA}" -Xverify:all -cp "${framework_classpath}" android.app.DownloadManagerTest) set_tests_properties(framework_download_manager PROPERTIES TIMEOUT 60) + add_test(NAME framework_gesture_detector COMMAND "${VENTURE_JAVA}" -Xverify:all -cp "${framework_classpath}" GestureDetectorTest) + set_tests_properties(framework_gesture_detector PROPERTIES TIMEOUT 60) add_test(NAME framework_android_keystore COMMAND "${VENTURE_JAVA}" -Xverify:all -cp "${framework_classpath}" AndroidKeyStoreTest) set_tests_properties(framework_android_keystore PROPERTIES TIMEOUT 60) diff --git a/tests/java/GestureDetectorTest.java b/tests/java/GestureDetectorTest.java new file mode 100644 index 0000000..3a5c56f --- /dev/null +++ b/tests/java/GestureDetectorTest.java @@ -0,0 +1,161 @@ +import android.os.Handler; +import android.os.Looper; +import android.view.GestureDetector; +import android.view.MotionEvent; + +/** android.view.GestureDetector: taps, scrolls, flings, double taps, long presses and cancels. */ +public final class GestureDetectorTest { + static int failures; + + static void check(boolean ok, String what) { + if (!ok) { + failures++; + System.out.println("FAIL: " + what); + } + } + + /** Counts what the detector reports. */ + static final class Recorder extends GestureDetector.SimpleOnGestureListener { + int down, showPress, singleTapUp, scroll, longPress, fling, doubleTap, doubleTapEvent, confirmed; + float lastDistanceX, lastDistanceY, lastVelocityX; + MotionEvent scrollFirst; + @Override public boolean onDown(MotionEvent e) { down++; return true; } + @Override public void onShowPress(MotionEvent e) { showPress++; } + @Override public boolean onSingleTapUp(MotionEvent e) { singleTapUp++; return true; } + @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) { + scroll++; lastDistanceX = dx; lastDistanceY = dy; scrollFirst = e1; return true; + } + @Override public void onLongPress(MotionEvent e) { longPress++; } + @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float vx, float vy) { + fling++; lastVelocityX = vx; return true; + } + @Override public boolean onDoubleTap(MotionEvent e) { doubleTap++; return true; } + @Override public boolean onDoubleTapEvent(MotionEvent e) { doubleTapEvent++; return true; } + @Override public boolean onSingleTapConfirmed(MotionEvent e) { confirmed++; return true; } + } + + static MotionEvent event(long down, long time, int action, float x, float y) { + return MotionEvent.obtain(down, time, action, x, y, 0); + } + + /** Runs body on a thread with its own Looper, which quits after waitMillis, so timers can fire. */ + static void withLooper(long waitMillis, java.util.function.Consumer body) throws Exception { + Thread thread = new Thread(() -> { + Looper.prepare(); + body.accept(Looper.myLooper()); + new Handler(Looper.myLooper()).postDelayed(() -> Looper.myLooper().quit(), waitMillis); + Looper.loop(); + }); + thread.start(); + thread.join(); + } + + public static void main(String[] args) throws Exception { + Looper.prepare(); + + // A quick touch and release in place is a tap. + Recorder r = new Recorder(); + GestureDetector d = new GestureDetector(null, r); + d.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + d.onTouchEvent(event(0, 50, MotionEvent.ACTION_UP, 100, 100)); + check(r.down == 1 && r.singleTapUp == 1 && r.scroll == 0 && r.fling == 0, "tap: down+singleTapUp only"); + + // Moving past the touch slop scrolls; the distance is the previous position minus the new one. + r = new Recorder(); + d = new GestureDetector(null, r); + MotionEvent down = event(0, 0, MotionEvent.ACTION_DOWN, 100, 100); + d.onTouchEvent(down); + d.onTouchEvent(event(0, 1000, MotionEvent.ACTION_MOVE, 100, 130)); + check(r.scroll == 1 && r.lastDistanceY == -30f && r.lastDistanceX == 0f, "scroll: reports distance, once past the slop"); + d.onTouchEvent(event(0, 2000, MotionEvent.ACTION_UP, 100, 130)); + check(r.fling == 0 && r.singleTapUp == 0, "slow release after a scroll is not a fling or a tap"); + + // Moving less than the slop is still a tap. + r = new Recorder(); + d = new GestureDetector(null, r); + d.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + d.onTouchEvent(event(0, 20, MotionEvent.ACTION_MOVE, 103, 102)); + d.onTouchEvent(event(0, 40, MotionEvent.ACTION_UP, 103, 102)); + check(r.scroll == 0 && r.singleTapUp == 1, "small jitter stays a tap"); + + // A fast swipe released at speed is a fling, with the velocity in pixels per second. + r = new Recorder(); + d = new GestureDetector(null, r); + d.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 0, 0)); + d.onTouchEvent(event(0, 30, MotionEvent.ACTION_MOVE, 100, 0)); + d.onTouchEvent(event(0, 60, MotionEvent.ACTION_UP, 200, 0)); + check(r.fling == 1 && r.lastVelocityX > 1000f && r.lastVelocityX <= 8000f * 4, "fling: reported with a velocity"); + + // Down, up, down again soon and close by is a double tap. + r = new Recorder(); + d = new GestureDetector(null, r); + d.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + d.onTouchEvent(event(0, 50, MotionEvent.ACTION_UP, 100, 100)); + d.onTouchEvent(event(150, 150, MotionEvent.ACTION_DOWN, 102, 101)); + d.onTouchEvent(event(150, 200, MotionEvent.ACTION_UP, 102, 101)); + check(r.doubleTap == 1 && r.doubleTapEvent >= 2, "double tap: reported with its events"); + + // Too soon is a bounce, too late is a second tap. + for (long second : new long[] {70, 450}) { + r = new Recorder(); + d = new GestureDetector(null, r); + d.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + d.onTouchEvent(event(0, 50, MotionEvent.ACTION_UP, 100, 100)); + d.onTouchEvent(event(second, second, MotionEvent.ACTION_DOWN, 100, 100)); + check(r.doubleTap == 0, "second tap at " + second + " ms is not a double tap"); + } + + // Too far away is not a double tap either. + r = new Recorder(); + d = new GestureDetector(null, r); + d.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + d.onTouchEvent(event(0, 50, MotionEvent.ACTION_UP, 100, 100)); + d.onTouchEvent(event(150, 150, MotionEvent.ACTION_DOWN, 600, 600)); + check(r.doubleTap == 0, "second tap far away is not a double tap"); + + // A listener is required. + boolean threw = false; + try { new GestureDetector(null, (GestureDetector.OnGestureListener) null); } catch (NullPointerException e) { threw = true; } + check(threw, "a null listener is refused"); + + // Timers: show press, long press, the confirmed single tap, long press off, and cancel. + final Recorder held = new Recorder(); + withLooper(900, looper -> { + GestureDetector detector = new GestureDetector(null, held); + detector.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + }); + check(held.showPress == 1 && held.longPress == 1, "holding reports show press then long press"); + + final Recorder released = new Recorder(); + withLooper(900, looper -> { + GestureDetector detector = new GestureDetector(null, released); + detector.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + detector.onTouchEvent(event(0, 40, MotionEvent.ACTION_UP, 100, 100)); + }); + check(released.longPress == 0 && released.confirmed == 1 && released.doubleTap == 0, + "a lone tap is confirmed after the double-tap window, with no long press"); + + final Recorder off = new Recorder(); + withLooper(900, looper -> { + GestureDetector detector = new GestureDetector(null, off); + detector.setIsLongpressEnabled(false); + check(!detector.isLongpressEnabled(), "long press can be turned off"); + detector.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + }); + check(off.longPress == 0, "no long press when disabled"); + + final Recorder cancelled = new Recorder(); + withLooper(900, looper -> { + GestureDetector detector = new GestureDetector(null, cancelled); + detector.onTouchEvent(event(0, 0, MotionEvent.ACTION_DOWN, 100, 100)); + detector.onTouchEvent(event(0, 10, MotionEvent.ACTION_CANCEL, 100, 100)); + }); + check(cancelled.longPress == 0 && cancelled.showPress == 0 && cancelled.singleTapUp == 0, "cancel stops the timers"); + + if (failures != 0) { + System.out.println(failures + " check(s) failed"); + System.exit(1); + } + System.out.println("gesture detector checks passed"); + } +}