| 1 |
import contextlib |
| 2 |
import os |
| 3 |
from typing import Generic, Iterator, Literal, NamedTuple, AnyStr, overload |
| 4 |
|
| 5 |
from . import _input, ecodes, ff, util |
| 6 |
|
| 7 |
try: |
| 8 |
from .eventio_async import EvdevError, EventIO |
| 9 |
except ImportError: |
| 10 |
from .eventio import EvdevError, EventIO |
| 11 |
|
| 12 |
PathLike = AnyStr | os.PathLike[AnyStr] |
| 13 |
|
| 14 |
|
| 15 |
class AbsInfo(NamedTuple): |
| 16 |
"""Absolute axis information. |
| 17 |
|
| 18 |
A ``namedtuple`` with absolute axis information - |
| 19 |
corresponds to the ``input_absinfo`` struct: |
| 20 |
|
| 21 |
Attributes |
| 22 |
--------- |
| 23 |
value |
| 24 |
Latest reported value for the axis. |
| 25 |
|
| 26 |
min |
| 27 |
Specifies minimum value for the axis. |
| 28 |
|
| 29 |
max |
| 30 |
Specifies maximum value for the axis. |
| 31 |
|
| 32 |
fuzz |
| 33 |
Specifies fuzz value that is used to filter noise from the |
| 34 |
event stream. |
| 35 |
|
| 36 |
flat |
| 37 |
Values that are within this value will be discarded by joydev |
| 38 |
interface and reported as 0 instead. |
| 39 |
|
| 40 |
resolution |
| 41 |
Specifies resolution for the values reported for the axis. |
| 42 |
Resolution for main axes (``ABS_X, ABS_Y, ABS_Z``) is reported |
| 43 |
in units per millimeter (units/mm), resolution for rotational |
| 44 |
axes (``ABS_RX, ABS_RY, ABS_RZ``) is reported in units per |
| 45 |
radian. |
| 46 |
|
| 47 |
Note |
| 48 |
---- |
| 49 |
The input core does not clamp reported values to the ``[minimum, |
| 50 |
maximum]`` limits, such task is left to userspace. |
| 51 |
|
| 52 |
""" |
| 53 |
|
| 54 |
value: int |
| 55 |
min: int |
| 56 |
max: int |
| 57 |
fuzz: int |
| 58 |
flat: int |
| 59 |
resolution: int |
| 60 |
|
| 61 |
def __str__(self) -> str: |
| 62 |
return "value {}, min {}, max {}, fuzz {}, flat {}, res {}".format(*self) # pylint: disable=not-an-iterable |
| 63 |
|
| 64 |
|
| 65 |
class KbdInfo(NamedTuple): |
| 66 |
"""Keyboard repeat rate. |
| 67 |
|
| 68 |
Attributes |
| 69 |
---------- |
| 70 |
delay |
| 71 |
Amount of time that a key must be depressed before it will start |
| 72 |
to repeat (in milliseconds). |
| 73 |
|
| 74 |
repeat |
| 75 |
Keyboard repeat rate in characters per second. |
| 76 |
""" |
| 77 |
|
| 78 |
delay: int |
| 79 |
repeat: int |
| 80 |
|
| 81 |
def __str__(self) -> str: |
| 82 |
return "delay {}, repeat {}".format(self.delay, self.repeat) |
| 83 |
|
| 84 |
|
| 85 |
class DeviceInfo(NamedTuple): |
| 86 |
""" |
| 87 |
Attributes |
| 88 |
---------- |
| 89 |
bustype |
| 90 |
vendor |
| 91 |
product |
| 92 |
version |
| 93 |
""" |
| 94 |
|
| 95 |
bustype: int |
| 96 |
vendor: int |
| 97 |
product: int |
| 98 |
version: int |
| 99 |
|
| 100 |
def __str__(self) -> str: |
| 101 |
msg = "bus: {:04x}, vendor {:04x}, product {:04x}, version {:04x}" |
| 102 |
return msg.format(*self) # pylint: disable=not-an-iterable |
| 103 |
|
| 104 |
|
| 105 |
class InputDevice(EventIO, Generic[AnyStr]): |
| 106 |
""" |
| 107 |
A linux input device from which input events can be read. |
| 108 |
""" |
| 109 |
|
| 110 |
__slots__ = ("path", "fd", "info", "name", "phys", "uniq", "_rawcapabilities", "version", "ff_effects_count") |
| 111 |
|
| 112 |
def __init__(self, dev: PathLike, readonly: bool = False): |
| 113 |
""" |
| 114 |
Arguments |
| 115 |
--------- |
| 116 |
dev : |
| 117 |
Path to input device |
| 118 |
readonly : bool |
| 119 |
Open in read-only mode (``O_RDONLY``) without attempting ``O_RDWR`` first. |
| 120 |
""" |
| 121 |
|
| 122 |
#: Path to input device. |
| 123 |
self.path: str | bytes = dev if not hasattr(dev, "__fspath__") else dev.__fspath__() |
| 124 |
|
| 125 |
try: |
| 126 |
# Certain operations are possible only when the device is opened in read-write mode. |
| 127 |
# This avoids triggering firmware side-effects (such as LED state re-assertion) on certain hardware. |
| 128 |
if readonly: |
| 129 |
raise OSError |
| 130 |
fd = os.open(dev, os.O_RDWR | os.O_NONBLOCK) |
| 131 |
except OSError: |
| 132 |
fd = os.open(dev, os.O_RDONLY | os.O_NONBLOCK) |
| 133 |
|
| 134 |
#: A non-blocking file descriptor to the device file. |
| 135 |
self.fd: int = fd |
| 136 |
|
| 137 |
# Returns (bustype, vendor, product, version, name, phys, capabilities). |
| 138 |
info_res = _input.ioctl_devinfo(self.fd) |
| 139 |
|
| 140 |
#: A :class:`DeviceInfo <evdev.device.DeviceInfo>` instance. |
| 141 |
self.info: DeviceInfo = DeviceInfo(*info_res[:4]) |
| 142 |
|
| 143 |
#: The name of the event device. |
| 144 |
self.name: str = info_res[4] |
| 145 |
|
| 146 |
#: The physical topology of the device. |
| 147 |
self.phys: str = info_res[5] |
| 148 |
|
| 149 |
#: The unique identifier of the device. |
| 150 |
self.uniq: str = info_res[6] |
| 151 |
|
| 152 |
#: The evdev protocol version. |
| 153 |
self.version: int = _input.ioctl_EVIOCGVERSION(self.fd) |
| 154 |
|
| 155 |
#: The raw dictionary of device capabilities - see `:func:capabilities()`. |
| 156 |
self._rawcapabilities = _input.ioctl_capabilities(self.fd) |
| 157 |
|
| 158 |
#: The number of force feedback effects the device can keep in its memory. |
| 159 |
self.ff_effects_count = _input.ioctl_EVIOCGEFFECTS(self.fd) |
| 160 |
|
| 161 |
def __del__(self) -> None: |
| 162 |
if hasattr(self, "fd") and self.fd is not None: |
| 163 |
try: |
| 164 |
self.close() |
| 165 |
except (OSError, ImportError, AttributeError): |
| 166 |
pass |
| 167 |
|
| 168 |
def _capabilities(self, absinfo: bool = True): |
| 169 |
res = {} |
| 170 |
|
| 171 |
for etype, _ecodes in self._rawcapabilities.items(): |
| 172 |
for code in _ecodes: |
| 173 |
l = res.setdefault(etype, []) |
| 174 |
if isinstance(code, tuple): |
| 175 |
if absinfo: |
| 176 |
a = code[1] # (0, 0, 0, 255, 0, 0) |
| 177 |
i = AbsInfo(*a) |
| 178 |
l.append((code[0], i)) |
| 179 |
else: |
| 180 |
l.append(code[0]) |
| 181 |
else: |
| 182 |
l.append(code) |
| 183 |
|
| 184 |
return res |
| 185 |
|
| 186 |
@overload |
| 187 |
def capabilities(self, verbose: Literal[False] = ..., absinfo: bool = ...) -> dict[int, list[int]]: |
| 188 |
... |
| 189 |
@overload |
| 190 |
def capabilities(self, verbose: Literal[True], absinfo: bool = ...) -> dict[tuple[str, int], list[tuple[str, int]]]: |
| 191 |
... |
| 192 |
def capabilities( |
| 193 |
self, verbose: bool = False, absinfo: bool = True |
| 194 |
) -> dict[int, list[int]] | dict[tuple[str, int], list[tuple[str, int]]]: |
| 195 |
""" |
| 196 |
Return the event types that this device supports as a mapping of |
| 197 |
supported event types to lists of handled event codes. |
| 198 |
|
| 199 |
Example |
| 200 |
-------- |
| 201 |
|
| 202 |
>>> device.capabilities() |
| 203 |
{ 1: [272, 273, 274], 2: [0, 1, 6, 8] } |
| 204 |
|
| 205 |
If ``verbose`` is ``True``, event codes and types will be resolved |
| 206 |
to their names. |
| 207 |
|
| 208 |
:: |
| 209 |
|
| 210 |
{ ('EV_KEY', 1): [('BTN_MOUSE', 272), |
| 211 |
('BTN_RIGHT', 273), |
| 212 |
('BTN_MIDDLE', 273)], |
| 213 |
('EV_REL', 2): [('REL_X', 0), |
| 214 |
('REL_Y', 1), |
| 215 |
('REL_HWHEEL', 6), |
| 216 |
('REL_WHEEL', 8)] } |
| 217 |
|
| 218 |
Unknown codes or types will be resolved to ``'?'``. |
| 219 |
|
| 220 |
If ``absinfo`` is ``True``, the list of capabilities will also |
| 221 |
include absolute axis information in the form of |
| 222 |
:class:`AbsInfo` instances:: |
| 223 |
|
| 224 |
{ 3: [ (0, AbsInfo(min=0, max=255, fuzz=0, flat=0)), |
| 225 |
(1, AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]} |
| 226 |
|
| 227 |
Combined with ``verbose`` the above becomes:: |
| 228 |
|
| 229 |
{ ('EV_ABS', 3): [ (('ABS_X', 0), AbsInfo(min=0, max=255, fuzz=0, flat=0)), |
| 230 |
(('ABS_Y', 1), AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]} |
| 231 |
|
| 232 |
""" |
| 233 |
|
| 234 |
if verbose: |
| 235 |
return dict(util.resolve_ecodes_dict(self._capabilities(absinfo))) |
| 236 |
else: |
| 237 |
return self._capabilities(absinfo) |
| 238 |
|
| 239 |
def input_props(self, verbose: bool = False): |
| 240 |
""" |
| 241 |
Get device properties and quirks. |
| 242 |
|
| 243 |
Example |
| 244 |
------- |
| 245 |
>>> device.input_props() |
| 246 |
[0, 5] |
| 247 |
|
| 248 |
If ``verbose`` is ``True``, input properties are resolved to their |
| 249 |
names. Unknown codes are resolved to ``'?'``:: |
| 250 |
|
| 251 |
[('INPUT_PROP_POINTER', 0), ('INPUT_PROP_POINTING_STICK', 5)] |
| 252 |
|
| 253 |
""" |
| 254 |
props = _input.ioctl_EVIOCGPROP(self.fd) |
| 255 |
if verbose: |
| 256 |
return util.resolve_ecodes(ecodes.INPUT_PROP, props) |
| 257 |
|
| 258 |
return props |
| 259 |
|
| 260 |
def leds(self, verbose: bool = False): |
| 261 |
""" |
| 262 |
Return currently set LED keys. |
| 263 |
|
| 264 |
Example |
| 265 |
------- |
| 266 |
>>> device.leds() |
| 267 |
[0, 1, 8, 9] |
| 268 |
|
| 269 |
If ``verbose`` is ``True``, event codes are resolved to their |
| 270 |
names. Unknown codes are resolved to ``'?'``:: |
| 271 |
|
| 272 |
[('LED_NUML', 0), ('LED_CAPSL', 1), ('LED_MISC', 8), ('LED_MAIL', 9)] |
| 273 |
|
| 274 |
""" |
| 275 |
leds = _input.ioctl_EVIOCG_bits(self.fd, ecodes.EV_LED) |
| 276 |
if verbose: |
| 277 |
return util.resolve_ecodes(ecodes.LED, leds) |
| 278 |
|
| 279 |
return leds |
| 280 |
|
| 281 |
def set_led(self, led_num: int, value: int) -> None: |
| 282 |
""" |
| 283 |
Set the state of the selected LED. |
| 284 |
|
| 285 |
Example |
| 286 |
------- |
| 287 |
>>> device.set_led(ecodes.LED_NUML, 1) |
| 288 |
""" |
| 289 |
self.write(ecodes.EV_LED, led_num, value) |
| 290 |
|
| 291 |
def __eq__(self, other) -> bool: |
| 292 |
""" |
| 293 |
Two devices are equal if their :data:`info` attributes are equal. |
| 294 |
""" |
| 295 |
return isinstance(other, self.__class__) and self.info == other.info and self.path == other.path |
| 296 |
|
| 297 |
def __str__(self) -> str: |
| 298 |
msg = 'device {}, name "{}", phys "{}", uniq "{}"' |
| 299 |
return msg.format(self.path, self.name, self.phys, self.uniq or "") |
| 300 |
|
| 301 |
def __repr__(self) -> str: |
| 302 |
msg = (self.__class__.__name__, self.path) |
| 303 |
return "{}({!r})".format(*msg) |
| 304 |
|
| 305 |
def __fspath__(self) -> AnyStr: |
| 306 |
return self.path |
| 307 |
|
| 308 |
def close(self) -> None: |
| 309 |
if self.fd > -1: |
| 310 |
try: |
| 311 |
super().close() |
| 312 |
os.close(self.fd) |
| 313 |
finally: |
| 314 |
self.fd = -1 |
| 315 |
|
| 316 |
def grab(self) -> None: |
| 317 |
""" |
| 318 |
Grab input device using ``EVIOCGRAB`` - other applications will |
| 319 |
be unable to receive events until the device is released. Only |
| 320 |
one process can hold a ``EVIOCGRAB`` on a device. |
| 321 |
|
| 322 |
Warning |
| 323 |
------- |
| 324 |
Grabbing an already grabbed device will raise an ``OSError``. |
| 325 |
""" |
| 326 |
|
| 327 |
_input.ioctl_EVIOCGRAB(self.fd, 1) |
| 328 |
|
| 329 |
def ungrab(self) -> None: |
| 330 |
""" |
| 331 |
Release device if it has been already grabbed (uses `EVIOCGRAB`). |
| 332 |
|
| 333 |
Warning |
| 334 |
------- |
| 335 |
Releasing an already released device will raise an |
| 336 |
``OSError('Invalid argument')``. |
| 337 |
""" |
| 338 |
|
| 339 |
_input.ioctl_EVIOCGRAB(self.fd, 0) |
| 340 |
|
| 341 |
@contextlib.contextmanager |
| 342 |
def grab_context(self) -> Iterator[None]: |
| 343 |
""" |
| 344 |
A context manager for the duration of which only the current |
| 345 |
process will be able to receive events from the device. |
| 346 |
""" |
| 347 |
self.grab() |
| 348 |
yield |
| 349 |
self.ungrab() |
| 350 |
|
| 351 |
def upload_effect(self, effect: "ff.Effect", writeback_id: bool = True) -> int: |
| 352 |
""" |
| 353 |
Upload a force feedback effect to a force feedback device and return its effect id. |
| 354 |
If ``writeback_id`` is ``True``, the effect id is written back to the ``effect`` struct. |
| 355 |
""" |
| 356 |
|
| 357 |
data = memoryview(effect).tobytes() |
| 358 |
ff_id = _input.upload_effect(self.fd, data) |
| 359 |
if writeback_id: |
| 360 |
effect.id = ff_id |
| 361 |
return ff_id |
| 362 |
|
| 363 |
def erase_effect(self, ff_id: int) -> None: |
| 364 |
""" |
| 365 |
Erase a force effect from a force feedback device. This also |
| 366 |
stops the effect. |
| 367 |
""" |
| 368 |
|
| 369 |
_input.erase_effect(self.fd, ff_id) |
| 370 |
|
| 371 |
@property |
| 372 |
def repeat(self): |
| 373 |
""" |
| 374 |
Get or set the keyboard repeat rate (in characters per |
| 375 |
minute) and delay (in milliseconds). |
| 376 |
""" |
| 377 |
|
| 378 |
return KbdInfo(*_input.ioctl_EVIOCGREP(self.fd)) |
| 379 |
|
| 380 |
@repeat.setter |
| 381 |
def repeat(self, value: tuple[int, int]): |
| 382 |
return _input.ioctl_EVIOCSREP(self.fd, *value) |
| 383 |
|
| 384 |
def active_keys(self, verbose: bool = False): |
| 385 |
""" |
| 386 |
Return currently active keys. |
| 387 |
|
| 388 |
Example |
| 389 |
------- |
| 390 |
|
| 391 |
>>> device.active_keys() |
| 392 |
[1, 42] |
| 393 |
|
| 394 |
If ``verbose`` is ``True``, key codes are resolved to their |
| 395 |
verbose names. Unknown codes are resolved to ``'?'``. For |
| 396 |
example:: |
| 397 |
|
| 398 |
[('KEY_ESC', 1), ('KEY_LEFTSHIFT', 42)] |
| 399 |
|
| 400 |
""" |
| 401 |
active_keys = _input.ioctl_EVIOCG_bits(self.fd, ecodes.EV_KEY) |
| 402 |
if verbose: |
| 403 |
return util.resolve_ecodes(ecodes.KEY, active_keys) |
| 404 |
|
| 405 |
return active_keys |
| 406 |
|
| 407 |
def absinfo(self, axis_num: int): |
| 408 |
""" |
| 409 |
Return current :class:`AbsInfo` for input device axis |
| 410 |
|
| 411 |
Arguments |
| 412 |
--------- |
| 413 |
axis_num : int |
| 414 |
EV_ABS keycode (example :attr:`ecodes.ABS_X`) |
| 415 |
|
| 416 |
Example |
| 417 |
------- |
| 418 |
>>> device.absinfo(ecodes.ABS_X) |
| 419 |
AbsInfo(value=1501, min=-32768, max=32767, fuzz=0, flat=128, resolution=0) |
| 420 |
""" |
| 421 |
return AbsInfo(*_input.ioctl_EVIOCGABS(self.fd, axis_num)) |
| 422 |
|
| 423 |
def set_absinfo( |
| 424 |
self, |
| 425 |
axis_num: int, |
| 426 |
value: int | None = None, |
| 427 |
min: int | None = None, |
| 428 |
max: int | None = None, |
| 429 |
fuzz: int | None = None, |
| 430 |
flat: int | None = None, |
| 431 |
resolution: int | None = None, |
| 432 |
) -> None: |
| 433 |
""" |
| 434 |
Update :class:`AbsInfo` values. Only specified values will be overwritten. |
| 435 |
|
| 436 |
Arguments |
| 437 |
--------- |
| 438 |
axis_num : int |
| 439 |
EV_ABS keycode (example :attr:`ecodes.ABS_X`) |
| 440 |
|
| 441 |
Example |
| 442 |
------- |
| 443 |
>>> device.set_absinfo(ecodes.ABS_X, min=-2000, max=2000) |
| 444 |
|
| 445 |
You can also unpack AbsInfo tuple that will overwrite all values |
| 446 |
|
| 447 |
>>> device.set_absinfo(ecodes.ABS_Y, *AbsInfo(0, -2000, 2000, 0, 15, 0)) |
| 448 |
""" |
| 449 |
|
| 450 |
cur_absinfo = self.absinfo(axis_num) |
| 451 |
new_absinfo = AbsInfo( |
| 452 |
value if value is not None else cur_absinfo.value, |
| 453 |
min if min is not None else cur_absinfo.min, |
| 454 |
max if max is not None else cur_absinfo.max, |
| 455 |
fuzz if fuzz is not None else cur_absinfo.fuzz, |
| 456 |
flat if flat is not None else cur_absinfo.flat, |
| 457 |
resolution if resolution is not None else cur_absinfo.resolution, |
| 458 |
) |
| 459 |
_input.ioctl_EVIOCSABS(self.fd, axis_num, new_absinfo) |