From 2a6c7a9443d17c6071ab467363728fc0d71a4a2e Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Thu, 29 Oct 2026 00:26:16 +0100 Subject: [PATCH] =?UTF-8?q?Maus=20wie=20eine=20Hand:=20gekr=C3=BCmmter=20W?= =?UTF-8?q?eg,=20gestreuter=20Treffpunkt,=20Halten?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hand/maus.py plant den Klick als reine, geseedete Funktionen: Fitts-Dauer, Bezier-Weg mit Minimum-Jerk-Tempo, Abtastung 6-14 ms mit Zittern, bei langen Wegen manchmal Überschuss und Korrektur, Verweilen und 45-180 ms Halten. hand/click.py spielt den Plan vom aktuellen Zeiger aus ab; act.py gibt die halbe Knopfgröße mit. tests/maus_spec.py: 10 Tests. Co-Authored-By: Claude Opus 5.5 --- hand/act.py | 2 +- hand/click.py | 42 ++++++++++++--- hand/maus.py | 123 ++++++++++++++++++++++++++++++++++++++++++ tests/maus_spec.py | 129 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 288 insertions(+), 8 deletions(-) create mode 100644 hand/maus.py create mode 100644 tests/maus_spec.py diff --git a/hand/act.py b/hand/act.py index dc244d8..280ae19 100644 --- a/hand/act.py +++ b/hand/act.py @@ -61,7 +61,7 @@ def ausfuehren(entscheidung, raum=None, warten=None): return None time.sleep(max(warten or 0.0, WARTEZEIT)) px, py = click.point_for(ziel, rect) - click.click(px, py, fenster=f) + click.click(px, py, fenster=f, halb=click.maus.halbe_groesse(ziel, rect)) groesse = entscheidung.get("size") return ziel + (f" {groesse}" if groesse else "") diff --git a/hand/click.py b/hand/click.py index 0a07a39..64e1ba1 100644 --- a/hand/click.py +++ b/hand/click.py @@ -21,10 +21,13 @@ for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"): if _os.path.isdir(_q) and _q not in _sys.path: _sys.path.insert(0, _q) import ctypes +import random import subprocess import sys import time as _time +import maus + FW = "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices" AS = ctypes.cdll.LoadLibrary(FW) @@ -38,6 +41,10 @@ AS.CGEventCreateMouseEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint32, CGPoint ctypes.c_uint32] AS.CGEventPost.argtypes = [ctypes.c_uint32, ctypes.c_void_p] AS.CGEventPostToPid.argtypes = [ctypes.c_int, ctypes.c_void_p] +AS.CGEventCreate.restype = ctypes.c_void_p +AS.CGEventCreate.argtypes = [ctypes.c_void_p] +AS.CGEventGetLocation.restype = CGPoint +AS.CGEventGetLocation.argtypes = [ctypes.c_void_p] MOVED, DOWN, UP = 5, 1, 2 # Anteil der Fensterbreite/-höhe (aus einem Bild vom Tisch abgelesen) @@ -100,15 +107,36 @@ def nach_vorn(fenster): osa(f'tell application "System Events" to set frontmost of {proc} to true') -def click(px, py, pid=None, fenster=None): - """Klickt global. Mit `fenster` (aus hand/fenster.py) wird es vorher angehoben.""" +def zeiger(): + """Wo der Mauszeiger gerade steht.""" + p = AS.CGEventGetLocation(AS.CGEventCreate(None)) + return p.x, p.y + + +def _senden(art, x, y): + AS.CGEventPost(0, AS.CGEventCreateMouseEvent(None, art, CGPoint(x, y), 0)) + + +def click(px, py, pid=None, fenster=None, halb=(0.0, 0.0), rng=random): + """Klickt global, mit der Hand geführt (hand/maus.py): vom aktuellen Zeiger auf einem + gekrümmten Weg zu einem gestreuten Punkt auf dem Knopf (Mitte px, py; halbe Größe `halb`), + kurz verweilen, drücken, halten, loslassen. Mit `fenster` (aus hand/fenster.py) wird das + Fenster vorher angehoben.""" if fenster: pid = fenster.get("pid") nach_vorn(fenster) - for kind in (MOVED, DOWN, UP): - event = AS.CGEventCreateMouseEvent(None, kind, CGPoint(px, py), 0) - AS.CGEventPost(0, event) - _time.sleep(0.03) + weg, verweilen, halten = maus.plan(zeiger(), (px, py), halb, rng) + beginn = _time.monotonic() + for ms, x, y in weg: + warte = beginn + ms / 1000.0 - _time.monotonic() + if warte > 0: + _time.sleep(warte) + _senden(MOVED, x, y) + x, y = weg[-1][1:] + _time.sleep(verweilen / 1000.0) + _senden(DOWN, x, y) + _time.sleep(halten / 1000.0) + _senden(UP, x, y) def main(): @@ -133,7 +161,7 @@ def main(): if px is None: print(f"unbekannt: {key}; bekannt: {', '.join(SPOTS)}") return 1 - click(px, py) + click(px, py, halb=maus.halbe_groesse(key, rect)) print(f"Klick auf {key} bei {px},{py}") return 0 diff --git a/hand/maus.py b/hand/maus.py new file mode 100644 index 0000000..aea5f67 --- /dev/null +++ b/hand/maus.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Maus - wie der Zeiger zum Knopf kommt und wie der Knopf gedrückt wird. + +Reine Funktionen, kein Zustand ausser dem übergebenen Zufallsgenerator: gleicher Seed, +gleicher Weg. hand/click.py spielt das Ergebnis als Mausereignisse ab; geprüft wird das +Verhalten in tests/maus_spec.py (läuft ohne Mac). + +Aufbau: + * Treffpunkt: nicht die Knopfmitte, sondern gestreut um sie (Normalverteilung, an den + Rand des Knopfes gekappt) - zwei Klicks treffen nie denselben Punkt. + * Weg: Bézier-Kurve mit seitlich versetzten Stützpunkten, keine Gerade. + * Tempo: langsam - schnell - langsam (Minimum-Jerk-Profil), Dauer nach Fitts: weiter + und kleiner dauert länger, mit Streuung. + * Abtastung: Ereignisse alle 6-14 ms, mit leichtem Zittern der Hand. + * Über das Ziel hinaus: bei langen Wegen ab und zu ein Stück zu weit, dann zurück. + * Klick: kurz verweilen, dann drücken und 45-180 ms halten. +""" +import math +import random + +# Halbe Knopfgröße als Anteil der Fensterbreite/-höhe (Knopfmitten in click.SPOTS). +# Vorsichtig kleiner als der Knopf, damit gestreute Treffer sicher auf ihm liegen. +HALB = {"fold": (0.040, 0.015), "call": (0.040, 0.015), "raise": (0.040, 0.015), + "amount": (0.030, 0.010)} +HALB_KLEIN = (0.018, 0.010) # Größen-Voreinstellungen (size33 ...), max + +SCHRITT_MS = (6.0, 14.0) +DAUER_S = (0.12, 0.90) +HALTEN_MS = (45.0, 180.0) +VERWEILEN_MS = (40.0, 160.0) +UEBERSCHUSS_AB_PX = 200.0 +UEBERSCHUSS_RATE = 0.18 +ZITTERN_PX = 0.6 + + +def halbe_groesse(name, rect): + _, _, w, h = rect + fx, fy = HALB.get(name, HALB_KLEIN) + return w * fx, h * fy + + +def treffpunkt(mitte, halb, rng=random): + """Ein Punkt auf dem Knopf, um die Mitte gestreut und an 80 % der halben Größe gekappt.""" + (mx, my), (hx, hy) = mitte, halb + dx = max(-0.8, min(0.8, rng.gauss(0.0, 0.35))) * hx + dy = max(-0.8, min(0.8, rng.gauss(0.0, 0.35))) * hy + return mx + dx, my + dy + + +def dauer(abstand, breite, rng=random): + """Bewegungsdauer in Sekunden nach Fitts (a + b * log2(d/w + 1)), mal Streuung.""" + schwierigkeit = math.log2(abstand / max(breite, 1.0) + 1.0) + t = (0.10 + 0.11 * schwierigkeit) * rng.lognormvariate(0.0, 0.18) + return max(DAUER_S[0], min(DAUER_S[1], t)) + + +def _profil(t): + """Minimum-Jerk: Anteil des Weges zur Zeit t in [0, 1].""" + return t * t * t * (10.0 - 15.0 * t + 6.0 * t * t) + + +def _bezier(p0, p1, p2, p3, s): + u = 1.0 - s + return (u ** 3 * p0[0] + 3 * u * u * s * p1[0] + 3 * u * s * s * p2[0] + s ** 3 * p3[0], + u ** 3 * p0[1] + 3 * u * u * s * p1[1] + 3 * u * s * s * p2[1] + s ** 3 * p3[1]) + + +def _strecke(start, ziel, sekunden, rng, zittern=True): + """[(ms, x, y)] von start bis genau ziel, ms ab 0.""" + (sx, sy), (zx, zy) = start, ziel + dx, dy = zx - sx, zy - sy + lang = math.hypot(dx, dy) + if lang < 1.0: + return [(0.0, zx, zy)] + nx, ny = -dy / lang, dx / lang # quer zur Strecke + seite = rng.choice((-1.0, 1.0)) + b1, b2 = rng.uniform(0.05, 0.22) * lang * seite, rng.uniform(0.0, 0.12) * lang * seite + p1 = (sx + dx * rng.uniform(0.2, 0.4) + nx * b1, sy + dy * rng.uniform(0.2, 0.4) + ny * b1) + p2 = (sx + dx * rng.uniform(0.6, 0.85) + nx * b2, sy + dy * rng.uniform(0.6, 0.85) + ny * b2) + gesamt = sekunden * 1000.0 + punkte, ms = [], 0.0 + while ms < gesamt: + x, y = _bezier(start, p1, p2, ziel, _profil(ms / gesamt)) + if zittern and ms > 0: + x += rng.gauss(0.0, ZITTERN_PX) + y += rng.gauss(0.0, ZITTERN_PX) + punkte.append((ms, x, y)) + ms += rng.uniform(*SCHRITT_MS) + if gesamt - punkte[-1][0] < SCHRITT_MS[0]: # kein Mini-Schritt ins Ziel (ein Sprung) + gesamt = punkte[-1][0] + rng.uniform(*SCHRITT_MS) + punkte.append((gesamt, zx, zy)) + return punkte + + +def weg(start, ziel, breite, rng=random): + """Zeigerweg [(ms, x, y)] vom aktuellen Punkt zum Treffpunkt; endet genau auf `ziel`. + + `breite` ist die Knopfbreite in Pixeln (für Fitts). Bei langen Wegen schießt die Hand + manchmal ein Stück über das Ziel hinaus und korrigiert zurück.""" + abstand = math.hypot(ziel[0] - start[0], ziel[1] - start[1]) + zeit = dauer(abstand, breite, rng) + if abstand >= UEBERSCHUSS_AB_PX and rng.random() < UEBERSCHUSS_RATE: + k = 1.0 + rng.uniform(0.03, 0.08) + drueber = (start[0] + (ziel[0] - start[0]) * k, start[1] + (ziel[1] - start[1]) * k) + hin = _strecke(start, drueber, zeit, rng) + zurueck = _strecke(drueber, ziel, dauer(abstand * (k - 1), breite, rng) * 0.8, rng) + versatz = hin[-1][0] + rng.uniform(*SCHRITT_MS) + return hin + [(versatz + ms, x, y) for ms, x, y in zurueck] + return _strecke(start, ziel, zeit, rng) + + +def druck(rng=random): + """(Verweilen vor dem Drücken, Halten) in Millisekunden.""" + verweilen = rng.uniform(*VERWEILEN_MS) + halten = max(HALTEN_MS[0], min(HALTEN_MS[1], rng.lognormvariate(math.log(85.0), 0.3))) + return verweilen, halten + + +def plan(start, mitte, halb, rng=random): + """Alles für einen Klick: (Weg [(ms, x, y)], Verweilen ms, Halten ms).""" + ziel = treffpunkt(mitte, halb, rng) + verweilen, halten = druck(rng) + return weg(start, ziel, 2 * halb[0], rng), verweilen, halten diff --git a/tests/maus_spec.py b/tests/maus_spec.py new file mode 100644 index 0000000..f8055d7 --- /dev/null +++ b/tests/maus_spec.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Maus: der Weg zum Knopf sieht nach Hand aus, nicht nach Sprung (hand/maus.py). + +Läuft ohne Mac - geprüft werden die reinen Funktionen, die hand/click.py abspielt. +Gegenprobe zu jedem Merkmal ist der alte Klick: Sprung auf die Knopfmitte, drei +Ereignisse im Abstand von 30 ms. + + python3 tests/maus_spec.py -v +""" +import math +import os +import random +import statistics +import sys +import unittest + +_w = os.path.dirname(os.path.abspath(__file__)) +while _w != "/" and not os.path.isdir(os.path.join(_w, "hand")): + _w = os.path.dirname(_w) +sys.path.insert(0, os.path.join(_w, "hand")) + +import maus + +FENSTER = (100.0, 80.0, 1200.0, 860.0) # x, y, Breite, Höhe +CALL = (100 + 1200 * 0.796, 80 + 860 * 0.943) # Mitte des Call-Knopfs wie in click.SPOTS + + +def abstand_zur_geraden(p, a, b): + (x, y), (ax, ay), (bx, by) = p, a, b + return abs((bx - ax) * (ay - y) - (ax - x) * (by - ay)) / math.hypot(bx - ax, by - ay) + + +class Treffpunkt(unittest.TestCase): + def test_immer_auf_dem_knopf_nie_zweimal_derselbe_punkt(self): + rng = random.Random(1) + halb = maus.halbe_groesse("call", FENSTER) + punkte = [maus.treffpunkt(CALL, halb, rng) for _ in range(3000)] + for x, y in punkte: + self.assertLessEqual(abs(x - CALL[0]), halb[0] * 0.8 + 1e-9) + self.assertLessEqual(abs(y - CALL[1]), halb[1] * 0.8 + 1e-9) + self.assertEqual(len(set(punkte)), len(punkte)) + # gestreut, aber um die Mitte: die meisten nah dran, nicht gleichverteilt + nah = sum(abs(x - CALL[0]) < halb[0] * 0.4 for x, _ in punkte) / len(punkte) + self.assertGreater(nah, 0.6) + self.assertGreater(statistics.pstdev([x for x, _ in punkte]), halb[0] * 0.2) + + def test_kleine_knoepfe_streuen_enger(self): + self.assertLess(maus.halbe_groesse("size33", FENSTER)[0], maus.halbe_groesse("raise", FENSTER)[0]) + + +class Weg(unittest.TestCase): + def wege(self, start, n=300, seed=2): + rng = random.Random(seed) + return [maus.weg(start, maus.treffpunkt(CALL, maus.halbe_groesse("call", FENSTER), rng), + 2 * maus.halbe_groesse("call", FENSTER)[0], rng) for _ in range(n)] + + def test_beginnt_am_zeiger_endet_genau_im_ziel(self): + rng = random.Random(3) + start = (300.0, 200.0) + ziel = maus.treffpunkt(CALL, maus.halbe_groesse("call", FENSTER), rng) + w = maus.weg(start, ziel, 96.0, rng) + self.assertEqual(w[0][1:], start) + self.assertEqual(w[-1][1:], ziel) + + def test_gleicher_seed_gleicher_weg(self): + a = maus.plan((300, 200), CALL, (48, 13), random.Random(7)) + b = maus.plan((300, 200), CALL, (48, 13), random.Random(7)) + c = maus.plan((300, 200), CALL, (48, 13), random.Random(8)) + self.assertEqual(a, b) + self.assertNotEqual(a, c) + + def test_viele_kleine_schritte_im_takt_einer_maus(self): + for w in self.wege((300.0, 200.0)): + self.assertGreater(len(w), 8) # der alte Klick: ein Sprung + zeiten = [ms for ms, _, _ in w] + luecken = [b - a for a, b in zip(zeiten, zeiten[1:])] + self.assertTrue(all(0 < l <= maus.SCHRITT_MS[1] + 1e-9 for l in luecken), luecken) + + def test_gekruemmt_nicht_gerade(self): + start = (300.0, 200.0) + krumm = 0 + for w in self.wege(start): + ziel = w[-1][1:] + weite = max(abstand_zur_geraden(p[1:], start, ziel) for p in w) + krumm += weite > 0.03 * math.dist(start, ziel) + self.assertGreater(krumm, 0.9 * 300) + + def test_langsam_schnell_langsam(self): + start = (300.0, 200.0) + for w in self.wege(start, n=100): + if max(math.dist(p[1:], w[-1][1:]) for p in w) > math.dist(start, w[-1][1:]) * 1.02: + continue # Überschuss: eigenes Profil + tempo = [(math.dist(a[1:], b[1:]) / (b[0] - a[0]), a[0]) + for a, b in zip(w, w[1:]) if b[0] > a[0]] + spitze_ms = max(tempo)[1] + self.assertTrue(0.2 * w[-1][0] < spitze_ms < 0.8 * w[-1][0], (spitze_ms, w[-1][0])) + self.assertLess(tempo[0][0], max(tempo)[0] * 0.5) + + def test_weiter_dauert_laenger(self): + nah = statistics.mean(w[-1][0] for w in self.wege((CALL[0] - 120, CALL[1] - 40))) + fern = statistics.mean(w[-1][0] for w in self.wege((CALL[0] - 900, CALL[1] - 600))) + self.assertGreater(fern, nah * 1.3) + for w in self.wege((CALL[0] - 900, CALL[1] - 600)): + self.assertLessEqual(w[-1][0], 2 * maus.DAUER_S[1] * 1000 + 50) + + def test_ueberschuss_nur_bei_langen_wegen_und_nur_manchmal(self): + def ueber(start): + n = 0 + for w in self.wege(start, n=400, seed=5): + ziel = w[-1][1:] + n += max(math.dist(start, p[1:]) for p in w) > math.dist(start, ziel) + 3 + return n / 400 + self.assertEqual(ueber((CALL[0] - 60, CALL[1] - 20)), 0.0) + self.assertTrue(0.05 < ueber((CALL[0] - 900, CALL[1] - 600)) < 0.35) + + +class Druck(unittest.TestCase): + def test_halten_und_verweilen_gestreut_in_grenzen(self): + rng = random.Random(4) + werte = [maus.druck(rng) for _ in range(2000)] + halten = [h for _, h in werte] + self.assertTrue(all(maus.HALTEN_MS[0] <= h <= maus.HALTEN_MS[1] for h in halten)) + self.assertTrue(all(maus.VERWEILEN_MS[0] <= v <= maus.VERWEILEN_MS[1] for v, _ in werte)) + self.assertGreater(statistics.pstdev(halten), 10.0) # der alte Klick: immer 30 ms + self.assertTrue(60 < statistics.median(halten) < 110) + + +if __name__ == "__main__": + unittest.main()