Skip to content

Commit

Permalink
Make the default macOS theme depend on Dark Mode
Browse files Browse the repository at this point in the history
We frequently get complaints from macOS users that bat does not work on
their default macOS terminal background, which is white.

Pay the price of slightly increased startup time to get a better default
on macOS. To avoid the slightly increased startup time, simply specify a
theme explicitly via `--theme`, `BAT_THEME`, or `~/.config/bat`.

Note that if there is an error when we check if Dark Mode is enabled, we
behave the same as on Windows and Linux; assume that the terminal
background is dark. This harmonizes behavior across platforms, and makes
bat behave the same as before, when Dark Mode was always assumed to be
enabled.
  • Loading branch information
Enselic committed May 21, 2022
1 parent 5f139e5 commit 6551690
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,65 @@ impl HighlightingAssets {
}
}

/// The default theme.
///
/// ### Windows and Linux
///
/// Windows and most Linux distributions has a dark terminal theme by
/// default. On these platforms, this function always returns a theme that
/// looks good on a dark background.
///
/// ### macOS
///
/// On macOS the default terminal background is light, but it is common that
/// Dark Mode active, which makes the terminal background dark. On this
/// platform, the default theme depends on
/// ```bash
/// defaults read -globalDomain AppleInterfaceStyle
/// ````
/// To avoid the overhead of the check on macOS, simply specify a theme
/// explicitly via `--theme`, `BAT_THEME`, or `~/.config/bat`.
///
/// See <https://github.com/sharkdp/bat/issues/1746> and
/// <https://github.com/sharkdp/bat/issues/1928> for more context.
pub fn default_theme() -> &'static str {
#[cfg(not(target_os = "macos"))]
{
Self::default_dark_theme()
}
#[cfg(target_os = "macos")]
{
fn macos_dark_mode_active() -> bool {
let mut defaults_cmd = std::process::Command::new("defaults");
defaults_cmd.args(&["read", "-globalDomain", "AppleInterfaceStyle"]);
match defaults_cmd.output() {
Ok(output) => output.stdout == b"Dark\n",
Err(_) => true,
}
}

if macos_dark_mode_active() {
Self::default_dark_theme()
} else {
Self::default_light_theme()
}
}
}

/**
* The default theme that looks good on a dark background.
*/
fn default_dark_theme() -> &'static str {
"Monokai Extended"
}

/**
* The default theme that looks good on a light background.
*/
fn default_light_theme() -> &'static str {
"Monokai Extended Light"
}

pub fn from_cache(cache_path: &Path) -> Result<Self> {
Ok(HighlightingAssets::new(
SerializedSyntaxSet::FromFile(cache_path.join("syntaxes.bin")),
Expand Down

0 comments on commit 6551690

Please sign in to comment.