-
Notifications
You must be signed in to change notification settings - Fork 0
/
mouse-listener.py
executable file
·100 lines (81 loc) · 2.69 KB
/
mouse-listener.py
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
#!/opt/homebrew/bin/python3
from pynput import mouse
from datetime import datetime
movement_sensitivity = 1 # pixels
longtap_sensitivity = 1000 # ms
lastx = 0
lasty = 0
inGesture = False # True if a gesture is in progress
swiped = False # True if a swipe has been detected
def on_move(x, y):
# print(f'Pointer moved to {x}, {y}')
# global lastx, mdeltax
global lastx, lasty, mdeltax, mdeltay
global swiped, inGesture, move_gesture
mdeltax = int(x - lastx)
mdeltay = int(y - lasty)
lastx = int(x)
lasty = int(y)
ymag = 0
if inGesture:
xmag = abs(mdeltax) if abs(mdeltax) > movement_sensitivity else 0
xdir = "none"
if xmag > 0:
xdir = "right" if mdeltax > 0 else "left"
ymag = 0 if abs(mdeltay) < movement_sensitivity else int(abs(mdeltay))
ydir = "none"
if ymag > 0:
ydir = "down" if mdeltay > 0 else "up"
# y-axis is inverted vs. cartesian (positive = down)
move_gesture = ""
if xdir == "left":
move_gesture += "swipe-left "
swiped = True
elif xdir == "right":
move_gesture += "swipe-right "
swiped = True
if ydir == "up":
move_gesture += "swipe-up"
swiped = True
elif ydir == "down":
move_gesture += "swipe-down"
swiped = True
if move_gesture == "":
move_gesture = "none"
print(f"Gesture: {move_gesture}; Magnitude: {ymag}")
pass
def on_click(x, y, button, pressed):
global presstime, releasetime, deltats, deltatms
global startx, deltax
global starty, deltay
global inGesture, gesture, swiped
presstext = "pressed" if pressed else "released"
print(f"{button} {presstext} at {int(x)}, {int(y)}")
if pressed:
presstime = datetime.now()
inGesture = True
startx = int(x)
starty = int(y)
pass
elif not pressed:
releasetime = datetime.now()
inGesture = False
deltax = int(int(x) - startx)
deltay = int(int(y) - starty)
deltats = int((releasetime - presstime).seconds * 1000)
deltatms = int((releasetime - presstime).microseconds // 1000 + deltats)
if not swiped:
gesture = "tap" if deltatms < longtap_sensitivity else "longtap"
elif swiped:
gesture = "swipe"
print(
f"Movement vector {deltax}, {deltay} in {deltatms} ms; Gesture: {gesture}"
)
swiped = False
pass
# Collect events until released
def main():
with mouse.Listener(on_move=on_move, on_click=on_click) as listener:
listener.join()
if __name__ == "__main__":
main()