This repository has no description
2.5 kB
72 lines
1#!/usr/bin/env bash
2# Print the best graphics protocol this terminal speaks: kitty, sixels, iterm
3# or symbols.
4#
5# The terminal is asked directly instead of guessing from the environment,
6# because over ssh nothing on the remote host knows what is in front of the
7# user. Run this once, before a full-screen program takes over the tty: chafa
8# can probe on its own, but doing it per image races with nnn killing the
9# previewer mid-sequence.
10
11emit() {
12 printf '%s\n' "$1"
13 exit 0
14}
15
16case "${NNN_IMGFORMAT:-}" in
17kitty | sixels | iterm | symbols) emit "$NNN_IMGFORMAT" ;;
18esac
19
20# Terminals that answer no query but identify themselves in the environment.
21[ -n "${WEZTERM_PANE:-}" ] && emit iterm
22[ "${TERM_PROGRAM:-}" = "iTerm.app" ] && emit iterm
23
24query() {
25 local saved
26 local reply=""
27 # a controlling terminal we can actually open, not just a device node;
28 # bash reports a failing redirect before it applies 2>, hence the group
29 { : <>/dev/tty; } 2>/dev/null || return 1
30 saved=$(stty -g </dev/tty) || return 1
31 stty raw -echo </dev/tty || return 1
32 # Kitty graphics support, then primary device attributes (which reports
33 # sixel as attribute 4). Inside tmux both are smuggled out to the real
34 # terminal: tmux would answer DA1 itself, on its own behalf, and that says
35 # nothing about what can actually be drawn. Getting no answer at all is
36 # informative too - it means passthrough is disabled.
37 if [ -n "${TMUX:-}" ]; then
38 printf '\033Ptmux;\033\033_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\033\033\134\033\134' >/dev/tty
39 printf '\033Ptmux;\033\033[c\033\134' >/dev/tty
40 else
41 printf '\033_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\033\134\033[c' >/dev/tty
42 fi
43 # terminals answer in order, so the device attributes reply comes last and
44 # its trailing "c" ends the exchange; the timeout only bites when nothing
45 # is listening
46 IFS= read -r -s -t 1 -d'c' reply </dev/tty || true
47 stty "$saved" </dev/tty 2>/dev/null || true
48 printf '%sc' "$reply"
49}
50
51capabilities=$(query || true)
52
53# No answer to the graphics query inside tmux also means passthrough is off,
54# in which case kitty images would arrive as blank placeholder cells.
55case $capabilities in
56*'_Gi=31;OK'*) emit kitty ;;
57esac
58
59case $capabilities in
60*';4;'* | *';4c'* | *'?4;'* | *'?4c'*)
61 # tmux advertises attribute 4 whenever it was built with sixel support,
62 # regardless of what the attached client can actually draw
63 if [ -z "${TMUX:-}" ]; then
64 emit sixels
65 fi
66 case $(tmux display -p '#{client_termfeatures}' 2>/dev/null || true) in
67 *sixel*) emit sixels ;;
68 esac
69 ;;
70esac
71
72emit symbols