use arc_swap::ArcSwapOption;
use std::sync::Arc;
#[cfg(target_os = "linux")]
const SUBPROCESS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
#[cfg(target_os = "linux")]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LinuxDesktop {
Kde,
Gnome,
Xfce,
Cinnamon,
Mate,
LxQt,
Budgie,
Hyprland,
Sway,
River,
Niri,
Wayfire,
CosmicDe,
Unknown,
}
#[cfg(target_os = "linux")]
pub(crate) fn xdg_current_desktop() -> String {
std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default()
}
#[cfg(target_os = "linux")]
#[must_use]
pub fn detect_linux_desktop() -> LinuxDesktop {
parse_linux_desktop(&xdg_current_desktop())
}
#[cfg(target_os = "linux")]
#[must_use]
pub fn parse_linux_desktop(xdg_current_desktop: &str) -> LinuxDesktop {
for component in xdg_current_desktop.split(':') {
match component {
"KDE" => return LinuxDesktop::Kde,
"Budgie" => return LinuxDesktop::Budgie,
"GNOME" => return LinuxDesktop::Gnome,
"XFCE" => return LinuxDesktop::Xfce,
"X-Cinnamon" | "Cinnamon" => return LinuxDesktop::Cinnamon,
"MATE" => return LinuxDesktop::Mate,
"LXQt" => return LinuxDesktop::LxQt,
"Hyprland" => return LinuxDesktop::Hyprland,
"sway" => return LinuxDesktop::Sway,
"river" => return LinuxDesktop::River,
"niri" => return LinuxDesktop::Niri,
"Wayfire" => return LinuxDesktop::Wayfire,
"COSMIC" => return LinuxDesktop::CosmicDe,
_ => {}
}
}
LinuxDesktop::Unknown
}
#[must_use]
pub fn system_is_dark() -> bool {
system().is_dark()
}
pub fn invalidate_caches() {
system().invalidate_all();
}
#[must_use]
pub fn detect_is_dark() -> bool {
detect_is_dark_inner()
}
#[cfg(target_os = "linux")]
const POLL_INTERVAL_CAP: std::time::Duration = std::time::Duration::from_millis(50);
#[cfg(target_os = "linux")]
fn poll_intervals() -> impl Iterator<Item = std::time::Duration> {
std::iter::successors(Some(std::time::Duration::from_millis(1)), |pause| {
Some(pause.saturating_mul(2).min(POLL_INTERVAL_CAP))
})
}
#[cfg(target_os = "linux")]
fn run_with_timeout(program: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
use std::io::Read;
use std::time::Instant;
let start = Instant::now();
let mut child = std::process::Command::new(program)
.args(args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.ok()?;
let mut intervals = poll_intervals();
loop {
match child.try_wait() {
Ok(Some(status)) if status.success() => {
let mut buf = String::new();
if let Some(mut stdout) = child.stdout.take() {
let _ = stdout.read_to_string(&mut buf);
}
return Some(buf);
}
Ok(Some(_)) => return None,
Ok(None) => {
let elapsed = start.elapsed();
if elapsed >= timeout {
if child.kill().is_ok() {
let _ = child.wait();
}
return None;
}
let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
}
Err(_) => return None,
}
}
}
#[cfg(target_os = "linux")]
fn run_gsettings_with_timeout(args: &[&str]) -> Option<String> {
let out = run_with_timeout("gsettings", args, SUBPROCESS_TIMEOUT)?;
let trimmed = out.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
fn read_xft_dpi() -> Option<f32> {
let out = run_with_timeout("xrdb", &["-query"], SUBPROCESS_TIMEOUT)?;
for line in out.lines() {
if let Some(rest) = line.strip_prefix("Xft.dpi:")
&& let Ok(dpi) = rest.trim().parse::<f32>()
&& dpi > 0.0
{
return Some(dpi);
}
}
None
}
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
fn detect_physical_dpi() -> Option<f32> {
let out = run_with_timeout("xrandr", &[], SUBPROCESS_TIMEOUT)?;
parse_xrandr_dpi(&out)
}
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
fn parse_xrandr_dpi(output: &str) -> Option<f32> {
let line = output
.lines()
.find(|l| l.contains(" connected") && l.contains("primary"))
.or_else(|| {
output
.lines()
.find(|l| l.contains(" connected") && !l.contains("disconnected"))
})?;
let res_token = line
.split_whitespace()
.find(|s| s.contains('x') && s.contains('+'))?;
let (w_str, rest) = res_token.split_once('x')?;
let h_str = rest.split('+').next()?;
let w_px: f32 = w_str.parse().ok()?;
let h_px: f32 = h_str.parse().ok()?;
let words: Vec<&str> = line.split_whitespace().collect();
let mut w_mm = None;
let mut h_mm = None;
for window in words.windows(3) {
let [prev, cur, next] = window else { continue };
if *cur == "x" {
w_mm = prev.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
h_mm = next.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
}
}
let w_mm = w_mm.filter(|&v| v > 0.0)?;
let h_mm = h_mm.filter(|&v| v > 0.0)?;
let h_dpi = w_px / (w_mm / 25.4);
let v_dpi = h_px / (h_mm / 25.4);
let avg = (h_dpi + v_dpi) / 2.0;
if avg > 0.0 { Some(avg) } else { None }
}
#[cfg(all(test, target_os = "linux", any(feature = "kde", feature = "portal")))]
#[allow(clippy::unwrap_used)]
mod xrandr_dpi_tests {
use super::parse_xrandr_dpi;
#[test]
fn primary_4k_display() {
let output = "Screen 0: minimum 16 x 16, current 3840 x 2160, maximum 32767 x 32767\n\
DP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 700mm x 390mm\n\
3840x2160 60.00*+\n";
let dpi = parse_xrandr_dpi(output).unwrap();
assert!((dpi - 140.0).abs() < 1.0, "expected ~140 DPI, got {dpi}");
}
#[test]
fn standard_1080p_display() {
let output = "DP-2 connected primary 1920x1080+0+0 (normal) 530mm x 300mm\n";
let dpi = parse_xrandr_dpi(output).unwrap();
assert!((dpi - 92.0).abs() < 1.0, "expected ~92 DPI, got {dpi}");
}
#[test]
fn no_primary_falls_back_to_first_connected() {
let output = "HDMI-1 connected 1920x1080+0+0 (normal) 480mm x 270mm\n\
DP-1 disconnected\n";
let dpi = parse_xrandr_dpi(output).unwrap();
assert!(dpi > 90.0 && dpi < 110.0, "expected ~100 DPI, got {dpi}");
}
#[test]
fn disconnected_only_returns_none() {
let output = "DP-1 disconnected\nHDMI-1 disconnected\n";
assert!(parse_xrandr_dpi(output).is_none());
}
#[test]
fn missing_physical_dimensions_returns_none() {
let output = "DP-1 connected primary 1920x1080+0+0 (normal)\n";
assert!(parse_xrandr_dpi(output).is_none());
}
#[test]
fn zero_mm_returns_none() {
let output = "DP-1 connected primary 1920x1080+0+0 (normal) 0mm x 0mm\n";
assert!(parse_xrandr_dpi(output).is_none());
}
#[test]
fn empty_output_returns_none() {
assert!(parse_xrandr_dpi("").is_none());
}
}
#[allow(unreachable_code)]
fn detect_system_font_dpi() -> f32 {
#[cfg(target_os = "macos")]
{
return 72.0;
}
#[cfg(all(target_os = "windows", feature = "windows"))]
{
return crate::windows::LOGICAL_DPI as f32;
}
#[cfg(all(target_os = "linux", feature = "kde"))]
{
if let Some(dpi) = read_kde_force_font_dpi() {
return dpi;
}
}
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
{
if let Some(dpi) = read_xft_dpi() {
return dpi;
}
if let Some(dpi) = detect_physical_dpi() {
return dpi;
}
}
96.0
}
#[cfg(all(target_os = "linux", feature = "kde"))]
fn read_kde_force_font_dpi() -> Option<f32> {
let path = crate::kde::kdeglobals_path();
if let Ok(content) = std::fs::read_to_string(&path) {
let mut ini = crate::kde::create_kde_parser();
if ini.read(content).is_ok()
&& let Some(dpi_str) = ini.get("General", "forceFontDPI")
&& let Ok(dpi) = dpi_str.trim().parse::<f32>()
&& dpi > 0.0
{
return Some(dpi);
}
}
if let Some(dpi_str) = crate::kde::read_kcmfontsrc_key("General", "forceFontDPI")
&& let Ok(dpi) = dpi_str.trim().parse::<f32>()
&& dpi > 0.0
{
return Some(dpi);
}
None
}
#[allow(unreachable_code)]
fn detect_is_dark_inner() -> bool {
#[cfg(target_os = "linux")]
{
if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
let lower = gtk_theme.to_lowercase();
if lower.ends_with(":dark") || lower.contains("-dark") {
return true;
}
}
#[cfg(feature = "kde")]
{
let de = parse_linux_desktop(&xdg_current_desktop());
if matches!(de, LinuxDesktop::Kde) {
let path = crate::kde::kdeglobals_path();
if let Ok(content) = std::fs::read_to_string(&path) {
let mut ini = crate::kde::create_kde_parser();
if ini.read(content).is_ok() {
return crate::kde::is_dark_theme(&ini);
}
}
}
}
if let Some(val) =
run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "color-scheme"])
{
if val.contains("prefer-dark") {
return true;
}
if val.contains("prefer-light") || val.contains("default") {
return false;
}
}
#[cfg(feature = "kde")]
{
let path = crate::kde::kdeglobals_path();
if let Ok(content) = std::fs::read_to_string(&path) {
let mut ini = crate::kde::create_kde_parser();
if ini.read(content).is_ok() {
return crate::kde::is_dark_theme(&ini);
}
}
}
let config_home = std::env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| {
let home = std::env::var("HOME").unwrap_or_default();
format!("{home}/.config")
});
let ini_path = format!("{config_home}/gtk-3.0/settings.ini");
if let Ok(content) = std::fs::read_to_string(&ini_path) {
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with("gtk-application-prefer-dark-theme")
&& let Some(val) = trimmed.split('=').nth(1)
&& (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
{
return true;
}
}
}
false
}
#[cfg(target_os = "macos")]
{
#[cfg(feature = "macos")]
{
use objc2_foundation::NSUserDefaults;
let defaults = NSUserDefaults::standardUserDefaults();
let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
if let Some(value) = defaults.stringForKey(key) {
return value.to_string().eq_ignore_ascii_case("dark");
}
return false;
}
#[cfg(not(feature = "macos"))]
{
if let Ok(output) = std::process::Command::new("defaults")
.args(["read", "-g", "AppleInterfaceStyle"])
.output()
&& output.status.success()
{
let val = String::from_utf8_lossy(&output.stdout);
return val.trim().eq_ignore_ascii_case("dark");
}
return false;
}
}
#[cfg(target_os = "windows")]
{
#[cfg(feature = "windows")]
{
let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
return false;
};
let Ok(fg) =
settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
else {
return false;
};
let luma = 0.299 * (fg.R as f32) + 0.587 * (fg.G as f32) + 0.114 * (fg.B as f32);
return luma > 128.0;
}
#[cfg(not(feature = "windows"))]
return false;
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
false
}
}
#[must_use]
pub fn prefers_reduced_motion() -> bool {
system().prefers_reduced_motion()
}
#[must_use]
pub fn detect_reduced_motion() -> bool {
detect_reduced_motion_inner()
}
#[allow(unreachable_code)]
fn detect_reduced_motion_inner() -> bool {
#[cfg(target_os = "linux")]
{
if let Some(val) =
run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "enable-animations"])
{
return val.trim() == "false";
}
false
}
#[cfg(target_os = "macos")]
{
#[cfg(feature = "macos")]
{
let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace();
return workspace.accessibilityDisplayShouldReduceMotion();
}
#[cfg(not(feature = "macos"))]
return false;
}
#[cfg(target_os = "windows")]
{
#[cfg(feature = "windows")]
{
let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
return false;
};
return match settings.AnimationsEnabled() {
Ok(enabled) => !enabled,
Err(_) => false,
};
}
#[cfg(not(feature = "windows"))]
return false;
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
false
}
}
pub struct DetectionContext {
is_dark: ArcSwapOption<bool>,
reduced_motion: ArcSwapOption<bool>,
icon_theme: ArcSwapOption<Result<String, crate::model::icons::IconThemeFailure>>,
#[cfg(target_os = "linux")]
linux_desktop: ArcSwapOption<LinuxDesktop>,
}
impl DetectionContext {
fn new() -> Self {
Self {
is_dark: ArcSwapOption::empty(),
reduced_motion: ArcSwapOption::empty(),
icon_theme: ArcSwapOption::empty(),
#[cfg(target_os = "linux")]
linux_desktop: ArcSwapOption::empty(),
}
}
#[must_use]
pub fn is_dark(&self) -> bool {
if let Some(v) = self.is_dark.load().as_deref() {
return *v;
}
let value = detect_is_dark_inner();
self.is_dark.store(Some(Arc::new(value)));
value
}
#[must_use]
pub fn prefers_reduced_motion(&self) -> bool {
if let Some(v) = self.reduced_motion.load().as_deref() {
return *v;
}
let value = detect_reduced_motion_inner();
self.reduced_motion.store(Some(Arc::new(value)));
value
}
pub fn icon_theme(&self) -> crate::Result<String> {
self.icon_theme_with(detect_icon_theme_inner)
}
fn icon_theme_with(
&self,
detect: impl FnOnce() -> Result<String, crate::model::icons::IconThemeFailure>,
) -> crate::Result<String> {
let outcome = match self.icon_theme.load_full() {
Some(cached) => cached,
None => {
let detected = Arc::new(detect());
self.icon_theme.store(Some(Arc::clone(&detected)));
detected
}
};
match outcome.as_ref() {
Ok(theme) => Ok(theme.clone()),
Err(failure) => Err(failure.to_error()),
}
}
#[cfg(target_os = "linux")]
#[must_use]
pub fn linux_desktop(&self) -> LinuxDesktop {
if let Some(v) = self.linux_desktop.load().as_deref() {
return *v;
}
let value = detect_linux_desktop();
self.linux_desktop.store(Some(Arc::new(value)));
value
}
pub fn invalidate_is_dark(&self) {
self.is_dark.store(None);
}
pub fn invalidate_reduced_motion(&self) {
self.reduced_motion.store(None);
}
pub fn invalidate_icon_theme(&self) {
self.icon_theme.store(None);
}
#[cfg(target_os = "linux")]
pub fn invalidate_linux_desktop(&self) {
self.linux_desktop.store(None);
}
pub fn invalidate_all(&self) {
self.invalidate_is_dark();
self.invalidate_reduced_motion();
self.invalidate_icon_theme();
#[cfg(target_os = "linux")]
self.invalidate_linux_desktop();
}
}
pub fn system() -> &'static DetectionContext {
static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
INSTANCE.get_or_init(DetectionContext::new)
}
fn detect_icon_theme_inner() -> Result<String, crate::model::icons::IconThemeFailure> {
crate::model::icons::detect_icon_theme_outcome()
}
#[cfg(all(target_os = "linux", feature = "portal"))]
pub(crate) fn gsettings_get(schema: &str, key: &str) -> Option<String> {
run_gsettings_with_timeout(&["get", schema, key])
}
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
pub(crate) fn xft_dpi() -> Option<f32> {
read_xft_dpi()
}
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
pub(crate) fn physical_dpi() -> Option<f32> {
detect_physical_dpi()
}
pub(crate) fn system_font_dpi() -> f32 {
detect_system_font_dpi()
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod reduced_motion_tests {
use super::*;
#[test]
fn prefers_reduced_motion_smoke_test() {
let _result = prefers_reduced_motion();
}
#[cfg(target_os = "linux")]
#[test]
fn detect_reduced_motion_inner_linux() {
let result = detect_reduced_motion_inner();
let _ = result;
}
#[cfg(target_os = "macos")]
#[test]
fn detect_reduced_motion_inner_macos() {
let result = detect_reduced_motion_inner();
let _ = result;
}
#[cfg(target_os = "windows")]
#[test]
fn detect_reduced_motion_inner_windows() {
let result = detect_reduced_motion_inner();
let _ = result;
}
}
#[cfg(test)]
mod detection_context_tests {
use super::*;
#[test]
fn system_returns_same_instance() {
let a = system() as *const DetectionContext;
let b = system() as *const DetectionContext;
assert_eq!(a, b);
}
#[test]
fn is_dark_caches_result() {
let ctx = DetectionContext::new();
let first = ctx.is_dark();
let second = ctx.is_dark();
assert_eq!(first, second);
}
#[test]
fn invalidate_is_dark_clears_cache() {
let ctx = DetectionContext::new();
let _ = ctx.is_dark(); ctx.invalidate_is_dark();
let _ = ctx.is_dark();
}
#[test]
fn prefers_reduced_motion_caches_result() {
let ctx = DetectionContext::new();
let first = ctx.prefers_reduced_motion();
let second = ctx.prefers_reduced_motion();
assert_eq!(first, second);
}
#[test]
fn invalidate_all_clears_all_caches() {
let ctx = DetectionContext::new();
let _ = ctx.is_dark();
let _ = ctx.prefers_reduced_motion();
let _ = ctx.icon_theme();
ctx.invalidate_all();
let _ = ctx.is_dark();
let _ = ctx.prefers_reduced_motion();
let _ = ctx.icon_theme();
}
fn undetected() -> Result<String, crate::model::icons::IconThemeFailure> {
Err(crate::model::icons::IconThemeFailure::for_tests(
"the test's failing detection",
))
}
#[test]
fn a_failed_icon_theme_detection_is_cached_and_reported() {
let ctx = DetectionContext::new();
let runs = std::cell::Cell::new(0);
let detect = || {
runs.set(runs.get() + 1);
undetected()
};
let first = ctx.icon_theme_with(detect);
let second = ctx.icon_theme_with(detect);
assert_eq!(runs.get(), 1, "a failed detection ran again");
for outcome in [first, second] {
match outcome {
Ok(name) => panic!("a failed detection gave the theme {name}"),
Err(e) => assert!(
e.to_string().contains("the test's failing detection"),
"got: {e}"
),
}
}
}
#[test]
fn invalidate_icon_theme_clears_a_cached_failure() {
let ctx = DetectionContext::new();
assert!(ctx.icon_theme_with(undetected).is_err());
ctx.invalidate_icon_theme();
let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
assert_eq!(theme.ok().as_deref(), Some("breeze"));
}
#[test]
fn invalidate_all_clears_a_cached_failure() {
let ctx = DetectionContext::new();
assert!(ctx.icon_theme_with(undetected).is_err());
ctx.invalidate_all();
let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
assert_eq!(theme.ok().as_deref(), Some("breeze"));
}
#[cfg(target_os = "linux")]
#[test]
fn linux_desktop_caches_result() {
let ctx = DetectionContext::new();
let first = ctx.linux_desktop();
let second = ctx.linux_desktop();
assert_eq!(first, second);
}
#[cfg(target_os = "linux")]
#[test]
fn invalidate_linux_desktop_clears_cache() {
let ctx = DetectionContext::new();
let _ = ctx.linux_desktop();
ctx.invalidate_linux_desktop();
let _ = ctx.linux_desktop(); }
}
#[cfg(all(test, target_os = "linux"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod subprocess_tests {
use super::*;
use std::path::PathBuf;
use std::time::{Duration, Instant};
fn on_path(program: &str) -> bool {
std::env::var_os("PATH")
.is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
}
#[test]
fn poll_intervals_double_from_1_ms_up_to_50_ms() {
let intervals: Vec<Duration> = poll_intervals().take(10).collect();
let expected: Vec<Duration> = [1, 2, 4, 8, 16, 32, 50, 50, 50, 50]
.into_iter()
.map(Duration::from_millis)
.collect();
assert_eq!(intervals, expected);
}
#[test]
fn run_with_timeout_returns_stdout_of_a_successful_command() {
if !on_path("echo") {
eprintln!("skipped: echo is not installed");
return;
}
let out = run_with_timeout("echo", &["hi"], SUBPROCESS_TIMEOUT);
assert_eq!(out.as_deref().map(str::trim), Some("hi"));
}
#[test]
fn run_with_timeout_returns_none_for_a_failing_command() {
if !on_path("false") {
eprintln!("skipped: false is not installed");
return;
}
assert_eq!(run_with_timeout("false", &[], SUBPROCESS_TIMEOUT), None);
}
#[test]
fn run_with_timeout_returns_none_for_a_missing_program() {
assert_eq!(
run_with_timeout("nt-test-no-such-program", &[], SUBPROCESS_TIMEOUT),
None
);
}
#[test]
fn run_with_timeout_returns_the_empty_stdout_of_a_quiet_command() {
if !on_path("true") {
eprintln!("skipped: true is not installed");
return;
}
let start = Instant::now();
assert_eq!(
run_with_timeout("true", &[], SUBPROCESS_TIMEOUT).as_deref(),
Some("")
);
eprintln!("`true` ran in {:?}", start.elapsed());
}
#[test]
fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
if !on_path("sleep") {
eprintln!("skipped: sleep is not installed");
return;
}
let seconds = format!("5.{}", std::process::id());
let start = Instant::now();
let out = run_with_timeout("sleep", &[&seconds], Duration::from_millis(100));
let elapsed = start.elapsed();
assert_eq!(out, None);
assert!(elapsed < Duration::from_secs(1), "took {elapsed:?}");
let cmdline = format!("sleep\0{seconds}\0");
let still_running: Vec<PathBuf> = std::fs::read_dir("/proc")
.unwrap()
.flatten()
.map(|entry| entry.path().join("cmdline"))
.filter(|path| std::fs::read(path).is_ok_and(|bytes| bytes == cmdline.as_bytes()))
.collect();
assert!(still_running.is_empty(), "not killed: {still_running:?}");
}
}