From f105143b5cc0c0f3a045810db798d7af18e310eb Mon Sep 17 00:00:00 2001 From: Daniel Bauer Date: Fri, 28 Aug 2026 13:31:16 +0200 Subject: [PATCH] fix: fix background color detection printing stuff into terminal on wsl boot --- bin/executable_term-background | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/bin/executable_term-background b/bin/executable_term-background index 68bba05..e857e6a 100644 --- a/bin/executable_term-background +++ b/bin/executable_term-background @@ -13,19 +13,43 @@ # export TERM_BACKGROUND=light # or dark # in ~/.environment.local on that machine. # -# Tune the response wait via TERM_BACKGROUND_TIMEOUT (tenths of a second). +# Tune the per-attempt wait via TERM_BACKGROUND_TIMEOUT (tenths of a second) +# and the number of attempts via TERM_BACKGROUND_ATTEMPTS. We poll rather than +# do a single fixed-length read because on a freshly booted WSL instance the +# very first terminal's OSC 11 reply can arrive well after a short window +# closes; if we restored cooked/echo mode by then, the late reply leaks onto +# the screen (and into the shell's input buffer) as literal text. Staying in +# raw/no-echo mode across multiple short attempts lets a slow first reply +# still be captured silently instead of leaking. # Need a controlling terminal to talk to. [ -t 0 ] || { echo dark; exit 0; } exec 3<>/dev/tty || { echo dark; exit 0; } -# Raw mode with a short read timeout (min 0 time N = up to N*0.1s) so an -# unresponsive terminal costs us at most that long. saved=$(stty -g <&3 2>/dev/null) || { echo dark; exit 0; } stty raw -echo min 0 time "${TERM_BACKGROUND_TIMEOUT:-4}" <&3 2>/dev/null printf '\033]11;?\033\\' >&3 # OSC 11 query -answer=$(dd bs=64 count=1 <&3 2>/dev/null) + +answer="" +attempts="${TERM_BACKGROUND_ATTEMPTS:-3}" +i=0 +while [ "$i" -lt "$attempts" ]; do + answer="$answer$(dd bs=64 count=1 <&3 2>/dev/null)" + # A full "rgb:RRRR/GGGG/BBBB" reply has two '/' separators; stop as soon + # as we have them instead of waiting out every remaining attempt. + rest=${answer#*rgb:} + if [ "$rest" != "$answer" ]; then + tmp=$rest + count=0 + while [ "$tmp" != "${tmp#*/}" ]; do + count=$((count + 1)) + tmp=${tmp#*/} + done + [ "$count" -ge 2 ] && break + fi + i=$((i + 1)) +done stty "$saved" <&3 2>/dev/null # restore before anything else exec 3>&-