| 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 fcntl |
| 8 |
import getpass |
| 9 |
import os |
| 10 |
import pty |
| 11 |
import shlex |
| 12 |
from queue import Full |
| 13 |
import signal |
| 14 |
import struct |
| 15 |
import sys |
| 16 |
import termios |
| 17 |
import threading |
| 18 |
import time |
| 19 |
import tty |
| 20 |
from select import select |
| 21 |
|
| 22 |
import pyte |
| 23 |
|
| 24 |
from fenrirscreenreader.core import debug |
| 25 |
from fenrirscreenreader.core.eventData import FenrirEventType |
| 26 |
from fenrirscreenreader.core.screenDriver import ScreenDriver as screenDriver |
| 27 |
from fenrirscreenreader.utils import screen_utils |
| 28 |
|
| 29 |
# PTY Driver Constants |
| 30 |
class PTYConstants: |
| 31 |
# Timeouts (in seconds) |
| 32 |
DEFAULT_READ_TIMEOUT = 0.3 |
| 33 |
INPUT_READ_TIMEOUT = 0.01 |
| 34 |
OUTPUT_READ_TIMEOUT = 0.05 # Faster than default but allows for network lag |
| 35 |
SELECT_TIMEOUT = 0.05 |
| 36 |
PROCESS_TERMINATION_TIMEOUT = 3.0 |
| 37 |
PROCESS_KILL_DELAY = 0.5 |
| 38 |
|
| 39 |
# Polling intervals (in seconds) |
| 40 |
MIN_POLL_INTERVAL = 0.001 |
| 41 |
|
| 42 |
# Limits |
| 43 |
MAX_TERMINAL_LINES = 10000 |
| 44 |
DEFAULT_READ_BUFFER_SIZE = 65536 |
| 45 |
INPUT_BUFFER_SIZE = 4096 |
| 46 |
|
| 47 |
# Error codes |
| 48 |
IO_ERROR_ERRNO = 5 |
| 49 |
|
| 50 |
|
| 51 |
class FenrirScreen(pyte.Screen): |
| 52 |
@property |
| 53 |
def display(self): |
| 54 |
def render(line): |
| 55 |
skip_stub = False |
| 56 |
for x in range(self.columns): |
| 57 |
if skip_stub: |
| 58 |
skip_stub = False |
| 59 |
continue |
| 60 |
char = line[x].data |
| 61 |
if not char: |
| 62 |
yield " " |
| 63 |
continue |
| 64 |
skip_stub = pyte.screens.wcwidth(char[0]) == 2 |
| 65 |
yield char |
| 66 |
|
| 67 |
return ["".join(render(self.buffer[y])) for y in range(self.lines)] |
| 68 |
|
| 69 |
def set_margins(self, *args, **kwargs): |
| 70 |
kwargs.pop("private", None) |
| 71 |
super(FenrirScreen, self).set_margins(*args, **kwargs) |
| 72 |
|
| 73 |
def select_graphic_rendition(self, *args, **kwargs): |
| 74 |
kwargs.pop("private", None) |
| 75 |
super(FenrirScreen, self).select_graphic_rendition(*args, **kwargs) |
| 76 |
|
| 77 |
|
| 78 |
class Terminal: |
| 79 |
def __init__(self, columns, lines, p_in, env=None): |
| 80 |
self.text = "" |
| 81 |
self.attributes = None |
| 82 |
self.screen = FenrirScreen(columns, lines) |
| 83 |
self.env = env # Environment for proper logging |
| 84 |
|
| 85 |
# Pre-create default attribute template to avoid repeated allocation |
| 86 |
self._default_attribute = [ |
| 87 |
"default", "default", False, False, False, False, False, False, |
| 88 |
"default", "default" |
| 89 |
] |
| 90 |
self.screen.write_process_input = lambda data: p_in.write( |
| 91 |
data.encode() |
| 92 |
) |
| 93 |
self.stream = pyte.ByteStream() |
| 94 |
self.stream.attach(self.screen) |
| 95 |
|
| 96 |
def _log_error(self, message, level=None): |
| 97 |
"""Log error message using proper debug manager if available.""" |
| 98 |
if self.env and "runtime" in self.env and "DebugManager" in self.env["runtime"]: |
| 99 |
try: |
| 100 |
log_level = level if level else debug.DebugLevel.ERROR |
| 101 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 102 |
f"PTY Terminal: {message}", |
| 103 |
log_level |
| 104 |
) |
| 105 |
return |
| 106 |
except Exception: |
| 107 |
pass # Fallback to print if debug manager fails |
| 108 |
|
| 109 |
# Fallback logging when debug manager unavailable |
| 110 |
print(f"PTY Terminal: {message}") |
| 111 |
|
| 112 |
def feed(self, data): |
| 113 |
self.stream.feed(data) |
| 114 |
|
| 115 |
def update_attributes(self, initialize=False): |
| 116 |
buffer = self.screen.buffer |
| 117 |
lines = None |
| 118 |
if not initialize: |
| 119 |
lines = self.screen.dirty |
| 120 |
else: |
| 121 |
lines = range(self.screen.lines) |
| 122 |
try: |
| 123 |
self.attributes = [ |
| 124 |
[ |
| 125 |
list(attribute[1:]) + [False, "default", "default"] |
| 126 |
if len(attribute) > 1 else [False, "default", "default"] |
| 127 |
for attribute in line.values() |
| 128 |
] |
| 129 |
for line in buffer.values() |
| 130 |
] |
| 131 |
except Exception as e: |
| 132 |
self._log_error(f"Error initializing attributes: {e}") |
| 133 |
# Fallback to empty attributes |
| 134 |
self.attributes = [[] for _ in range(self.screen.lines)] |
| 135 |
for y in lines: |
| 136 |
# Validate y is within reasonable bounds (prevent memory exhaustion) |
| 137 |
if y >= PTYConstants.MAX_TERMINAL_LINES: |
| 138 |
self._log_error( |
| 139 |
f"Line index {y} exceeds maximum {PTYConstants.MAX_TERMINAL_LINES}, " |
| 140 |
f"skipping attribute update", |
| 141 |
debug.DebugLevel.WARNING |
| 142 |
) |
| 143 |
continue |
| 144 |
|
| 145 |
# Check if line y exists in buffer before accessing it |
| 146 |
if y not in buffer: |
| 147 |
# Only log this occasionally to prevent spam |
| 148 |
if y % 10 == 0: # Log every 10th missing line |
| 149 |
# Pre-format string to avoid repeated f-string operations |
| 150 |
line_range = f"{y}-{y+9}" |
| 151 |
self._log_error( |
| 152 |
f"Lines {line_range} not found in buffer, skipping attribute updates", |
| 153 |
debug.DebugLevel.WARNING |
| 154 |
) |
| 155 |
continue |
| 156 |
|
| 157 |
# Ensure attributes array is large enough for line y |
| 158 |
while len(self.attributes) <= y: |
| 159 |
self.attributes.append([]) |
| 160 |
|
| 161 |
try: |
| 162 |
self.attributes[y] = [ |
| 163 |
list(attribute[1:]) + [False, "default", "default"] |
| 164 |
for attribute in (buffer[y].values()) |
| 165 |
] |
| 166 |
except Exception as e: |
| 167 |
self._log_error(f"Error updating attributes for line {y}: {e}") |
| 168 |
# Initialize with empty attributes if update fails |
| 169 |
self.attributes[y] = [] |
| 170 |
if len(self.attributes[y]) < self.screen.columns: |
| 171 |
diff = self.screen.columns - len(self.attributes[y]) |
| 172 |
# Use pre-created template for efficiency |
| 173 |
self.attributes[y] += [self._default_attribute[:] for _ in range(diff)] |
| 174 |
|
| 175 |
def resize(self, lines, columns): |
| 176 |
self.screen.resize(lines, columns) |
| 177 |
self.set_cursor() |
| 178 |
self.update_attributes(True) |
| 179 |
|
| 180 |
def set_cursor(self, x=-1, y=-1): |
| 181 |
# Determine target cursor position |
| 182 |
x_pos = x if x != -1 else self.screen.cursor.x |
| 183 |
y_pos = y if y != -1 else self.screen.cursor.y |
| 184 |
|
| 185 |
# Validate and clamp cursor position to screen bounds |
| 186 |
max_x = max(0, self.screen.columns - 1) |
| 187 |
max_y = max(0, self.screen.lines - 1) |
| 188 |
|
| 189 |
self.screen.cursor.x = max(0, min(x_pos, max_x)) |
| 190 |
self.screen.cursor.y = max(0, min(y_pos, max_y)) |
| 191 |
|
| 192 |
def get_screen_content(self): |
| 193 |
cursor = self.screen.cursor |
| 194 |
# Only regenerate text if screen is dirty or text doesn't exist |
| 195 |
if not hasattr(self, 'text') or self.screen.dirty: |
| 196 |
self.text = "\n".join(self.screen.display) |
| 197 |
self.update_attributes(self.attributes is None) |
| 198 |
self.screen.dirty.clear() |
| 199 |
|
| 200 |
# Return screen content without unnecessary copying |
| 201 |
# Only copy attributes if they exist and need protection |
| 202 |
screen_data = { |
| 203 |
"cursor": (cursor.x, cursor.y), |
| 204 |
"lines": self.screen.lines, |
| 205 |
"columns": self.screen.columns, |
| 206 |
"text": self.text, |
| 207 |
"attributes": self.attributes[:] if self.attributes else [], # Shallow copy only if needed |
| 208 |
"screen": "pty", |
| 209 |
"screenUpdateTime": time.time(), |
| 210 |
} |
| 211 |
return screen_data |
| 212 |
|
| 213 |
|
| 214 |
class driver(screenDriver): |
| 215 |
def __init__(self): |
| 216 |
screenDriver.__init__(self) |
| 217 |
self.signalPipe = os.pipe() |
| 218 |
self.p_out = None |
| 219 |
self.terminal = None |
| 220 |
self.p_pid = -1 |
| 221 |
self.terminal_lock = threading.Lock() # Synchronize terminal operations |
| 222 |
self.stdin_interrupt_lock = threading.Lock() |
| 223 |
self.stdin_interrupt_running = False |
| 224 |
self.stdin_interrupt_thread = None |
| 225 |
signal.signal(signal.SIGWINCH, self.handle_sigwinch) |
| 226 |
|
| 227 |
# Runtime configuration storage |
| 228 |
self.pty_config = {} |
| 229 |
|
| 230 |
def _load_pty_settings(self): |
| 231 |
"""Load PTY-specific settings from configuration with fallbacks to defaults.""" |
| 232 |
try: |
| 233 |
settings_manager = self.env["runtime"]["SettingsManager"] |
| 234 |
|
| 235 |
self.pty_config = { |
| 236 |
'input_timeout': self._get_optional_float_setting( |
| 237 |
settings_manager, 'screen', 'ptyInputTimeout', |
| 238 |
PTYConstants.INPUT_READ_TIMEOUT |
| 239 |
), |
| 240 |
'output_timeout': self._get_optional_float_setting( |
| 241 |
settings_manager, 'screen', 'ptyOutputTimeout', |
| 242 |
PTYConstants.OUTPUT_READ_TIMEOUT |
| 243 |
), |
| 244 |
'select_timeout': self._get_optional_float_setting( |
| 245 |
settings_manager, 'screen', 'ptySelectTimeout', |
| 246 |
PTYConstants.SELECT_TIMEOUT |
| 247 |
), |
| 248 |
'process_termination_timeout': self._get_optional_float_setting( |
| 249 |
settings_manager, 'screen', 'ptyProcessTimeout', |
| 250 |
PTYConstants.PROCESS_TERMINATION_TIMEOUT |
| 251 |
), |
| 252 |
'poll_interval': self._get_optional_float_setting( |
| 253 |
settings_manager, 'screen', 'ptyPollInterval', |
| 254 |
PTYConstants.MIN_POLL_INTERVAL |
| 255 |
) |
| 256 |
} |
| 257 |
|
| 258 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 259 |
f"PTY screenDriver: Loaded configuration: {self.pty_config}", |
| 260 |
debug.DebugLevel.INFO |
| 261 |
) |
| 262 |
|
| 263 |
except Exception as e: |
| 264 |
# Fallback to constants if settings fail |
| 265 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 266 |
f"PTY screenDriver: Failed to load settings, using defaults: {e}", |
| 267 |
debug.DebugLevel.WARNING |
| 268 |
) |
| 269 |
self.pty_config = { |
| 270 |
'input_timeout': PTYConstants.INPUT_READ_TIMEOUT, |
| 271 |
'output_timeout': PTYConstants.OUTPUT_READ_TIMEOUT, |
| 272 |
'select_timeout': PTYConstants.SELECT_TIMEOUT, |
| 273 |
'process_termination_timeout': PTYConstants.PROCESS_TERMINATION_TIMEOUT, |
| 274 |
'poll_interval': PTYConstants.MIN_POLL_INTERVAL |
| 275 |
} |
| 276 |
|
| 277 |
def _get_optional_float_setting( |
| 278 |
self, settings_manager, section, setting, default |
| 279 |
): |
| 280 |
try: |
| 281 |
value = settings_manager.get_setting(section, setting) |
| 282 |
if value == "": |
| 283 |
return default |
| 284 |
return float(value) |
| 285 |
except Exception: |
| 286 |
return default |
| 287 |
|
| 288 |
def initialize(self, environment): |
| 289 |
self.env = environment |
| 290 |
self.command = self.env["runtime"]["SettingsManager"].get_setting( |
| 291 |
"general", "shell" |
| 292 |
) |
| 293 |
|
| 294 |
# Load configurable timeouts from settings |
| 295 |
self._load_pty_settings() |
| 296 |
|
| 297 |
self.env["runtime"]["ProcessManager"].add_custom_event_thread( |
| 298 |
self.terminal_emulation |
| 299 |
) |
| 300 |
|
| 301 |
def get_curr_screen(self): |
| 302 |
self.env["screen"]["oldTTY"] = "pty" |
| 303 |
self.env["screen"]["newTTY"] = "pty" |
| 304 |
|
| 305 |
def inject_text_to_screen(self, msg_bytes, screen=None): |
| 306 |
if not screen: |
| 307 |
screen = self.p_out.fileno() |
| 308 |
if isinstance(msg_bytes, str): |
| 309 |
msg_bytes = bytes(msg_bytes, "UTF-8") |
| 310 |
os.write(screen, msg_bytes) |
| 311 |
|
| 312 |
def interrupt_output_on_stdin_input(self, msg_bytes): |
| 313 |
if not msg_bytes: |
| 314 |
return |
| 315 |
settings_manager = self.env["runtime"]["SettingsManager"] |
| 316 |
if not settings_manager.get_setting_as_bool( |
| 317 |
"keyboard", "interrupt_on_key_press" |
| 318 |
): |
| 319 |
return |
| 320 |
if settings_manager.get_setting( |
| 321 |
"keyboard", "interrupt_on_key_press_filter" |
| 322 |
).strip(): |
| 323 |
return |
| 324 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 325 |
"ptyDriver interrupt_output_on_stdin_input: " |
| 326 |
+ repr(msg_bytes), |
| 327 |
debug.DebugLevel.INFO, |
| 328 |
) |
| 329 |
self.start_stdin_interrupt_thread() |
| 330 |
|
| 331 |
def start_stdin_interrupt_thread(self): |
| 332 |
with self.stdin_interrupt_lock: |
| 333 |
if self.stdin_interrupt_running: |
| 334 |
return |
| 335 |
self.stdin_interrupt_running = True |
| 336 |
self.stdin_interrupt_thread = threading.Thread( |
| 337 |
target=self.run_stdin_interrupt, |
| 338 |
daemon=True, |
| 339 |
) |
| 340 |
self.stdin_interrupt_thread.start() |
| 341 |
|
| 342 |
def run_stdin_interrupt(self): |
| 343 |
try: |
| 344 |
self.env["runtime"]["OutputManager"].interrupt_output() |
| 345 |
except Exception as e: |
| 346 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 347 |
"ptyDriver interrupt_output_on_stdin_input: " |
| 348 |
+ str(e), |
| 349 |
debug.DebugLevel.ERROR, |
| 350 |
) |
| 351 |
finally: |
| 352 |
with self.stdin_interrupt_lock: |
| 353 |
self.stdin_interrupt_running = False |
| 354 |
|
| 355 |
def handle_stdin_input(self, msg_bytes, event_queue): |
| 356 |
if self.synthesize_backspace_shortcut(msg_bytes, event_queue): |
| 357 |
return |
| 358 |
if self.handle_vmenu_stdin_input(msg_bytes, event_queue): |
| 359 |
return |
| 360 |
if self.suppress_recent_review_stdin_tail(msg_bytes): |
| 361 |
return |
| 362 |
self.record_stdin_keypress(msg_bytes) |
| 363 |
self.interrupt_output_on_stdin_input(msg_bytes) |
| 364 |
self.inject_text_to_screen(msg_bytes) |
| 365 |
|
| 366 |
def suppress_recent_review_stdin_tail(self, msg_bytes): |
| 367 |
if not self.is_keyboard_control_sequence(msg_bytes): |
| 368 |
return False |
| 369 |
try: |
| 370 |
command_info = self.env["commandInfo"] |
| 371 |
last_command = command_info.get("lastCommand", "") |
| 372 |
last_section = command_info.get("lastCommandSection", "") |
| 373 |
last_run_time = command_info.get("lastCommandRunTime", 0) |
| 374 |
except Exception: |
| 375 |
return False |
| 376 |
if last_section != "commands" or not last_command.startswith("REVIEW_"): |
| 377 |
return False |
| 378 |
if time.time() - last_run_time > 0.8: |
| 379 |
return False |
| 380 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 381 |
"ptyDriver suppressing recent review stdin tail: " |
| 382 |
+ repr(msg_bytes), |
| 383 |
debug.DebugLevel.INFO, |
| 384 |
) |
| 385 |
return True |
| 386 |
|
| 387 |
def is_keyboard_control_sequence(self, msg_bytes): |
| 388 |
if not msg_bytes: |
| 389 |
return False |
| 390 |
if msg_bytes.startswith(b"\x1b"): |
| 391 |
return True |
| 392 |
if len(msg_bytes) == 1: |
| 393 |
value = msg_bytes[0] |
| 394 |
return value < 32 and msg_bytes not in [b"\t", b"\n", b"\r"] |
| 395 |
return False |
| 396 |
|
| 397 |
def handle_vmenu_stdin_input(self, msg_bytes, event_queue): |
| 398 |
if not self.is_vmenu_active(): |
| 399 |
return False |
| 400 |
key_name = self.vmenu_stdin_key_name(msg_bytes) |
| 401 |
if key_name and not self.vmenu_key_already_handled(key_name): |
| 402 |
self.queue_keypress(key_name, event_queue) |
| 403 |
return True |
| 404 |
|
| 405 |
def is_vmenu_active(self): |
| 406 |
try: |
| 407 |
return self.env["runtime"]["VmenuManager"].get_active() |
| 408 |
except Exception: |
| 409 |
return False |
| 410 |
|
| 411 |
def vmenu_stdin_key_name(self, msg_bytes): |
| 412 |
key_map = { |
| 413 |
b"\x1b": "KEY_ESC", |
| 414 |
b"\x1b[A": "KEY_UP", |
| 415 |
b"\x1b[B": "KEY_DOWN", |
| 416 |
b"\x1b[C": "KEY_RIGHT", |
| 417 |
b"\x1b[D": "KEY_LEFT", |
| 418 |
b"\x1b[5~": "KEY_PAGEUP", |
| 419 |
b"\x1b[6~": "KEY_PAGEDOWN", |
| 420 |
b"\r": "KEY_ENTER", |
| 421 |
b"\n": "KEY_ENTER", |
| 422 |
b" ": "KEY_SPACE", |
| 423 |
} |
| 424 |
if msg_bytes in key_map: |
| 425 |
return key_map[msg_bytes] |
| 426 |
if len(msg_bytes) != 1: |
| 427 |
return None |
| 428 |
char = chr(msg_bytes[0]) |
| 429 |
if "a" <= char <= "z" or "A" <= char <= "Z": |
| 430 |
return "KEY_" + char.upper() |
| 431 |
return None |
| 432 |
|
| 433 |
def vmenu_key_already_handled(self, key_name): |
| 434 |
try: |
| 435 |
return key_name in self.env["input"]["curr_input"] |
| 436 |
except Exception: |
| 437 |
return False |
| 438 |
|
| 439 |
def queue_keypress(self, key_name, event_queue): |
| 440 |
event_time = time.time() |
| 441 |
for event_state in [1, 0]: |
| 442 |
try: |
| 443 |
event_queue.put( |
| 444 |
{ |
| 445 |
"Type": FenrirEventType.keyboard_input, |
| 446 |
"data": { |
| 447 |
"event_name": key_name, |
| 448 |
"event_value": 0, |
| 449 |
"event_sec": int(event_time), |
| 450 |
"event_usec": int((event_time % 1) * 1000000), |
| 451 |
"event_state": event_state, |
| 452 |
"event_type": 0, |
| 453 |
}, |
| 454 |
}, |
| 455 |
block=False, |
| 456 |
) |
| 457 |
except Full: |
| 458 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 459 |
"ptyDriver queue_keypress: Event queue full, dropping " |
| 460 |
+ key_name, |
| 461 |
debug.DebugLevel.WARNING, |
| 462 |
) |
| 463 |
|
| 464 |
def record_stdin_keypress(self, msg_bytes): |
| 465 |
key_name = self.stdin_key_name(msg_bytes) |
| 466 |
try: |
| 467 |
self.env["runtime"]["InputManager"].record_unmanaged_keypress( |
| 468 |
key_name |
| 469 |
) |
| 470 |
except Exception as e: |
| 471 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 472 |
"ptyDriver record_stdin_keypress: " + str(e), |
| 473 |
debug.DebugLevel.ERROR, |
| 474 |
) |
| 475 |
|
| 476 |
def stdin_key_name(self, msg_bytes): |
| 477 |
key_map = { |
| 478 |
b"\t": "KEY_TAB", |
| 479 |
b"\x08": "KEY_BACKSPACE", |
| 480 |
b"\x7f": "KEY_BACKSPACE", |
| 481 |
b"\x1b[A": "KEY_UP", |
| 482 |
b"\x1bOA": "KEY_UP", |
| 483 |
b"\x1b[B": "KEY_DOWN", |
| 484 |
b"\x1bOB": "KEY_DOWN", |
| 485 |
b"\x1b[C": "KEY_RIGHT", |
| 486 |
b"\x1bOC": "KEY_RIGHT", |
| 487 |
b"\x1b[D": "KEY_LEFT", |
| 488 |
b"\x1bOD": "KEY_LEFT", |
| 489 |
b"\x1b[H": "KEY_HOME", |
| 490 |
b"\x1bOH": "KEY_HOME", |
| 491 |
b"\x1b[F": "KEY_END", |
| 492 |
b"\x1bOF": "KEY_END", |
| 493 |
b"\x1b[5~": "KEY_PAGEUP", |
| 494 |
b"\x1b[6~": "KEY_PAGEDOWN", |
| 495 |
b"\x1b[3~": "KEY_DELETE", |
| 496 |
b"\r": "KEY_ENTER", |
| 497 |
b"\n": "KEY_ENTER", |
| 498 |
b" ": "KEY_SPACE", |
| 499 |
} |
| 500 |
if msg_bytes in key_map: |
| 501 |
return key_map[msg_bytes] |
| 502 |
if len(msg_bytes) == 1: |
| 503 |
char = chr(msg_bytes[0]) |
| 504 |
if char.isascii() and char.isalnum(): |
| 505 |
return "KEY_" + char.upper() |
| 506 |
return "KEY_TERMINAL_INPUT" |
| 507 |
|
| 508 |
def synthesize_backspace_shortcut(self, msg_bytes, event_queue): |
| 509 |
if not self.is_backspace_shortcut_sequence(msg_bytes): |
| 510 |
return False |
| 511 |
if "KEY_FENRIR" not in self.env["input"]["curr_input"]: |
| 512 |
return False |
| 513 |
|
| 514 |
event_time = time.time() |
| 515 |
for event_state in [1, 0]: |
| 516 |
try: |
| 517 |
event_queue.put( |
| 518 |
{ |
| 519 |
"Type": FenrirEventType.keyboard_input, |
| 520 |
"data": { |
| 521 |
"event_name": "KEY_BACKSPACE", |
| 522 |
"event_value": 0, |
| 523 |
"event_sec": int(event_time), |
| 524 |
"event_usec": int((event_time % 1) * 1000000), |
| 525 |
"event_state": event_state, |
| 526 |
"event_type": 0, |
| 527 |
}, |
| 528 |
}, |
| 529 |
block=False, |
| 530 |
) |
| 531 |
except Full: |
| 532 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 533 |
"ptyDriver synthesize_backspace_shortcut: Event queue full, dropping backspace events", |
| 534 |
debug.DebugLevel.WARNING, |
| 535 |
) |
| 536 |
return True |
| 537 |
|
| 538 |
def is_backspace_shortcut_sequence(self, msg_bytes): |
| 539 |
if msg_bytes in [b"\x7f", b"\x08"]: |
| 540 |
return True |
| 541 |
try: |
| 542 |
sequence = msg_bytes.decode("ascii") |
| 543 |
except UnicodeDecodeError: |
| 544 |
return False |
| 545 |
if not sequence.startswith("\x1b["): |
| 546 |
return False |
| 547 |
if sequence.endswith("~"): |
| 548 |
parts = sequence[2:-1].split(";") |
| 549 |
if parts[0] == "3": |
| 550 |
return True |
| 551 |
if parts[0] == "27" and parts[-1] in ["8", "127"]: |
| 552 |
return True |
| 553 |
elif sequence.endswith("u"): |
| 554 |
parts = sequence[2:-1].split(";") |
| 555 |
if parts[0] in ["8", "127"]: |
| 556 |
return True |
| 557 |
return False |
| 558 |
|
| 559 |
def get_session_information(self): |
| 560 |
self.env["screen"]["autoIgnoreScreens"] = [] |
| 561 |
self.env["general"]["prev_user"] = getpass.getuser() |
| 562 |
self.env["general"]["curr_user"] = getpass.getuser() |
| 563 |
|
| 564 |
def read_all(self, fd, timeout=PTYConstants.DEFAULT_READ_TIMEOUT, interruptFd=None, len=PTYConstants.DEFAULT_READ_BUFFER_SIZE): |
| 565 |
"""Read all available data from file descriptor with efficient polling. |
| 566 |
|
| 567 |
Uses progressively longer wait times to balance responsiveness with CPU usage. |
| 568 |
""" |
| 569 |
msg_bytes = b"" |
| 570 |
fd_list = [fd] |
| 571 |
if interruptFd: |
| 572 |
fd_list.append(interruptFd) |
| 573 |
|
| 574 |
starttime = time.time() |
| 575 |
poll_timeout = self.pty_config.get('poll_interval', PTYConstants.MIN_POLL_INTERVAL) # Use configured interval |
| 576 |
|
| 577 |
while True: |
| 578 |
# Use consistent short polling for responsiveness |
| 579 |
r = screen_utils.has_more_what(fd_list, poll_timeout) |
| 580 |
|
| 581 |
# Nothing more to read |
| 582 |
if fd not in r: |
| 583 |
# Check overall timeout |
| 584 |
if (time.time() - starttime) >= timeout: |
| 585 |
break |
| 586 |
continue |
| 587 |
|
| 588 |
try: |
| 589 |
data = os.read(fd, len) |
| 590 |
if data == b"": |
| 591 |
raise EOFError |
| 592 |
msg_bytes += data |
| 593 |
except OSError as e: |
| 594 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 595 |
f"PTY screenDriver read_all: OS error reading from fd {fd}: {e}", |
| 596 |
debug.DebugLevel.ERROR |
| 597 |
) |
| 598 |
# For I/O errors, exit immediately to prevent endless retry loops |
| 599 |
if e.errno == PTYConstants.IO_ERROR_ERRNO: # Input/output error |
| 600 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 601 |
"PTY screenDriver: Terminal connection lost, stopping read loop", |
| 602 |
debug.DebugLevel.ERROR |
| 603 |
) |
| 604 |
raise EOFError("Terminal connection lost") |
| 605 |
break |
| 606 |
|
| 607 |
# Exit on interrupt available |
| 608 |
if interruptFd and interruptFd in r: |
| 609 |
break |
| 610 |
|
| 611 |
# Check overall timeout |
| 612 |
if (time.time() - starttime) >= timeout: |
| 613 |
break |
| 614 |
|
| 615 |
return msg_bytes |
| 616 |
|
| 617 |
def open_terminal(self, columns, lines, command): |
| 618 |
p_pid, master_fd = pty.fork() |
| 619 |
if p_pid == 0: # Child. |
| 620 |
argv = shlex.split(command) |
| 621 |
env = os.environ.copy() |
| 622 |
# values are VT100,xterm-256color,linux |
| 623 |
try: |
| 624 |
if env["TERM"] == "": |
| 625 |
env["TERM"] = "linux" |
| 626 |
except Exception as e: |
| 627 |
# Child process doesn't have access to debug manager |
| 628 |
# Use fallback logging with more context |
| 629 |
print( |
| 630 |
f"ptyDriver open_terminal (child): TERM environment error: {e}" |
| 631 |
) |
| 632 |
env["TERM"] = "linux" |
| 633 |
os.execvpe(argv[0], argv, env) |
| 634 |
# File-like object for I/O with the child process aka command. |
| 635 |
p_out = os.fdopen(master_fd, "w+b", 0) |
| 636 |
return Terminal(columns, lines, p_out, self.env), p_pid, p_out |
| 637 |
|
| 638 |
def resize_terminal(self, fd): |
| 639 |
s = struct.pack("HHHH", 0, 0, 0, 0) |
| 640 |
s = fcntl.ioctl(0, termios.TIOCGWINSZ, s) |
| 641 |
fcntl.ioctl(fd, termios.TIOCSWINSZ, s) |
| 642 |
lines, columns, _, _ = struct.unpack("hhhh", s) |
| 643 |
return lines, columns |
| 644 |
|
| 645 |
def get_terminal_size(self, fd): |
| 646 |
s = struct.pack("HHHH", 0, 0, 0, 0) |
| 647 |
lines, columns, _, _ = struct.unpack( |
| 648 |
"HHHH", fcntl.ioctl(fd, termios.TIOCGWINSZ, s) |
| 649 |
) |
| 650 |
return lines, columns |
| 651 |
|
| 652 |
def handle_sigwinch(self, *args): |
| 653 |
os.write(self.signalPipe[1], b"w") |
| 654 |
|
| 655 |
def terminal_emulation(self, active, event_queue): |
| 656 |
try: |
| 657 |
old_attr = termios.tcgetattr(sys.stdin) |
| 658 |
tty.setraw(0) |
| 659 |
lines, columns = self.get_terminal_size(0) |
| 660 |
if self.command == "": |
| 661 |
self.command = screen_utils.get_shell() |
| 662 |
self.terminal, self.p_pid, self.p_out = self.open_terminal( |
| 663 |
columns, lines, self.command |
| 664 |
) |
| 665 |
lines, columns = self.resize_terminal(self.p_out) |
| 666 |
self.terminal.resize(lines, columns) |
| 667 |
fd_list = [sys.stdin, self.p_out, self.signalPipe[0]] |
| 668 |
while active.value: |
| 669 |
r, _, _ = select(fd_list, [], [], self.pty_config.get('select_timeout', PTYConstants.SELECT_TIMEOUT)) # Configurable timeout |
| 670 |
# none |
| 671 |
if r == []: |
| 672 |
continue |
| 673 |
# signals |
| 674 |
if self.signalPipe[0] in r: |
| 675 |
os.read(self.signalPipe[0], 1) |
| 676 |
lines, columns = self.resize_terminal(self.p_out) |
| 677 |
self.terminal.resize(lines, columns) |
| 678 |
# input |
| 679 |
if sys.stdin in r: |
| 680 |
try: |
| 681 |
msg_bytes = self.read_all(sys.stdin.fileno(), timeout=self.pty_config.get('input_timeout', PTYConstants.INPUT_READ_TIMEOUT), len=PTYConstants.INPUT_BUFFER_SIZE) |
| 682 |
except (EOFError, OSError): |
| 683 |
event_queue.put( |
| 684 |
{ |
| 685 |
"Type": FenrirEventType.stop_main_loop, |
| 686 |
"data": None, |
| 687 |
} |
| 688 |
) |
| 689 |
break |
| 690 |
try: |
| 691 |
self.handle_stdin_input(msg_bytes, event_queue) |
| 692 |
except Exception as e: |
| 693 |
self.env["runtime"][ |
| 694 |
"DebugManager" |
| 695 |
].write_debug_out( |
| 696 |
"ptyDriver getInputData: Error injecting text to screen: " |
| 697 |
+ str(e), |
| 698 |
debug.DebugLevel.ERROR, |
| 699 |
) |
| 700 |
event_queue.put( |
| 701 |
{ |
| 702 |
"Type": FenrirEventType.stop_main_loop, |
| 703 |
"data": None, |
| 704 |
} |
| 705 |
) |
| 706 |
break |
| 707 |
# output |
| 708 |
if self.p_out in r: |
| 709 |
try: |
| 710 |
msg_bytes = self.read_all( |
| 711 |
self.p_out.fileno(), |
| 712 |
timeout=self.pty_config.get('output_timeout', PTYConstants.OUTPUT_READ_TIMEOUT), |
| 713 |
interruptFd=sys.stdin.fileno() |
| 714 |
) |
| 715 |
except (EOFError, OSError): |
| 716 |
event_queue.put( |
| 717 |
{ |
| 718 |
"Type": FenrirEventType.stop_main_loop, |
| 719 |
"data": None, |
| 720 |
} |
| 721 |
) |
| 722 |
break |
| 723 |
# Synchronize terminal operations to prevent race conditions |
| 724 |
with self.terminal_lock: |
| 725 |
# Feed data to terminal and get consistent screen state |
| 726 |
self.terminal.feed(msg_bytes) |
| 727 |
screen_content = self.terminal.get_screen_content() |
| 728 |
|
| 729 |
# Send screen update event with consistent state |
| 730 |
event_queue.put( |
| 731 |
{ |
| 732 |
"Type": FenrirEventType.screen_update, |
| 733 |
"data": screen_utils.create_screen_event_data( |
| 734 |
screen_content |
| 735 |
), |
| 736 |
} |
| 737 |
) |
| 738 |
|
| 739 |
# Inject to actual screen (outside lock to avoid blocking) |
| 740 |
self.inject_text_to_screen( |
| 741 |
msg_bytes, screen=sys.stdout.fileno() |
| 742 |
) |
| 743 |
except Exception as e: # Process died? |
| 744 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 745 |
f"PTY screenDriver terminal_emulation: Exception occurred: {e}", |
| 746 |
debug.DebugLevel.ERROR |
| 747 |
) |
| 748 |
event_queue.put( |
| 749 |
{"Type": FenrirEventType.stop_main_loop, "data": None} |
| 750 |
) |
| 751 |
finally: |
| 752 |
self._safe_cleanup_process() |
| 753 |
self._safe_cleanup_resources(old_attr) |
| 754 |
event_queue.put( |
| 755 |
{"Type": FenrirEventType.stop_main_loop, "data": None} |
| 756 |
) |
| 757 |
|
| 758 |
def _safe_cleanup_process(self): |
| 759 |
"""Safely terminate the child process with timeout and fallback to SIGKILL.""" |
| 760 |
if not hasattr(self, 'p_pid') or self.p_pid is None: |
| 761 |
return |
| 762 |
|
| 763 |
try: |
| 764 |
# Check if process is still alive |
| 765 |
os.kill(self.p_pid, 0) # Signal 0 checks if process exists |
| 766 |
except OSError: |
| 767 |
# Process already dead |
| 768 |
self.p_pid = None |
| 769 |
return |
| 770 |
|
| 771 |
try: |
| 772 |
# Try graceful termination first |
| 773 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 774 |
f"PTY screenDriver: Terminating process {self.p_pid} gracefully", |
| 775 |
debug.DebugLevel.INFO |
| 776 |
) |
| 777 |
os.kill(self.p_pid, signal.SIGTERM) |
| 778 |
|
| 779 |
# Wait for graceful termination |
| 780 |
timeout = self.pty_config.get('process_termination_timeout', PTYConstants.PROCESS_TERMINATION_TIMEOUT) |
| 781 |
start_time = time.time() |
| 782 |
while time.time() - start_time < timeout: |
| 783 |
try: |
| 784 |
os.kill(self.p_pid, 0) # Check if still alive |
| 785 |
time.sleep(0.1) |
| 786 |
except OSError: |
| 787 |
# Process terminated gracefully |
| 788 |
self.p_pid = None |
| 789 |
return |
| 790 |
|
| 791 |
# Process didn't terminate gracefully, use SIGKILL |
| 792 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 793 |
f"PTY screenDriver: Process {self.p_pid} didn't terminate gracefully, using SIGKILL", |
| 794 |
debug.DebugLevel.WARNING |
| 795 |
) |
| 796 |
os.kill(self.p_pid, signal.SIGKILL) |
| 797 |
time.sleep(PTYConstants.PROCESS_KILL_DELAY) # Give it a moment |
| 798 |
|
| 799 |
except OSError as e: |
| 800 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 801 |
f"PTY screenDriver: Error terminating process {self.p_pid}: {e}", |
| 802 |
debug.DebugLevel.ERROR |
| 803 |
) |
| 804 |
finally: |
| 805 |
self.p_pid = None |
| 806 |
|
| 807 |
def _safe_cleanup_resources(self, old_attr=None): |
| 808 |
"""Safely clean up file descriptors and terminal attributes.""" |
| 809 |
# Close output pipe safely |
| 810 |
if hasattr(self, 'p_out') and self.p_out is not None: |
| 811 |
try: |
| 812 |
self.p_out.close() |
| 813 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 814 |
"PTY screenDriver: Closed output pipe", |
| 815 |
debug.DebugLevel.INFO |
| 816 |
) |
| 817 |
except Exception as e: |
| 818 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 819 |
f"PTY screenDriver: Error closing output pipe: {e}", |
| 820 |
debug.DebugLevel.ERROR |
| 821 |
) |
| 822 |
finally: |
| 823 |
self.p_out = None |
| 824 |
|
| 825 |
# Restore terminal attributes safely |
| 826 |
if old_attr is not None: |
| 827 |
try: |
| 828 |
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attr) |
| 829 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 830 |
"PTY screenDriver: Restored terminal attributes", |
| 831 |
debug.DebugLevel.INFO |
| 832 |
) |
| 833 |
except Exception as e: |
| 834 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 835 |
f"PTY screenDriver: Error restoring terminal attributes: {e}", |
| 836 |
debug.DebugLevel.ERROR |
| 837 |
) |
| 838 |
|
| 839 |
def get_curr_application(self): |
| 840 |
pass |