Skip to content

Instantly share code, notes, and snippets.

@burke
Last active April 27, 2017 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burke/1614fdb86c934fea6ae3835a1d28c289 to your computer and use it in GitHub Desktop.
Save burke/1614fdb86c934fea6ae3835a1d28c289 to your computer and use it in GitHub Desktop.
# detects whether a terminal is dark-on-light or light-on-dark.
# Only purposefully supports Terminal.app and iTerm, but a bunch of things use
# $COLORFGBG.
module BackgroundDetector
DARK = :dark
LIGHT = :light
def terminal_app
theme = `/usr/libexec/PlistBuddy -c "Print :'Default Window Settings'" ~/Library/Preferences/com.apple.Terminal.plist`.chomp
blob = `/usr/libexec/PlistBuddy -c "Print :'Window Settings':'#{theme}':BackgroundColor" ~/Library/Preferences/com.apple.Terminal.plist`.chomp
md = blob.force_encoding(Encoding::BINARY).match(/([01]\.\d+) ([01]\.\d+) ([01]\.\d+)/m)
r = md[1].to_f
g = md[2].to_f
b = md[3].to_f
avg = (r + g + b) / 3.0
avg < 0.5 ? DARK : LIGHT
end
def call
if fgbg = ENV['COLORFGBG']
parts = fgbg.split(';')
fg = parts[0].to_i
bg = parts[1].to_i
fg <= 6 || bg == 8 ? DARK : LIGHT
else
terminal_app
end
end
end
@kevintpeng
Copy link

Oh man, hahah nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment