-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacos_pointer.py
More file actions
106 lines (90 loc) · 2.97 KB
/
Copy pathmacos_pointer.py
File metadata and controls
106 lines (90 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
"""Privacy-safe recent-click tracking for macOS pointer placement."""
from __future__ import annotations
import sys
import threading
import time
from dataclasses import dataclass
@dataclass(frozen=True)
class PointerClick:
x: float
y: float
happened_at: float
class RecentPointerClick:
"""Retain only the latest pointer coordinate for a short placement window."""
def __init__(self, max_age_seconds: float = 8.0) -> None:
self.max_age_seconds = max(0.0, float(max_age_seconds))
self._latest: PointerClick | None = None
self._lock = threading.Lock()
def record(
self,
x: float,
y: float,
happened_at: float | None = None,
) -> None:
click = PointerClick(
x=float(x),
y=float(y),
happened_at=(
time.monotonic() if happened_at is None else happened_at
),
)
with self._lock:
self._latest = click
def latest(self, now: float | None = None) -> PointerClick | None:
checked_at = time.monotonic() if now is None else now
with self._lock:
click = self._latest
if click is None:
return None
age = checked_at - click.happened_at
if age < 0.0:
return None
if age > self.max_age_seconds:
self._latest = None
return None
return click
class MacOSPointerMonitor:
"""Record primary pointer presses without inspecting their UI targets."""
def __init__(self, recent_click: RecentPointerClick, debug: bool = False) -> None:
self._recent_click = recent_click
self._debug = debug
self._listener: object | None = None
def start(self) -> bool:
if self._listener is not None:
return True
try:
from pynput import mouse
def on_click(
x: float,
y: float,
button: object,
pressed: bool,
) -> None:
if pressed and button == mouse.Button.left:
self._recent_click.record(x, y)
listener = mouse.Listener(on_click=on_click)
listener.start()
self._listener = listener
return True
except Exception as exc:
self._listener = None
if self._debug:
print(
f"Pointer click monitoring unavailable: {exc}",
file=sys.stderr,
)
return False
def stop(self) -> None:
listener = self._listener
self._listener = None
if listener is None:
return
try:
listener.stop()
listener.join(timeout=1.0)
except Exception as exc:
if self._debug:
print(
f"Could not stop pointer click monitoring: {exc}",
file=sys.stderr,
)