use arc_swap::ArcSwapOption;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
mod icon_theme;
pub(crate) use icon_theme::IconThemeFailure;
pub use icon_theme::{detect_icon_theme, system_icon_set, system_icon_theme};
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) 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
}
#[cfg(target_os = "linux")]
pub(crate) fn refine_linux_desktop(
raw: LinuxDesktop,
portal_backend: Option<LinuxDesktop>,
kdeglobals_exists: impl FnOnce() -> bool,
) -> LinuxDesktop {
refine_desktop(raw, portal_backend, kdeglobals_exists).desktop
}
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RefinedDesktop {
pub(crate) desktop: LinuxDesktop,
pub(crate) by_kdeglobals: bool,
}
#[cfg(target_os = "linux")]
pub(crate) fn refine_desktop(
raw: LinuxDesktop,
portal_backend: Option<LinuxDesktop>,
kdeglobals_exists: impl FnOnce() -> bool,
) -> RefinedDesktop {
let (desktop, by_kdeglobals) = match (raw, portal_backend) {
(LinuxDesktop::Unknown, Some(backend)) => (backend, false),
(LinuxDesktop::Unknown, None) if kdeglobals_exists() => (LinuxDesktop::Kde, true),
(other, _) => (other, false),
};
RefinedDesktop {
desktop,
by_kdeglobals,
}
}
#[cfg(target_os = "linux")]
fn kdeglobals_exists() -> bool {
#[cfg(feature = "kde")]
{
crate::kde::kdeglobals_path().is_some_and(|path| path.exists())
}
#[cfg(not(feature = "kde"))]
{
false
}
}
#[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(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const POLL_INTERVAL_CAP: std::time::Duration = std::time::Duration::from_millis(50);
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
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(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn run_with_timeout(
program: &str,
args: &[&str],
timeout: std::time::Duration,
) -> std::io::Result<std::process::Output> {
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::time::Instant;
fn kill_and_reap(child: &mut Child) {
if child.kill().is_ok() {
let _ = child.wait();
}
}
let timed_out = || {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
format!("timed out after {timeout:?}"),
)
};
let start = Instant::now();
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let readers = read_on_a_thread(child.stdout.take())
.and_then(|stdout| Ok((stdout, read_on_a_thread(child.stderr.take())?)));
let (stdout, stderr) = match readers {
Ok(readers) => readers,
Err(e) => {
kill_and_reap(&mut child);
return Err(e);
}
};
let mut intervals = poll_intervals();
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {
let elapsed = start.elapsed();
if elapsed >= timeout {
kill_and_reap(&mut child);
return Err(timed_out());
}
let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
}
Err(e) => {
kill_and_reap(&mut child);
return Err(e);
}
}
};
let received = |reader: Receiver<Vec<u8>>| {
reader
.recv_timeout(timeout.saturating_sub(start.elapsed()))
.map_err(|e| match e {
RecvTimeoutError::Timeout => timed_out(),
RecvTimeoutError::Disconnected => {
std::io::Error::other("the output reader stopped without a result")
}
})
};
Ok(std::process::Output {
status,
stdout: received(stdout)?,
stderr: received(stderr)?,
})
}
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn read_on_a_thread(
pipe: Option<impl std::io::Read + Send + 'static>,
) -> std::io::Result<std::sync::mpsc::Receiver<Vec<u8>>> {
let (sender, receiver) = std::sync::mpsc::channel();
match pipe {
Some(mut pipe) => {
std::thread::Builder::new()
.name("native-theme-subprocess-output".to_string())
.spawn(move || {
let mut read = Vec::new();
let _ = pipe.read_to_end(&mut read);
let _ = sender.send(read);
})?;
}
None => {
let _ = sender.send(Vec::new());
}
}
Ok(receiver)
}
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn stdout_with_timeout(
program: &str,
args: &[&str],
timeout: std::time::Duration,
) -> Option<String> {
let output = run_with_timeout(program, args, timeout).ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
}
#[cfg(target_os = "linux")]
pub(crate) fn xdg_config_home() -> Option<std::path::PathBuf> {
xdg_config_home_from(
std::env::var_os("XDG_CONFIG_HOME").as_deref(),
std::env::var_os("HOME").as_deref(),
)
}
#[cfg(target_os = "linux")]
fn xdg_config_home_from(
var: Option<&std::ffi::OsStr>,
home: Option<&std::ffi::OsStr>,
) -> Option<std::path::PathBuf> {
var.map(std::path::PathBuf::from)
.filter(|dir| dir.is_absolute())
.or_else(|| {
home.filter(|home| !home.is_empty())
.map(|home| std::path::Path::new(home).join(".config"))
})
}
#[cfg(target_os = "linux")]
pub(crate) const CONFIG_HOME_UNRESOLVED: &str = "the config directory is unresolved: \
$XDG_CONFIG_HOME is not an absolute path and $HOME is unset or empty";
#[cfg(target_os = "linux")]
pub(crate) fn gsettings_get(
schema: &str,
key: &str,
timeout: std::time::Duration,
) -> Option<String> {
let out = stdout_with_timeout("gsettings", &["get", schema, key], 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 = stdout_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 = stdout_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());
}
}
#[cfg(all(target_os = "linux", feature = "portal"))]
pub(crate) const GNOME_FONT_DPI: f32 = 96.0;
#[cfg(all(target_os = "linux", feature = "portal"))]
fn desktop_font_dpi(desktop: LinuxDesktop) -> Option<f32> {
matches!(desktop, LinuxDesktop::Gnome | LinuxDesktop::Budgie).then_some(GNOME_FONT_DPI)
}
#[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 = "portal"))]
{
if let Some(dpi) = desktop_font_dpi(system().refined_linux_desktop_sync()) {
return dpi;
}
}
#[cfg(all(target_os = "linux", feature = "kde"))]
{
if let Some(dpi) = kde_force_font_dpi(session_type().as_deref(), || {
crate::kde::read_kcmfonts_key("General", "forceFontDPI")
}) {
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", any(feature = "kde", feature = "portal")))]
pub(crate) fn session_type() -> Option<String> {
std::env::var("XDG_SESSION_TYPE").ok()
}
#[cfg(all(target_os = "linux", feature = "kde"))]
pub(crate) fn reads_force_font_dpi(session_type: Option<&str>) -> bool {
session_type == Some("x11")
}
#[cfg(all(target_os = "linux", feature = "kde"))]
pub(crate) fn parse_force_font_dpi(value: &str) -> Option<f32> {
let dpi = value.trim().parse::<u32>().ok()?;
(dpi > 0).then_some(dpi as f32)
}
#[cfg(all(target_os = "linux", feature = "kde"))]
fn kde_force_font_dpi(
session_type: Option<&str>,
kcmfonts: impl FnOnce() -> Option<String>,
) -> Option<f32> {
if !reads_force_font_dpi(session_type) {
return None;
}
kcmfonts().as_deref().and_then(parse_force_font_dpi)
}
#[cfg(target_os = "linux")]
pub(crate) fn color_scheme_is_dark(
portal: Option<bool>,
gsetting: impl FnOnce(&str, &str) -> Option<String>,
) -> Option<bool> {
if portal.is_some() {
return portal;
}
let val = gsetting("org.gnome.desktop.interface", "color-scheme")?;
if val.contains("prefer-dark") {
Some(true)
} else if val.contains("prefer-light") || val.contains("default") {
Some(false)
} else {
None
}
}
#[cfg(target_os = "linux")]
fn desktop_is_dark(
detection: &DetectionContext,
kdeglobals: impl FnOnce() -> Option<bool>,
gsettings: impl FnOnce() -> Option<bool>,
) -> Option<bool> {
if detection.refined_linux_desktop_sync() == LinuxDesktop::Kde {
kdeglobals().or_else(gsettings)
} else {
gsettings().or_else(kdeglobals)
}
}
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;
}
}
if let Some(dark) = desktop_is_dark(
system(),
|| {
#[cfg(feature = "kde")]
{
crate::kde::kdeglobals_is_dark()
}
#[cfg(not(feature = "kde"))]
{
None
}
},
|| {
color_scheme_is_dark(None, |schema, key| {
gsettings_get(schema, key, SUBPROCESS_TIMEOUT)
})
},
) {
return dark;
}
if let Some(content) = xdg_config_home()
.and_then(|dir| std::fs::read_to_string(dir.join("gtk-3.0/settings.ini")).ok())
{
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");
defaults
.stringForKey(key)
.is_some_and(|value| value.to_string().eq_ignore_ascii_case("dark"))
}
#[cfg(not(feature = "macos"))]
{
stdout_with_timeout(
"defaults",
&["read", "-g", "AppleInterfaceStyle"],
SUBPROCESS_TIMEOUT,
)
.is_some_and(|value| value.trim().eq_ignore_ascii_case("dark"))
}
}
#[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;
};
crate::windows::is_dark_mode(&crate::windows::win_color_to_rgba(fg))
}
#[cfg(not(feature = "windows"))]
{
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()
}
#[must_use]
pub fn accessibility_preferences() -> crate::AccessibilityPreferences {
system().accessibility_preferences()
}
#[cfg(target_os = "linux")]
pub(crate) fn gnome_reduce_motion(
portal: Option<bool>,
gsetting: impl FnOnce(&str, &str) -> Option<String>,
) -> Option<bool> {
if portal.is_some() {
return portal;
}
let enabled = gsetting("org.gnome.desktop.interface", "enable-animations")?;
enabled.trim().parse::<bool>().ok().map(|enabled| !enabled)
}
#[cfg(target_os = "linux")]
fn desktop_reduce_motion(
desktop: LinuxDesktop,
kdeglobals: impl FnOnce() -> Option<bool>,
portal: impl FnOnce() -> Option<bool>,
gsetting: impl FnOnce(&str, &str) -> Option<String>,
) -> bool {
match desktop {
LinuxDesktop::Kde => kdeglobals().or_else(|| gnome_reduce_motion(None, gsetting)),
LinuxDesktop::Gnome | LinuxDesktop::Budgie => gnome_reduce_motion(portal(), gsetting),
_ => gnome_reduce_motion(None, gsetting),
}
.unwrap_or(false)
}
fn detect_reduced_motion_inner() -> bool {
#[cfg(target_os = "linux")]
{
desktop_reduce_motion(
system().refined_linux_desktop_sync(),
|| {
#[cfg(feature = "kde")]
{
Some(crate::kde::kdeglobals_reduce_motion())
}
#[cfg(not(feature = "kde"))]
{
None
}
},
|| {
#[cfg(feature = "portal")]
{
pollster::block_on(crate::gnome::portal_reduce_motion())
}
#[cfg(not(feature = "portal"))]
{
None
}
},
|schema, key| gsettings_get(schema, key, SUBPROCESS_TIMEOUT),
)
}
#[cfg(target_os = "macos")]
{
#[cfg(feature = "macos")]
{
crate::macos::reduce_motion()
}
#[cfg(not(feature = "macos"))]
{
false
}
}
#[cfg(target_os = "windows")]
{
#[cfg(feature = "windows")]
{
crate::windows::read_reduce_motion().unwrap_or(false)
}
#[cfg(not(feature = "windows"))]
{
false
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
false
}
}
struct Stamped<T> {
generation: u64,
value: T,
}
struct CacheSlot<T> {
value: ArcSwapOption<Stamped<T>>,
generation: AtomicU64,
}
pub(crate) struct CacheFill<T> {
generation: u64,
seen: Option<Arc<Stamped<T>>>,
}
impl<T> CacheFill<T> {
fn cached(&self) -> Option<&T> {
self.seen
.as_deref()
.filter(|entry| entry.generation == self.generation)
.map(|entry| &entry.value)
}
}
impl<T> CacheSlot<T> {
fn empty() -> Self {
Self {
value: ArcSwapOption::empty(),
generation: AtomicU64::new(0),
}
}
fn begin_fill(&self) -> CacheFill<T> {
let generation = self.generation.load(Ordering::Acquire);
CacheFill {
generation,
seen: self.value.load_full(),
}
}
fn finish_fill(&self, fill: CacheFill<T>, value: T) {
if self.generation.load(Ordering::Acquire) != fill.generation {
return;
}
let stamped = Arc::new(Stamped {
generation: fill.generation,
value,
});
let _ = self.value.compare_and_swap(&fill.seen, Some(stamped));
}
fn get_or_fill(&self, detect: impl FnOnce() -> T) -> T
where
T: Clone,
{
let fill = self.begin_fill();
if let Some(value) = fill.cached() {
return value.clone();
}
let value = detect();
self.finish_fill(fill, value.clone());
value
}
#[cfg(any(test, target_os = "linux"))]
fn get(&self) -> Option<T>
where
T: Clone,
{
self.begin_fill().cached().cloned()
}
fn invalidate(&self) {
self.value.store(None);
self.generation.fetch_add(1, Ordering::Release);
}
}
pub struct DetectionContext {
is_dark: CacheSlot<bool>,
reduced_motion: CacheSlot<bool>,
reader_accessibility: CacheSlot<crate::AccessibilityPreferences>,
icon_theme: CacheSlot<Result<String, IconThemeFailure>>,
#[cfg(target_os = "linux")]
linux_desktop: CacheSlot<LinuxDesktop>,
#[cfg(target_os = "linux")]
refined_linux_desktop: CacheSlot<RefinedDesktop>,
font_dpi: CacheSlot<f32>,
}
impl DetectionContext {
pub(crate) fn new() -> Self {
Self {
is_dark: CacheSlot::empty(),
reduced_motion: CacheSlot::empty(),
reader_accessibility: CacheSlot::empty(),
icon_theme: CacheSlot::empty(),
#[cfg(target_os = "linux")]
linux_desktop: CacheSlot::empty(),
#[cfg(target_os = "linux")]
refined_linux_desktop: CacheSlot::empty(),
font_dpi: CacheSlot::empty(),
}
}
#[must_use]
pub fn is_dark(&self) -> bool {
self.is_dark.get_or_fill(detect_is_dark_inner)
}
#[must_use]
pub fn prefers_reduced_motion(&self) -> bool {
self.reduced_motion.get_or_fill(detect_reduced_motion_inner)
}
#[must_use]
pub fn accessibility_preferences(&self) -> crate::AccessibilityPreferences {
self.reader_accessibility_with(|| {
pollster::block_on(crate::pipeline::reader_accessibility())
})
}
pub(crate) fn reader_accessibility_with(
&self,
read: impl FnOnce() -> crate::AccessibilityPreferences,
) -> crate::AccessibilityPreferences {
self.reader_accessibility.get_or_fill(read)
}
pub(crate) fn begin_reader_accessibility(&self) -> CacheFill<crate::AccessibilityPreferences> {
self.reader_accessibility.begin_fill()
}
pub(crate) fn store_reader_accessibility(
&self,
fill: CacheFill<crate::AccessibilityPreferences>,
prefs: crate::AccessibilityPreferences,
) {
self.reader_accessibility.finish_fill(fill, prefs);
}
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, IconThemeFailure>,
) -> crate::Result<String> {
self.icon_theme
.get_or_fill(detect)
.map_err(|failure| failure.to_error())
}
#[cfg(target_os = "linux")]
#[must_use]
pub fn linux_desktop(&self) -> LinuxDesktop {
self.linux_desktop.get_or_fill(detect_linux_desktop)
}
#[cfg(target_os = "linux")]
pub(crate) async fn refined_linux_desktop(&self) -> RefinedDesktop {
let fill = self.refined_linux_desktop.begin_fill();
if let Some(v) = fill.cached() {
return *v;
}
let raw = self.linux_desktop();
#[cfg(feature = "portal")]
let portal_backend = if raw == LinuxDesktop::Unknown {
crate::gnome::detect_portal_backend().await
} else {
None
};
#[cfg(not(feature = "portal"))]
let portal_backend = None;
let refined = refine_desktop(raw, portal_backend, kdeglobals_exists);
let without_portal = refine_linux_desktop(raw, None, kdeglobals_exists);
self.finish_refined_desktop(fill, refined, without_portal);
refined
}
#[cfg(target_os = "linux")]
fn finish_refined_desktop(
&self,
fill: CacheFill<RefinedDesktop>,
refined: RefinedDesktop,
without_portal: LinuxDesktop,
) {
self.refined_linux_desktop.finish_fill(fill, refined);
if refined.desktop != without_portal {
self.invalidate_font_dpi();
self.invalidate_icon_theme();
self.invalidate_is_dark();
self.invalidate_reduced_motion();
}
}
#[cfg(target_os = "linux")]
#[must_use]
pub fn refined_linux_desktop_sync(&self) -> LinuxDesktop {
if let Some(v) = self.refined_linux_desktop.get() {
return v.desktop;
}
refine_linux_desktop(self.linux_desktop(), None, kdeglobals_exists)
}
pub(crate) fn font_dpi(&self) -> f32 {
self.font_dpi_with(detect_system_font_dpi)
}
fn font_dpi_with(&self, detect: impl FnOnce() -> f32) -> f32 {
self.font_dpi.get_or_fill(detect)
}
pub fn invalidate_is_dark(&self) {
self.is_dark.invalidate();
}
pub fn invalidate_reduced_motion(&self) {
self.reduced_motion.invalidate();
}
pub fn invalidate_accessibility_preferences(&self) {
self.reader_accessibility.invalidate();
}
pub fn invalidate_icon_theme(&self) {
self.icon_theme.invalidate();
}
pub fn invalidate_font_dpi(&self) {
self.font_dpi.invalidate();
}
#[cfg(target_os = "linux")]
pub fn invalidate_linux_desktop(&self) {
self.linux_desktop.invalidate();
self.refined_linux_desktop.invalidate();
}
pub fn invalidate_all(&self) {
self.invalidate_is_dark();
self.invalidate_reduced_motion();
self.invalidate_accessibility_preferences();
self.invalidate_icon_theme();
#[cfg(target_os = "linux")]
self.invalidate_linux_desktop();
self.invalidate_font_dpi();
}
}
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, IconThemeFailure> {
icon_theme::detect_icon_theme_outcome()
}
pub(crate) fn system_font_dpi() -> f32 {
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 = "linux")]
fn animations<'a>(
enabled: &'static str,
asked: &'a std::cell::Cell<u32>,
) -> impl FnOnce(&str, &str) -> Option<String> + 'a {
move |schema, key| {
asked.set(asked.get() + 1);
((schema, key) == ("org.gnome.desktop.interface", "enable-animations"))
.then(|| enabled.to_string())
}
}
#[cfg(target_os = "linux")]
#[test]
fn kde_reduced_motion_is_kdeglobals_not_gsettings() {
let asked = std::cell::Cell::new(0);
let portal = || -> Option<bool> { panic!("KDE does not ask the portal") };
assert!(desktop_reduce_motion(
LinuxDesktop::Kde,
|| Some(true),
portal,
animations("true", &asked)
));
assert!(!desktop_reduce_motion(
LinuxDesktop::Kde,
|| Some(false),
portal,
animations("false", &asked)
));
assert_eq!(asked.get(), 0);
assert!(desktop_reduce_motion(
LinuxDesktop::Kde,
|| None,
portal,
animations("false", &asked)
));
assert_eq!(asked.get(), 1);
}
#[cfg(target_os = "linux")]
#[test]
fn gnome_reduced_motion_is_the_portal_then_gsettings() {
let asked = std::cell::Cell::new(0);
let kdeglobals = || -> Option<bool> { panic!("GNOME does not read kdeglobals") };
for desktop in [LinuxDesktop::Gnome, LinuxDesktop::Budgie] {
assert!(desktop_reduce_motion(
desktop,
kdeglobals,
|| Some(true),
animations("true", &asked)
));
assert!(!desktop_reduce_motion(
desktop,
kdeglobals,
|| Some(false),
animations("false", &asked)
));
assert_eq!(asked.get(), 0);
assert!(desktop_reduce_motion(
desktop,
kdeglobals,
|| None,
animations("false", &asked)
));
assert_eq!(asked.get(), 1);
asked.set(0);
}
}
#[cfg(target_os = "linux")]
#[test]
fn other_desktops_reduced_motion_is_gsettings() {
let asked = std::cell::Cell::new(0);
assert!(desktop_reduce_motion(
LinuxDesktop::Xfce,
|| -> Option<bool> { panic!("XFCE does not read kdeglobals") },
|| -> Option<bool> { panic!("XFCE does not ask the portal") },
animations("false", &asked)
));
assert!(!desktop_reduce_motion(
LinuxDesktop::Unknown,
|| None,
|| None,
|_, _| None
));
}
#[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(all(test, target_os = "linux", feature = "kde"))]
mod force_font_dpi_tests {
use super::*;
#[test]
fn force_font_dpi_is_a_positive_u32() {
assert_eq!(parse_force_font_dpi("120"), Some(120.0));
assert_eq!(parse_force_font_dpi(" 144 "), Some(144.0));
for value in ["0", "inf", "-inf", "NaN", "-96", "96.5", "1e3", ""] {
assert_eq!(parse_force_font_dpi(value), None, "forceFontDPI={value}");
}
}
#[test]
fn only_an_x11_session_reads_force_font_dpi() {
assert!(reads_force_font_dpi(Some("x11")));
for session in [Some("wayland"), Some("tty"), Some(""), None] {
assert!(!reads_force_font_dpi(session), "{session:?}");
}
}
#[test]
fn a_wayland_session_ignores_force_font_dpi() {
let reads = std::cell::Cell::new(0);
let file = || {
reads.set(reads.get() + 1);
Some("120".to_string())
};
for session in [Some("wayland"), None] {
assert_eq!(kde_force_font_dpi(session, file), None, "{session:?}");
}
assert_eq!(reads.get(), 0, "a file was read off X11");
}
#[test]
fn an_x11_session_takes_a_valid_kcmfonts_key() {
assert_eq!(
kde_force_font_dpi(Some("x11"), || Some("144".into())),
Some(144.0)
);
for kcmfonts in [None, Some("0"), Some("inf")] {
assert_eq!(
kde_force_font_dpi(Some("x11"), || kcmfonts.map(String::from)),
None,
"kcmfonts {kcmfonts:?}"
);
}
}
}
#[cfg(test)]
mod cache_slot_tests {
use super::*;
#[test]
fn a_value_detected_across_an_invalidation_is_not_cached() {
let slot = CacheSlot::empty();
assert!(slot.get_or_fill(|| {
slot.invalidate();
true
}));
assert!(slot.get().is_none());
assert!(!slot.get_or_fill(|| false));
assert_eq!(slot.get(), Some(false));
}
#[test]
fn an_entry_stamped_before_an_invalidation_is_not_returned() {
let slot = CacheSlot::empty();
let fill = slot.begin_fill();
slot.invalidate();
let stale = Arc::new(Stamped {
generation: fill.generation,
value: true,
});
let _ = slot.value.compare_and_swap(&fill.seen, Some(stale));
assert!(slot.get().is_none());
assert!(!slot.get_or_fill(|| false));
assert_eq!(slot.get(), Some(false));
}
#[test]
fn a_fill_does_not_replace_a_value_stored_since_it_began() {
let slot = CacheSlot::empty();
let slow = slot.begin_fill();
let _ = slot.get_or_fill(|| 2);
slot.finish_fill(slow, 1);
assert_eq!(slot.get(), Some(2));
}
}
#[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);
}
fn filled() -> DetectionContext {
let ctx = DetectionContext::new();
ctx.is_dark.get_or_fill(|| true);
ctx.reduced_motion.get_or_fill(|| true);
ctx.reader_accessibility
.get_or_fill(crate::AccessibilityPreferences::default);
let _ = ctx.icon_theme.get_or_fill(|| Ok("breeze".to_string()));
#[cfg(target_os = "linux")]
ctx.linux_desktop.get_or_fill(|| LinuxDesktop::Kde);
#[cfg(target_os = "linux")]
ctx.refined_linux_desktop.get_or_fill(|| RefinedDesktop {
desktop: LinuxDesktop::Kde,
by_kdeglobals: false,
});
ctx.font_dpi.get_or_fill(|| 120.0);
ctx
}
#[test]
fn invalidate_all_empties_every_slot() {
let ctx = filled();
ctx.invalidate_all();
let DetectionContext {
is_dark,
reduced_motion,
reader_accessibility,
icon_theme,
#[cfg(target_os = "linux")]
linux_desktop,
#[cfg(target_os = "linux")]
refined_linux_desktop,
font_dpi,
} = &ctx;
assert!(is_dark.get().is_none(), "is_dark");
assert!(reduced_motion.get().is_none(), "reduced_motion");
assert!(reader_accessibility.get().is_none(), "reader_accessibility");
assert!(icon_theme.get().is_none(), "icon_theme");
#[cfg(target_os = "linux")]
assert!(linux_desktop.get().is_none(), "linux_desktop");
#[cfg(target_os = "linux")]
assert!(
refined_linux_desktop.get().is_none(),
"refined_linux_desktop"
);
assert!(font_dpi.get().is_none(), "font_dpi");
}
#[test]
fn invalidate_is_dark_empties_only_is_dark() {
let ctx = filled();
ctx.invalidate_is_dark();
assert_eq!(ctx.is_dark.get(), None);
assert_eq!(ctx.font_dpi.get(), Some(120.0));
}
#[test]
fn font_dpi_is_cached_until_invalidate_all() {
let ctx = DetectionContext::new();
let runs = std::cell::Cell::new(0);
let detect = |dpi| {
runs.set(runs.get() + 1);
dpi
};
assert_eq!(ctx.font_dpi_with(|| detect(120.0)), 120.0);
assert_eq!(ctx.font_dpi_with(|| detect(96.0)), 120.0);
assert_eq!(runs.get(), 1, "a cached font DPI was detected again");
ctx.invalidate_all();
assert_eq!(ctx.font_dpi_with(|| detect(96.0)), 96.0);
assert_eq!(runs.get(), 2);
}
fn undetected() -> Result<String, IconThemeFailure> {
Err(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"));
}
fn scaled_by(text_scaling_factor: f32) -> crate::AccessibilityPreferences {
crate::AccessibilityPreferences {
text_scaling_factor,
..crate::AccessibilityPreferences::default()
}
}
#[test]
fn a_second_accessibility_read_does_not_run_the_reader() {
let ctx = DetectionContext::new();
let runs = std::cell::Cell::new(0);
let read = || {
runs.set(runs.get() + 1);
scaled_by(1.5)
};
assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
assert_eq!(runs.get(), 1, "the second call ran the reader");
}
#[test]
fn a_stored_accessibility_block_is_returned_until_invalidated() {
let ctx = DetectionContext::new();
let runs = std::cell::Cell::new(0);
let read = || {
runs.set(runs.get() + 1);
scaled_by(1.25)
};
ctx.store_reader_accessibility(ctx.begin_reader_accessibility(), scaled_by(2.0));
assert_eq!(ctx.reader_accessibility_with(read), scaled_by(2.0));
assert_eq!(runs.get(), 0, "a stored block ran the reader");
ctx.invalidate_all();
assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
assert_eq!(runs.get(), 1);
ctx.invalidate_accessibility_preferences();
assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
assert_eq!(runs.get(), 2);
}
#[test]
fn a_font_dpi_detected_across_an_invalidation_is_not_cached() {
let ctx = DetectionContext::new();
let stale = ctx.font_dpi_with(|| {
ctx.invalidate_font_dpi();
120.0
});
assert_eq!(stale, 120.0);
assert_eq!(ctx.font_dpi_with(|| 96.0), 96.0);
}
#[test]
fn an_icon_theme_detected_across_an_invalidation_is_not_cached() {
let ctx = DetectionContext::new();
let stale = ctx.icon_theme_with(|| {
ctx.invalidate_icon_theme();
Ok("breeze".to_string())
});
assert_eq!(stale.ok().as_deref(), Some("breeze"));
let theme = ctx.icon_theme_with(|| Ok("Adwaita".to_string()));
assert_eq!(theme.ok().as_deref(), Some("Adwaita"));
}
#[test]
fn an_accessibility_block_read_across_an_invalidation_is_not_cached() {
let ctx = DetectionContext::new();
let stale = ctx.reader_accessibility_with(|| {
ctx.invalidate_all();
scaled_by(1.5)
});
assert_eq!(stale, scaled_by(1.5));
assert_eq!(
ctx.reader_accessibility_with(|| scaled_by(2.0)),
scaled_by(2.0)
);
}
#[cfg(target_os = "linux")]
#[test]
fn the_sync_refined_desktop_is_the_cached_one() {
let ctx = DetectionContext::new();
let fill = ctx.refined_linux_desktop.begin_fill();
let gnome = refine_desktop(LinuxDesktop::Gnome, None, || false);
ctx.refined_linux_desktop.finish_fill(fill, gnome);
assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
assert_eq!(pollster::block_on(ctx.refined_linux_desktop()), gnome);
ctx.invalidate_linux_desktop();
assert!(ctx.refined_linux_desktop.get().is_none());
}
#[cfg(target_os = "linux")]
fn refined_unknown(portal_backend: Option<LinuxDesktop>) -> DetectionContext {
let ctx = DetectionContext::new();
ctx.linux_desktop
.finish_fill(ctx.linux_desktop.begin_fill(), LinuxDesktop::Unknown);
ctx.finish_refined_desktop(
ctx.refined_linux_desktop.begin_fill(),
refine_desktop(LinuxDesktop::Unknown, portal_backend, || false),
LinuxDesktop::Unknown,
);
ctx
}
#[cfg(target_os = "linux")]
#[test]
fn a_portal_answer_that_changes_the_desktop_clears_what_was_read_from_it() {
let ctx = DetectionContext::new();
assert_eq!(ctx.font_dpi_with(|| 120.0), 120.0);
assert_eq!(
ctx.icon_theme_with(|| Ok("breeze".to_string()))
.ok()
.as_deref(),
Some("breeze")
);
assert!(ctx.is_dark.get_or_fill(|| true));
assert!(ctx.reduced_motion.get_or_fill(|| true));
let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), || true);
ctx.finish_refined_desktop(
ctx.refined_linux_desktop.begin_fill(),
refined,
LinuxDesktop::Kde,
);
assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
assert_eq!(ctx.font_dpi_with(|| 96.0), 96.0);
assert_eq!(
ctx.icon_theme_with(|| Ok("Adwaita".to_string()))
.ok()
.as_deref(),
Some("Adwaita")
);
assert_eq!(ctx.is_dark.get(), None);
assert_eq!(ctx.reduced_motion.get(), None);
}
#[cfg(target_os = "linux")]
#[test]
fn a_portal_answer_that_keeps_the_desktop_keeps_what_was_read() {
let ctx = DetectionContext::new();
assert_eq!(ctx.font_dpi_with(|| 120.0), 120.0);
let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), || true);
ctx.finish_refined_desktop(
ctx.refined_linux_desktop.begin_fill(),
refined,
LinuxDesktop::Kde,
);
assert_eq!(ctx.font_dpi_with(|| 96.0), 120.0);
}
#[cfg(target_os = "linux")]
#[test]
fn dark_mode_follows_the_refined_desktop() {
let kde = refined_unknown(Some(LinuxDesktop::Kde));
assert_eq!(
desktop_is_dark(&kde, || Some(true), || Some(false)),
Some(true)
);
let gnome = refined_unknown(Some(LinuxDesktop::Gnome));
assert_eq!(
desktop_is_dark(&gnome, || Some(true), || Some(false)),
Some(false)
);
assert_eq!(desktop_is_dark(&gnome, || Some(true), || None), Some(true));
}
}
#[cfg(all(test, target_os = "linux"))]
mod refine_linux_desktop_tests {
use super::*;
fn asked() -> bool {
panic!("kdeglobals asked where the desktop is already decided")
}
#[test]
fn the_raw_desktop_then_the_portal_backend_then_kdeglobals() {
let refine = |raw, portal_backend, kdeglobals_exists: fn() -> bool| {
refine_linux_desktop(raw, portal_backend, kdeglobals_exists)
};
assert_eq!(
refine(LinuxDesktop::Gnome, Some(LinuxDesktop::Kde), asked),
LinuxDesktop::Gnome
);
assert_eq!(refine(LinuxDesktop::Xfce, None, asked), LinuxDesktop::Xfce);
assert_eq!(
refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), asked),
LinuxDesktop::Kde
);
assert_eq!(
refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), asked),
LinuxDesktop::Gnome
);
assert_eq!(
refine(LinuxDesktop::Unknown, None, || true),
LinuxDesktop::Kde
);
assert_eq!(
refine(LinuxDesktop::Unknown, None, || false),
LinuxDesktop::Unknown
);
}
}
#[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};
const GENEROUS: Duration = Duration::from_secs(10);
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 = stdout_with_timeout("echo", &["hi"], GENEROUS);
assert_eq!(out.as_deref().map(str::trim), Some("hi"));
}
#[test]
fn run_with_timeout_returns_the_status_and_stderr_of_a_failing_command() {
if !on_path("sh") {
eprintln!("skipped: sh is not installed");
return;
}
let output = run_with_timeout("sh", &["-c", "echo oops >&2; exit 3"], GENEROUS).unwrap();
assert_eq!(output.status.code(), Some(3));
assert_eq!(output.stderr, b"oops\n");
assert_eq!(stdout_with_timeout("sh", &["-c", "exit 3"], GENEROUS), None);
}
#[test]
fn run_with_timeout_reports_a_missing_program_as_not_found() {
let error = run_with_timeout("nt-test-no-such-program", &[], GENEROUS).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
}
#[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!(
stdout_with_timeout("true", &[], GENEROUS).as_deref(),
Some("")
);
eprintln!("`true` ran in {:?}", start.elapsed());
}
fn running(cmdline: &str) -> 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()
}
#[test]
fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
if !on_path("sleep") {
eprintln!("skipped: sleep is not installed");
return;
}
let timeout = Duration::from_millis(100);
let seconds = format!("30.{}", std::process::id());
let start = Instant::now();
let error = run_with_timeout("sleep", &[&seconds], timeout).unwrap_err();
let elapsed = start.elapsed();
assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
assert_eq!(error.to_string(), "timed out after 100ms");
assert!(
elapsed >= timeout && elapsed < Duration::from_secs(5),
"took {elapsed:?}"
);
let still_running = running(&format!("sleep\0{seconds}\0"));
assert!(still_running.is_empty(), "not killed: {still_running:?}");
}
#[test]
fn run_with_timeout_returns_all_of_an_output_larger_than_a_pipe() {
if !on_path("sh") || !on_path("head") {
eprintln!("skipped: sh or head is not installed");
return;
}
let out = stdout_with_timeout("sh", &["-c", "head -c 102400 /dev/zero"], GENEROUS);
assert_eq!(out.map(|out| out.len()), Some(102_400));
}
#[test]
fn run_with_timeout_ends_at_the_deadline_when_a_grandchild_holds_stdout() {
if !on_path("sh") || !on_path("sleep") {
eprintln!("skipped: sh or sleep is not installed");
return;
}
let script = format!("sleep 10.{} & echo hi", std::process::id());
let start = Instant::now();
let error =
run_with_timeout("sh", &["-c", &script], Duration::from_millis(100)).unwrap_err();
let elapsed = start.elapsed();
assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
assert!(elapsed < Duration::from_secs(5), "took {elapsed:?}");
}
}
#[cfg(all(test, target_os = "linux"))]
mod config_home_tests {
use super::*;
use std::ffi::OsStr;
use std::path::PathBuf;
fn config_home(var: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
xdg_config_home_from(var.map(OsStr::new), home.map(OsStr::new))
}
#[test]
fn an_absolute_xdg_config_home_is_the_config_directory() {
assert_eq!(
config_home(Some("/tmp/cfg"), Some("/home/u")),
Some(PathBuf::from("/tmp/cfg"))
);
assert_eq!(
config_home(Some("/tmp/cfg"), None),
Some(PathBuf::from("/tmp/cfg"))
);
}
#[test]
fn an_unset_empty_or_relative_xdg_config_home_falls_back_to_home() {
for var in [None, Some(""), Some("relative/cfg"), Some(".config")] {
assert_eq!(
config_home(var, Some("/home/u")),
Some(PathBuf::from("/home/u/.config")),
"{var:?}"
);
}
}
#[test]
fn without_xdg_config_home_and_home_there_is_no_config_directory() {
for home in [None, Some("")] {
for var in [None, Some(""), Some("relative")] {
assert_eq!(config_home(var, home), None, "{var:?} {home:?}");
}
}
}
}
#[cfg(all(test, target_os = "linux", feature = "portal"))]
mod gnome_font_dpi_tests {
use super::*;
#[test]
fn gnome_desktops_fix_the_font_dpi() {
assert_eq!(desktop_font_dpi(LinuxDesktop::Gnome), Some(96.0));
assert_eq!(desktop_font_dpi(LinuxDesktop::Budgie), Some(96.0));
assert_eq!(desktop_font_dpi(LinuxDesktop::Kde), None);
assert_eq!(desktop_font_dpi(LinuxDesktop::Unknown), None);
}
#[test]
fn an_unknown_desktop_with_a_gnome_portal_has_gnomes_font_dpi() {
for kdeglobals in [false, true] {
let desktop =
refine_linux_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), || {
kdeglobals
});
assert_eq!(desktop_font_dpi(desktop), Some(GNOME_FONT_DPI));
assert_eq!(GNOME_FONT_DPI, 96.0);
}
}
}