Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save johnhpatton/dfc089b9e8ca90c1c97a2b9053bb357b to your computer and use it in GitHub Desktop.
Save johnhpatton/dfc089b9e8ca90c1c97a2b9053bb357b to your computer and use it in GitHub Desktop.
#!/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)
# enable stty raw echo
stty raw -echo min 0 time 0
# sequence to query background.
printf "%b" "${ansi_sequence_query_bg}"
# small delay needed to allow terminal time to respond.
sleep .2
# terminal response is on STDIN, read ignoring '\r'
read -r bg_color
# reset stty
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_DARK=0; } || { IS_BG_LIGHT=0; IS_BG_DARK=1; }
(( IS_BG_DARK )) && echo "Background is: DARK! Use light foregrounds." || echo "Background is: DARK! Use light foregrounds."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment