Skip to content

Instantly share code, notes, and snippets.

@burke burke/darkness.rb
Last active Apr 27, 2017

Embed
What would you like to do?
# 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

This comment has been minimized.

Copy link

kevintpeng commented Apr 27, 2017

Oh man, hahah nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.