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

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,528 @@
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
+ payload = struct.pack("HHiiiii", code, 0, 0, minimum, maximum, 0, 0)
191
+ fcntl.ioctl(self.fd, UI_ABS_SETUP, payload)
192
+ return self
193
+
194
+ def enable_prop(self, *props: int) -> "UinputDevice":
195
+ for prop in props:
196
+ fcntl.ioctl(self.fd, UI_SET_PROPBIT, prop)
197
+ return self
198
+
199
+ # -- creation --------------------------------------------------------- #
200
+ def create(self, vendor: int = 0x4453, product: int = 0x4C43) -> "UinputDevice":
201
+ # struct uinput_setup { struct input_id id; char name[80]; __u32 ff; }
202
+ setup = struct.pack(
203
+ "HHHH80sI",
204
+ BUS_VIRTUAL,
205
+ vendor & 0xFFFF,
206
+ product & 0xFFFF,
207
+ 1,
208
+ self.name.encode("utf-8")[:79],
209
+ 0,
210
+ )
211
+ fcntl.ioctl(self.fd, UI_DEV_SETUP, setup)
212
+ fcntl.ioctl(self.fd, UI_DEV_CREATE)
213
+ time.sleep(0.12) # let udev/libinput finish device setup
214
+ return self
215
+
216
+ # -- events ----------------------------------------------------------- #
217
+ def emit(self, etype: int, code: int, value: int) -> None:
218
+ os.write(self.fd, INPUT_EVENT.pack(0, 0, etype, code, value))
219
+
220
+ def sync(self) -> None:
221
+ self.emit(EV_SYN, SYN_REPORT, 0)
222
+
223
+ def tap(self, code: int) -> None:
224
+ self.emit(EV_KEY, code, 1)
225
+ self.sync()
226
+ self.emit(EV_KEY, code, 0)
227
+ self.sync()
228
+
229
+ def close(self) -> None:
230
+ if self._closed:
231
+ return
232
+ self._closed = True
233
+ try:
234
+ fcntl.ioctl(self.fd, UI_DEV_DESTROY)
235
+ except OSError:
236
+ pass
237
+ try:
238
+ os.close(self.fd)
239
+ except OSError:
240
+ pass
241
+
242
+
243
+ class UinputBackend:
244
+ """Lazily created absolute pointer, wheel and keyboard devices."""
245
+
246
+ name = "uinput"
247
+
248
+ def __init__(self, uinput_path: str = DEFAULT_UINPUT) -> None:
249
+ self.uinput_path = uinput_path
250
+ self._pointer: UinputDevice | None = None
251
+ self._wheel: UinputDevice | None = None
252
+ self._keyboard: UinputDevice | None = None
253
+
254
+ # -- capability check -------------------------------------------------- #
255
+ @classmethod
256
+ def available(cls, uinput_path: str = DEFAULT_UINPUT) -> bool:
257
+ return os.access(uinput_path, os.R_OK | os.W_OK)
258
+
259
+ # -- devices ----------------------------------------------------------- #
260
+ def pointer(self) -> UinputDevice:
261
+ if self._pointer is None:
262
+ device = UinputDevice("DSH Computer Use Pointer")
263
+ device.enable_event(EV_KEY, EV_ABS, EV_SYN)
264
+ device.enable_keys((BTN_LEFT, BTN_RIGHT, BTN_MIDDLE))
265
+ device.enable_abs(ABS_X, 0, ABS_MAX_VALUE)
266
+ device.enable_abs(ABS_Y, 0, ABS_MAX_VALUE)
267
+ device.enable_prop(INPUT_PROP_POINTER)
268
+ self._pointer = device.create(product=0x0001)
269
+ return self._pointer
270
+
271
+ def wheel(self) -> UinputDevice:
272
+ if self._wheel is None:
273
+ device = UinputDevice("DSH Computer Use Wheel")
274
+ device.enable_event(EV_REL, EV_KEY, EV_SYN)
275
+ device.enable_rel((REL_WHEEL, REL_HWHEEL))
276
+ device.enable_keys((BTN_LEFT,))
277
+ self._wheel = device.create(product=0x0002)
278
+ return self._wheel
279
+
280
+ def keyboard(self) -> UinputDevice:
281
+ if self._keyboard is None:
282
+ device = UinputDevice("DSH Computer Use Keyboard")
283
+ device.enable_event(EV_KEY, EV_SYN)
284
+ device.enable_keys(range(1, KEY_MAX + 1))
285
+ self._keyboard = device.create(product=0x0003)
286
+ return self._keyboard
287
+
288
+ # -- primitives -------------------------------------------------------- #
289
+ def move(self, x: int, y: int, layout) -> None:
290
+ """Move the absolute pointer to logical desktop coordinate (x, y)."""
291
+ abs_x, abs_y = layout.to_absolute(x, y)
292
+ device = self.pointer()
293
+ device.emit(EV_ABS, ABS_X, abs_x)
294
+ device.emit(EV_ABS, ABS_Y, abs_y)
295
+ device.sync()
296
+
297
+ def button(self, name: str, pressed: bool) -> None:
298
+ code = {"left": BTN_LEFT, "right": BTN_RIGHT, "middle": BTN_MIDDLE}[name]
299
+ device = self.pointer()
300
+ device.emit(EV_KEY, code, 1 if pressed else 0)
301
+ device.sync()
302
+
303
+ def scroll(self, dx: int, dy: int) -> None:
304
+ device = self.wheel()
305
+ if dy:
306
+ device.emit(EV_REL, REL_WHEEL, -int(dy))
307
+ device.sync()
308
+ if dx:
309
+ device.emit(EV_REL, REL_HWHEEL, -int(dx))
310
+ device.sync()
311
+
312
+ def press(self, codes) -> None:
313
+ device = self.keyboard()
314
+ for code in codes:
315
+ device.emit(EV_KEY, code, 1)
316
+ device.sync()
317
+
318
+ def release(self, codes) -> None:
319
+ device = self.keyboard()
320
+ for code in reversed(list(codes)):
321
+ device.emit(EV_KEY, code, 0)
322
+ device.sync()
323
+
324
+ def tap_key(self, code: int) -> None:
325
+ self.keyboard().tap(code)
326
+
327
+ def type_char(self, char: str) -> None:
328
+ if char == "\n":
329
+ self.tap_key(KEYS["ENTER"])
330
+ return
331
+ if char == "\t":
332
+ self.tap_key(KEYS["TAB"])
333
+ return
334
+ shift = char in _CHAR_PLAIN
335
+ base = _CHAR_PLAIN.get(char, char)
336
+ if not base.isprintable():
337
+ raise ValueError(f"cannot type character {char!r}")
338
+ code = KEYS[base.upper()] if base.isalpha() else KEYS[_CHAR_KEY_NAME[base]]
339
+ device = self.keyboard()
340
+ if shift:
341
+ device.emit(EV_KEY, KEYS["LEFTSHIFT"], 1)
342
+ device.sync()
343
+ device.emit(EV_KEY, code, 1)
344
+ device.sync()
345
+ device.emit(EV_KEY, code, 0)
346
+ device.sync()
347
+ if shift:
348
+ device.emit(EV_KEY, KEYS["LEFTSHIFT"], 0)
349
+ device.sync()
350
+
351
+ def close(self) -> None:
352
+ for device in (self._pointer, self._wheel, self._keyboard):
353
+ if device is not None:
354
+ device.close()
355
+ self._pointer = self._wheel = self._keyboard = None
356
+
357
+
358
+ _CHAR_KEY_NAME = {
359
+ " ": "SPACE", "-": "MINUS", "=": "EQUAL", "[": "LEFTBRACE",
360
+ "]": "RIGHTBRACE", ";": "SEMICOLON", "'": "APOSTROPHE", "`": "GRAVE",
361
+ "\\": "BACKSLASH", ",": "COMMA", ".": "DOT", "/": "SLASH",
362
+ "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6", "7": "7",
363
+ "8": "8", "9": "9", "0": "0",
364
+ }
365
+
366
+
367
+ # --------------------------------------------------------------------------- #
368
+ # ydotool backend
369
+ # --------------------------------------------------------------------------- #
370
+ class YdotoolBackend:
371
+ """Fallback backend that delegates to the ydotool client."""
372
+
373
+ name = "ydotool"
374
+
375
+ def __init__(self, socket_path: str = DEFAULT_YDOTOOL_SOCKET, binary: str | None = None) -> None:
376
+ self.socket_path = socket_path
377
+ self.binary = binary or shutil.which("ydotool") or "ydotool"
378
+
379
+ @classmethod
380
+ def available(cls, socket_path: str = DEFAULT_YDOTOOL_SOCKET) -> bool:
381
+ return bool(shutil.which("ydotool")) and os.path.exists(socket_path)
382
+
383
+ def _run(self, *args: str) -> None:
384
+ command = [self.binary]
385
+ if self.socket_path:
386
+ command += ["-s", self.socket_path]
387
+ command += list(args)
388
+ result = subprocess.run(command, capture_output=True, text=True, timeout=20)
389
+ if result.returncode != 0:
390
+ raise RuntimeError(
391
+ f"ydotool {' '.join(args)} failed ({result.returncode}): "
392
+ f"{(result.stderr or result.stdout).strip()}"
393
+ )
394
+
395
+ def move(self, x: int, y: int, layout) -> None:
396
+ # ydotool 0.1.x drives a relative device, so track our own cursor and
397
+ # send the delta. Approximate by nature; the uinput backend is exact.
398
+ x, y = int(x), int(y)
399
+ last_x, last_y = getattr(self, "_pos", (0, 0))
400
+ self._run("mousemove_relative", str(x - last_x), str(y - last_y))
401
+ self._pos = (x, y)
402
+
403
+ def button(self, name: str, pressed: bool) -> None:
404
+ # BTN_LEFT/MIDDLE/RIGHT are EV_KEY codes, so `ydotool key` can press them.
405
+ code = {"left": BTN_LEFT, "right": BTN_RIGHT, "middle": BTN_MIDDLE}[name]
406
+ self._run("key", f"{code}:{1 if pressed else 0}")
407
+
408
+ def scroll(self, dx: int, dy: int) -> None:
409
+ raise RuntimeError(
410
+ "the ydotool backend cannot synthesize wheel events (ydotool 0.1.x has "
411
+ "no REL_WHEEL support); install/enable the uinput backend for scrolling"
412
+ )
413
+
414
+ def press(self, codes) -> None:
415
+ self._run("key", *[f"{code}:1" for code in codes])
416
+
417
+ def release(self, codes) -> None:
418
+ self._run("key", *[f"{code}:0" for code in reversed(list(codes))])
419
+
420
+ def tap_key(self, code: int) -> None:
421
+ self._run("key", f"{code}:1", f"{code}:0")
422
+
423
+ def type_char(self, char: str) -> None:
424
+ try:
425
+ self._run("type", "--key-delay", "12", char)
426
+ except RuntimeError:
427
+ self._run("type", char)
428
+
429
+ def close(self) -> None:
430
+ return None
431
+
432
+
433
+ # --------------------------------------------------------------------------- #
434
+ # facade
435
+ # --------------------------------------------------------------------------- #
436
+ class InputController:
437
+ """Layout-aware pointer/keyboard controller over the selected backend."""
438
+
439
+ def __init__(self, layout, preferred: str = "auto", uinput_path: str = DEFAULT_UINPUT,
440
+ ydotool_socket: str = DEFAULT_YDOTOOL_SOCKET) -> None:
441
+ self.layout = layout
442
+ self.backend = self._select(preferred, uinput_path, ydotool_socket)
443
+
444
+ @staticmethod
445
+ def _select(preferred: str, uinput_path: str, ydotool_socket: str):
446
+ if preferred in ("auto", "uinput") and UinputBackend.available(uinput_path):
447
+ return UinputBackend(uinput_path)
448
+ if preferred in ("auto", "ydotool") and YdotoolBackend.available(ydotool_socket):
449
+ return YdotoolBackend(ydotool_socket)
450
+ raise InputError(
451
+ "no input backend available: /dev/uinput is not readable+writable "
452
+ f"({uinput_path}) and ydotool is not usable. Run the prep script "
453
+ "(linux-computer-use-prep.sh) once (it adds a uaccess ACL on the "
454
+ "device), then RESTART the app that launches this server - a "
455
+ "long-running process keeps the permissions it started with."
456
+ )
457
+
458
+ @property
459
+ def backend_name(self) -> str:
460
+ return "uinput" if isinstance(self.backend, UinputBackend) else "ydotool"
461
+
462
+ # -- pointer ----------------------------------------------------------- #
463
+ def move(self, x: int, y: int) -> None:
464
+ self.move_to(x, y)
465
+
466
+ def move_to(self, x: int, y: int) -> None:
467
+ self.backend.move(int(x), int(y), self.layout)
468
+
469
+ def click(self, x: int | None = None, y: int | None = None, button: str = "left",
470
+ double: bool = False, count: int = 1) -> None:
471
+ if button not in ("left", "right", "middle"):
472
+ raise ValueError("button must be left, right or middle")
473
+ if x is not None and y is not None:
474
+ self.move_to(x, y)
475
+ time.sleep(0.05)
476
+ for _ in range(max(1, count)):
477
+ self.backend.button(button, True)
478
+ time.sleep(0.02)
479
+ self.backend.button(button, False)
480
+ if _ < count - 1 or double:
481
+ time.sleep(0.06)
482
+
483
+ def press_hold(self, button: str = "left") -> None:
484
+ self.backend.button(button, True)
485
+
486
+ def release_hold(self, button: str = "left") -> None:
487
+ self.backend.button(button, False)
488
+
489
+ def drag(self, x1: int, y1: int, x2: int, y2: int, duration_ms: int = 400,
490
+ button: str = "left") -> None:
491
+ self.move_to(x1, y1)
492
+ time.sleep(0.06)
493
+ self.backend.button(button, True)
494
+ steps = max(4, min(60, duration_ms // 12))
495
+ for step in range(1, steps + 1):
496
+ ratio = step / steps
497
+ self.move_to(round(x1 + (x2 - x1) * ratio), round(y1 + (y2 - y1) * ratio))
498
+ time.sleep(max(0.004, duration_ms / 1000 / steps))
499
+ time.sleep(0.05)
500
+ self.backend.button(button, False)
501
+
502
+ def scroll(self, x: int | None = None, y: int | None = None, dx: int = 0, dy: int = 0) -> None:
503
+ if x is not None and y is not None:
504
+ self.move_to(x, y)
505
+ time.sleep(0.03)
506
+ self.backend.scroll(int(dx), int(dy))
507
+
508
+ # -- keyboard ---------------------------------------------------------- #
509
+ @staticmethod
510
+ def parse_combo(combo: str) -> list[int]:
511
+ parts = [part for part in re.split(r"\s*\+\s*", combo.strip()) if part]
512
+ if not parts:
513
+ raise ValueError("empty key combination")
514
+ return [key_code(part) for part in parts]
515
+
516
+ def key(self, combo: str) -> None:
517
+ codes = self.parse_combo(combo)
518
+ self.backend.press(codes[:-1])
519
+ self.backend.tap_key(codes[-1])
520
+ self.backend.release(codes[:-1])
521
+
522
+ def type_text(self, text: str, delay_ms: int = 12) -> None:
523
+ for char in text:
524
+ self.backend.type_char(char)
525
+ time.sleep(max(0.001, delay_ms / 1000))
526
+
527
+ def close(self) -> None:
528
+ self.backend.close()