Created
April 1, 2021 12:54
-
-
Save johnhpatton/49443c4eff7d66b8f42312c85b569002 to your computer and use it in GitHub Desktop.
Gets terminal background luminosity with ANSI escape sequence to help select a foreground color palette
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
get_bg_color() { | |
local -n bg_color="$1" | |
local ansi_sequence_query_bg='\e]11;?\e\' | |
local cur_stty=$(stty -g) | |
stty raw -echo min 0 time 0 | |
printf "%b" "${ansi_sequence_query_bg}" | |
sleep .2 | |
# for i in {1..50}; do | |
# sleep .050 | |
read -r bg_color | |
# [ -n "${bg_color}" ] && break | |
# done | |
stty $cur_stty | |
bg_color=${bg_color#*;} | |
bg_color=${bg_color#*:} | |
local rgb=(${bg_color//\// }) | |
printf -v bg_color "%.2s/%.2s/%.2s" ${rgb[@]} | |
rgb=(${bg_color//\// }) | |
printf -v bg_color "%d/%d/%d" $((16#${rgb[0]})) $((16#${rgb[1]})) $((16#${rgb[2]})) | |
} | |
get_luminescence() { | |
local -n luma="$1" | |
local background="" | |
get_bg_color "background" | |
local rgb=(${background//\// }) | |
local r_lumin g_lumin b_lumin | |
# Adobe | |
printf -v luma "%.0f" $(awk -v r=${rgb[0]} -v g=${rgb[1]} -v b=${rgb[2]} 'BEGIN{print (r*.212)+(g*.701)+(b*.087)}') | |
} | |
LUMA=0 | |
get_luminescence "LUMA" | |
(( LUMA > 50 )) && IS_BG_LIGHT=1 || IS_BG_LIGHT=0 | |
(( LUMA <= 50 )) && IS_BG_DARK=1 || IS_BG_DARK=0 | |
(( IS_BG_DARK )) && echo "DARK!" || echo "LIGHT." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment