Debian Codegraph @

src/fenrirscreenreader/core/fenrirManager.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Fenrir TTY screen reader
5 # By Chrys, Storm Dragon, and contributors.
6
7 import os
8 import socket
9 import signal
10 import sys
11 import time
12
13 from fenrirscreenreader.core import debug
14 from fenrirscreenreader.core import remoteInstanceRegistry
15 from fenrirscreenreader.core import settingsManager
16 from fenrirscreenreader.core.eventData import FenrirEventType
17 from fenrirscreenreader.core.i18n import _
18
19
20 class FenrirManager:
21 def __init__(self, cliArgs):
22 self.is_initialized = False
23 self.environment = None
24 self.signal_handlers_set = False
25
26 try:
27 self.environment = (
28 settingsManager.SettingsManager().init_fenrir_config(
29 cliArgs, self
30 )
31 )
32 if not self.environment:
33 raise RuntimeError(
34 "Cannot Initialize. Maybe the configfile is not available or not parseable"
35 )
36
37 self.environment["runtime"]["OutputManager"].present_text(
38 _("Start Fenrir"), sound_icon="ScreenReaderOn", interrupt=True
39 )
40
41 # Set signal handlers after successful initialization
42 signal.signal(signal.SIGINT, self.capture_signal)
43 signal.signal(signal.SIGTERM, self.capture_signal)
44 signal.signal(signal.SIGHUP, self.capture_signal)
45 self.signal_handlers_set = True
46
47 self.is_initialized = True
48 self.modifierInput = False
49 self.modifier_prefix_input = False
50 self.singleKeyCommand = False
51 self.command = ""
52 self.set_process_name()
53
54 except Exception as e:
55 # Clean up any partial initialization
56 self.cleanup_on_error()
57 raise
58
59 def proceed(self):
60 if not self.is_initialized:
61 return
62 self.environment["runtime"]["EventManager"].start_main_event_loop()
63 self.shutdown()
64
65 def handle_input(self, event):
66 self.environment["runtime"]["DebugManager"].write_debug_out(
67 "DEBUG INPUT fenrirMan:" + str(event), debug.DebugLevel.INFO
68 )
69
70 if not event["data"]:
71 event["data"] = self.environment["runtime"][
72 "InputManager"
73 ].get_input_event()
74
75 if event["data"]:
76 event["data"]["event_name"] = self.environment["runtime"][
77 "InputManager"
78 ].convert_event_name(event["data"]["event_name"])
79 self.environment["runtime"]["InputManager"].handle_input_event(
80 event["data"]
81 )
82 else:
83 return
84
85 tutorial_mode = self.environment["runtime"][
86 "HelpManager"
87 ].is_tutorial_mode()
88 if (
89 self.environment["runtime"]["ScreenManager"].is_ignored_screen()
90 and not tutorial_mode
91 ):
92 self.environment["runtime"]["InputManager"].write_event_buffer()
93 else:
94 if tutorial_mode:
95 self.environment["runtime"][
96 "InputManager"
97 ].clear_event_buffer()
98 if self.environment["runtime"][
99 "ScreenManager"
100 ].is_ignored_screen():
101 self.environment["runtime"]["InputManager"].key_echo(
102 event["data"]
103 )
104
105 if self.environment["runtime"]["VmenuManager"].get_active():
106 self.environment["runtime"][
107 "InputManager"
108 ].clear_event_buffer()
109 if self.environment["runtime"]["DiffReviewManager"].is_active():
110 self.environment["runtime"][
111 "InputManager"
112 ].clear_event_buffer()
113 if self.environment["runtime"]["SpeechHistoryManager"].is_active():
114 self.environment["runtime"][
115 "InputManager"
116 ].clear_event_buffer()
117
118 self.detect_shortcut_command()
119
120 if self.modifierInput:
121 self.environment["runtime"][
122 "InputManager"
123 ].clear_event_buffer()
124 if self.singleKeyCommand:
125 if self.environment["runtime"][
126 "InputManager"
127 ].no_key_pressed():
128 self.environment["runtime"][
129 "InputManager"
130 ].clear_event_buffer()
131 # Hold conventional modifier presses long enough to determine
132 # whether a Fenrir or Script modifier follows them.
133 elif not self.modifier_prefix_input:
134 self.environment["runtime"][
135 "InputManager"
136 ].write_event_buffer()
137
138 if self.environment["runtime"]["InputManager"].no_key_pressed():
139 self.modifierInput = False
140 self.modifier_prefix_input = False
141 self.singleKeyCommand = False
142 self.environment["runtime"]["InputManager"].write_event_buffer()
143 self.environment["runtime"]["InputManager"].handle_device_grab()
144
145 self.update_key_forward()
146
147 self.environment["runtime"]["CommandManager"].execute_default_trigger(
148 "onKeyInput"
149 )
150
151 def handle_execute_command(self, event):
152 if not event["data"] or event["data"] == "":
153 return
154 current_command = event["data"]
155
156 # Check for active read-all and interrupt it on any other key press
157 self._interrupt_read_all_if_active(current_command)
158
159 # special modes
160 if self.environment["runtime"]["HelpManager"].is_tutorial_mode():
161 if self.environment["runtime"]["CommandManager"].command_exists(
162 current_command, "help"
163 ):
164 self.environment["runtime"]["CommandManager"].run_command(
165 current_command, "help"
166 )
167 return
168 if current_command == "TOGGLE_TUTORIAL_MODE":
169 self.environment["runtime"]["CommandManager"].run_command(
170 current_command, "commands"
171 )
172 return
173 elif self.environment["runtime"]["VmenuManager"].get_active():
174 if self.environment["runtime"]["CommandManager"].command_exists(
175 current_command, "vmenu-navigation"
176 ):
177 self.environment["runtime"]["CommandManager"].execute_command(
178 current_command, "vmenu-navigation"
179 )
180 return
181 elif self.environment["runtime"]["SpeechHistoryManager"].is_active():
182 if self.environment["runtime"]["CommandManager"].command_exists(
183 current_command, "speech-history"
184 ):
185 self.environment["runtime"]["CommandManager"].execute_command(
186 current_command, "speech-history"
187 )
188 return
189
190 # default
191 self.environment["runtime"]["CommandManager"].execute_command(
192 current_command, "commands"
193 )
194
195 def _interrupt_read_all_if_active(self, current_command):
196 """Check for active read-all and interrupt it on any other key press."""
197 try:
198 # Skip interruption for read-all commands themselves (they toggle)
199 if current_command in ["read_all_by_line", "read_all_by_page"]:
200 return
201
202 # Stop read-all if any other command is executed
203 if ("ReadAllManager" in self.environment["runtime"] and
204 self.environment["runtime"]["ReadAllManager"] and
205 self.environment["runtime"]["ReadAllManager"].is_active()):
206
207 self.environment["runtime"]["ReadAllManager"].stop_read_all()
208
209 except Exception as e:
210 # Ignore errors in interrupt logic to prevent cascading issues
211 self.environment["runtime"]["DebugManager"].write_debug_out(
212 f"_interrupt_read_all_if_active: {e}",
213 debug.DebugLevel.ERROR
214 )
215
216
217 def handle_remote_incomming(self, event):
218 if not event["data"]:
219 return
220 self.environment["runtime"]["RemoteManager"].handle_remote_incomming(
221 event["data"]
222 )
223
224 def handle_background_task_result(self, event):
225 self.environment["runtime"]["BackgroundTaskManager"].handle_result(
226 event["data"]
227 )
228
229 def handle_screen_change(self, event):
230 self.environment["runtime"]["ScreenManager"].handle_screen_change(
231 event["data"]
232 )
233 if self.environment["runtime"]["VmenuManager"].get_active():
234 return
235 self.environment["runtime"]["CommandManager"].execute_default_trigger(
236 "onScreenChanged"
237 )
238 self.environment["runtime"]["ScreenDriver"].get_curr_screen()
239
240 def handle_screen_update(self, event):
241 self.environment["runtime"]["ScreenManager"].handle_screen_update(
242 event["data"]
243 )
244
245 if (
246 time.time()
247 - self.environment["runtime"]["InputManager"].get_last_input_time()
248 >= 0.3
249 ):
250 self.environment["runtime"]["InputManager"].clear_last_deep_input()
251
252 if not self._input_target_is_active():
253 self.environment["runtime"]["InputManager"].clear_last_deep_input()
254 return
255
256 if (
257 self._has_direct_user_input()
258 and (
259 self.environment["runtime"][
260 "CursorManager"
261 ].is_cursor_vertical_move()
262 or self.environment["runtime"][
263 "CursorManager"
264 ].is_cursor_horizontal_move()
265 )
266 ):
267 self.environment["runtime"][
268 "CommandManager"
269 ].execute_default_trigger("onCursorChange")
270
271 self.environment["runtime"]["CommandManager"].execute_default_trigger(
272 "onScreenUpdate"
273 )
274
275 def _input_target_is_active(self):
276 input_driver = self.environment["runtime"].get("InputDriver")
277 if input_driver is None:
278 return True
279 return input_driver.is_active()
280
281 def _has_direct_user_input(self):
282 deepest_input = self.environment["runtime"][
283 "InputManager"
284 ].get_last_deepest_input()
285 if not deepest_input:
286 return False
287 return not any(
288 key in deepest_input for key in ("KEY_FENRIR", "KEY_SCRIPT")
289 )
290
291 def handle_plug_input_device(self, event):
292 try:
293 self.environment["runtime"][
294 "InputManager"
295 ].set_last_detected_devices(event["data"])
296 except Exception as e:
297 self.environment["runtime"]["DebugManager"].write_debug_out(
298 "handle_plug_input_device: Error setting last detected devices: "
299 + str(e),
300 debug.DebugLevel.ERROR,
301 )
302 self.environment["runtime"]["InputManager"].handle_plug_input_device(
303 event["data"]
304 )
305 self.environment["runtime"]["CommandManager"].execute_default_trigger(
306 "onPlugInputDevice", force=True
307 )
308 self.environment["runtime"]["InputManager"].set_last_detected_devices(
309 None
310 )
311
312 def handle_heart_beat(self, event):
313 if not self._input_target_is_active():
314 return
315 self.environment["runtime"]["CommandManager"].execute_default_trigger(
316 "onHeartBeat", force=True
317 )
318
319 def handle_clipboard_sync(self, event):
320 clipboard_sync_manager = self.environment["runtime"].get(
321 "ClipboardSyncManager"
322 )
323 if clipboard_sync_manager:
324 clipboard_sync_manager.handle_sync_event()
325
326 def detect_shortcut_command(self):
327 if self.environment["input"]["key_forward"] != 0:
328 return
329
330 if len(self.environment["input"]["prev_input"]) > len(
331 self.environment["input"]["curr_input"]
332 ):
333 return
334
335 input_manager = self.environment["runtime"]["InputManager"]
336 if input_manager.is_key_press():
337 self.modifierInput = input_manager.curr_input_has_command_modifier()
338 self.modifier_prefix_input = (
339 not self.modifierInput
340 and input_manager.curr_input_is_modifier_prefix()
341 )
342 else:
343 if (
344 not self.modifierInput
345 and input_manager.curr_input_has_command_modifier()
346 ):
347 self.modifierInput = True
348 self.modifier_prefix_input = False
349 elif (
350 self.modifier_prefix_input
351 and not input_manager.curr_input_is_modifier_prefix()
352 ):
353 self.modifier_prefix_input = False
354 if not input_manager.no_key_pressed():
355 if self.singleKeyCommand:
356 self.singleKeyCommand = (
357 len(self.environment["input"]["curr_input"]) == 1
358 )
359
360 if not (
361 self.singleKeyCommand
362 and self.environment["runtime"]["InputManager"].no_key_pressed()
363 ):
364 current_shortcut = self.environment["runtime"][
365 "InputManager"
366 ].get_curr_shortcut()
367 self.command = self.environment["runtime"][
368 "InputManager"
369 ].get_command_for_shortcut(current_shortcut)
370
371 if not self.modifierInput:
372 if self.environment["runtime"]["InputManager"].is_key_press():
373 if self.command != "":
374 self.singleKeyCommand = True
375 elif (
376 (
377 (
378 "HelpManager" in self.environment["runtime"]
379 and self.environment["runtime"][
380 "HelpManager"
381 ].is_tutorial_mode()
382 )
383 or self.environment["runtime"]["VmenuManager"].get_active()
384 or self.environment["runtime"][
385 "DiffReviewManager"
386 ].is_active()
387 or self.environment["runtime"][
388 "SpeechHistoryManager"
389 ].is_active()
390 )
391 and self.command != ""
392 ):
393 # Modal modes use non-Fenrir modified bindings.
394 # Promote resolved shortcuts to executable commands so
395 # combinations like Shift+H, Ctrl+Right, and plain arrows
396 # are dispatched.
397 self.singleKeyCommand = True
398
399 if not (self.singleKeyCommand or self.modifierInput):
400 return
401
402 # fire event
403 if self.command != "":
404 if self.modifierInput:
405 self.environment["runtime"]["EventManager"].put_to_event_queue(
406 FenrirEventType.execute_command, self.command
407 )
408 self.command = ""
409 else:
410 if self.singleKeyCommand:
411 self.environment["runtime"][
412 "EventManager"
413 ].put_to_event_queue(
414 FenrirEventType.execute_command, self.command
415 )
416 self.command = ""
417
418 def update_key_forward(self):
419 key_forward = self.environment["input"]["key_forward"]
420 input_manager = self.environment["runtime"]["InputManager"]
421 if key_forward == -1 and input_manager.no_key_pressed():
422 self.environment["input"]["key_forward"] = 1
423 elif key_forward == 1 and input_manager.no_key_pressed():
424 self.environment["input"]["key_forward"] = 0
425
426 def set_process_name(self, name="fenrir"):
427 """Attempts to set the process name to 'fenrir'."""
428 try:
429 from setproctitle import setproctitle
430 except ImportError:
431 pass
432 else:
433 setproctitle(name)
434 return True
435
436 try:
437 from ctypes import byref
438 from ctypes import cdll
439 from ctypes import create_string_buffer
440
441 libc = cdll.LoadLibrary("libc.so.6")
442 string_buffer = create_string_buffer(len(name) + 1)
443 string_buffer.value = bytes(name, "UTF-8")
444 libc.prctl(15, byref(string_buffer), 0, 0, 0)
445 return True
446 except Exception as e:
447 self.environment["runtime"]["DebugManager"].write_debug_out(
448 "setProcName: Error setting process name: " + str(e),
449 debug.DebugLevel.ERROR,
450 )
451
452 return False
453
454 def shutdown_request(self):
455 try:
456 self.environment["runtime"]["EventManager"].stop_main_event_loop()
457 except Exception as e:
458 self.environment["runtime"]["DebugManager"].write_debug_out(
459 "shutdown_request: Error stopping main event loop: " + str(e),
460 debug.DebugLevel.ERROR,
461 )
462
463 def capture_signal(self, sigInit, frame):
464 self.shutdown_request()
465
466 def shutdown(self):
467 self.environment["runtime"]["InputManager"].ungrab_all_devices()
468 self.environment["runtime"]["EventManager"].stop_main_event_loop()
469 self.environment["runtime"]["OutputManager"].present_text(
470 _("Quit Fenrir"), sound_icon="ScreenReaderOff", interrupt=True
471 )
472 self.environment["runtime"]["EventManager"].clean_event_queue()
473 time.sleep(0.6)
474
475 for currentManager in self.environment["general"]["managerList"]:
476 try:
477 if (
478 currentManager in self.environment["runtime"]
479 and self.environment["runtime"][currentManager]
480 ):
481 self.environment["runtime"][currentManager].shutdown()
482 del self.environment["runtime"][currentManager]
483 except Exception:
484 pass # Ignore errors during individual manager shutdown
485
486 self.environment = None
487
488 def cleanup_on_error(self):
489 """Clean up partially initialized state when initialization fails"""
490 try:
491 # Reset signal handlers to default if they were set
492 if self.signal_handlers_set:
493 signal.signal(signal.SIGINT, signal.SIG_DFL)
494 signal.signal(signal.SIGTERM, signal.SIG_DFL)
495 signal.signal(signal.SIGHUP, signal.SIG_DFL)
496 self.signal_handlers_set = False
497
498 # Clean up any initialized managers
499 if self.environment:
500 try:
501 # Try to ungrab devices if input manager exists
502 if (
503 "runtime" in self.environment
504 and "InputManager" in self.environment["runtime"]
505 ):
506 if self.environment["runtime"]["InputManager"]:
507 self.environment["runtime"][
508 "InputManager"
509 ].ungrab_all_devices()
510 except Exception:
511 pass # Ignore errors during cleanup
512
513 try:
514 # Try to stop event manager if it exists
515 if (
516 "runtime" in self.environment
517 and "EventManager" in self.environment["runtime"]
518 ):
519 if self.environment["runtime"]["EventManager"]:
520 self.environment["runtime"][
521 "EventManager"
522 ].stop_main_event_loop()
523 except Exception:
524 pass # Ignore errors during cleanup
525
526 try:
527 # Try to clean up all managers
528 if (
529 "general" in self.environment
530 and "managerList" in self.environment["general"]
531 ):
532 for currentManager in self.environment["general"][
533 "managerList"
534 ]:
535 if (
536 "runtime" in self.environment
537 and currentManager
538 in self.environment["runtime"]
539 and self.environment["runtime"][currentManager]
540 ):
541 try:
542 self.environment["runtime"][
543 currentManager
544 ].shutdown()
545 del self.environment["runtime"][
546 currentManager
547 ]
548 except Exception:
549 pass # Ignore errors during cleanup
550 except Exception:
551 pass # Ignore errors during cleanup
552
553 # Clean up socket files that might not be removed by the driver
554 try:
555 socket_file = None
556 if (
557 "runtime" in self.environment
558 and "SettingsManager" in self.environment["runtime"]
559 ):
560 try:
561 socket_file = self.environment["runtime"][
562 "SettingsManager"
563 ].get_setting("remote", "socket_file")
564 except Exception:
565 pass # Use default socket file path
566
567 if not socket_file:
568 # Always clean up PID-specific socket
569 pid_socket_file = (
570 "/tmp/fenrirscreenreader-"
571 + str(os.getpid())
572 + ".sock"
573 )
574 if os.path.exists(pid_socket_file):
575 os.unlink(pid_socket_file)
576
577 # Clean up main socket only if it is stale (not active)
578 main_socket_file = "/tmp/fenrirscreenreader-daemon.sock"
579 if os.path.exists(main_socket_file):
580 try:
581 test_sock = socket.socket(
582 socket.AF_UNIX, socket.SOCK_STREAM
583 )
584 test_sock.settimeout(0.2)
585 test_sock.connect(main_socket_file)
586 except OSError:
587 os.unlink(main_socket_file)
588 finally:
589 test_sock.close()
590 elif os.path.exists(socket_file):
591 os.unlink(socket_file)
592 remoteInstanceRegistry.remove_instance()
593 except Exception:
594 pass # Ignore errors during socket cleanup
595
596 self.environment = None
597 except Exception:
598 pass # Ignore all errors during error cleanup