dsh-plugin-linux-computer-use 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,552 @@
1
+ """Pointer and keyboard injection for the Linux desktop MCP server.
2
+
3
+ Backends
4
+ --------
5
+ uinput (default)
6
+ Writes struct input_event records straight into /dev/uinput. The kernel turns
7
+ them into a real virtual device, so they are indistinguishable from hardware
8
+ for Wayland compositors and X11 alike. Requires write access to /dev/uinput
9
+ (udev rule: GROUP="input" MODE="0660" plus the user in group "input").
10
+
11
+ ydotool (fallback)
12
+ Shells out to the ydotool client, which talks to ydotoold over a unix socket.
13
+ Used only when /dev/uinput cannot be opened.
14
+
15
+ The virtual pointer is an *absolute* pointer (ABS_X/ABS_Y, range 0..32767), the
16
+ same shape as a QEMU usb-tablet: libinput classifies it as an ordinary pointer,
17
+ so clicks, drags and double-clicks behave normally while positioning stays exact
18
+ (no pointer acceleration to fight). Wheel scrolling uses a second, relative
19
+ device because high-resolution wheel events are EV_REL.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import fcntl
25
+ import os
26
+ import re
27
+ import shutil
28
+ import struct
29
+ import subprocess
30
+ import time
31
+
32
+ # --------------------------------------------------------------------------- #
33
+ # kernel constants
34
+ # --------------------------------------------------------------------------- #
35
+ EV_SYN, EV_KEY, EV_REL, EV_ABS = 0x00, 0x01, 0x02, 0x03
36
+ SYN_REPORT = 0x00
37
+ REL_WHEEL, REL_HWHEEL = 0x08, 0x06
38
+ ABS_X, ABS_Y = 0x00, 0x01
39
+ BTN_LEFT, BTN_RIGHT, BTN_MIDDLE = 0x110, 0x111, 0x112
40
+ BUS_VIRTUAL = 0x06
41
+ INPUT_PROP_POINTER = 0x00
42
+
43
+ UI_DEV_CREATE = 0x5501
44
+ UI_DEV_DESTROY = 0x5502
45
+ UI_DEV_SETUP = 0x405C5503
46
+ UI_ABS_SETUP = 0x401C5504
47
+ UI_SET_EVBIT = 0x40045564
48
+ UI_SET_KEYBIT = 0x40045565
49
+ UI_SET_RELBIT = 0x40045566
50
+ UI_SET_ABSBIT = 0x40045567
51
+ UI_SET_PROPBIT = 0x4004556E
52
+
53
+ ABS_MAX_VALUE = 32767
54
+ KEY_MAX = 0x2FF
55
+ REL_MAX = 0x0F
56
+ ABS_MAX = 0x3F
57
+
58
+ INPUT_EVENT = struct.Struct("llHHi") # struct input_event on 64-bit Linux
59
+
60
+ class InputError(RuntimeError):
61
+ """Input injection is unavailable or was rejected."""
62
+
63
+
64
+ DEFAULT_UINPUT = "/dev/uinput"
65
+ DEFAULT_YDOTOOL_SOCKET = "/run/ydotoold.socket"
66
+
67
+ # --------------------------------------------------------------------------- #
68
+ # key codes
69
+ # --------------------------------------------------------------------------- #
70
+
71
+ # Only the names the tool surfaces to the model; the full table is loaded from
72
+ # the kernel headers when they are installed.
73
+ _BUILTIN_KEYS = {
74
+ "ESC": 1, "1": 2, "2": 3, "3": 4, "4": 5, "5": 6, "6": 7, "7": 8, "8": 9,
75
+ "9": 10, "0": 11, "MINUS": 12, "EQUAL": 13, "BACKSPACE": 14, "TAB": 15,
76
+ "Q": 16, "W": 17, "E": 18, "R": 19, "T": 20, "Y": 21, "U": 22, "I": 23,
77
+ "O": 24, "P": 25, "LEFTBRACE": 26, "RIGHTBRACE": 27, "ENTER": 28,
78
+ "LEFTCTRL": 29, "A": 30, "S": 31, "D": 32, "F": 33, "G": 34, "H": 35,
79
+ "J": 36, "K": 37, "L": 38, "SEMICOLON": 39, "APOSTROPHE": 40, "GRAVE": 41,
80
+ "LEFTSHIFT": 42, "BACKSLASH": 43, "Z": 44, "X": 45, "C": 46, "V": 47,
81
+ "B": 48, "N": 49, "M": 50, "COMMA": 51, "DOT": 52, "SLASH": 53,
82
+ "RIGHTSHIFT": 54, "LEFTALT": 56, "SPACE": 57, "CAPSLOCK": 58,
83
+ "F1": 59, "F2": 60, "F3": 61, "F4": 62, "F5": 63, "F6": 64, "F7": 65,
84
+ "F8": 66, "F9": 67, "F10": 68, "F11": 87, "F12": 88,
85
+ "RIGHTCTRL": 97, "RIGHTALT": 100, "HOME": 102, "UP": 103, "PAGEUP": 104,
86
+ "LEFT": 105, "RIGHT": 106, "END": 107, "DOWN": 108, "PAGEDOWN": 109,
87
+ "INSERT": 110, "DELETE": 111, "LEFTMETA": 125, "RIGHTMETA": 126,
88
+ "SYSRQ": 99, "PAUSE": 119, "MENU": 139,
89
+ }
90
+
91
+ _ALIASES = {
92
+ "ctrl": "LEFTCTRL", "control": "LEFTCTRL", "shift": "LEFTSHIFT",
93
+ "alt": "LEFTALT", "option": "LEFTALT", "super": "LEFTMETA",
94
+ "meta": "LEFTMETA", "cmd": "LEFTMETA", "win": "LEFTMETA",
95
+ "enter": "ENTER", "return": "ENTER", "esc": "ESC", "escape": "ESC",
96
+ "space": "SPACE", "spacebar": "SPACE", "tab": "TAB",
97
+ "backspace": "BACKSPACE", "delete": "DELETE", "del": "DELETE",
98
+ "insert": "INSERT", "ins": "INSERT", "home": "HOME", "end": "END",
99
+ "up": "UP", "down": "DOWN", "left": "LEFT", "right": "RIGHT",
100
+ "pageup": "PAGEUP", "pgup": "PAGEUP", "pagedown": "PAGEDOWN",
101
+ "pgdn": "PAGEDOWN", "print": "SYSRQ", "printscreen": "SYSRQ",
102
+ "capslock": "CAPSLOCK", "minus": "MINUS", "equal": "EQUAL",
103
+ "comma": "COMMA", "period": "DOT", "dot": "DOT", "slash": "SLASH",
104
+ "semicolon": "SEMICOLON", "apostrophe": "APOSTROPHE", "grave": "GRAVE",
105
+ "backslash": "BACKSLASH", "leftbrace": "LEFTBRACE",
106
+ "rightbrace": "RIGHTBRACE",
107
+ }
108
+
109
+ _CHAR_SHIFT = {
110
+ "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&",
111
+ "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", "[": "{", "]": "}",
112
+ ";": ":", "'": '"', ",": "<", ".": ">", "/": "?", "\\": "|", "`": "~",
113
+ }
114
+ _CHAR_PLAIN = {v: k for k, v in _CHAR_SHIFT.items()}
115
+
116
+
117
+ def _load_key_codes() -> dict[str, int]:
118
+ """Merge the builtin table with /usr/include/linux/input-event-codes.h."""
119
+ codes = dict(_BUILTIN_KEYS)
120
+ for header in (
121
+ "/usr/include/linux/input-event-codes.h",
122
+ "/usr/src/linux-headers/include/uapi/linux/input-event-codes.h",
123
+ ):
124
+ try:
125
+ with open(header, "r", encoding="utf-8", errors="replace") as handle:
126
+ text = handle.read()
127
+ except OSError:
128
+ continue
129
+ for name, value in re.findall(r"#define\s+KEY_(\w+)\s+(0x[0-9a-fA-F]+|\d+)", text):
130
+ codes.setdefault(name, int(value, 0))
131
+ break
132
+ return codes
133
+
134
+
135
+ KEYS = _load_key_codes()
136
+
137
+
138
+ def key_code(name: str) -> int:
139
+ """Resolve one key name ("a", "Return", "F5", "LEFTCTRL") to an EV_KEY code."""
140
+ raw = name.strip()
141
+ if not raw:
142
+ raise ValueError("empty key name")
143
+ if re.fullmatch(r"0x[0-9a-fA-F]+|\d+", raw):
144
+ return int(raw, 0)
145
+ lowered = raw.lower()
146
+ if lowered in _ALIASES:
147
+ lowered = _ALIASES[lowered].lower()
148
+ if len(raw) == 1 and raw.isalpha():
149
+ return KEYS[raw.upper()]
150
+ if lowered in _ALIASES:
151
+ return KEYS[_ALIASES[lowered]]
152
+ upper = lowered.upper()
153
+ if upper in KEYS:
154
+ return KEYS[upper]
155
+ if upper.startswith("KEY_") and upper[4:] in KEYS:
156
+ return KEYS[upper[4:]]
157
+ raise ValueError(f"unknown key name {name!r}")
158
+
159
+
160
+ # --------------------------------------------------------------------------- #
161
+ # /dev/uinput backend
162
+ # --------------------------------------------------------------------------- #
163
+ class UinputDevice:
164
+ """One virtual input device created from /dev/uinput and kept open."""
165
+
166
+ def __init__(self, name: str) -> None:
167
+ self.name = name
168
+ self.fd = os.open(DEFAULT_UINPUT, os.O_WRONLY | os.O_NONBLOCK)
169
+ self._closed = False
170
+
171
+ # -- capability bits -------------------------------------------------- #
172
+ def enable_event(self, *types: int) -> "UinputDevice":
173
+ for value in types:
174
+ fcntl.ioctl(self.fd, UI_SET_EVBIT, value)
175
+ return self
176
+
177
+ def enable_keys(self, codes) -> "UinputDevice":
178
+ for code in codes:
179
+ fcntl.ioctl(self.fd, UI_SET_KEYBIT, code)
180
+ return self
181
+
182
+ def enable_rel(self, codes) -> "UinputDevice":
183
+ for code in codes:
184
+ fcntl.ioctl(self.fd, UI_SET_RELBIT, code)
185
+ return self
186
+
187
+ def enable_abs(self, code: int, minimum: int, maximum: int) -> "UinputDevice":
188
+ fcntl.ioctl(self.fd, UI_SET_ABSBIT, code)
189
+ # struct uinput_abs_setup { __u16 code; __u16 pad; struct input_absinfo; }
190
+ # input_absinfo carries six ints (value, min, max, fuzz, flat, resolution);
191
+ # leaving one out makes libinput drop the device with "kernel has only x or
192
+ # y resolution, not both".
193
+ payload = struct.pack("HHiiiiii", code, 0, 0, minimum, maximum, 0, 0, 0)
194
+ fcntl.ioctl(self.fd, UI_ABS_SETUP, payload)
195
+ return self
196
+
197
+ def enable_prop(self, *props: int) -> "UinputDevice":
198
+ for prop in props:
199
+ fcntl.ioctl(self.fd, UI_SET_PROPBIT, prop)
200
+ return self
201
+
202
+ # -- creation --------------------------------------------------------- #
203
+ def create(self, vendor: int = 0x4453, product: int = 0x4C43) -> "UinputDevice":
204
+ # struct uinput_setup { struct input_id id; char name[80]; __u32 ff; }
205
+ setup = struct.pack(
206
+ "HHHH80sI",
207
+ BUS_VIRTUAL,
208
+ vendor & 0xFFFF,
209
+ product & 0xFFFF,
210
+ 1,
211
+ self.name.encode("utf-8")[:79],
212
+ 0,
213
+ )
214
+ fcntl.ioctl(self.fd, UI_DEV_SETUP, setup)
215
+ fcntl.ioctl(self.fd, UI_DEV_CREATE)
216
+ time.sleep(0.12) # let udev/libinput finish device setup
217
+ return self
218
+
219
+ # -- events ----------------------------------------------------------- #
220
+ def emit(self, etype: int, code: int, value: int) -> None:
221
+ os.write(self.fd, INPUT_EVENT.pack(0, 0, etype, code, value))
222
+
223
+ def sync(self) -> None:
224
+ self.emit(EV_SYN, SYN_REPORT, 0)
225
+
226
+ def tap(self, code: int) -> None:
227
+ self.emit(EV_KEY, code, 1)
228
+ self.sync()
229
+ self.emit(EV_KEY, code, 0)
230
+ self.sync()
231
+
232
+ def close(self) -> None:
233
+ if self._closed:
234
+ return
235
+ self._closed = True
236
+ try:
237
+ fcntl.ioctl(self.fd, UI_DEV_DESTROY)
238
+ except OSError:
239
+ pass
240
+ try:
241
+ os.close(self.fd)
242
+ except OSError:
243
+ pass
244
+
245
+
246
+ class UinputBackend:
247
+ """Lazily created absolute pointer, wheel and keyboard devices."""
248
+
249
+ name = "uinput"
250
+
251
+ def __init__(self, uinput_path: str = DEFAULT_UINPUT) -> None:
252
+ self.uinput_path = uinput_path
253
+ self._pointer: UinputDevice | None = None
254
+ self._wheel: UinputDevice | None = None
255
+ self._keyboard: UinputDevice | None = None
256
+
257
+ # -- capability check -------------------------------------------------- #
258
+ @classmethod
259
+ def available(cls, uinput_path: str = DEFAULT_UINPUT) -> bool:
260
+ return os.access(uinput_path, os.R_OK | os.W_OK)
261
+
262
+ def reset(self) -> None:
263
+ """Drop every uinput device so the next call recreates them.
264
+
265
+ Useful after a compositor restart: mutter can stop honouring a
266
+ virtual pointer that was created before the session restarted.
267
+ """
268
+ for attribute in ("_pointer", "_wheel", "_keyboard"):
269
+ device = getattr(self, attribute, None)
270
+ if device is not None:
271
+ try:
272
+ device.close()
273
+ except Exception: # noqa: BLE001
274
+ pass
275
+ setattr(self, attribute, None)
276
+
277
+ # -- devices ----------------------------------------------------------- #
278
+ def pointer(self) -> UinputDevice:
279
+ if self._pointer is None:
280
+ device = UinputDevice("DSH Computer Use Pointer")
281
+ device.enable_event(EV_KEY, EV_ABS, EV_SYN)
282
+ device.enable_keys((BTN_LEFT, BTN_RIGHT, BTN_MIDDLE))
283
+ device.enable_abs(ABS_X, 0, ABS_MAX_VALUE)
284
+ device.enable_abs(ABS_Y, 0, ABS_MAX_VALUE)
285
+ device.enable_prop(INPUT_PROP_POINTER)
286
+ self._pointer = device.create(product=0x0001)
287
+ return self._pointer
288
+
289
+ def wheel(self) -> UinputDevice:
290
+ if self._wheel is None:
291
+ device = UinputDevice("DSH Computer Use Wheel")
292
+ device.enable_event(EV_REL, EV_KEY, EV_SYN)
293
+ device.enable_rel((REL_WHEEL, REL_HWHEEL))
294
+ device.enable_keys((BTN_LEFT,))
295
+ self._wheel = device.create(product=0x0002)
296
+ return self._wheel
297
+
298
+ def keyboard(self) -> UinputDevice:
299
+ if self._keyboard is None:
300
+ device = UinputDevice("DSH Computer Use Keyboard")
301
+ device.enable_event(EV_KEY, EV_SYN)
302
+ device.enable_keys(range(1, KEY_MAX + 1))
303
+ self._keyboard = device.create(product=0x0003)
304
+ return self._keyboard
305
+
306
+ # -- primitives -------------------------------------------------------- #
307
+ def move(self, x: int, y: int, layout) -> None:
308
+ """Move the absolute pointer to logical desktop coordinate (x, y)."""
309
+ abs_x, abs_y = layout.to_absolute(x, y)
310
+ device = self.pointer()
311
+ device.emit(EV_ABS, ABS_X, abs_x)
312
+ device.emit(EV_ABS, ABS_Y, abs_y)
313
+ device.sync()
314
+
315
+ def button(self, name: str, pressed: bool) -> None:
316
+ code = {"left": BTN_LEFT, "right": BTN_RIGHT, "middle": BTN_MIDDLE}[name]
317
+ device = self.pointer()
318
+ device.emit(EV_KEY, code, 1 if pressed else 0)
319
+ device.sync()
320
+
321
+ def scroll(self, dx: int, dy: int) -> None:
322
+ device = self.wheel()
323
+ if dy:
324
+ device.emit(EV_REL, REL_WHEEL, -int(dy))
325
+ device.sync()
326
+ if dx:
327
+ device.emit(EV_REL, REL_HWHEEL, -int(dx))
328
+ device.sync()
329
+
330
+ def press(self, codes) -> None:
331
+ device = self.keyboard()
332
+ for code in codes:
333
+ device.emit(EV_KEY, code, 1)
334
+ device.sync()
335
+
336
+ def release(self, codes) -> None:
337
+ device = self.keyboard()
338
+ for code in reversed(list(codes)):
339
+ device.emit(EV_KEY, code, 0)
340
+ device.sync()
341
+
342
+ def tap_key(self, code: int) -> None:
343
+ self.keyboard().tap(code)
344
+
345
+ def type_char(self, char: str) -> None:
346
+ if char == "\n":
347
+ self.tap_key(KEYS["ENTER"])
348
+ return
349
+ if char == "\t":
350
+ self.tap_key(KEYS["TAB"])
351
+ return
352
+ shift = char in _CHAR_PLAIN
353
+ base = _CHAR_PLAIN.get(char, char)
354
+ if not base.isprintable():
355
+ raise ValueError(f"cannot type character {char!r}")
356
+ code = KEYS[base.upper()] if base.isalpha() else KEYS[_CHAR_KEY_NAME[base]]
357
+ device = self.keyboard()
358
+ if shift:
359
+ device.emit(EV_KEY, KEYS["LEFTSHIFT"], 1)
360
+ device.sync()
361
+ device.emit(EV_KEY, code, 1)
362
+ device.sync()
363
+ device.emit(EV_KEY, code, 0)
364
+ device.sync()
365
+ if shift:
366
+ device.emit(EV_KEY, KEYS["LEFTSHIFT"], 0)
367
+ device.sync()
368
+
369
+ def close(self) -> None:
370
+ for device in (self._pointer, self._wheel, self._keyboard):
371
+ if device is not None:
372
+ device.close()
373
+ self._pointer = self._wheel = self._keyboard = None
374
+
375
+
376
+ _CHAR_KEY_NAME = {
377
+ " ": "SPACE", "-": "MINUS", "=": "EQUAL", "[": "LEFTBRACE",
378
+ "]": "RIGHTBRACE", ";": "SEMICOLON", "'": "APOSTROPHE", "`": "GRAVE",
379
+ "\\": "BACKSLASH", ",": "COMMA", ".": "DOT", "/": "SLASH",
380
+ "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6", "7": "7",
381
+ "8": "8", "9": "9", "0": "0",
382
+ }
383
+
384
+
385
+ # --------------------------------------------------------------------------- #
386
+ # ydotool backend
387
+ # --------------------------------------------------------------------------- #
388
+ class YdotoolBackend:
389
+ """Fallback backend that delegates to the ydotool client."""
390
+
391
+ name = "ydotool"
392
+
393
+ def __init__(self, socket_path: str = DEFAULT_YDOTOOL_SOCKET, binary: str | None = None) -> None:
394
+ self.socket_path = socket_path
395
+ self.binary = binary or shutil.which("ydotool") or "ydotool"
396
+
397
+ @classmethod
398
+ def available(cls, socket_path: str = DEFAULT_YDOTOOL_SOCKET) -> bool:
399
+ return bool(shutil.which("ydotool")) and os.path.exists(socket_path)
400
+
401
+ def _run(self, *args: str) -> None:
402
+ command = [self.binary]
403
+ if self.socket_path:
404
+ command += ["-s", self.socket_path]
405
+ command += list(args)
406
+ result = subprocess.run(command, capture_output=True, text=True, timeout=20)
407
+ if result.returncode != 0:
408
+ raise RuntimeError(
409
+ f"ydotool {' '.join(args)} failed ({result.returncode}): "
410
+ f"{(result.stderr or result.stdout).strip()}"
411
+ )
412
+
413
+ def move(self, x: int, y: int, layout) -> None:
414
+ # ydotool 0.1.x drives a relative device, so track our own cursor and
415
+ # send the delta. Approximate by nature; the uinput backend is exact.
416
+ x, y = int(x), int(y)
417
+ last_x, last_y = getattr(self, "_pos", (0, 0))
418
+ self._run("mousemove_relative", str(x - last_x), str(y - last_y))
419
+ self._pos = (x, y)
420
+
421
+ def button(self, name: str, pressed: bool) -> None:
422
+ # BTN_LEFT/MIDDLE/RIGHT are EV_KEY codes, so `ydotool key` can press them.
423
+ code = {"left": BTN_LEFT, "right": BTN_RIGHT, "middle": BTN_MIDDLE}[name]
424
+ self._run("key", f"{code}:{1 if pressed else 0}")
425
+
426
+ def scroll(self, dx: int, dy: int) -> None:
427
+ raise RuntimeError(
428
+ "the ydotool backend cannot synthesize wheel events (ydotool 0.1.x has "
429
+ "no REL_WHEEL support); install/enable the uinput backend for scrolling"
430
+ )
431
+
432
+ def press(self, codes) -> None:
433
+ self._run("key", *[f"{code}:1" for code in codes])
434
+
435
+ def release(self, codes) -> None:
436
+ self._run("key", *[f"{code}:0" for code in reversed(list(codes))])
437
+
438
+ def tap_key(self, code: int) -> None:
439
+ self._run("key", f"{code}:1", f"{code}:0")
440
+
441
+ def type_char(self, char: str) -> None:
442
+ try:
443
+ self._run("type", "--key-delay", "12", char)
444
+ except RuntimeError:
445
+ self._run("type", char)
446
+
447
+ def close(self) -> None:
448
+ return None
449
+
450
+
451
+ # --------------------------------------------------------------------------- #
452
+ # facade
453
+ # --------------------------------------------------------------------------- #
454
+ class InputController:
455
+ """Layout-aware pointer/keyboard controller over the selected backend."""
456
+
457
+ def __init__(self, layout, preferred: str = "auto", uinput_path: str = DEFAULT_UINPUT,
458
+ ydotool_socket: str = DEFAULT_YDOTOOL_SOCKET) -> None:
459
+ self.layout = layout
460
+ self.backend = self._select(preferred, uinput_path, ydotool_socket)
461
+
462
+ @staticmethod
463
+ def _select(preferred: str, uinput_path: str, ydotool_socket: str):
464
+ if preferred in ("auto", "uinput") and UinputBackend.available(uinput_path):
465
+ return UinputBackend(uinput_path)
466
+ if preferred in ("auto", "ydotool") and YdotoolBackend.available(ydotool_socket):
467
+ return YdotoolBackend(ydotool_socket)
468
+ raise InputError(
469
+ "no input backend available: /dev/uinput is not readable+writable "
470
+ f"({uinput_path}) and ydotool is not usable. Run the prep script "
471
+ "(linux-computer-use-prep.sh) once (it adds a uaccess ACL on the "
472
+ "device), then RESTART the app that launches this server - a "
473
+ "long-running process keeps the permissions it started with."
474
+ )
475
+
476
+ @property
477
+ def backend_name(self) -> str:
478
+ return "uinput" if isinstance(self.backend, UinputBackend) else "ydotool"
479
+
480
+ def reset_input(self) -> None:
481
+ """Recreate the injection devices (used after a session restart)."""
482
+ reset = getattr(self.backend, "reset", None)
483
+ if reset is not None:
484
+ reset()
485
+
486
+ # -- pointer ----------------------------------------------------------- #
487
+ def move(self, x: int, y: int) -> None:
488
+ self.move_to(x, y)
489
+
490
+ def move_to(self, x: int, y: int) -> None:
491
+ self.backend.move(int(x), int(y), self.layout)
492
+
493
+ def click(self, x: int | None = None, y: int | None = None, button: str = "left",
494
+ double: bool = False, count: int = 1) -> None:
495
+ if button not in ("left", "right", "middle"):
496
+ raise ValueError("button must be left, right or middle")
497
+ if x is not None and y is not None:
498
+ self.move_to(x, y)
499
+ time.sleep(0.05)
500
+ for _ in range(max(1, count)):
501
+ self.backend.button(button, True)
502
+ time.sleep(0.02)
503
+ self.backend.button(button, False)
504
+ if _ < count - 1 or double:
505
+ time.sleep(0.06)
506
+
507
+ def press_hold(self, button: str = "left") -> None:
508
+ self.backend.button(button, True)
509
+
510
+ def release_hold(self, button: str = "left") -> None:
511
+ self.backend.button(button, False)
512
+
513
+ def drag(self, x1: int, y1: int, x2: int, y2: int, duration_ms: int = 400,
514
+ button: str = "left") -> None:
515
+ self.move_to(x1, y1)
516
+ time.sleep(0.06)
517
+ self.backend.button(button, True)
518
+ steps = max(4, min(60, duration_ms // 12))
519
+ for step in range(1, steps + 1):
520
+ ratio = step / steps
521
+ self.move_to(round(x1 + (x2 - x1) * ratio), round(y1 + (y2 - y1) * ratio))
522
+ time.sleep(max(0.004, duration_ms / 1000 / steps))
523
+ time.sleep(0.05)
524
+ self.backend.button(button, False)
525
+
526
+ def scroll(self, x: int | None = None, y: int | None = None, dx: int = 0, dy: int = 0) -> None:
527
+ if x is not None and y is not None:
528
+ self.move_to(x, y)
529
+ time.sleep(0.03)
530
+ self.backend.scroll(int(dx), int(dy))
531
+
532
+ # -- keyboard ---------------------------------------------------------- #
533
+ @staticmethod
534
+ def parse_combo(combo: str) -> list[int]:
535
+ parts = [part for part in re.split(r"\s*\+\s*", combo.strip()) if part]
536
+ if not parts:
537
+ raise ValueError("empty key combination")
538
+ return [key_code(part) for part in parts]
539
+
540
+ def key(self, combo: str) -> None:
541
+ codes = self.parse_combo(combo)
542
+ self.backend.press(codes[:-1])
543
+ self.backend.tap_key(codes[-1])
544
+ self.backend.release(codes[:-1])
545
+
546
+ def type_text(self, text: str, delay_ms: int = 12) -> None:
547
+ for char in text:
548
+ self.backend.type_char(char)
549
+ time.sleep(max(0.001, delay_ms / 1000))
550
+
551
+ def close(self) -> None:
552
+ self.backend.close()