cli (base): Add a failsafe on guess_background:

In some cases (e.g. inherited env values in a wrapping tool), the background detection
code can be validated but hangs. This patch avoids that by adding a timeout with a
`SIGALRM`.
This commit is contained in:
Goffi 2026-04-30 13:29:06 +02:00
commit 70ad837e5d

View file

@ -26,6 +26,7 @@ import logging as log
import os
import os.path
from pathlib import Path
import signal
import sys
import termios
import tty
@ -168,7 +169,15 @@ class LiberviaCli:
or vte_version >= 3502
)
):
# ANSI escape sequence
# ANSI escape sequence with alarm timeout to avoid hanging on unresponsive ptys
_bg_timeout = 0.5
def _alarm_handler(signum, frame):
raise TimeoutError("ANSI query timed out")
old_handler = signal.signal(signal.SIGALRM, _alarm_handler)
signal.setitimer(signal.ITIMER_REAL, _bg_timeout)
stdin_fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(stdin_fd)
try:
@ -188,7 +197,11 @@ class LiberviaCli:
]
# '\a' is the last character
sys.stdin.read(1)
except TimeoutError:
return "dark"
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, old_handler)
termios.tcsetattr(stdin_fd, termios.TCSADRAIN, old_settings)
lum = utils.per_luminance(red, green, blue)