summaryrefslogtreecommitdiff
path: root/bin/isdarktty
blob: a09579b152d721e93e2784b0dc331342222a5602 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/sh

# Detect terminal darkness. Return 0 if dark, else 1.

trap "stty $(stty -g)" EXIT  # restore terminal settings at exit
stty raw -echo min 0 time 0  # set terminal in raw mode for query
printf '\e]11;?\e\\'         # xterm escape sequence to get bg color
sleep 0.01                   # 10ms delay to let terminal respond

# parse terminal response in form of: ...rgb:cf00/ff00/ff00...
# luma equation adapted from https://en.wikipedia.org/wiki/Luma_(video)
awk -v FS='' -v hex=123456789abcdef '{
	r = (16 * index(hex, $10) + index(hex, $11)) / 255
	g = (16 * index(hex, $15) + index(hex, $16)) / 255
	b = (16 * index(hex, $20) + index(hex, $21)) / 255
	exit (0.3 * r + 0.6 * g + 0.1 * b > 0.5)
}'