蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 GestureDetector 回调序列、onFling 阈值修正及 GestureLibrary 相似度识别验证

PYTHONWindows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。explore-tutorial-gestures.py
explore-tutorial-gestures.py237 行
"""Offline Android GestureDetector, SimpleOnGestureListener fling, and GestureLibrary verifier."""
import json
import math

VERSION = "CPython 3.12.14 offline Android component/IPC/Fragment verifier (Android SDK/emulator absent)"


class SimulatedGestureDetector:
    """Models MotionEvent -> GestureDetector -> OnGestureListener callback sequence."""

    SHOW_PRESS_MS = 100
    LONG_PRESS_MS = 500
    TOUCH_SLOP = 16.0
    MIN_FLING_VELOCITY = 300.0  # px/s

    def process_sequence(self, events: list[tuple[str, float, float, int]]) -> list[str]:
        callbacks = []
        down_ev = None
        last_ev = None
        moved = False
        show_press_fired = False
        long_press_fired = False

        for action, x, y, ts in events:
            if action == "DOWN":
                down_ev = (x, y, ts)
                last_ev = down_ev
                callbacks.append("onDown")
            elif action == "HOLD" and down_ev is not None:
                dt = ts - down_ev[2]
                if not moved and dt >= self.SHOW_PRESS_MS and not show_press_fired:
                    show_press_fired = True
                    callbacks.append("onShowPress")
                if not moved and dt >= self.LONG_PRESS_MS and not long_press_fired:
                    long_press_fired = True
                    callbacks.append("onLongPress")
            elif action == "MOVE" and down_ev is not None:
                dt = ts - down_ev[2]
                if not moved and dt >= self.SHOW_PRESS_MS and not show_press_fired:
                    show_press_fired = True
                    callbacks.append("onShowPress")
                dist = math.hypot(x - down_ev[0], y - down_ev[1])
                if dist > self.TOUCH_SLOP:
                    moved = True
                    callbacks.append("onScroll")
                last_ev = (x, y, ts)
            elif action == "UP" and down_ev is not None:
                dt_ms = max(1, ts - down_ev[2])
                if not moved and not long_press_fired:
                    callbacks.append("onSingleTapUp")
                elif moved and last_ev is not None:
                    vx = (x - down_ev[0]) / (dt_ms / 1000.0)
                    vy = (y - down_ev[1]) / (dt_ms / 1000.0)
                    speed = math.hypot(vx, vy)
                    if speed >= self.MIN_FLING_VELOCITY:
                        callbacks.append("onFling")
        return callbacks


def case_motion_event_gesture_detector_callbacks():
    det = SimulatedGestureDetector()
    tap = det.process_sequence([("DOWN", 100, 100, 0), ("UP", 102, 101, 50)])
    long_press = det.process_sequence([
        ("DOWN", 100, 100, 0),
        ("HOLD", 100, 100, 150),
        ("HOLD", 100, 100, 550),
        ("UP", 100, 100, 620),
    ])
    quick_fling = det.process_sequence([
        ("DOWN", 200, 800, 0),
        ("MOVE", 200, 650, 40),
        ("UP", 200, 450, 90),
    ])
    slow_drag = det.process_sequence([
        ("DOWN", 200, 400, 0),
        ("HOLD", 200, 400, 120),
        ("MOVE", 200, 460, 400),
        ("MOVE", 200, 520, 900),
        ("UP", 200, 520, 1200),
    ])

    actual = {
        "tap": tap,
        "long_press": long_press,
        "quick_fling": quick_fling,
        "slow_drag": slow_drag,
    }
    expected = {
        "tap": ["onDown", "onSingleTapUp"],
        "long_press": ["onDown", "onShowPress", "onLongPress"],
        "quick_fling": ["onDown", "onScroll", "onFling"],
        "slow_drag": ["onDown", "onShowPress", "onScroll", "onScroll"],
    }
    return {
        "name": "motion_event_gesture_detector_callbacks",
        "summary": "验证 MotionEvent 经 GestureDetector 转发给 OnGestureListener 在轻触、长按、快滑抛掷与慢速拖动四种场景下的回调序列。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_simple_gesture_fling_navigation():
    min_move = 200

    def classify_corrected(y1: float, y2: float) -> str:
        # Upward swipe: y decreases (y1 - y2 > MIN_MOVE) -> start new Activity
        # Downward swipe: y increases (y2 - y1 > MIN_MOVE) -> finish current Activity
        if y1 - y2 > min_move:
            return "startActivity"
        if y2 - y1 > min_move:
            return "finish"
        return "ignore"

    def classify_source_buggy(y1: float, y2: float) -> str:
        # Source snippet wrote `else if (e1.getY() - e2.getY() < MIN_MOVE)` which misclassifies small upward moves as finish
        if y1 - y2 > min_move:
            return "startActivity"
        if y1 - y2 < min_move:
            return "finish"
        return "ignore"

    actual = {
        "swipe_up_350px": classify_corrected(800, 450),
        "swipe_down_350px": classify_corrected(450, 800),
        "small_up_50px_corrected": classify_corrected(800, 750),
        "small_up_50px_source_buggy": classify_source_buggy(800, 750),
    }
    expected = {
        "swipe_up_350px": "startActivity",
        "swipe_down_350px": "finish",
        "small_up_50px_corrected": "ignore",
        "small_up_50px_source_buggy": "finish",
    }
    return {
        "name": "simple_gesture_fling_navigation",
        "summary": "验证 SimpleOnGestureListener.onFling 上滑启动与下滑关闭 Activity 的位移阈值判定,并复现原示例条件漏写负号的边界缺陷。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def _normalize_stroke(points: list[tuple[float, float]]) -> list[float]:
    vec = []
    for (x0, y0), (x1, y1) in zip(points, points[1:]):
        vec.extend([x1 - x0, y1 - y0])
    norm = math.sqrt(sum(v * v for v in vec)) or 1.0
    return [v / norm for v in vec]


class SimulatedGestureLibrary:
    """Models GestureLibrary add/entries/recognize/remove/save/load."""

    def __init__(self):
        self._store: dict[str, list[list[tuple[float, float]]]] = {}
        self.saved = False

    def add_gesture(self, name: str, points: list[tuple[float, float]]):
        self._store.setdefault(name, []).append(points)

    def get_gesture_entries(self) -> list[str]:
        return sorted(self._store.keys())

    def remove_entry(self, name: str):
        self._store.pop(name, None)

    def save(self) -> bool:
        self.saved = True
        return True

    def recognize(self, query_points: list[tuple[float, float]]) -> list[tuple[str, float]]:
        qv = _normalize_stroke(query_points)
        scored = []
        for name, samples in self._store.items():
            best = -1.0
            for pts in samples:
                sv = _normalize_stroke(pts)
                if len(sv) == len(qv):
                    cos = sum(a * b for a, b in zip(qv, sv))
                    # Scale similarity to Android Prediction.score-like range (0..5)
                    score = round(max(0.0, (cos + 1.0) * 2.5), 2)
                    best = max(best, score)
            scored.append((name, best))
        scored.sort(key=lambda item: item[1], reverse=True)
        return scored


def case_gesture_library_store_and_recognition():
    lib = SimulatedGestureLibrary()
    # Two canonical 3-point gestures: 'V' shape and 'L' shape
    lib.add_gesture("check_v", [(0, 0), (50, 100), (100, 0)])
    lib.add_gesture("letter_l", [(0, 0), (0, 100), (100, 100)])
    lib.add_gesture("temp_z", [(0, 0), (100, 0), (0, 100)])
    lib.remove_entry("temp_z")
    saved_ok = lib.save()

    preds = lib.recognize([(2, 0), (52, 98), (99, 2)])
    matched = [name for name, score in preds if score > 2.0]

    actual = {
        "entries": lib.get_gesture_entries(),
        "saved": saved_ok,
        "top_match": preds[0][0],
        "top_score_gt_2": preds[0][1] > 2.0,
        "matched_above_threshold": matched,
        "legacy_permissions": ["WRITE_EXTERNAL_STORAGE", "READ_EXTERNAL_STORAGE"],
    }
    expected = {
        "entries": ["check_v", "letter_l"],
        "saved": True,
        "top_match": "check_v",
        "top_score_gt_2": True,
        "matched_above_threshold": ["check_v", "letter_l"],
        "legacy_permissions": ["WRITE_EXTERNAL_STORAGE", "READ_EXTERNAL_STORAGE"],
    }
    return {
        "name": "gesture_library_store_and_recognition",
        "summary": "验证 GestureLibrary 添加、删除、持久化保存及基于向量相似度的 recognize() 阈值(score > 2.0)匹配。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_motion_event_gesture_detector_callbacks(),
        case_simple_gesture_fling_navigation(),
        case_gesture_library_store_and_recognition(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。

入口文件:projects/android-tutorial-gestures-lab/explore-tutorial-gestures.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-gestures.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1895.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习