Debian Codegraph @

src/fenrirscreenreader/core/screenManager.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 difflib
8 import os
9 import re
10 import time
11
12 from fenrirscreenreader.core import debug
13 from fenrirscreenreader.utils import screen_utils
14
15
16 class ScreenManager:
17 def __init__(self):
18 self.differ = difflib.Differ()
19 self.currScreenIgnored = False
20 self.prevScreenIgnored = False
21 self.prevScreenText = ""
22 self.currScreenText = ""
23 self.colums = None
24 self.rows = None
25 # Compile regex once for better performance
26 self._space_normalize_regex = re.compile(" +")
27
28 def get_rows(self):
29 return self.rows
30
31 def get_columns(self):
32 return self.colums
33
34 def initialize(self, environment):
35 self.env = environment
36 self.env["runtime"]["SettingsManager"].load_driver(
37 self.env["runtime"]["SettingsManager"].get_setting(
38 "screen", "driver"
39 ),
40 "ScreenDriver",
41 )
42 self.get_curr_screen()
43 self.get_curr_screen()
44 self.get_session_information()
45 self.update_screen_ignored()
46 self.update_screen_ignored()
47
48 def reset_screen_text(self, screen_text):
49 self.prevScreenText = ""
50 self.currScreenText = screen_text
51
52 def set_screen_text(self, screen_text):
53 self.prevScreenText = self.currScreenText
54 self.currScreenText = screen_text
55
56 def get_screen_text(self):
57 return self.currScreenText
58
59 def get_line_text(self, line_number):
60 """Get text from a specific line (0-based index)"""
61 if not self.env["screen"]["new_content_text"]:
62 return ""
63
64 lines = self.env["screen"]["new_content_text"].split("\n")
65 if line_number < 0 or line_number >= len(lines):
66 return ""
67
68 return lines[line_number]
69
70 def get_curr_screen(self):
71 try:
72 self.env["runtime"]["ScreenDriver"].get_curr_screen()
73 except Exception as e:
74 self.env["runtime"]["DebugManager"].write_debug_out(
75 "ScreenManager get_curr_screen: Error getting current screen: "
76 + str(e),
77 debug.DebugLevel.ERROR,
78 )
79
80 def get_session_information(self):
81 try:
82 self.env["runtime"]["ScreenDriver"].get_session_information()
83 except Exception as e:
84 self.env["runtime"]["DebugManager"].write_debug_out(
85 "ScreenManager get_session_information: Error getting session info: "
86 + str(e),
87 debug.DebugLevel.ERROR,
88 )
89
90 def shutdown(self):
91 self.env["runtime"]["SettingsManager"].shutdown_driver("ScreenDriver")
92
93 def is_curr_screen_ignored_changed(self):
94 return self.get_curr_screen_ignored() != self.get_prev_screen_ignored()
95
96 def handle_screen_change(self, event_data):
97 self.get_curr_screen()
98 self.get_session_information()
99 self.update_screen_ignored()
100 if self.is_curr_screen_ignored_changed():
101 self.env["runtime"]["InputManager"].set_execute_device_grab()
102 self.env["runtime"]["InputManager"].handle_device_grab()
103
104 # Update current application detection on screen change
105 try:
106 self.env["runtime"]["ScreenDriver"].get_curr_application()
107 except Exception as e:
108 self.env["runtime"]["DebugManager"].write_debug_out(
109 f"Application detection failed: {str(e)}", debug.DebugLevel.ERROR
110 )
111
112 if not self.is_ignored_screen(self.env["screen"]["newTTY"]):
113 self.update(event_data, "onScreenChange")
114 self.env["screen"]["lastScreenUpdate"] = time.time()
115 else:
116 self.env["runtime"]["OutputManager"].interrupt_output()
117
118 def handle_screen_update(self, event_data):
119 self.env["screen"]["oldApplication"] = self.env["screen"][
120 "new_application"
121 ]
122 self.update_screen_ignored()
123 if self.is_curr_screen_ignored_changed():
124 self.env["runtime"]["InputManager"].set_execute_device_grab()
125 self.env["runtime"]["InputManager"].handle_device_grab()
126 if not self.get_curr_screen_ignored():
127 self.update(event_data, "onScreenUpdate")
128 self.env["screen"]["lastScreenUpdate"] = time.time()
129 elif self.is_curr_screen_ignored_changed():
130 self.env["runtime"]["OutputManager"].interrupt_output()
131
132 def get_curr_screen_ignored(self):
133 return self.currScreenIgnored
134
135 def get_prev_screen_ignored(self):
136 return self.prevScreenIgnored
137
138 def update_screen_ignored(self):
139 self.prevScreenIgnored = self.currScreenIgnored
140 self.currScreenIgnored = self.is_ignored_screen(
141 self.env["screen"]["newTTY"]
142 )
143
144 def update(self, event_data, trigger="onUpdate"):
145 # set new "old" values
146 self.env["screen"]["oldContentBytes"] = self.env["screen"][
147 "newContentBytes"
148 ]
149 self.env["screen"]["old_content_text"] = self.env["screen"][
150 "new_content_text"
151 ]
152 self.env["screen"]["old_cursor"] = self.env["screen"][
153 "new_cursor"
154 ].copy()
155 self.env["screen"]["oldDelta"] = self.env["screen"]["new_delta"]
156 self.env["screen"]["oldNegativeDelta"] = self.env["screen"][
157 "newNegativeDelta"
158 ]
159 self.env["screen"]["newContentBytes"] = event_data["bytes"]
160
161 # get metadata like cursor or screensize
162 self.env["screen"]["lines"] = int(event_data["lines"])
163 self.env["screen"]["columns"] = int(event_data["columns"])
164 self.colums = int(event_data["columns"])
165 self.rows = int(event_data["lines"])
166 self.env["screen"]["new_cursor"]["x"] = int(
167 event_data["textCursor"]["x"]
168 )
169 self.env["screen"]["new_cursor"]["y"] = int(
170 event_data["textCursor"]["y"]
171 )
172 self.env["screen"]["newTTY"] = event_data["screen"]
173 self.env["screen"]["new_content_text"] = event_data["text"]
174
175
176 # screen change
177 if self.is_screen_change():
178 self.env["screen"]["oldContentBytes"] = b""
179 self.reset_screen_text(event_data["text"])
180 self.env["runtime"]["AttributeManager"].reset_attributes(
181 event_data["attributes"]
182 )
183 self.env["runtime"]["AttributeManager"].reset_attribute_cursor()
184 self.env["screen"]["old_content_text"] = ""
185 self.env["screen"]["old_cursor"]["x"] = 0
186 self.env["screen"]["old_cursor"]["y"] = 0
187 self.env["screen"]["oldDelta"] = ""
188 self.env["screen"]["oldNegativeDelta"] = ""
189 else:
190 self.set_screen_text(event_data["text"])
191 self.env["runtime"]["AttributeManager"].set_attributes(
192 event_data["attributes"]
193 )
194 # initialize current deltas
195 self.env["screen"]["newNegativeDelta"] = ""
196 self.env["screen"]["new_delta"] = ""
197 self.env["screen"]["new_delta_is_typing"] = False
198 self.env["runtime"]["AttributeManager"].reset_attribute_delta()
199
200 # Diff generation - critical for screen reader functionality
201 # This code detects and categorizes screen content changes to provide appropriate
202 # speech feedback (typing echo vs incoming text vs screen updates)
203
204 # Track whether this appears to be typing (user input) vs other screen
205 # changes
206 typing = False
207 diff_list = []
208
209 if (
210 self.env["screen"]["old_content_text"]
211 != self.env["screen"]["new_content_text"]
212 ):
213 # Special case: Initial screen content (going from empty to populated)
214 # This handles first screen load or TTY switch scenarios
215 if (
216 self.env["screen"]["new_content_text"] != ""
217 and self.env["screen"]["old_content_text"] == ""
218 ):
219 # Pre-process screen text for comparison - collapse multiple spaces to single space
220 # This normalization prevents spurious diffs from spacing
221 # inconsistencies
222 old_screen_text = self._space_normalize_regex.sub(
223 " ",
224 self.env["runtime"][
225 "ScreenManager"
226 ].get_window_area_in_text(
227 self.env["screen"]["old_content_text"]
228 ),
229 )
230 new_screen_text = self._space_normalize_regex.sub(
231 " ",
232 self.env["runtime"][
233 "ScreenManager"
234 ].get_window_area_in_text(
235 self.env["screen"]["new_content_text"]
236 ),
237 )
238 if old_screen_text == "" and new_screen_text != "":
239 self.env["screen"]["new_delta"] = new_screen_text
240 else:
241 # Calculate byte positions for the current cursor's line in the flat text buffer
242 # Formula: (line_number * columns) + line_number accounts for newlines
243 # Each line contributes 'columns' chars + 1 newline char
244 cursor_line_start = (
245 self.env["screen"]["new_cursor"]["y"]
246 * self.env["screen"]["columns"]
247 + self.env["screen"]["new_cursor"]["y"]
248 )
249 cursor_line_end = (
250 cursor_line_start + self.env["screen"]["columns"]
251 )
252 cursor_moved_horizontally = (
253 abs(
254 self.env["screen"]["old_cursor"]["x"]
255 - self.env["screen"]["new_cursor"]["x"]
256 )
257 >= 1
258 and self.env["screen"]["old_cursor"]["y"]
259 == self.env["screen"]["new_cursor"]["y"]
260 )
261 cursor_line_typing_delta = (
262 self._get_cursor_line_typing_delta()
263 )
264 cursor_line_is_typing = (
265 cursor_line_typing_delta is not None
266 and (
267 cursor_moved_horizontally
268 or self._is_recent_input()
269 )
270 )
271
272 # TYPING DETECTION ALGORITHM
273 # Determines if this screen change is likely user typing vs other content changes
274 # All conditions must be met for typing detection:
275 if (
276 cursor_line_is_typing
277 and cursor_line_typing_delta["changed_lines"]
278 == [cursor_line_typing_delta["cursor_y"]]
279 ):
280 diff_list = [
281 "+ " + cursor_line_typing_delta["text"]
282 ]
283 typing = True
284 elif (
285 cursor_moved_horizontally
286 and self.env["screen"]["new_content_text"][
287 :cursor_line_start
288 ]
289 == self.env["screen"]["old_content_text"][
290 :cursor_line_start
291 ]
292 and self.env["screen"]["new_content_text"][
293 cursor_line_end:
294 ]
295 == self.env["screen"]["old_content_text"][cursor_line_end:]
296 ):
297 # Condition 1: Cursor moved horizontally by at least 1 position (typical of typing)
298 # Condition 2: Cursor stayed on same line (typing doesn't usually change lines)
299 # Condition 3: Content BEFORE cursor line is unchanged (text above typing area)
300 # Condition 4: Content AFTER cursor line is unchanged (text below typing area)
301 # Together: only the current line changed, cursor moved
302 # horizontally = likely typing
303
304 # Optimize diff calculation for typing by focusing on a
305 # small window around cursor
306 cursor_line_start_offset = cursor_line_start
307 cursor_line_end_offset = cursor_line_end
308
309 # Limit analysis window to avoid processing entire long lines
310 # +3 provides safety buffer beyond cursor position to catch edge cases
311 if (
312 cursor_line_end
313 > cursor_line_start
314 + self.env["screen"]["new_cursor"]["x"]
315 + 3
316 ):
317 cursor_line_end_offset = (
318 cursor_line_start
319 + self.env["screen"]["new_cursor"]["x"]
320 + 3
321 )
322
323 # Extract just the relevant text sections for
324 # character-level diff
325 old_screen_text = self.env["screen"]["old_content_text"][
326 cursor_line_start_offset:cursor_line_end_offset
327 ]
328 new_screen_text = self.env["screen"]["new_content_text"][
329 cursor_line_start_offset:cursor_line_end_offset
330 ]
331
332 # Character-level diff for typing detection (not
333 # line-level)
334 diff = self.differ.compare(
335 old_screen_text, new_screen_text
336 )
337 diff_list = list(diff)
338 typing = True
339
340 # Validate typing assumption by checking if detected
341 # changes match cursor movement
342 temp_new_delta = "".join(
343 x[2:] for x in diff_list if x[0] == "+"
344 )
345 if temp_new_delta.strip() != "":
346 # Compare diff result against expected typing pattern
347 # Expected: characters between old and new cursor
348 # positions
349 expected_typing = "".join(
350 new_screen_text[
351 self.env["screen"]["old_cursor"][
352 "x"
353 ] : self.env["screen"]["new_cursor"]["x"]
354 ].rstrip()
355 )
356
357 # Prompt/status repaints can add extra diff text while
358 # the user's typed characters are still at the cursor.
359 # Keep those as typing so incoming speech does not
360 # announce the repainted prompt line.
361 if temp_new_delta != expected_typing:
362 if expected_typing.strip() != "":
363 diff_list = ["+ " + expected_typing]
364 else:
365 # Fallback: treat entire current line as new
366 # content
367 current_line = self.env["screen"][
368 "new_content_text"
369 ].split("\n")[
370 self.env["screen"]["new_cursor"]["y"]
371 ]
372 diff_list = [
373 "+ " + current_line + "\n"
374 ]
375 typing = False
376 else:
377 # GENERAL SCREEN CHANGE DETECTION
378 # Not typing - handle as line-by-line content change
379 # This catches: incoming messages, screen updates,
380 # application output, etc.
381 typing_delta = (
382 cursor_line_typing_delta
383 if cursor_line_is_typing
384 else None
385 )
386 if (
387 typing_delta is not None
388 and typing_delta["changed_lines"]
389 == [typing_delta["cursor_y"]]
390 ):
391 diff_list = ["+ " + typing_delta["text"]]
392 typing = True
393 else:
394 old_content_text = self.env["screen"][
395 "old_content_text"
396 ]
397 new_content_text = self.env["screen"][
398 "new_content_text"
399 ]
400 if typing_delta is not None:
401 old_lines = old_content_text.split("\n")
402 new_lines = new_content_text.split("\n")
403 new_lines[typing_delta["cursor_y"]] = old_lines[
404 typing_delta["cursor_y"]
405 ]
406 old_content_text = "\n".join(old_lines)
407 new_content_text = "\n".join(new_lines)
408
409 # Pre-process screen text for comparison - collapse multiple spaces to single space
410 # This normalization prevents spurious diffs from spacing
411 # inconsistencies
412 old_screen_text = self._space_normalize_regex.sub(
413 " ",
414 self.env["runtime"][
415 "ScreenManager"
416 ].get_window_area_in_text(old_content_text),
417 )
418 new_screen_text = self._space_normalize_regex.sub(
419 " ",
420 self.env["runtime"][
421 "ScreenManager"
422 ].get_window_area_in_text(new_content_text),
423 )
424
425 diff = self.differ.compare(
426 old_screen_text.split("\n"),
427 new_screen_text.split("\n"),
428 )
429 diff_list = list(diff)
430
431 # Extract added and removed content from diff results
432 # Output format depends on whether this was detected as typing
433 # or general change
434 if not typing:
435 # Line-based changes: join with newlines for proper speech
436 # cadence
437 self.env["screen"]["new_delta"] = "\n".join(
438 x[2:] for x in diff_list if x[0] == "+"
439 )
440 else:
441 # Character-based changes: no newlines for smooth typing
442 # echo
443 self.env["screen"]["new_delta"] = "".join(
444 x[2:] for x in diff_list if x[0] == "+"
445 )
446 self.env["screen"]["new_delta_is_typing"] = typing
447
448 # Negative delta (removed content) - used for backspace/delete
449 # detection
450 self.env["screen"]["newNegativeDelta"] = "".join(
451 x[2:] for x in diff_list if x[0] == "-"
452 )
453
454 # track highlighted
455 try:
456 if self.env["runtime"]["AttributeManager"].is_attribute_change():
457 if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
458 "focus", "highlight"
459 ):
460 attribute_delta, attributeCursor = self.env["runtime"][
461 "AttributeManager"
462 ].track_highlights()
463 if attributeCursor:
464 self.env["runtime"][
465 "AttributeManager"
466 ].set_attribute_cursor(attributeCursor)
467 self.env["runtime"][
468 "AttributeManager"
469 ].set_attribute_delta(attribute_delta)
470 except Exception as e:
471 self.env["runtime"]["DebugManager"].write_debug_out(
472 "ScreenManager:update:highlight: " + str(e),
473 debug.DebugLevel.ERROR,
474 )
475
476 def is_ignored_screen(self, screen=None):
477 if screen is None:
478 screen = self.env["screen"]["newTTY"]
479 # Check if force all screens flag is set
480 if self.env["runtime"].get("force_all_screens", False):
481 return False
482 ignore_screens = []
483 fix_ignore_screens = self.env["runtime"][
484 "SettingsManager"
485 ].get_setting("screen", "ignore_screen")
486 if fix_ignore_screens != "":
487 ignore_screens.extend(fix_ignore_screens.split(","))
488 if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
489 "screen", "autodetect_ignore_screen"
490 ):
491 ignore_screens.extend(self.env["screen"]["autoIgnoreScreens"])
492 self.env["runtime"]["DebugManager"].write_debug_out(
493 "ScreenManager:is_ignored_screen ignore:"
494 + str(ignore_screens)
495 + " current:"
496 + str(screen),
497 debug.DebugLevel.INFO,
498 )
499 return screen in ignore_screens
500
501 def _is_recent_input(self):
502 try:
503 return (
504 time.time()
505 - self.env["runtime"][
506 "InputManager"
507 ].get_last_input_time()
508 <= 0.3
509 )
510 except Exception:
511 return False
512
513 def _get_cursor_line_typing_delta(self):
514 try:
515 old_lines = self.env["screen"]["old_content_text"].split("\n")
516 new_lines = self.env["screen"]["new_content_text"].split("\n")
517 cursor_y = self.env["screen"]["new_cursor"]["y"]
518 if (
519 len(old_lines) != len(new_lines)
520 or cursor_y < 0
521 or cursor_y >= len(new_lines)
522 ):
523 return None
524
525 changed_lines = [
526 index
527 for index, old_line in enumerate(old_lines)
528 if index >= len(new_lines) or old_line != new_lines[index]
529 ]
530 if cursor_y not in changed_lines:
531 return None
532
533 old_line = old_lines[cursor_y].rstrip()
534 new_line = new_lines[cursor_y].rstrip()
535 if old_line == new_line:
536 return None
537
538 matcher = difflib.SequenceMatcher(
539 None,
540 old_line,
541 new_line,
542 autojunk=False,
543 )
544 inserted_parts = []
545 for tag, i1, i2, j1, j2 in matcher.get_opcodes():
546 if tag == "equal":
547 continue
548 if tag == "insert":
549 inserted_parts.append(new_line[j1:j2])
550 continue
551 if tag == "replace" and old_line[i1:i2].strip() == "":
552 inserted_parts.append(new_line[j1:j2])
553 continue
554 return None
555
556 typed_text = "".join(inserted_parts).strip()
557 if typed_text == "" or len(typed_text) > 4:
558 return None
559 return {
560 "text": typed_text,
561 "cursor_y": cursor_y,
562 "changed_lines": changed_lines,
563 }
564 except Exception:
565 return None
566
567 def is_screen_change(self):
568 if not self.env["screen"]["oldTTY"]:
569 return False
570 return self.env["screen"]["newTTY"] != self.env["screen"]["oldTTY"]
571
572 def is_delta(self, ignoreSpace=False):
573 new_delta = self.env["screen"]["new_delta"]
574 if ignoreSpace:
575 new_delta = new_delta.strip()
576 return new_delta != ""
577
578 def is_negative_delta(self):
579 return self.env["screen"]["newNegativeDelta"] != ""
580
581 def get_window_area_in_text(self, text):
582 if not self.env["runtime"][
583 "CursorManager"
584 ].is_application_window_set():
585 return text
586 window_text = ""
587 window_list = text.split("\n")
588 curr_app = self.env["runtime"][
589 "ApplicationManager"
590 ].get_current_application()
591 window_list = window_list[
592 self.env["commandBuffer"]["windowArea"][curr_app]["1"][
593 "y"
594 ] : self.env["commandBuffer"]["windowArea"][curr_app]["2"]["y"]
595 + 1
596 ]
597 for line in window_list:
598 window_text += (
599 line[
600 self.env["commandBuffer"]["windowArea"][curr_app]["1"][
601 "x"
602 ] : self.env["commandBuffer"]["windowArea"][curr_app]["2"][
603 "x"
604 ]
605 + 1
606 ]
607 + "\n"
608 )
609 return window_text
610
611 def inject_text_to_screen(self, text, screen=None):
612 try:
613 self.env["runtime"]["ScreenDriver"].inject_text_to_screen(
614 text, screen
615 )
616 except Exception as e:
617 self.env["runtime"]["DebugManager"].write_debug_out(
618 "ScreenManager:inject_text_to_screen " + str(e),
619 debug.DebugLevel.ERROR,
620 )