Debian Codegraph @

src/fenrirscreenreader/inputDriver/evdevDriver.py

raw
1 # Fenrir TTY screen reader
2 # By Chrys, Storm Dragon, and contributors.
3
4 import multiprocessing
5 import threading
6 import time
7 from ctypes import c_bool
8 from multiprocessing.sharedctypes import Value
9 from select import select
10
11 from fenrirscreenreader.core import debug
12 from fenrirscreenreader.core import inputData
13 from fenrirscreenreader.core.eventData import FenrirEventType
14 from fenrirscreenreader.core.inputDriver import InputDriver as inputDriver
15
16 _evdevAvailable = False
17 _udevAvailable = False
18 _evdevAvailableError = ""
19 _udevAvailableError = ""
20 try:
21 import evdev
22 from evdev import InputDevice
23 from evdev import UInput
24 from evdev import ecodes as e
25
26 _evdevAvailable = True
27
28 except Exception as e:
29 _evdevAvailableError = str(e)
30
31 try:
32 import pyudev
33
34 _udevAvailable = True
35 except Exception as e:
36 _udevAvailableError = str(e)
37
38
39 class driver(inputDriver):
40 """Linux evdev input driver for Fenrir screen reader.
41
42 This driver provides access to Linux input devices through the evdev interface,
43 allowing Fenrir to capture keyboard input, manage device grabbing for exclusive
44 access, and inject synthetic input events.
45
46 Features:
47 - Automatic device detection and hotplug support via udev
48 - Device grabbing to prevent input from reaching other applications
49 - Key event mapping and filtering
50 - UInput support for synthetic key injection
51 - Multi-device support with thread-safe access
52
53 Attributes:
54 iDevices (dict): Map of file descriptor to InputDevice objects
55 iDevicesFD (list): Shared list of file descriptors for multiprocessing
56 uDevices (dict): Map of file descriptor to UInput devices
57 gDevices (dict): Map of file descriptor to grab status
58 iDeviceNo (int): Total number of input devices
59 UInputinject (UInput): Device for injecting synthetic events
60 _deviceLock (Lock): Thread lock for device access
61 """
62 def __init__(self):
63 inputDriver.__init__(self)
64 self._manager = multiprocessing.Manager()
65 self.iDevices = {}
66 self.iDevicesFD = self._manager.list()
67 self.uDevices = {}
68 self.gDevices = {}
69 self.iDeviceNo = 0
70 self.watch_dog = Value(c_bool, True)
71 self.UInputinject = (
72 UInput() if _evdevAvailable and "UInput" in globals() else None
73 )
74 self._deviceLock = threading.Lock()
75
76 def initialize(self, environment):
77 """Initialize the evdev input driver.
78
79 Sets up device monitoring, starts watchdog threads for device hotplug
80 detection and input monitoring, and configures the input subsystem.
81
82 Args:
83 environment: Fenrir environment dictionary with runtime managers
84
85 Note:
86 Requires evdev and optionally pyudev libraries. Falls back gracefully
87 if libraries are not available.
88 """
89 self.env = environment
90 global _evdevAvailable
91 global _udevAvailable
92 global _evdevAvailableError
93 global _udevAvailableError
94 if not _udevAvailable:
95 self.env["runtime"]["DebugManager"].write_debug_out(
96 "InputDriver:" + _udevAvailableError, debug.DebugLevel.ERROR
97 )
98 if not _evdevAvailable:
99 self.env["runtime"]["DebugManager"].write_debug_out(
100 "InputDriver:" + _evdevAvailableError, debug.DebugLevel.ERROR
101 )
102 return
103
104 if _udevAvailable:
105 self.env["runtime"]["ProcessManager"].add_custom_event_thread(
106 self.plug_input_device_watchdog_udev
107 )
108 self.env["runtime"]["ProcessManager"].add_custom_event_thread(
109 self.input_watchdog
110 )
111 self._initialized = True
112
113 def plug_input_device_watchdog_udev(self, active, event_queue):
114 """Monitor for input device hotplug events via udev.
115
116 Runs in a separate thread to detect when input devices are
117 plugged/unplugged and generates appropriate events for device
118 management.
119
120 Args:
121 active: Shared boolean controlling the watchdog loop
122 event_queue: Queue for sending device events to main process
123
124 Events Generated:
125 FenrirEventType.plug_input_device: When new devices are detected
126
127 Note:
128 Filters out virtual devices and devices from assistive technologies
129 like BRLTTY to avoid conflicts.
130 """
131 context = pyudev.Context()
132 monitor = pyudev.Monitor.from_netlink(context)
133 monitor.filter_by(subsystem="input")
134 monitor.start()
135 ignore_plug = False
136 while active.value:
137 valid_devices = []
138 device = monitor.poll(1)
139 while device:
140 self.env["runtime"]["DebugManager"].write_debug_out(
141 "plug_input_device_watchdog_udev:" + str(device),
142 debug.DebugLevel.INFO,
143 )
144 try:
145 try:
146 # FIX: Check if attributes exist before accessing them
147 if (
148 hasattr(device, "name")
149 and device.name
150 and device.name.upper()
151 in ["", "SPEAKUP", "FENRIR-UINPUT"]
152 ):
153 ignore_plug = True
154 if (
155 hasattr(device, "phys")
156 and device.phys
157 and device.phys.upper()
158 in ["", "SPEAKUP", "FENRIR-UINPUT"]
159 ):
160 ignore_plug = True
161 if (
162 hasattr(device, "name")
163 and device.name
164 and "BRLTTY" in device.name.upper()
165 ):
166 ignore_plug = True
167 except Exception as e:
168 self.env["runtime"]["DebugManager"].write_debug_out(
169 "plug_input_device_watchdog_udev CHECK NAME CRASH: "
170 + str(e),
171 debug.DebugLevel.ERROR,
172 )
173
174 if not ignore_plug:
175 virtual = (
176 "/sys/devices/virtual/input/" in device.sys_path
177 )
178 if device.device_node:
179 valid_devices.append(
180 {
181 "device": device.device_node,
182 "virtual": virtual,
183 }
184 )
185 except Exception as e:
186 self.env["runtime"]["DebugManager"].write_debug_out(
187 "plug_input_device_watchdog_udev APPEND CRASH: "
188 + str(e),
189 debug.DebugLevel.ERROR,
190 )
191 try:
192 poll_timeout = 1
193 device = monitor.poll(poll_timeout)
194 except Exception:
195 device = None
196 ignore_plug = False
197 if valid_devices:
198 event_queue.put(
199 {
200 "Type": FenrirEventType.plug_input_device,
201 "data": valid_devices,
202 }
203 )
204 return time.time()
205
206 def input_watchdog(self, active, event_queue):
207 """Main input monitoring loop.
208
209 Monitors all registered input devices for key events using select().
210 Processes key events, maps them to Fenrir's internal format, and
211 forwards them to the main application.
212
213 Args:
214 active: Shared boolean controlling the watchdog loop
215 event_queue: Queue for sending input events to main process
216
217 Events Generated:
218 FenrirEventType.keyboard_input: For key press/release events
219
220 Note:
221 Uses thread-safe device access and handles device disconnection
222 gracefully. Non-keyboard events are forwarded to UInput devices.
223 """
224 try:
225 while active.value:
226 # Get a snapshot of devices for select() to avoid lock
227 # contention
228 with self._deviceLock:
229 devices_snapshot = self.iDevices.copy()
230
231 if not devices_snapshot:
232 time.sleep(0.1)
233 continue
234
235 r, w, x = select(devices_snapshot, [], [], 0.8)
236 event = None
237 found_key_in_sequence = False
238 foreward = False
239 event_fired = False
240 for fd in r:
241 # Check if device still exists before accessing
242 with self._deviceLock:
243 if fd not in self.iDevices:
244 continue
245 device = self.iDevices[fd]
246 udevice = self.uDevices.get(fd)
247
248 try:
249 event = device.read_one()
250 except Exception as e:
251 self.env["runtime"]["DebugManager"].write_debug_out(
252 "evdevDriver handle_input_event: Error reading event: "
253 + str(e),
254 debug.DebugLevel.ERROR,
255 )
256 self.remove_device(fd)
257 continue
258 while event:
259 self.env["runtime"]["DebugManager"].write_debug_out(
260 "input_watchdog: EVENT:" + str(event),
261 debug.DebugLevel.INFO,
262 )
263 self.env["input"]["event_buffer"].append(
264 [device, udevice, event]
265 )
266 if event.type == evdev.events.EV_KEY:
267 if not found_key_in_sequence:
268 found_key_in_sequence = True
269 if event.code != 0:
270 curr_map_event = self.map_event(event)
271 if not curr_map_event:
272 event = device.read_one()
273 continue
274 if not isinstance(
275 curr_map_event["event_name"], str
276 ):
277 event = device.read_one()
278 continue
279 if curr_map_event["event_state"] in [0, 1, 2]:
280 event_queue.put(
281 {
282 "Type": FenrirEventType.keyboard_input,
283 "data": curr_map_event.copy(),
284 }
285 )
286 event_fired = True
287 else:
288 # Forward non-keyboard events: 2=EV_REL, 3=EV_ABS, 17=EV_LED
289 if event.type in [2, 3, 17]:
290 foreward = True
291
292 event = device.read_one()
293 if not found_key_in_sequence:
294 if foreward and not event_fired:
295 self.write_event_buffer()
296 self.clear_event_buffer()
297 except Exception as e:
298 self.env["runtime"]["DebugManager"].write_debug_out(
299 "INPUT WATCHDOG CRASH: " + str(e), debug.DebugLevel.ERROR
300 )
301
302 def write_event_buffer(self):
303 if not self._initialized:
304 return
305 for iDevice, uDevice, event in self.env["input"]["event_buffer"]:
306 try:
307 if uDevice:
308 if self.gDevices[iDevice.fd]:
309 self.write_u_input(uDevice, event)
310 except Exception as e:
311 self.env["runtime"]["DebugManager"].write_debug_out(
312 "evdevDriver write_event_buffer: Error writing event: "
313 + str(e),
314 debug.DebugLevel.ERROR,
315 )
316
317 def write_u_input(self, uDevice, event):
318 if not self._initialized:
319 return
320 uDevice.write_event(event)
321 time.sleep(0.0000002)
322 uDevice.syn()
323
324 def update_input_devices(self, new_devices=None, init=False):
325 """Update the list of monitored input devices.
326
327 Scans for available input devices and adds suitable ones based on
328 the configured device mode. Supports filtering by device type and
329 name matching.
330
331 Args:
332 new_devices (list, optional): Specific devices to add
333 init (bool): Whether this is initial device setup
334
335 Device Modes:
336 - 'ALL': Monitor all keyboard devices
337 - 'NOMICE': Monitor keyboards but exclude pointing devices
338 - Device names: Comma-separated list of specific device names
339
340 Note:
341 Automatically filters out virtual devices, assistive technology
342 devices, and devices with insufficient key counts.
343 """
344 if init:
345 self.remove_all_devices()
346
347 device_file_list = None
348
349 if new_devices and not init:
350 if not isinstance(new_devices, list):
351 new_devices = [new_devices]
352 device_file_list = new_devices
353 else:
354 device_file_list = evdev.list_devices()
355 if len(device_file_list) == self.iDeviceNo:
356 return
357 if not device_file_list:
358 return
359
360 mode = (
361 self.env["runtime"]["SettingsManager"]
362 .get_setting("keyboard", "device")
363 .upper()
364 )
365
366 i_devices_files = []
367 for device in self.iDevices:
368 i_devices_files.append(self.iDevices[device].path)
369
370 event_type = evdev.events
371 for deviceFile in device_file_list:
372 try:
373 if not deviceFile:
374 continue
375 if deviceFile == "":
376 continue
377 if deviceFile in i_devices_files:
378 continue
379 try:
380 with open(deviceFile) as f:
381 pass
382 except Exception as e:
383 self.env["runtime"]["DebugManager"].write_debug_out(
384 "evdevDriver update_input_devices: Error opening device file: "
385 + str(e),
386 debug.DebugLevel.ERROR,
387 )
388 continue
389 # 3 pos absolute
390 # 2 pos relative
391 # 1 Keys
392 try:
393 curr_device = evdev.InputDevice(deviceFile)
394 except Exception as e:
395 self.env["runtime"]["DebugManager"].write_debug_out(
396 "evdevDriver createDeviceType: Error creating device: "
397 + str(e),
398 debug.DebugLevel.ERROR,
399 )
400 continue
401 try:
402 # FIX: Check if attributes exist before accessing them
403 if (
404 hasattr(curr_device, "name")
405 and curr_device.name
406 and curr_device.name.upper()
407 in ["", "SPEAKUP", "FENRIR-UINPUT"]
408 ):
409 continue
410 if (
411 hasattr(curr_device, "phys")
412 and curr_device.phys
413 and curr_device.phys.upper()
414 in ["", "SPEAKUP", "FENRIR-UINPUT"]
415 ):
416 continue
417 if (
418 hasattr(curr_device, "name")
419 and curr_device.name
420 and "BRLTTY" in curr_device.name.upper()
421 ):
422 continue
423 except Exception as e:
424 self.env["runtime"]["DebugManager"].write_debug_out(
425 "evdevDriver: Error checking device capabilities: "
426 + str(e),
427 debug.DebugLevel.ERROR,
428 )
429 cap = curr_device.capabilities()
430 if mode in ["ALL", "NOMICE"]:
431 if event_type.EV_KEY in cap:
432 if (
433 116 in cap[event_type.EV_KEY]
434 and len(cap[event_type.EV_KEY]) < 10
435 ):
436 self.env["runtime"][
437 "DebugManager"
438 ].write_debug_out(
439 "Device Skipped (has 116):" + curr_device.name,
440 debug.DebugLevel.INFO,
441 )
442 continue
443 # Check if device has numpad keys - use lower threshold for dedicated numpads
444 numpad_keys = [
445 evdev.ecodes.KEY_KP0, evdev.ecodes.KEY_KP1, evdev.ecodes.KEY_KP2,
446 evdev.ecodes.KEY_KP3, evdev.ecodes.KEY_KP4, evdev.ecodes.KEY_KP5,
447 evdev.ecodes.KEY_KP6, evdev.ecodes.KEY_KP7, evdev.ecodes.KEY_KP8,
448 evdev.ecodes.KEY_KP9, evdev.ecodes.KEY_KPPLUS, evdev.ecodes.KEY_KPMINUS,
449 evdev.ecodes.KEY_KPASTERISK, evdev.ecodes.KEY_KPSLASH, evdev.ecodes.KEY_KPENTER,
450 evdev.ecodes.KEY_KPDOT
451 ]
452
453 has_numpad_keys = any(key in cap[event_type.EV_KEY] for key in numpad_keys)
454 min_key_threshold = 10 if has_numpad_keys else 60
455
456 if len(cap[event_type.EV_KEY]) < min_key_threshold:
457 threshold_type = "numpad" if has_numpad_keys else "keyboard"
458 self.env["runtime"][
459 "DebugManager"
460 ].write_debug_out(
461 f"Device Skipped (< {min_key_threshold} keys for {threshold_type}):"
462 + curr_device.name,
463 debug.DebugLevel.INFO,
464 )
465 continue
466 if mode == "ALL":
467 self.add_device(curr_device)
468 self.env["runtime"][
469 "DebugManager"
470 ].write_debug_out(
471 "Device added (ALL):"
472 + self.iDevices[curr_device.fd].name,
473 debug.DebugLevel.INFO,
474 )
475 elif mode == "NOMICE":
476 if not (
477 (event_type.EV_REL in cap)
478 or (event_type.EV_ABS in cap)
479 ):
480 self.add_device(curr_device)
481 self.env["runtime"][
482 "DebugManager"
483 ].write_debug_out(
484 "Device added (NOMICE):"
485 + self.iDevices[curr_device.fd].name,
486 debug.DebugLevel.INFO,
487 )
488 else:
489 self.env["runtime"][
490 "DebugManager"
491 ].write_debug_out(
492 "Device Skipped (NOMICE):"
493 + curr_device.name,
494 debug.DebugLevel.INFO,
495 )
496 else:
497 self.env["runtime"]["DebugManager"].write_debug_out(
498 "Device Skipped (no EV_KEY):" + curr_device.name,
499 debug.DebugLevel.INFO,
500 )
501 elif curr_device.name.upper() in mode.split(","):
502 self.add_device(curr_device)
503 self.env["runtime"]["DebugManager"].write_debug_out(
504 "Device added (Name):"
505 + self.iDevices[curr_device.fd].name,
506 debug.DebugLevel.INFO,
507 )
508 except Exception as e:
509 try:
510 device_name = (
511 curr_device.name
512 if hasattr(curr_device, "name")
513 else "unknown"
514 )
515 self.env["runtime"]["DebugManager"].write_debug_out(
516 "Device Skipped (Exception): "
517 + deviceFile
518 + " "
519 + device_name
520 + " "
521 + str(e),
522 debug.DebugLevel.INFO,
523 )
524 except Exception as ex:
525 self.env["runtime"]["DebugManager"].write_debug_out(
526 "Device Skipped (Exception): "
527 + deviceFile
528 + " "
529 + str(ex),
530 debug.DebugLevel.INFO,
531 )
532 self.iDeviceNo = len(evdev.list_devices())
533 self.update_m_pi_devices_fd()
534
535 def update_m_pi_devices_fd(self):
536 try:
537 for fd in self.iDevices:
538 if fd not in self.iDevicesFD:
539 self.iDevicesFD.append(fd)
540 for fd in self.iDevicesFD:
541 if fd not in self.iDevices:
542 self.iDevicesFD.remove(fd)
543 except Exception as e:
544 self.env["runtime"]["DebugManager"].write_debug_out(
545 "evdevDriver update_m_pi_devices_fd: Error updating device file descriptors: "
546 + str(e),
547 debug.DebugLevel.ERROR,
548 )
549
550 def map_event(self, event):
551 if not self._initialized:
552 return None
553 if not event:
554 return None
555 m_event = inputData.input_event
556 try:
557 # mute is a list = ['KEY_MIN_INTERESTING', 'KEY_MUTE']
558 m_event["event_name"] = evdev.ecodes.keys[event.code]
559 if isinstance(m_event["event_name"], list):
560 if len(m_event["event_name"]) > 0:
561 m_event["event_name"] = m_event["event_name"][0]
562 if isinstance(m_event["event_name"], list):
563 if len(m_event["event_name"]) > 0:
564 m_event["event_name"] = m_event["event_name"][0]
565 m_event["event_value"] = event.code
566 m_event["event_sec"] = event.sec
567 m_event["event_usec"] = event.usec
568 m_event["event_state"] = event.value
569 m_event["event_type"] = event.type
570 return m_event
571 except Exception as e:
572 return None
573
574 def get_led_state(self, led=0):
575 if not self.has_i_devices():
576 return False
577 # 0 = Numlock
578 # 1 = Capslock
579 # 2 = Rollen
580
581 # Use the first device with LED capability as authoritative source
582 # to avoid inconsistent readings from multiple devices during initialization
583 for fd, dev in self.iDevices.items():
584 # Check if device has LED capability (capability 17)
585 if 17 in dev.capabilities():
586 return led in dev.leds()
587
588 # Fallback to old behavior if no device has LED capability
589 for fd, dev in self.iDevices.items():
590 if led in dev.leds():
591 return True
592 return False
593
594 def toggle_led_state(self, led=0):
595 if not self.has_i_devices():
596 return False
597 led_state = self.get_led_state(led)
598 for i in self.iDevices:
599 if self.gDevices[i]:
600 # 17 LEDs
601 if 17 in self.iDevices[i].capabilities():
602 if led_state == 1:
603 self.iDevices[i].set_led(led, 0)
604 else:
605 self.iDevices[i].set_led(led, 1)
606
607 def grab_all_devices(self):
608 if not self._initialized:
609 return True
610 ok = True
611 for fd in self.iDevices:
612 if not self.gDevices[fd]:
613 ok = ok and self.grab_device(fd)
614 return ok
615
616 def ungrab_all_devices(self):
617 if not self._initialized:
618 return True
619 ok = True
620 for fd in self.iDevices:
621 if self.gDevices[fd]:
622 ok = ok and self.ungrab_device(fd)
623 return ok
624
625 def create_u_input_dev(self, fd):
626 if not self.env["runtime"]["SettingsManager"].get_setting_as_bool(
627 "keyboard", "grab_devices"
628 ):
629 self.uDevices[fd] = None
630 return
631 try:
632 test = self.uDevices[fd]
633 return
634 except KeyError:
635 self.uDevices[fd] = None
636 if self.uDevices[fd] is not None:
637 return
638 if "UInput" not in globals():
639 return
640 try:
641 self.uDevices[fd] = UInput.from_device(
642 self.iDevices[fd], name="fenrir-uinput", phys="fenrir-uinput"
643 )
644 except Exception as e:
645 try:
646 self.env["runtime"]["DebugManager"].write_debug_out(
647 "InputDriver evdev: compat fallback: " + str(e),
648 debug.DebugLevel.WARNING,
649 )
650 dev = self.iDevices[fd]
651 cap = dev.capabilities()
652 del cap[0]
653 self.uDevices[fd] = UInput(
654 cap, name="fenrir-uinput", phys="fenrir-uinput"
655 )
656 except Exception as e:
657 self.env["runtime"]["DebugManager"].write_debug_out(
658 "InputDriver evdev: init Uinput not possible: " + str(e),
659 debug.DebugLevel.ERROR,
660 )
661 return
662
663 def add_device(self, newDevice):
664 """Add a new input device to the monitoring list.
665
666 Creates the necessary data structures for device monitoring,
667 sets up UInput forwarding if device grabbing is enabled, and
668 initializes device state.
669
670 Args:
671 newDevice: evdev.InputDevice object to add
672
673 Note:
674 Thread-safe operation. Automatically cleans up on failure.
675 """
676 self.env["runtime"]["DebugManager"].write_debug_out(
677 "InputDriver evdev: device added: "
678 + str(newDevice.fd)
679 + " "
680 + str(newDevice),
681 debug.DebugLevel.INFO,
682 )
683 with self._deviceLock:
684 try:
685 self.iDevices[newDevice.fd] = newDevice
686 self.create_u_input_dev(newDevice.fd)
687 self.gDevices[newDevice.fd] = False
688 except Exception as e:
689 self.env["runtime"]["DebugManager"].write_debug_out(
690 "InputDriver evdev: error adding device: " + str(e),
691 debug.DebugLevel.ERROR,
692 )
693 # if it doesnt work clean up
694 try:
695 del self.iDevices[newDevice.fd]
696 except Exception as e:
697 self.env["runtime"]["DebugManager"].write_debug_out(
698 "evdevDriver remove_device: Error removing iDevice: "
699 + str(e),
700 debug.DebugLevel.ERROR,
701 )
702 try:
703 del self.uDevices[newDevice.fd]
704 except Exception as e:
705 self.env["runtime"]["DebugManager"].write_debug_out(
706 "evdevDriver remove_device: Error removing uDevice: "
707 + str(e),
708 debug.DebugLevel.ERROR,
709 )
710 try:
711 del self.gDevices[newDevice.fd]
712 except Exception as e:
713 self.env["runtime"]["DebugManager"].write_debug_out(
714 "evdevDriver add_device: Error cleaning up gDevice: "
715 + str(e),
716 debug.DebugLevel.ERROR,
717 )
718
719 def grab_device(self, fd):
720 """Grab exclusive access to an input device.
721
722 Takes exclusive control of the device, preventing other applications
723 from receiving its input. Also resets modifier key states to prevent
724 stuck keys.
725
726 Args:
727 fd (int): File descriptor of device to grab
728
729 Returns:
730 bool: True if grab successful, False otherwise
731
732 Note:
733 Only effective if grabDevices setting is enabled.
734 """
735 if not self.env["runtime"]["SettingsManager"].get_setting_as_bool(
736 "keyboard", "grab_devices"
737 ):
738 return True
739
740 # FIX: Handle exception variable scope correctly
741 grab_error = None
742 try:
743 self.iDevices[fd].grab()
744 self.gDevices[fd] = True
745 self.env["runtime"]["DebugManager"].write_debug_out(
746 "InputDriver evdev: grab device ("
747 + str(self.iDevices[fd].name)
748 + ")",
749 debug.DebugLevel.INFO,
750 )
751 # Reset modifier keys on successful grab
752 if self.uDevices[fd]:
753 modifier_keys = [
754 e.KEY_LEFTCTRL,
755 e.KEY_RIGHTCTRL,
756 e.KEY_LEFTALT,
757 e.KEY_RIGHTALT,
758 e.KEY_LEFTSHIFT,
759 e.KEY_RIGHTSHIFT,
760 ]
761 for key in modifier_keys:
762 try:
763 self.uDevices[fd].write(e.EV_KEY, key, 0) # 0 = key up
764 self.uDevices[fd].syn()
765 except Exception as mod_error:
766 self.env["runtime"]["DebugManager"].write_debug_out(
767 "Failed to reset modifier key: " + str(mod_error),
768 debug.DebugLevel.WARNING,
769 )
770 except IOError:
771 if not self.gDevices[fd]:
772 return False
773 except Exception as ex:
774 grab_error = ex
775
776 if grab_error:
777 self.env["runtime"]["DebugManager"].write_debug_out(
778 "InputDriver evdev: grabing not possible: " + str(grab_error),
779 debug.DebugLevel.ERROR,
780 )
781 return False
782
783 return True
784
785 def ungrab_device(self, fd):
786 """Release exclusive access to an input device.
787
788 Returns control of the device to the system, allowing other
789 applications to receive its input.
790
791 Args:
792 fd (int): File descriptor of device to ungrab
793
794 Returns:
795 bool: True if ungrab successful, False otherwise
796 """
797 if not self.env["runtime"]["SettingsManager"].get_setting_as_bool(
798 "keyboard", "grab_devices"
799 ):
800 return True
801
802 # FIX: Handle exception variable scope correctly
803 ungrab_error = None
804 try:
805 self.iDevices[fd].ungrab()
806 self.gDevices[fd] = False
807 self.env["runtime"]["DebugManager"].write_debug_out(
808 "InputDriver evdev: ungrab device ("
809 + str(self.iDevices[fd].name)
810 + ")",
811 debug.DebugLevel.INFO,
812 )
813 except IOError:
814 if self.gDevices[fd]:
815 return False
816 except Exception as ex:
817 ungrab_error = ex
818
819 if ungrab_error:
820 self.env["runtime"]["DebugManager"].write_debug_out(
821 "InputDriver evdev: ungrabing not possible: "
822 + str(ungrab_error),
823 debug.DebugLevel.ERROR,
824 )
825 return False
826
827 return True
828
829 def remove_device(self, fd):
830 """Remove an input device from monitoring.
831
832 Cleanly removes a device by ungrabbing it, closing file handles,
833 and cleaning up all associated data structures.
834
835 Args:
836 fd (int): File descriptor of device to remove
837
838 Note:
839 Thread-safe operation with comprehensive error handling.
840 """
841 with self._deviceLock:
842 try:
843 self.env["runtime"]["DebugManager"].write_debug_out(
844 "InputDriver evdev: device removed: "
845 + str(fd)
846 + " "
847 + str(self.iDevices[fd]),
848 debug.DebugLevel.INFO,
849 )
850 except Exception as e:
851 self.env["runtime"]["DebugManager"].write_debug_out(
852 "InputDriver evdev: device removed: "
853 + str(fd)
854 + " Error: "
855 + str(e),
856 debug.DebugLevel.INFO,
857 )
858 self.clear_event_buffer()
859 try:
860 self.ungrab_device(fd)
861 except Exception as e:
862 self.env["runtime"]["DebugManager"].write_debug_out(
863 "evdevDriver remove_device: Error ungrabbing device "
864 + str(fd)
865 + ": "
866 + str(e),
867 debug.DebugLevel.ERROR,
868 )
869 try:
870 self.iDevices[fd].close()
871 except Exception as e:
872 self.env["runtime"]["DebugManager"].write_debug_out(
873 "evdevDriver remove_device: Error closing iDevice "
874 + str(fd)
875 + ": "
876 + str(e),
877 debug.DebugLevel.ERROR,
878 )
879 try:
880 self.uDevices[fd].close()
881 except Exception as e:
882 self.env["runtime"]["DebugManager"].write_debug_out(
883 "evdevDriver remove_device: Error closing uDevice "
884 + str(fd)
885 + ": "
886 + str(e),
887 debug.DebugLevel.ERROR,
888 )
889 try:
890 del self.iDevices[fd]
891 except Exception as e:
892 self.env["runtime"]["DebugManager"].write_debug_out(
893 "evdevDriver remove_device: Error deleting iDevice "
894 + str(fd)
895 + ": "
896 + str(e),
897 debug.DebugLevel.ERROR,
898 )
899 try:
900 del self.uDevices[fd]
901 except Exception as e:
902 self.env["runtime"]["DebugManager"].write_debug_out(
903 "evdevDriver remove_device: Error deleting uDevice "
904 + str(fd)
905 + ": "
906 + str(e),
907 debug.DebugLevel.ERROR,
908 )
909 try:
910 del self.gDevices[fd]
911 except Exception as e:
912 self.env["runtime"]["DebugManager"].write_debug_out(
913 "evdevDriver remove_device: Error deleting gDevice "
914 + str(fd)
915 + ": "
916 + str(e),
917 debug.DebugLevel.ERROR,
918 )
919 self.update_m_pi_devices_fd()
920
921 def has_i_devices(self):
922 if not self._initialized:
923 return False
924 if not self.iDevices:
925 return False
926 if len(self.iDevices) == 0:
927 return False
928 return True
929
930 def send_key(self, key, state):
931 """Inject a synthetic key event.
932
933 Sends a key press or release event using UInput. Used for
934 features like key forwarding and macro execution.
935
936 Args:
937 key (str): Key name (e.g., 'KEY_A')
938 state (int): Key state (0=release, 1=press, 2=repeat)
939 """
940 if not self._initialized:
941 return
942 if self.UInputinject is None:
943 return
944 try:
945 self.UInputinject.write(e.EV_KEY, e.ecodes[key], state)
946 self.UInputinject.syn()
947 except Exception as ex:
948 self.env["runtime"]["DebugManager"].write_debug_out(
949 "evdevDriver send_key: Error sending key "
950 + str(key)
951 + ": "
952 + str(ex),
953 debug.DebugLevel.ERROR,
954 )
955
956 def remove_all_devices(self):
957 if not self.has_i_devices():
958 return
959 devices = self.iDevices.copy()
960 for fd in devices:
961 self.remove_device(fd)
962 self.iDevices.clear()
963 self.uDevices.clear()
964 self.gDevices.clear()
965 self.iDeviceNo = 0