By Jason Snell
September 6, 2020 9:33 AM PT
BitBar, PHP, AppleScript, and Dark mode
Note: This story has not been updated since 2020.
I woke up this morning to find a challenge from Reader Max Velasco Knott. Max apparently enjoys Dark Mode on macOS — and my BitBar plugins don’t consider the existence of Dark Mode, mostly because I never use it.
So I set about trying to figure out how to make a BitBar plugin support Dark Mode. The answer, of course, is AppleScript:
tell application "System Events"
tell appearance preferences
set theMode to dark mode
end tell
end tell
return theMode
This script will return true
if we’re in Dark Mode and false
if we aren’t. (I found several other suggestions online that used Apple’s defaults read
terminal command to detect the theme status, but they didn’t work for me in the Big Sur beta and this did, so I’m going with this.)
But… my air quality script is written in PHP, so how to pipe AppleScript into a PHP script? Here’s how:
$darkmode = shell_exec('osascript <<EOF
tell application "System Events"
tell appearance preferences
set theMode to dark mode
end tell
end tell
return theMode
EOF
');
$darkmodestate = filter_var($darkmode, FILTER_VALIDATE_BOOLEAN);
Essentially, you use shell_exec
to run the osascript
command which is how you run AppleScript scripts from the command line. Then I create a boolean, $darkmodestate
, because I am bad at PHP and matching strings is hard.
Reader Max doesn’t actually like my use of color in the menu bar, so he said he had created a version of my plugin that was monochrome. Which, fair enough! Here’s my “AQI colors” subroutine, rebuilt to support Max’s desire for Dark Mode and monochrome:
if ( $darkmodestate ) {
// we are in dark mode
return '#ffffff';
} else {
// we are in light mode
return '#000000';
}
}
My personal version of this plugin has been updated to support Dark Mode, with different colors selected for both modes for (somewhat) improved legibility. And I’ve made the monochrome version available too. BitBar remains a free utility.
If you appreciate articles like this one, support us by becoming a Six Colors subscriber. Subscribers get access to an exclusive podcast, members-only stories, and a special community.