Debian Codegraph @

src/fenrirscreenreader/screenDriver/vcsaDriver.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 # attrib:
7 # http://rampex.ihep.su/Linux/linux_howto/html/tutorials/mini/Colour-ls-6.html
8 # 0 = black, 1 = blue, 2 = green, 3 = cyan, 4 = red, 5 = purple, 6 = brown/yellow, 7 = white.
9 # https://github.com/jwilk/vcsapeek/blob/master/linuxvt.py
10 # blink = 5 if attr & 1 else 0
11 # bold = 1 if attr & 16 else 0
12
13 import errno
14 import fcntl
15 import glob
16 import os
17 import select
18 import subprocess
19 import termios
20 import time
21 from array import array
22 from fcntl import ioctl
23 from struct import pack
24 from struct import unpack
25 from struct import unpack_from
26
27 import dbus
28
29 from fenrirscreenreader.core import debug
30 from fenrirscreenreader.core.eventData import FenrirEventType
31 from fenrirscreenreader.core.screenDriver import ScreenDriver as screenDriver
32 from fenrirscreenreader.utils import screen_utils
33
34
35 class driver(screenDriver):
36 """Linux VCSA (Virtual Console Screen Access) driver for Fenrir screen reader.
37
38 This driver provides access to Linux virtual consoles (TTYs) through the VCSA
39 interface, allowing real-time monitoring of screen content and cursor position.
40 It supports both text content extraction and color/attribute detection.
41
42 The driver monitors multiple virtual consoles simultaneously and can detect:
43 - Screen content changes (text updates)
44 - Cursor movement
45 - TTY switching
46 - Text attributes (colors, bold, etc.)
47 - Session information via D-Bus/logind
48
49 Attributes:
50 ListSessions: D-Bus method for listing login sessions
51 sysBus: D-Bus system bus connection
52 charmap: Character mapping for text decoding
53 bgColorValues: Background color value mappings
54 fgColorValues: Foreground color value mappings
55 hichar: High character mask for Unicode support
56 """
57 read_retry_attempts = 10
58 read_retry_delay = 0.05
59
60 def __init__(self):
61 screenDriver.__init__(self)
62 self.ListSessions = None
63 self.sysBus = None
64 self.charmap = {}
65 self.bgColorValues = {
66 0: "black",
67 1: "blue",
68 2: "green",
69 3: "cyan",
70 4: "red",
71 5: "magenta",
72 6: "brown/yellow",
73 7: "white",
74 }
75 self.fgColorValues = {
76 0: "black",
77 1: "blue",
78 2: "green",
79 3: "cyan",
80 4: "red",
81 5: "magenta",
82 6: "brown/yellow",
83 7: "light gray",
84 8: "dark gray",
85 9: "light blue",
86 10: "light green",
87 11: "light cyan",
88 12: "light red",
89 13: "light magenta",
90 14: "light yellow",
91 15: "white",
92 }
93 self.hichar = None
94 try:
95 # set workaround for paste clipboard -> inject_text_to_screen
96 subprocess.run(
97 ["sysctl", "dev.tty.legacy_tiocsti=1"],
98 check=False,
99 capture_output=True,
100 timeout=5,
101 )
102 except Exception as e:
103 self.env["runtime"]["DebugManager"].write_debug_out(
104 "vcsaDriver shutdown: Error running fgconsole: " + str(e),
105 debug.DebugLevel.ERROR,
106 )
107
108 def initialize(self, environment):
109 """Initialize the VCSA driver with the given environment.
110
111 Sets up default attributes, starts the screen monitoring watchdog process,
112 and prepares the driver for screen content monitoring.
113
114 Args:
115 environment: The Fenrir environment dictionary containing runtime managers
116 and configuration settings.
117 """
118 self.env = environment
119 self.env["runtime"]["AttributeManager"].append_default_attributes(
120 [
121 self.fgColorValues[7], # fg
122 self.bgColorValues[0], # bg
123 False, # bold
124 False, # italics
125 False, # underscore
126 False, # strikethrough
127 False, # reverse
128 False, # blink
129 "default", # fontsize
130 "default", # fontfamily
131 ]
132 ) # end attribute )
133 # Use threading instead of multiprocessing to avoid pickle issues
134 # with self.env (which contains unpicklable file handles)
135 self.env["runtime"]["ProcessManager"].add_custom_event_thread(
136 self.update_watchdog, multiprocess=False
137 )
138
139 def get_curr_screen(self):
140 """Get the currently active TTY number.
141
142 Reads from /sys/devices/virtual/tty/tty0/active to determine which
143 virtual console is currently active and updates the environment.
144
145 Updates:
146 env['screen']['oldTTY']: Previous TTY number
147 env['screen']['newTTY']: Current TTY number
148 """
149 self.env["screen"]["oldTTY"] = self.env["screen"]["newTTY"]
150 try:
151 with open(
152 "/sys/devices/virtual/tty/tty0/active", "r"
153 ) as currScreenFile:
154 self.env["screen"]["newTTY"] = str(currScreenFile.read()[3:-1])
155 except Exception as e:
156 self.env["runtime"]["DebugManager"].write_debug_out(
157 str(e), debug.DebugLevel.ERROR
158 )
159
160 def inject_text_to_screen(self, text, screen=None):
161 """Inject text into the specified screen as if typed by user.
162
163 Uses the TIOCSTI ioctl to simulate keystrokes on the target TTY.
164 This is primarily used for clipboard paste functionality.
165
166 Args:
167 text (str): Text to inject into the screen
168 screen (str, optional): Target screen device (e.g., '/dev/tty1').
169 If None, uses current TTY.
170
171 Note:
172 Requires appropriate permissions and may need legacy_tiocsti=1
173 kernel parameter on newer systems.
174 """
175 use_screen = "/dev/tty" + self.env["screen"]["newTTY"]
176 if screen is not None:
177 use_screen = screen
178 with open(use_screen, "w") as fd:
179 text_bytes = text.encode('utf-8')
180 for byte in text_bytes:
181 fcntl.ioctl(fd, termios.TIOCSTI, bytes([byte]))
182
183 def get_session_information(self):
184 """Retrieve session information via D-Bus logind interface.
185
186 Connects to systemd-logind to gather information about active sessions,
187 including session types and TTY assignments. This helps identify which
188 screens should be automatically ignored (e.g., X11 sessions).
189
190 Updates:
191 env['screen']['autoIgnoreScreens']: List of screens to ignore
192 env['general']['curr_user']: Current user for active session
193 env['general']['prev_user']: Previous user
194
195 Note:
196 Gracefully handles cases where logind is not available.
197 """
198 self.env["screen"]["autoIgnoreScreens"] = []
199 try:
200 if not self.sysBus:
201 self.sysBus = dbus.SystemBus()
202 obj = self.sysBus.get_object(
203 "org.freedesktop.login1", "/org/freedesktop/login1"
204 )
205 inf = dbus.Interface(obj, "org.freedesktop.login1.Manager")
206 self.ListSessions = inf.get_dbus_method("ListSessions")
207 sessions = self.ListSessions()
208
209 for session in sessions:
210 obj = self.sysBus.get_object(
211 "org.freedesktop.login1", session[4]
212 )
213 inf = dbus.Interface(obj, "org.freedesktop.DBus.Properties")
214 session_type = inf.Get(
215 "org.freedesktop.login1.Session", "Type"
216 )
217 screen = str(inf.Get("org.freedesktop.login1.Session", "VTNr"))
218 if screen == "":
219 screen = str(
220 inf.Get("org.freedesktop.login1.Session", "TTY")
221 )
222 screen = screen[screen.upper().find("TTY") + 3 :]
223 if screen == "":
224 self.env["runtime"]["DebugManager"].write_debug_out(
225 "No TTY found for session:" + session[4],
226 debug.DebugLevel.ERROR,
227 )
228 return
229 if session_type.upper() != "TTY":
230 self.env["screen"]["autoIgnoreScreens"] += [screen]
231 if screen == self.env["screen"]["newTTY"]:
232 if self.env["general"]["curr_user"] != session[2]:
233 self.env["general"]["prev_user"] = self.env["general"][
234 "curr_user"
235 ]
236 self.env["general"]["curr_user"] = session[2]
237 except Exception as e:
238 self.env["runtime"]["DebugManager"].write_debug_out(
239 "get_session_information: Maybe no LoginD:" + str(e),
240 debug.DebugLevel.ERROR,
241 )
242 # self.env['runtime']['DebugManager'].write_debug_out('get_session_information:' + str(self.env['screen']['autoIgnoreScreens']) + ' ' + str(self.env['general']) ,debug.DebugLevel.INFO)
243
244 def read_file(self, file):
245 """Read content from a file handle with error recovery.
246
247 Attempts to read the entire file content, falling back to
248 line-by-line reading if the initial read fails. This is used
249 for reading VCSA/VCSU device files.
250
251 Args:
252 file: Open file handle to read from
253
254 Returns:
255 bytes: File content as bytes
256 """
257 d = b""
258 for attempt in range(self.read_retry_attempts + 1):
259 file.seek(0)
260 try:
261 return file.read()
262 except OSError as e:
263 if (
264 e.errno == errno.EINVAL
265 and attempt < self.read_retry_attempts
266 ):
267 time.sleep(self.read_retry_delay)
268 continue
269 self.env["runtime"]["DebugManager"].write_debug_out(
270 "vcsaDriver get_screen_text: Error reading file: "
271 + str(e),
272 debug.DebugLevel.ERROR,
273 )
274 break
275 except Exception as e:
276 self.env["runtime"]["DebugManager"].write_debug_out(
277 "vcsaDriver get_screen_text: Error reading file: "
278 + str(e),
279 debug.DebugLevel.ERROR,
280 )
281 break
282
283 file.seek(0)
284 while True:
285 try:
286 chunk = file.readline(1)
287 if not chunk:
288 break
289 d += chunk
290 except Exception:
291 break
292 return d
293
294 def update_watchdog(self, active, event_queue):
295 """Main watchdog loop for monitoring screen changes.
296
297 This is the core monitoring function that runs in a separate process.
298 It uses epoll to efficiently monitor multiple VCSA devices and the
299 active TTY file for changes. When changes are detected, it generates
300 appropriate events for the main Fenrir process.
301
302 The watchdog monitors:
303 - Screen content changes (text updates)
304 - TTY switches (screen changes)
305 - Cursor position changes
306
307 Args:
308 active: Shared boolean value controlling the watchdog loop
309 event_queue: Queue for sending events to the main process
310
311 Events Generated:
312 - FenrirEventType.screen_changed: When switching TTYs
313 - FenrirEventType.screen_update: When screen content changes
314
315 Note:
316 This method runs in a multiprocess context and includes comprehensive
317 cleanup of file handles in the finally block.
318 """
319 vcsa = {}
320 vcsu = {}
321 tty = None
322 watchdog = None
323 try:
324 use_vcsu = os.access("/dev/vcsu", os.R_OK)
325 vcsa_devices = glob.glob("/dev/vcsa*")
326 vcsu_devices = None
327 last_screen_content = b""
328
329 # Open TTY file with proper cleanup
330 tty = open("/sys/devices/virtual/tty/tty0/active", "r")
331 curr_screen = str(tty.read()[3:-1])
332 old_screen = curr_screen
333
334 # Open VCSA devices with proper cleanup tracking
335 for vcsaDev in vcsa_devices:
336 index = str(vcsaDev[9:])
337 vcsa[index] = open(vcsaDev, "rb")
338 if index == curr_screen:
339 last_screen_content = self.read_file(vcsa[index])
340
341 # Open VCSU devices if available
342 if use_vcsu:
343 vcsu_devices = glob.glob("/dev/vcsu*")
344 for vcsuDev in vcsu_devices:
345 index = str(vcsuDev[9:])
346 vcsu[index] = open(vcsuDev, "rb")
347
348 self.update_char_map(curr_screen)
349 watchdog = select.epoll()
350 watchdog.register(
351 vcsa[curr_screen], select.POLLPRI | select.POLLERR
352 )
353 watchdog.register(tty, select.POLLPRI | select.POLLERR)
354 while active.value:
355 changes = watchdog.poll(1)
356 for change in changes:
357 fileno = change[0]
358 event = change[1]
359 if fileno == tty.fileno():
360 self.env["runtime"]["DebugManager"].write_debug_out(
361 "ScreenChange", debug.DebugLevel.INFO
362 )
363 tty.seek(0)
364 curr_screen = str(tty.read()[3:-1])
365 if curr_screen != old_screen:
366 try:
367 watchdog.unregister(vcsa[old_screen])
368 except Exception as e:
369 self.env["runtime"][
370 "DebugManager"
371 ].write_debug_out(
372 "vcsaDriver update_watchdog: Error unregistering watchdog: "
373 + str(e),
374 debug.DebugLevel.ERROR,
375 )
376 try:
377 watchdog.register(
378 vcsa[curr_screen],
379 select.POLLPRI | select.POLLERR,
380 )
381 except Exception as e:
382 self.env["runtime"][
383 "DebugManager"
384 ].write_debug_out(
385 "vcsaDriver update_watchdog: Error registering watchdog: "
386 + str(e),
387 debug.DebugLevel.ERROR,
388 )
389 self.update_char_map(curr_screen)
390 old_screen = curr_screen
391 try:
392 vcsa[curr_screen].seek(0)
393 last_screen_content = self.read_file(
394 vcsa[curr_screen]
395 )
396 except Exception as e:
397 self.env["runtime"][
398 "DebugManager"
399 ].write_debug_out(
400 "vcsaDriver update_watchdog: Error reading screen content: "
401 + str(e),
402 debug.DebugLevel.ERROR,
403 )
404 vcsu_content = None
405 if use_vcsu:
406 vcsu[curr_screen].seek(0)
407 vcsu_content = self.read_file(
408 vcsu[curr_screen]
409 )
410 event_queue.put(
411 {
412 "Type": FenrirEventType.screen_changed,
413 "data": self.create_screen_event_data(
414 curr_screen,
415 last_screen_content,
416 vcsu_content,
417 ),
418 }
419 )
420 else:
421 self.env["runtime"]["DebugManager"].write_debug_out(
422 "screen_update", debug.DebugLevel.INFO
423 )
424 vcsa[curr_screen].seek(0)
425 time.sleep(0.01)
426 dirty_content = self.read_file(vcsa[curr_screen])
427 screen_content = dirty_content
428 vcsu_content = None
429 timeout = time.time()
430 # error case
431 if screen_content == b"":
432 continue
433 if last_screen_content == b"":
434 last_screen_content = screen_content
435 if (
436 abs(
437 int(screen_content[2])
438 - int(last_screen_content[2])
439 )
440 in [1, 2]
441 ) and (
442 int(screen_content[3])
443 == int(last_screen_content[3])
444 ):
445 # Skip X Movement
446 pass
447 elif (
448 abs(
449 int(screen_content[3])
450 - int(last_screen_content[3])
451 )
452 in [1]
453 ) and (
454 int(screen_content[2])
455 == int(last_screen_content[2])
456 ):
457 # Skip Y Movement
458 pass
459 else:
460 # anything else? wait for completion
461 while True:
462 screen_content = dirty_content
463 time.sleep(0.02)
464 # r,_,_ = select.select([vcsa[curr_screen]], [], [], 0.07)
465 # if not vcsa[curr_screen] in r:
466 # break
467 vcsa[curr_screen].seek(0)
468 dirty_content = self.read_file(
469 vcsa[curr_screen]
470 )
471 if screen_content == dirty_content:
472 break
473 if time.time() - timeout >= 0.1:
474 screen_content = dirty_content
475 break
476 if use_vcsu:
477 vcsu[curr_screen].seek(0)
478 vcsu_content = self.read_file(vcsu[curr_screen])
479 last_screen_content = screen_content
480 event_queue.put(
481 {
482 "Type": FenrirEventType.screen_update,
483 "data": self.create_screen_event_data(
484 curr_screen, screen_content, vcsu_content
485 ),
486 }
487 )
488 except Exception as e:
489 self.env["runtime"]["DebugManager"].write_debug_out(
490 "VCSA:update_watchdog:" + str(e), debug.DebugLevel.ERROR
491 )
492 time.sleep(0.2)
493 finally:
494 # Clean up all file handles
495 try:
496 if watchdog:
497 watchdog.close()
498 except Exception as e:
499 self.env["runtime"]["DebugManager"].write_debug_out(
500 "vcsaDriver update_watchdog: Error closing watchdog: "
501 + str(e),
502 debug.DebugLevel.ERROR,
503 )
504 try:
505 if tty:
506 tty.close()
507 except Exception as e:
508 self.env["runtime"]["DebugManager"].write_debug_out(
509 "vcsaDriver shutdown: Error closing TTY: " + str(e),
510 debug.DebugLevel.ERROR,
511 )
512 for handle in vcsa.values():
513 try:
514 handle.close()
515 except Exception as e:
516 self.env["runtime"]["DebugManager"].write_debug_out(
517 "vcsaDriver shutdown: Error closing VCSA handle: "
518 + str(e),
519 debug.DebugLevel.ERROR,
520 )
521 for handle in vcsu.values():
522 try:
523 handle.close()
524 except Exception as e:
525 self.env["runtime"]["DebugManager"].write_debug_out(
526 "vcsaDriver shutdown: Error closing VCSU handle: "
527 + str(e),
528 debug.DebugLevel.ERROR,
529 )
530
531 def create_screen_event_data(self, screen, vcsaContent, vcsu_content=None):
532 """Create standardized screen event data from VCSA content.
533
534 Processes raw VCSA bytes into a structured event data dictionary
535 containing screen dimensions, cursor position, text content, and
536 color attributes.
537
538 Args:
539 screen (str): TTY number (e.g., '1' for tty1)
540 vcsaContent (bytes): Raw VCSA device content
541 vcsu_content (bytes, optional): VCSU content for Unicode support
542
543 Returns:
544 dict: Event data with keys:
545 - bytes: Raw VCSA content
546 - lines: Screen height
547 - columns: Screen width
548 - textCursor: Cursor position {x, y}
549 - screen: TTY number
550 - screenUpdateTime: Timestamp
551 - text: Decoded text content
552 - attributes: Color/formatting attributes
553 """
554 event_data = {
555 "bytes": vcsaContent,
556 "lines": int(vcsaContent[0]),
557 "columns": int(vcsaContent[1]),
558 "textCursor": {"x": int(vcsaContent[2]), "y": int(vcsaContent[3])},
559 "screen": screen,
560 "screenUpdateTime": time.time(),
561 "text": "",
562 "attributes": [],
563 }
564 try:
565 event_data["text"], event_data["attributes"] = (
566 self.auto_decode_vcsa(
567 vcsaContent[4:], event_data["lines"], event_data["columns"]
568 )
569 )
570 except Exception as e:
571 self.env["runtime"]["DebugManager"].write_debug_out(
572 "vcsaDriver create_screen_event_data: Error decoding VCSA content: "
573 + str(e),
574 debug.DebugLevel.ERROR,
575 )
576 # VCSU seems to give b' ' instead of b'\x00\x00\x00' (tsp),
577 # deactivated until its fixed
578 if vcsu_content is not None:
579 try:
580 vcsu_content_as_text = vcsu_content.decode("UTF-32")
581 event_data["text"] = screen_utils.insert_newlines(
582 vcsu_content_as_text, event_data["columns"]
583 )
584 except Exception as e:
585 self.env["runtime"]["DebugManager"].write_debug_out(
586 "vcsaDriver create_screen_event_data: Error decoding VCSU content: "
587 + str(e),
588 debug.DebugLevel.ERROR,
589 )
590 return event_data.copy()
591
592 def update_char_map(self, screen):
593 """Update character mapping for the specified screen.
594
595 Reads the Unicode font mapping from the TTY to properly decode
596 character data from VCSA. This handles special characters and
597 Unicode properly.
598
599 Args:
600 screen (str): TTY number to update mapping for
601
602 Updates:
603 self.charmap: Dictionary mapping byte values to Unicode characters
604 self.hichar: High character mask for extended characters
605 """
606 self.charmap = {}
607 try:
608 with open("/dev/tty" + screen, "rb") as tty:
609 GIO_UNIMAP = 0x4B66
610 VT_GETHIFONTMASK = 0x560D
611 himask = array("H", (0,))
612 ioctl(tty, VT_GETHIFONTMASK, himask)
613 (self.hichar,) = unpack_from("@H", himask)
614 sz = 512
615 line = ""
616 while True:
617 try:
618 unipairs = array("H", [0] * (2 * sz))
619 unimapdesc = array(
620 "B", pack("@HP", sz, unipairs.buffer_info()[0])
621 )
622 ioctl(tty.fileno(), GIO_UNIMAP, unimapdesc)
623 break
624 except Exception as e:
625 self.env["runtime"]["DebugManager"].write_debug_out(
626 "VCSA:update_char_map:scaling up sz="
627 + str(sz)
628 + " "
629 + str(e),
630 debug.DebugLevel.WARNING,
631 )
632 sz *= 2
633 except Exception as e:
634 self.env["runtime"]["DebugManager"].write_debug_out(
635 "VCSA:update_char_map:" + str(e), debug.DebugLevel.ERROR
636 )
637 return
638 (ncodes,) = unpack_from("@H", unimapdesc)
639 utable = unpack_from("@%dH" % (2 * ncodes), unipairs)
640 for u, b in zip(utable[::2], utable[1::2]):
641 if self.charmap.get(b) is None:
642 self.charmap[b] = chr(u)
643
644 def auto_decode_vcsa(self, allData, rows, cols):
645 """Decode raw VCSA data into text and attributes.
646
647 Processes the character and attribute data from VCSA devices,
648 extracting both the text content and formatting information
649 (colors, bold, blink, etc.).
650
651 Args:
652 allData (bytes): Raw character and attribute data from VCSA
653 rows (int): Number of screen rows
654 cols (int): Number of screen columns
655
656 Returns:
657 tuple: (text_content, attributes)
658 - text_content (str): Decoded text with newlines
659 - attributes (list): List of attribute arrays for each character
660
661 Note:
662 Each character in VCSA is stored as 2 bytes: character + attribute.
663 Attributes encode foreground/background colors, bold, blink, etc.
664 """
665 all_text = ""
666 all_attrib = []
667 i = 0
668 for y in range(rows):
669 line_text = ""
670 line_attrib = []
671 blink = 0
672 bold = 0
673 ink = 7
674 paper = 0
675 for x in range(cols):
676 data = allData[i : i + 2]
677 i += 2
678 if data == b" \x07":
679 # attr = 7
680 # ink = 7
681 # paper = 0
682 # ch = ' '
683 char_attrib = [
684 self.fgColorValues[7], # fg
685 self.bgColorValues[0], # bg
686 False, # bold
687 False, # italics
688 False, # underscore
689 False, # strikethrough
690 False, # reverse
691 False, # blink
692 "default", # fontsize
693 "default",
694 ] # fontfamily
695 line_attrib.append(char_attrib)
696 line_text += " "
697 continue
698 ch = None
699 try:
700 (sh,) = unpack("=H", data)
701 attr = (sh >> 8) & 0xFF
702 ch = sh & 0xFF
703 try:
704 if sh & self.hichar:
705 ch |= 0x100
706 except Exception as e:
707 self.env["runtime"]["DebugManager"].write_debug_out(
708 "vcsaDriver auto_decode_vcsa: Error processing character: "
709 + str(e),
710 debug.DebugLevel.ERROR,
711 )
712 ch = None
713 if self.hichar == 0x100:
714 attr >>= 1
715 ink = attr & 0x0F
716 paper = (attr >> 4) & 0x0F
717 if attr & 1:
718 blink = 1
719 # blink seems to be set always, ignore for now
720 blink = 0
721 bold = 0
722 if attr & 16:
723 bold = 1
724 # if (ink != 7) or (paper != 0):
725 # print(ink,paper)
726 except Exception as e:
727 self.env["runtime"]["DebugManager"].write_debug_out(
728 "vcsaDriver auto_decode_vcsa: Error processing attributes: "
729 + str(e),
730 debug.DebugLevel.ERROR,
731 )
732 try:
733 line_text += self.charmap[ch]
734 except KeyError:
735 line_text += "?"
736
737 char_attrib = [
738 self.fgColorValues[ink],
739 self.bgColorValues[paper],
740 bold == 1, # bold
741 False, # italics
742 False, # underscore
743 False, # strikethrough
744 False, # reverse
745 blink == 1, # blink
746 "default", # fontsize
747 "default",
748 ] # fontfamily
749 line_attrib.append(char_attrib)
750 all_text += line_text
751 if y + 1 < rows:
752 all_text += "\n"
753 all_attrib.append(line_attrib)
754 return str(all_text), all_attrib
755
756 def get_screen_process_for_tty(self, tty_num):
757 """Find the screen process associated with specific TTY"""
758 try:
759 result = subprocess.run([
760 'ps', '-eo', 'pid,ppid,comm,tty,stat', '--no-headers'
761 ], capture_output=True, text=True, timeout=2)
762
763 for line in result.stdout.strip().split('\n'):
764 if not line.strip():
765 continue
766 parts = line.split()
767 if len(parts) >= 4 and parts[2] == 'screen' and f'tty{tty_num}' in parts[3]:
768 return parts[0] # Return PID of screen process
769 except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
770 pass
771 return None
772
773 def get_screen_session_process(self, screen_tty_pid):
774 """Get the session manager process for a TTY screen process"""
775 try:
776 result = subprocess.run([
777 'ps', '-eo', 'pid,ppid,comm', '--no-headers'
778 ], capture_output=True, text=True, timeout=2)
779
780 for line in result.stdout.strip().split('\n'):
781 if not line.strip():
782 continue
783 parts = line.split()
784 if len(parts) >= 3 and parts[1] == screen_tty_pid and parts[2] == 'screen':
785 return parts[0] # Return session manager PID
786 except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
787 pass
788 return None
789
790 def parse_active_app_from_pstree(self, pstree_output):
791 """Parse pstree output to find currently active application"""
792 try:
793 # Look for processes that indicate active applications
794 # Example: screen(1786)---bash(1787)---irssi(2016)
795 import re
796
797 # Find all application processes (non-bash, non-screen)
798 # Pattern excludes --- prefix from pstree connection lines
799 app_pattern = r'([a-zA-Z0-9_]+)\((\d+)\)'
800 matches = re.findall(app_pattern, pstree_output)
801
802 skip_processes = {'screen', 'bash', 'sh', 'grep', 'ps', 'sudo', 'sleep', 'clipboard_sync'}
803 applications = []
804
805 for app_name, pid in matches:
806 if app_name.lower() not in skip_processes:
807 # Check if this process is in foreground state
808 try:
809 ps_result = subprocess.run([
810 'ps', '-p', pid, '-o', 'stat', '--no-headers'
811 ], capture_output=True, text=True, timeout=1)
812
813 if ps_result.returncode == 0:
814 stat = ps_result.stdout.strip()
815 # Prioritize active processes
816 priority = 0
817 if 'S' in stat or 'R' in stat: # Active processes
818 priority += 10
819 if '+' in stat: # Foreground processes
820 priority += 20
821 if 'l' in stat.lower(): # Locked processes
822 priority += 5
823
824 applications.append((app_name, pid, priority, stat))
825 except:
826 # If we can't check status, still consider it with low priority
827 applications.append((app_name, pid, 1, 'unknown'))
828
829 # Sort by priority and return the highest priority application
830 if applications:
831 applications.sort(key=lambda x: (x[2], int(x[1])), reverse=True)
832 best_app = applications[0][0].upper()
833
834 self.env["runtime"]["DebugManager"].write_debug_out(
835 f"parse_active_app_from_pstree found {len(applications)} apps, selected: {best_app}",
836 debug.DebugLevel.INFO
837 )
838 return best_app
839
840 except Exception as e:
841 self.env["runtime"]["DebugManager"].write_debug_out(
842 f"Error parsing pstree output: {str(e)}", debug.DebugLevel.ERROR
843 )
844 return None
845
846 def get_app_from_screen_session(self, tty_num):
847 """Get current application from active screen window on specific TTY"""
848 try:
849 # Find the screen session PID for this TTY
850 ps_result = subprocess.run([
851 'ps', '-eo', 'pid,ppid,comm,tty,args', '--no-headers'
852 ], capture_output=True, text=True, timeout=2)
853
854 if ps_result.returncode == 0:
855 # Find the main screen process for our TTY
856 screen_pid = None
857 for line in ps_result.stdout.split('\n'):
858 if not line.strip():
859 continue
860 parts = line.split(None, 4)
861 if len(parts) >= 4 and parts[2] == 'screen' and f'tty{tty_num}' in parts[3]:
862 screen_pid = parts[0]
863 break
864
865 if not screen_pid:
866 return None
867
868 # Get the session manager screen process (child of TTY screen)
869 session_pid = None
870 for line in ps_result.stdout.split('\n'):
871 if not line.strip():
872 continue
873 parts = line.split(None, 4)
874 if len(parts) >= 3 and parts[1] == screen_pid and parts[2] == 'screen':
875 session_pid = parts[0]
876 break
877
878 if not session_pid:
879 return None
880
881 self.env["runtime"]["DebugManager"].write_debug_out(
882 f"Found screen session PID: {session_pid}",
883 debug.DebugLevel.INFO
884 )
885
886 # Get all bash processes under this screen session
887 bash_processes = []
888 for line in ps_result.stdout.split('\n'):
889 if not line.strip():
890 continue
891 parts = line.split(None, 4)
892 if len(parts) >= 3 and parts[1] == session_pid and parts[2] == 'bash':
893 bash_processes.append(parts[0])
894
895 # Check each bash for child applications, prioritizing active ones
896 best_app = None
897 best_priority = 0
898
899 for bash_pid in bash_processes:
900 child_result = subprocess.run([
901 'ps', '--ppid', bash_pid, '-o', 'comm,stat', '--no-headers'
902 ], capture_output=True, text=True, timeout=1)
903
904 if child_result.returncode == 0:
905 for child_line in child_result.stdout.split('\n'):
906 if not child_line.strip():
907 continue
908 child_parts = child_line.split()
909 if len(child_parts) >= 2:
910 child_comm, child_stat = child_parts[0], child_parts[1]
911 if child_comm.lower() not in ['grep', 'ps', 'bash', 'sh', 'sudo', 'sleep']:
912 # Calculate priority based on process state
913 priority = 0
914 if 'R' in child_stat: # Running
915 priority += 30
916 elif 'S' in child_stat: # Sleeping
917 priority += 20
918 if '+' in child_stat: # Foreground
919 priority += 20
920
921 self.env["runtime"]["DebugManager"].write_debug_out(
922 f"Found child process: {child_comm} ({child_stat}) priority: {priority}",
923 debug.DebugLevel.INFO
924 )
925
926 if priority > best_priority:
927 best_app = child_comm.upper()
928 best_priority = priority
929
930 if best_app:
931 self.env["runtime"]["DebugManager"].write_debug_out(
932 f"Selected best app: {best_app} (priority: {best_priority})",
933 debug.DebugLevel.INFO
934 )
935 return best_app
936
937 except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError) as e:
938 self.env["runtime"]["DebugManager"].write_debug_out(
939 f"Error getting app from screen session: {str(e)}", debug.DebugLevel.ERROR
940 )
941 return None
942
943 def parse_latest_active_app_from_pstree(self, pstree_output):
944 """Parse pstree output to find the most recently active application"""
945 try:
946 import re
947
948 # Find all application processes with PIDs
949 app_pattern = r'([a-zA-Z0-9_]+)\((\d+)\)'
950 matches = re.findall(app_pattern, pstree_output)
951
952 skip_processes = {'screen', 'bash', 'sh', 'grep', 'ps', 'sudo', 'sleep', 'clipboard_sync'}
953 applications = []
954
955 for app_name, pid in matches:
956 if app_name.lower() not in skip_processes:
957 # Check if this process is still active and get its start time
958 try:
959 ps_result = subprocess.run([
960 'ps', '-p', pid, '-o', 'stat,lstart', '--no-headers'
961 ], capture_output=True, text=True, timeout=1)
962
963 if ps_result.returncode == 0:
964 stat_info = ps_result.stdout.strip().split(None, 1)
965 if len(stat_info) >= 2:
966 stat = stat_info[0]
967 start_time = stat_info[1]
968
969 # Prioritize processes that are active or have recent activity
970 priority = 0
971 if 'S' in stat or 'R' in stat: # Running or sleeping (active)
972 priority += 10
973 if '+' in stat: # Foreground process
974 priority += 20
975
976 applications.append((app_name, pid, priority, start_time))
977 except:
978 # If we can't get status, still consider it but with low priority
979 applications.append((app_name, pid, 1, 'unknown'))
980
981 # Sort by priority (highest first), then by PID (most recent)
982 if applications:
983 applications.sort(key=lambda x: (x[2], int(x[1])), reverse=True)
984 best_app = applications[0][0].upper()
985
986 self.env["runtime"]["DebugManager"].write_debug_out(
987 f"Found {len(applications)} applications, selected: {best_app}",
988 debug.DebugLevel.INFO
989 )
990 return best_app
991
992 except Exception as e:
993 self.env["runtime"]["DebugManager"].write_debug_out(
994 f"Error parsing latest active app from pstree: {str(e)}",
995 debug.DebugLevel.ERROR
996 )
997 return None
998
999 def get_app_from_tmux_session(self, tty_num):
1000 """Get current application from tmux session on specific TTY"""
1001 try:
1002 # Try tmux list-panes to find active application
1003 result = subprocess.run([
1004 'tmux', 'list-panes', '-F', '#{pane_active} #{pane_current_command} #{pane_tty}'
1005 ], capture_output=True, text=True, timeout=2)
1006
1007 if result.returncode == 0:
1008 for line in result.stdout.strip().split('\n'):
1009 if not line.strip():
1010 continue
1011 parts = line.split()
1012 if len(parts) >= 3 and parts[0] == '1': # Active pane
1013 tty_part = parts[2]
1014 if tty_num in tty_part:
1015 app = parts[1].upper()
1016 if app not in ['BASH', 'SH']:
1017 self.env["runtime"]["DebugManager"].write_debug_out(
1018 f"Found tmux application: {app}",
1019 debug.DebugLevel.INFO
1020 )
1021 return app
1022
1023 except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError):
1024 pass
1025 return None
1026
1027 def get_curr_application(self):
1028 """Enhanced application detection supporting screen/tmux sessions.
1029
1030 Multi-method approach:
1031 1. Try screen session detection via process tree analysis
1032 2. Try tmux session detection via tmux commands
1033 3. Fall back to standard ps-based detection
1034
1035 Updates:
1036 env['screen']['new_application']: Name of current application
1037
1038 Features:
1039 - Detects applications inside screen/tmux sessions
1040 - Handles multiple screen sessions on different TTYs
1041 - Provides detailed debug logging for troubleshooting
1042 """
1043 curr_screen = self.env["screen"]["newTTY"]
1044 detected_app = None
1045
1046 self.env["runtime"]["DebugManager"].write_debug_out(
1047 f"Starting application detection for TTY{curr_screen}",
1048 debug.DebugLevel.INFO
1049 )
1050
1051 # Method 1: Try screen session detection
1052 try:
1053 detected_app = self.get_app_from_screen_session(curr_screen)
1054 if detected_app:
1055 self.env["runtime"]["DebugManager"].write_debug_out(
1056 f"Screen session detection found: {detected_app}",
1057 debug.DebugLevel.INFO
1058 )
1059 except Exception as e:
1060 self.env["runtime"]["DebugManager"].write_debug_out(
1061 f"Screen session detection failed: {str(e)}", debug.DebugLevel.ERROR
1062 )
1063
1064 # Method 2: Try tmux session detection
1065 if not detected_app:
1066 try:
1067 detected_app = self.get_app_from_tmux_session(curr_screen)
1068 if detected_app:
1069 self.env["runtime"]["DebugManager"].write_debug_out(
1070 f"Tmux session detection found: {detected_app}",
1071 debug.DebugLevel.INFO
1072 )
1073 except Exception as e:
1074 self.env["runtime"]["DebugManager"].write_debug_out(
1075 f"Tmux session detection failed: {str(e)}", debug.DebugLevel.ERROR
1076 )
1077
1078 # Method 3: Fall back to standard ps-based detection
1079 if not detected_app:
1080 try:
1081 detected_app = self.get_app_via_standard_ps(curr_screen)
1082 if detected_app:
1083 self.env["runtime"]["DebugManager"].write_debug_out(
1084 f"Standard ps detection found: {detected_app}",
1085 debug.DebugLevel.INFO
1086 )
1087 except Exception as e:
1088 self.env["runtime"]["DebugManager"].write_debug_out(
1089 f"Standard ps detection failed: {str(e)}", debug.DebugLevel.ERROR
1090 )
1091
1092 # Update application if we found one and it's different
1093 if detected_app and self.env["screen"]["new_application"] != detected_app:
1094 self.env["screen"]["new_application"] = detected_app
1095 self.env["runtime"]["DebugManager"].write_debug_out(
1096 f"Application changed to: {detected_app}",
1097 debug.DebugLevel.INFO
1098 )
1099
1100 def get_app_via_standard_ps(self, curr_screen):
1101 """Fallback ps-based application detection for non-screen/tmux environments"""
1102 try:
1103 # Simple TTY-specific detection as fallback
1104 result = subprocess.run([
1105 'ps', '-t', f'tty{curr_screen}', '-o', 'comm,stat', '--no-headers'
1106 ], capture_output=True, text=True, timeout=2)
1107
1108 if result.returncode == 0:
1109 for line in result.stdout.split('\n'):
1110 if not line.strip():
1111 continue
1112 parts = line.split()
1113 if len(parts) >= 2:
1114 comm, stat = parts[0], parts[1]
1115 if '+' in stat and comm.upper() not in ['BASH', 'SH', 'SCREEN', 'GREP', 'PS']:
1116 self.env["runtime"]["DebugManager"].write_debug_out(
1117 f"Fallback detection found: {comm}",
1118 debug.DebugLevel.INFO
1119 )
1120 return comm.upper()
1121 except Exception as e:
1122 self.env["runtime"]["DebugManager"].write_debug_out(
1123 f"Standard ps detection error: {str(e)}", debug.DebugLevel.ERROR
1124 )
1125 return None