Refactor clipboard management and graphics query scripts

This commit is contained in:
2026-02-07 16:18:18 +01:00
parent 0863da0f47
commit 2a5b2fd9c2
12 changed files with 472 additions and 11 deletions
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env bash
# Description:
# Query terminal capabilities for graphics support, including:
# - Kitty Graphics Protocol (KGP)
# - iTerm2 inline images
# - Sixel graphics
# This script will print three lines of output:
# SUPPORT_KGP=1 or 0
# SUPPORT_ITERM2=1 or 0
# SUPPORT_SIXEL=1 or 0
#
# Usage:
# Do NOT source this script directly, as it will modify the terminal state
# and print its result directly to stdout.
# Instead, use command substitution to capture the output, for example:
# eval "$(graphics-query)"
# or parse the output manually.
#
# See also:
# - kgp-query: specifically checks for Kitty Graphics Protocol support
# - iterm2-query: specifically checks for iTerm2 inline image support
# - sixel-query: specifically checks for Sixel graphics support
set -euo pipefail
# Ensure in a interactive terminal
[ ! -t 0 ] && exit 1
# Construct query
KGP_QUERY_ID=$RANDOM
KGP_QUERY_CODE=$(printf "\033_Gi=%d,s=1,v=1,a=q,t=d,f=24;AAAA\033\\" "$KGP_QUERY_ID")
ITERM2_QUERY_CODE=$(printf "\033]1337;ReportCellSize\a")
KGP_EXPECTED_RESPONSE=$(printf "\033_Gi=%d;OK\033\\" "$KGP_QUERY_ID")
ITERM2_EXPECTED_RESPONSE=$(printf "\033]1337;") # followed by "ReportCellSize=...", but only the prefix is enough
FENCE_CODE=$(printf "\033[c")
# Set terminal to raw mode with timeout
stty_orig=$(stty -g)
trap 'stty "$stty_orig"' EXIT
stty -echo -icanon min 1 time 0
printf "%s%s%s" "$ITERM2_QUERY_CODE" "$KGP_QUERY_CODE" "$FENCE_CODE" > /dev/tty
response=""
support_kgp=0
support_iterm2=0
while true; do
IFS= read -r -N 1 -t 0.3 char || {
[ -z "$char" ] && break
}
response+="$char"
if [[ "$response" == *"$KGP_EXPECTED_RESPONSE"* ]]; then
support_kgp=1
fi
if [[ "$response" == *"$ITERM2_EXPECTED_RESPONSE"* ]]; then
support_iterm2=1
fi
if [[ "$response" == *$'\033['*'c' ]]; then
break
fi
if [ ${#response} -gt 1024 ]; then
break
fi
done
support_sixel=0
if [[ "$response" =~ $'\x1b'\[\?([0-9;]*)c ]]; then
params="${BASH_REMATCH[1]}"
IFS=';' read -ra codes <<< "$params"
for code in "${codes[@]}"; do
if [[ "$code" == "4" ]]; then
support_sixel=1
break
fi
done
fi
if [ "$support_kgp" -eq 1 ]; then
echo "SUPPORT_KGP=1"
else
echo "SUPPORT_KGP=0"
fi
if [ "$support_iterm2" -eq 1 ]; then
echo "SUPPORT_ITERM2=1"
else
echo "SUPPORT_ITERM2=0"
fi
if [ "$support_sixel" -eq 1 ]; then
echo "SUPPORT_SIXEL=1"
else
echo "SUPPORT_SIXEL=0"
fi