Debian Codegraph @

src/evdev/uinput.py

raw
1 import ctypes
2 import os
3 import platform
4 import re
5 import stat
6 import time
7 from collections import defaultdict
8 from typing import Sequence
9
10 from . import _uinput, ecodes, ff, util
11 from .device import InputDevice, AbsInfo
12 from .events import InputEvent
13
14 try:
15 from evdev.eventio_async import EventIO
16 except ImportError:
17 from evdev.eventio import EventIO
18
19
20 class UInputError(Exception):
21 pass
22
23
24 class UInput(EventIO):
25 """
26 A userland input device and that can inject input events into the
27 linux input subsystem.
28 """
29
30 __slots__ = (
31 "name",
32 "vendor",
33 "product",
34 "version",
35 "bustype",
36 "events",
37 "devnode",
38 "fd",
39 "device",
40 )
41
42 @classmethod
43 def from_device(
44 cls,
45 *devices: InputDevice | str | bytes | os.PathLike,
46 filtered_types: tuple[int] = (ecodes.EV_SYN, ecodes.EV_FF),
47 **kwargs,
48 ) -> "UInput":
49 """
50 Create an UInput device with the capabilities of one or more input
51 devices.
52
53 Arguments
54 ---------
55 devices : InputDevice|str
56 Varargs of InputDevice instances or paths to input devices.
57
58 filtered_types : Tuple[event type codes]
59 Event types to exclude from the capabilities of the uinput device.
60
61 **kwargs
62 Keyword arguments to UInput constructor (i.e. name, vendor etc.).
63 """
64
65 device_instances = []
66 for dev in devices:
67 if not isinstance(dev, InputDevice):
68 dev = InputDevice(str(dev))
69 device_instances.append(dev)
70
71 all_capabilities = defaultdict(set)
72
73 if "max_effects" not in kwargs:
74 kwargs["max_effects"] = min([dev.ff_effects_count for dev in device_instances])
75
76 # Merge the capabilities of all devices into one dictionary.
77 for dev in device_instances:
78 for ev_type, ev_codes in dev.capabilities().items():
79 all_capabilities[ev_type].update(ev_codes)
80
81 for evtype in filtered_types:
82 if evtype in all_capabilities:
83 del all_capabilities[evtype]
84
85 return cls(events=all_capabilities, **kwargs)
86
87 def __init__(
88 self,
89 events: dict[int, Sequence[int]] | None = None,
90 name: str = "py-evdev-uinput",
91 vendor: int = 0x1,
92 product: int = 0x1,
93 version: int = 0x1,
94 bustype: int = 0x3,
95 devnode: str = "/dev/uinput",
96 phys: str = "py-evdev-uinput",
97 input_props: Sequence[int] | None = None,
98 # CentOS 7 has sufficiently old headers that FF_MAX_EFFECTS is not defined there,
99 # which causes the whole module to fail loading. Fallback on a hardcoded value of
100 # FF_MAX_EFFECTS if it is not defined in the ecodes.
101 max_effects: int = ecodes.ecodes.get("FF_MAX_EFFECTS", 96),
102 ):
103 """
104 Arguments
105 ---------
106 events : dict
107 Dictionary of event types mapping to lists of event codes. The
108 event types and codes that the uinput device will be able to
109 inject - defaults to all key codes. An event type mapped to an
110 empty sequence enables the event type without enabling any event
111 codes, which is useful for types such as ``EV_REP``.
112
113 name
114 The name of the input device.
115
116 vendor
117 Vendor identifier.
118
119 product
120 Product identifier.
121
122 version
123 Version identifier.
124
125 bustype
126 Bustype identifier.
127
128 phys
129 Physical path.
130
131 input_props
132 Input properties and quirks.
133
134 max_effects
135 Maximum simultaneous force-feedback effects.
136
137 Note
138 ----
139 If you do not specify any events, the uinput device will be able
140 to inject only ``KEY_*`` and ``BTN_*`` event codes.
141 """
142
143 self.name: str = name #: Uinput device name.
144 self.vendor: int = vendor #: Device vendor identifier.
145 self.product: int = product #: Device product identifier.
146 self.version: int = version #: Device version identifier.
147 self.bustype: int = bustype #: Device bustype - e.g. ``BUS_USB``.
148 self.phys: str = phys #: Uinput device physical path.
149 self.devnode: str = devnode #: Uinput device node - e.g. ``/dev/uinput/``.
150
151 if not events:
152 events = {ecodes.EV_KEY: ecodes.keys.keys()}
153
154 self._verify()
155
156 #: Write-only, non-blocking file descriptor to the uinput device node.
157 self.fd = _uinput.open(devnode)
158
159 # Prepare the list of events for passing to _uinput.enable and _uinput.setup.
160 absinfo, prepared_events = self._prepare_events(events)
161
162 # Set phys name
163 _uinput.set_phys(self.fd, phys)
164
165 # Set properties
166 input_props = input_props or []
167 for prop in input_props:
168 _uinput.set_prop(self.fd, prop)
169
170 for etype, codes in events.items():
171 if not codes:
172 _uinput.enable_type(self.fd, etype)
173
174 for etype, code in prepared_events:
175 _uinput.enable(self.fd, etype, code)
176
177 _uinput.setup(self.fd, name, vendor, product, version, bustype, absinfo, max_effects)
178
179 # Create the uinput device.
180 _uinput.create(self.fd)
181
182 self.dll = ctypes.CDLL(_uinput.__file__)
183 self.dll._uinput_begin_upload.restype = ctypes.c_int
184 self.dll._uinput_end_upload.restype = ctypes.c_int
185
186 #: An :class:`InputDevice <evdev.device.InputDevice>` instance
187 #: for the fake input device. ``None`` if the device cannot be
188 #: opened for reading and writing.
189 self.device: InputDevice = self._find_device(self.fd)
190
191 def _prepare_events(self, events: dict[int, Sequence[int]]):
192 """Prepare events for passing to _uinput.enable and _uinput.setup"""
193 absinfo, prepared_events = [], []
194 for etype, codes in events.items():
195 for code in codes:
196 # Handle max, min, fuzz, flat.
197 if isinstance(code, (tuple, list, AbsInfo)):
198 # Flatten (ABS_Y, (0, 255, 0, 0, 0, 0)) to (ABS_Y, 0, 255, 0, 0, 0, 0).
199 f = [code[0]]
200 f.extend(code[1])
201 # Ensure the tuple is always 6 ints long, since uinput.c:uinput_create
202 # does little in the way of checking the length.
203 f.extend([0] * (6 - len(code[1])))
204 absinfo.append(f)
205 code = code[0]
206 prepared_events.append((etype, code))
207 return absinfo, prepared_events
208
209 def __enter__(self) -> "UInput":
210 return self
211
212 def __exit__(self, type, value, tb) -> None:
213 if hasattr(self, "fd"):
214 self.close()
215
216 def __repr__(self) -> str:
217 # TODO:
218 v = (repr(getattr(self, i)) for i in ("name", "bustype", "vendor", "product", "version", "phys"))
219 return "{}({})".format(self.__class__.__name__, ", ".join(v))
220
221 def __str__(self) -> str:
222 msg = 'name "{}", bus "{}", vendor "{:04x}", product "{:04x}", version "{:04x}", phys "{}"\nevent types: {}'
223
224 evtypes = [i[0] for i in self.capabilities(True).keys()]
225 msg = msg.format(
226 self.name, ecodes.BUS[self.bustype], self.vendor, self.product, self.version, self.phys, " ".join(evtypes)
227 )
228
229 return msg
230
231 def close(self) -> None:
232 # Close the associated InputDevice, if it was previously opened.
233 if self.device is not None:
234 self.device.close()
235
236 # Destroy the uinput device.
237 if self.fd > -1:
238 _uinput.close(self.fd)
239 self.fd = -1
240
241 def capabilities( self, verbose: bool = False, absinfo: bool = True):
242 """See :func:`capabilities <evdev.device.InputDevice.capabilities>`."""
243 if self.device is None:
244 raise UInputError("input device not opened - cannot read capabilities")
245
246 return self.device.capabilities(verbose, absinfo)
247
248 def begin_upload(self, effect_id: int) -> ff.UInputUpload:
249 upload = ff.UInputUpload()
250 upload.effect_id = effect_id
251
252 ret = self.dll._uinput_begin_upload(self.fd, ctypes.byref(upload))
253 if ret:
254 raise UInputError("Failed to begin uinput upload: " + os.strerror(ret))
255
256 return upload
257
258 def end_upload(self, upload: ff.UInputUpload) -> None:
259 ret = self.dll._uinput_end_upload(self.fd, ctypes.byref(upload))
260 if ret:
261 raise UInputError("Failed to end uinput upload: " + os.strerror(ret))
262
263 def begin_erase(self, effect_id: int) -> ff.UInputErase:
264 erase = ff.UInputErase()
265 erase.effect_id = effect_id
266
267 ret = self.dll._uinput_begin_erase(self.fd, ctypes.byref(erase))
268 if ret:
269 raise UInputError("Failed to begin uinput erase: " + os.strerror(ret))
270 return erase
271
272 def end_erase(self, erase: ff.UInputErase) -> None:
273 ret = self.dll._uinput_end_erase(self.fd, ctypes.byref(erase))
274 if ret:
275 raise UInputError("Failed to end uinput erase: " + os.strerror(ret))
276
277 def _verify(self) -> None:
278 """
279 Verify that an uinput device exists and is readable and writable
280 by the current process.
281 """
282 try:
283 m = os.stat(self.devnode)[stat.ST_MODE]
284 assert stat.S_ISCHR(m)
285 except (IndexError, OSError, AssertionError):
286 msg = '"{}" does not exist or is not a character device file - verify that the uinput module is loaded'
287 raise UInputError(msg.format(self.devnode))
288
289 if not os.access(self.devnode, os.W_OK):
290 msg = '"{}" cannot be opened for writing'
291 raise UInputError(msg.format(self.devnode))
292
293 if len(self.name) > _uinput.maxnamelen:
294 msg = "uinput device name must not be longer than {} characters"
295 raise UInputError(msg.format(_uinput.maxnamelen))
296
297 def _find_device(self, fd: int) -> InputDevice:
298 """
299 Tries to find the device node. Will delegate this task to one of
300 several platform-specific functions.
301 """
302 if platform.system() == "Linux":
303 try:
304 sysname = _uinput.get_sysname(fd)
305 return self._find_device_linux(sysname)
306 except OSError:
307 # UI_GET_SYSNAME returned an error code. We're likely dealing with
308 # an old kernel. Guess the device based on the filesystem.
309 pass
310
311 # If we're not running or Linux or the above method fails for any reason,
312 # use the generic fallback method.
313 return self._find_device_fallback()
314
315 def _find_device_linux(self, sysname: str) -> InputDevice:
316 """
317 Tries to find the device node when running on Linux.
318 """
319
320 syspath = f"/sys/devices/virtual/input/{sysname}"
321
322 # The sysfs entry for event devices should contain exactly one folder
323 # whose name matches the format "event[0-9]+". It is then assumed that
324 # the device node in /dev/input uses the same name.
325 regex = re.compile("event[0-9]+")
326 for entry in os.listdir(syspath):
327 if regex.fullmatch(entry):
328 device_path = f"/dev/input/{entry}"
329 break
330 else: # no break
331 raise FileNotFoundError()
332
333 # It is possible that there is some delay before /dev/input/event* shows
334 # up on old systems that do not use devtmpfs, so if the device cannot be
335 # found, wait for a short amount and then try again once.
336 #
337 # Furthermore, even if devtmpfs is in use, it is possible that the device
338 # does show up immediately, but without the correct permissions that
339 # still need to be set by udev. Wait for up to two seconds for either the
340 # device to show up or the permissions to be set.
341 for attempt in range(19):
342 try:
343 return InputDevice(device_path)
344 except (FileNotFoundError, PermissionError):
345 time.sleep(0.1)
346
347 # Last attempt. If this fails, whatever exception the last attempt raises
348 # shall be the exception that this function raises.
349 return InputDevice(device_path)
350
351 def _find_device_fallback(self) -> InputDevice | None:
352 """
353 Tries to find the device node when UI_GET_SYSNAME is not available or
354 we're running on a system sufficiently exotic that we do not know how
355 to interpret its return value.
356 """
357 #:bug: the device node might not be immediately available
358 time.sleep(0.1)
359
360 # There could also be another device with the same name already present,
361 # make sure to select the newest one.
362 # Strictly speaking, we cannot be certain that everything returned by list_devices()
363 # ends at event[0-9]+: it might return something like "/dev/input/events_all". Find
364 # the devices that have the expected structure and extract their device number.
365 path_number_pairs = []
366 regex = re.compile("/dev/input/event([0-9]+)")
367 for path in util.list_devices("/dev/input/"):
368 regex_match = regex.fullmatch(path)
369 if not regex_match:
370 continue
371 device_number = int(regex_match[1])
372 path_number_pairs.append((path, device_number))
373
374 # The modification date of the devnode is not reliable unfortunately, so we
375 # are sorting by the number in the name
376 path_number_pairs.sort(key=lambda pair: pair[1], reverse=True)
377
378 for path, _ in path_number_pairs:
379 d = InputDevice(path)
380 if d.name == self.name:
381 return d