1use arc_swap::ArcSwapOption;
4use std::sync::Arc;
5
6#[cfg(target_os = "linux")]
11const SUBPROCESS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
12
13#[cfg(target_os = "linux")]
15#[non_exhaustive]
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum LinuxDesktop {
18 Kde,
20 Gnome,
22 Xfce,
24 Cinnamon,
26 Mate,
28 LxQt,
30 Budgie,
32 Hyprland,
34 Sway,
36 River,
38 Niri,
40 Wayfire,
42 CosmicDe,
44 Unknown,
46}
47
48#[cfg(target_os = "linux")]
51pub(crate) fn xdg_current_desktop() -> String {
52 std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default()
53}
54
55#[cfg(target_os = "linux")]
77#[must_use]
78pub fn detect_linux_desktop() -> LinuxDesktop {
79 parse_linux_desktop(&xdg_current_desktop())
80}
81
82#[cfg(target_os = "linux")]
88#[must_use]
89pub fn parse_linux_desktop(xdg_current_desktop: &str) -> LinuxDesktop {
90 for component in xdg_current_desktop.split(':') {
91 match component {
92 "KDE" => return LinuxDesktop::Kde,
93 "Budgie" => return LinuxDesktop::Budgie,
94 "GNOME" => return LinuxDesktop::Gnome,
95 "XFCE" => return LinuxDesktop::Xfce,
96 "X-Cinnamon" | "Cinnamon" => return LinuxDesktop::Cinnamon,
97 "MATE" => return LinuxDesktop::Mate,
98 "LXQt" => return LinuxDesktop::LxQt,
99 "Hyprland" => return LinuxDesktop::Hyprland,
100 "sway" => return LinuxDesktop::Sway,
101 "river" => return LinuxDesktop::River,
102 "niri" => return LinuxDesktop::Niri,
103 "Wayfire" => return LinuxDesktop::Wayfire,
104 "COSMIC" => return LinuxDesktop::CosmicDe,
105 _ => {}
106 }
107 }
108 LinuxDesktop::Unknown
109}
110
111#[must_use]
141pub fn system_is_dark() -> bool {
142 system().is_dark()
143}
144
145pub fn invalidate_caches() {
154 system().invalidate_all();
155}
156
157#[must_use]
165pub fn detect_is_dark() -> bool {
166 detect_is_dark_inner()
167}
168
169#[cfg(target_os = "linux")]
178fn run_gsettings_with_timeout(args: &[&str]) -> Option<String> {
179 use std::io::Read;
180 use std::time::{Duration, Instant};
181
182 let start = Instant::now();
183 let timeout = SUBPROCESS_TIMEOUT;
184 let mut child = std::process::Command::new("gsettings")
185 .args(args)
186 .stdout(std::process::Stdio::piped())
187 .stderr(std::process::Stdio::null())
188 .spawn()
189 .ok()?;
190
191 loop {
192 match child.try_wait() {
193 Ok(Some(status)) if status.success() => {
194 let mut buf = String::new();
195 if let Some(mut stdout) = child.stdout.take() {
196 let _ = stdout.read_to_string(&mut buf);
197 }
198 let trimmed = buf.trim().to_string();
199 return if trimmed.is_empty() {
200 None
201 } else {
202 Some(trimmed)
203 };
204 }
205 Ok(Some(_)) => return None,
206 Ok(None) => {
207 if start.elapsed() >= timeout {
208 let _ = child.kill();
209 return None;
210 }
211 std::thread::sleep(Duration::from_millis(50));
212 }
213 Err(_) => return None,
214 }
215 }
216}
217
218#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
223fn read_xft_dpi() -> Option<f32> {
224 use std::io::Read;
225 use std::time::{Duration, Instant};
226
227 let start = Instant::now();
228 let timeout = SUBPROCESS_TIMEOUT;
229 let mut child = std::process::Command::new("xrdb")
230 .arg("-query")
231 .stdout(std::process::Stdio::piped())
232 .stderr(std::process::Stdio::null())
233 .spawn()
234 .ok()?;
235
236 loop {
237 match child.try_wait() {
238 Ok(Some(status)) if status.success() => {
239 let mut buf = String::new();
240 if let Some(mut stdout) = child.stdout.take() {
241 let _ = stdout.read_to_string(&mut buf);
242 }
243 for line in buf.lines() {
245 if let Some(rest) = line.strip_prefix("Xft.dpi:")
246 && let Ok(dpi) = rest.trim().parse::<f32>()
247 && dpi > 0.0
248 {
249 return Some(dpi);
250 }
251 }
252 return None;
253 }
254 Ok(Some(_)) => return None,
255 Ok(None) => {
256 if start.elapsed() >= timeout {
257 let _ = child.kill();
258 return None;
259 }
260 std::thread::sleep(Duration::from_millis(50));
261 }
262 Err(_) => return None,
263 }
264 }
265}
266
267#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
277fn detect_physical_dpi() -> Option<f32> {
278 use std::io::Read;
279 use std::time::{Duration, Instant};
280
281 let start = Instant::now();
282 let timeout = SUBPROCESS_TIMEOUT;
283 let mut child = std::process::Command::new("xrandr")
284 .stdout(std::process::Stdio::piped())
285 .stderr(std::process::Stdio::null())
286 .spawn()
287 .ok()?;
288
289 loop {
290 match child.try_wait() {
291 Ok(Some(status)) if status.success() => {
292 let mut buf = String::new();
293 if let Some(mut stdout) = child.stdout.take() {
294 let _ = stdout.read_to_string(&mut buf);
295 }
296 return parse_xrandr_dpi(&buf);
297 }
298 Ok(Some(_)) => return None,
299 Ok(None) => {
300 if start.elapsed() >= timeout {
301 let _ = child.kill();
302 return None;
303 }
304 std::thread::sleep(Duration::from_millis(50));
305 }
306 Err(_) => return None,
307 }
308 }
309}
310
311#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
320fn parse_xrandr_dpi(output: &str) -> Option<f32> {
321 let line = output
323 .lines()
324 .find(|l| l.contains(" connected") && l.contains("primary"))
325 .or_else(|| {
326 output
327 .lines()
328 .find(|l| l.contains(" connected") && !l.contains("disconnected"))
329 })?;
330
331 let res_token = line
333 .split_whitespace()
334 .find(|s| s.contains('x') && s.contains('+'))?;
335 let (w_str, rest) = res_token.split_once('x')?;
336 let h_str = rest.split('+').next()?;
337 let w_px: f32 = w_str.parse().ok()?;
338 let h_px: f32 = h_str.parse().ok()?;
339
340 let words: Vec<&str> = line.split_whitespace().collect();
342 let mut w_mm = None;
343 let mut h_mm = None;
344 for window in words.windows(3) {
345 let [prev, cur, next] = window else { continue };
346 if *cur == "x" {
347 w_mm = prev.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
348 h_mm = next.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
349 }
350 }
351 let w_mm = w_mm.filter(|&v| v > 0.0)?;
352 let h_mm = h_mm.filter(|&v| v > 0.0)?;
353
354 let h_dpi = w_px / (w_mm / 25.4);
355 let v_dpi = h_px / (h_mm / 25.4);
356 let avg = (h_dpi + v_dpi) / 2.0;
357
358 if avg > 0.0 { Some(avg) } else { None }
359}
360
361#[cfg(all(test, target_os = "linux", any(feature = "kde", feature = "portal")))]
362#[allow(clippy::unwrap_used)]
363mod xrandr_dpi_tests {
364 use super::parse_xrandr_dpi;
365
366 #[test]
367 fn primary_4k_display() {
368 let output = "Screen 0: minimum 16 x 16, current 3840 x 2160, maximum 32767 x 32767\n\
370 DP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 700mm x 390mm\n\
371 3840x2160 60.00*+\n";
372 let dpi = parse_xrandr_dpi(output).unwrap();
373 assert!((dpi - 140.0).abs() < 1.0, "expected ~140 DPI, got {dpi}");
375 }
376
377 #[test]
378 fn standard_1080p_display() {
379 let output = "DP-2 connected primary 1920x1080+0+0 (normal) 530mm x 300mm\n";
380 let dpi = parse_xrandr_dpi(output).unwrap();
381 assert!((dpi - 92.0).abs() < 1.0, "expected ~92 DPI, got {dpi}");
383 }
384
385 #[test]
386 fn no_primary_falls_back_to_first_connected() {
387 let output = "HDMI-1 connected 1920x1080+0+0 (normal) 480mm x 270mm\n\
388 DP-1 disconnected\n";
389 let dpi = parse_xrandr_dpi(output).unwrap();
390 assert!(dpi > 90.0 && dpi < 110.0, "expected ~100 DPI, got {dpi}");
391 }
392
393 #[test]
394 fn disconnected_only_returns_none() {
395 let output = "DP-1 disconnected\nHDMI-1 disconnected\n";
396 assert!(parse_xrandr_dpi(output).is_none());
397 }
398
399 #[test]
400 fn missing_physical_dimensions_returns_none() {
401 let output = "DP-1 connected primary 1920x1080+0+0 (normal)\n";
403 assert!(parse_xrandr_dpi(output).is_none());
404 }
405
406 #[test]
407 fn zero_mm_returns_none() {
408 let output = "DP-1 connected primary 1920x1080+0+0 (normal) 0mm x 0mm\n";
409 assert!(parse_xrandr_dpi(output).is_none());
410 }
411
412 #[test]
413 fn empty_output_returns_none() {
414 assert!(parse_xrandr_dpi("").is_none());
415 }
416}
417
418#[allow(unreachable_code)]
430fn detect_system_font_dpi() -> f32 {
431 #[cfg(target_os = "macos")]
432 {
433 return 72.0;
434 }
435
436 #[cfg(all(target_os = "windows", feature = "windows"))]
437 {
438 return crate::windows::read_dpi() as f32;
439 }
440
441 #[cfg(all(target_os = "linux", feature = "kde"))]
443 {
444 if let Some(dpi) = read_kde_force_font_dpi() {
445 return dpi;
446 }
447 }
448
449 #[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
450 {
451 if let Some(dpi) = read_xft_dpi() {
452 return dpi;
453 }
454 if let Some(dpi) = detect_physical_dpi() {
455 return dpi;
456 }
457 }
458
459 96.0
460}
461
462#[cfg(all(target_os = "linux", feature = "kde"))]
468fn read_kde_force_font_dpi() -> Option<f32> {
469 let path = crate::kde::kdeglobals_path();
471 if let Ok(content) = std::fs::read_to_string(&path) {
472 let mut ini = crate::kde::create_kde_parser();
473 if ini.read(content).is_ok()
474 && let Some(dpi_str) = ini.get("General", "forceFontDPI")
475 && let Ok(dpi) = dpi_str.trim().parse::<f32>()
476 && dpi > 0.0
477 {
478 return Some(dpi);
479 }
480 }
481 if let Some(dpi_str) = crate::kde::read_kcmfontsrc_key("General", "forceFontDPI")
483 && let Ok(dpi) = dpi_str.trim().parse::<f32>()
484 && dpi > 0.0
485 {
486 return Some(dpi);
487 }
488 None
489}
490
491#[allow(unreachable_code)]
495fn detect_is_dark_inner() -> bool {
496 #[cfg(target_os = "linux")]
497 {
498 if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
500 let lower = gtk_theme.to_lowercase();
501 if lower.ends_with(":dark") || lower.contains("-dark") {
502 return true;
503 }
504 }
505
506 #[cfg(feature = "kde")]
509 {
510 let de = parse_linux_desktop(&xdg_current_desktop());
511 if matches!(de, LinuxDesktop::Kde) {
512 let path = crate::kde::kdeglobals_path();
513 if let Ok(content) = std::fs::read_to_string(&path) {
514 let mut ini = crate::kde::create_kde_parser();
515 if ini.read(content).is_ok() {
516 return crate::kde::is_dark_theme(&ini);
517 }
518 }
519 }
520 }
521
522 if let Some(val) =
524 run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "color-scheme"])
525 {
526 if val.contains("prefer-dark") {
527 return true;
528 }
529 if val.contains("prefer-light") || val.contains("default") {
530 return false;
531 }
532 }
533
534 #[cfg(feature = "kde")]
538 {
539 let path = crate::kde::kdeglobals_path();
540 if let Ok(content) = std::fs::read_to_string(&path) {
541 let mut ini = crate::kde::create_kde_parser();
542 if ini.read(content).is_ok() {
543 return crate::kde::is_dark_theme(&ini);
544 }
545 }
546 }
547
548 let config_home = std::env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| {
550 let home = std::env::var("HOME").unwrap_or_default();
551 format!("{home}/.config")
552 });
553 let ini_path = format!("{config_home}/gtk-3.0/settings.ini");
554 if let Ok(content) = std::fs::read_to_string(&ini_path) {
555 for line in content.lines() {
556 let trimmed = line.trim();
557 if trimmed.starts_with("gtk-application-prefer-dark-theme")
558 && let Some(val) = trimmed.split('=').nth(1)
559 && (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
560 {
561 return true;
562 }
563 }
564 }
565
566 false
567 }
568
569 #[cfg(target_os = "macos")]
570 {
571 #[cfg(feature = "macos")]
574 {
575 use objc2_foundation::NSUserDefaults;
576 let defaults = NSUserDefaults::standardUserDefaults();
577 let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
578 if let Some(value) = defaults.stringForKey(key) {
579 return value.to_string().eq_ignore_ascii_case("dark");
580 }
581 return false;
582 }
583 #[cfg(not(feature = "macos"))]
584 {
585 if let Ok(output) = std::process::Command::new("defaults")
586 .args(["read", "-g", "AppleInterfaceStyle"])
587 .output()
588 && output.status.success()
589 {
590 let val = String::from_utf8_lossy(&output.stdout);
591 return val.trim().eq_ignore_ascii_case("dark");
592 }
593 return false;
594 }
595 }
596
597 #[cfg(target_os = "windows")]
598 {
599 #[cfg(feature = "windows")]
600 {
601 let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
603 return false;
604 };
605 let Ok(fg) =
606 settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
607 else {
608 return false;
609 };
610 let luma = 0.299 * (fg.R as f32) + 0.587 * (fg.G as f32) + 0.114 * (fg.B as f32);
611 return luma > 128.0;
612 }
613 #[cfg(not(feature = "windows"))]
614 return false;
615 }
616
617 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
618 {
619 false
620 }
621}
622
623#[must_use]
654pub fn prefers_reduced_motion() -> bool {
655 system().prefers_reduced_motion()
656}
657
658#[must_use]
666pub fn detect_reduced_motion() -> bool {
667 detect_reduced_motion_inner()
668}
669
670#[allow(unreachable_code)]
674fn detect_reduced_motion_inner() -> bool {
675 #[cfg(target_os = "linux")]
676 {
677 if let Some(val) =
680 run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "enable-animations"])
681 {
682 return val.trim() == "false";
683 }
684 false
685 }
686
687 #[cfg(target_os = "macos")]
688 {
689 #[cfg(feature = "macos")]
690 {
691 let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace();
692 return workspace.accessibilityDisplayShouldReduceMotion();
694 }
695 #[cfg(not(feature = "macos"))]
696 return false;
697 }
698
699 #[cfg(target_os = "windows")]
700 {
701 #[cfg(feature = "windows")]
702 {
703 let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
704 return false;
705 };
706 return match settings.AnimationsEnabled() {
708 Ok(enabled) => !enabled,
709 Err(_) => false,
710 };
711 }
712 #[cfg(not(feature = "windows"))]
713 return false;
714 }
715
716 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
717 {
718 false
719 }
720}
721
722pub struct DetectionContext {
737 is_dark: ArcSwapOption<bool>,
738 reduced_motion: ArcSwapOption<bool>,
739 icon_theme: ArcSwapOption<String>,
740 #[cfg(target_os = "linux")]
741 linux_desktop: ArcSwapOption<LinuxDesktop>,
742}
743
744impl DetectionContext {
745 fn new() -> Self {
747 Self {
748 is_dark: ArcSwapOption::empty(),
749 reduced_motion: ArcSwapOption::empty(),
750 icon_theme: ArcSwapOption::empty(),
751 #[cfg(target_os = "linux")]
752 linux_desktop: ArcSwapOption::empty(),
753 }
754 }
755
756 #[must_use]
763 pub fn is_dark(&self) -> bool {
764 if let Some(v) = self.is_dark.load().as_deref() {
765 return *v;
766 }
767 let value = detect_is_dark_inner();
768 self.is_dark.store(Some(Arc::new(value)));
769 value
770 }
771
772 #[must_use]
778 pub fn prefers_reduced_motion(&self) -> bool {
779 if let Some(v) = self.reduced_motion.load().as_deref() {
780 return *v;
781 }
782 let value = detect_reduced_motion_inner();
783 self.reduced_motion.store(Some(Arc::new(value)));
784 value
785 }
786
787 #[must_use]
795 pub fn icon_theme(&self) -> Arc<String> {
796 if let Some(v) = self.icon_theme.load_full() {
797 return v;
798 }
799 let value = Arc::new(detect_icon_theme_inner());
800 self.icon_theme.store(Some(Arc::clone(&value)));
801 value
802 }
803
804 #[cfg(target_os = "linux")]
811 #[must_use]
812 pub fn linux_desktop(&self) -> LinuxDesktop {
813 if let Some(v) = self.linux_desktop.load().as_deref() {
814 return *v;
815 }
816 let value = detect_linux_desktop();
817 self.linux_desktop.store(Some(Arc::new(value)));
818 value
819 }
820
821 pub fn invalidate_is_dark(&self) {
823 self.is_dark.store(None);
824 }
825
826 pub fn invalidate_reduced_motion(&self) {
828 self.reduced_motion.store(None);
829 }
830
831 pub fn invalidate_icon_theme(&self) {
833 self.icon_theme.store(None);
834 }
835
836 #[cfg(target_os = "linux")]
838 pub fn invalidate_linux_desktop(&self) {
839 self.linux_desktop.store(None);
840 }
841
842 pub fn invalidate_all(&self) {
844 self.invalidate_is_dark();
845 self.invalidate_reduced_motion();
846 self.invalidate_icon_theme();
847 #[cfg(target_os = "linux")]
848 self.invalidate_linux_desktop();
849 }
850}
851
852pub fn system() -> &'static DetectionContext {
857 static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
858 INSTANCE.get_or_init(DetectionContext::new)
859}
860
861#[allow(unreachable_code)]
866fn detect_icon_theme_inner() -> String {
867 crate::model::icons::detect_icon_theme()
868}
869
870#[cfg(all(target_os = "linux", feature = "portal"))]
874pub(crate) fn gsettings_get(schema: &str, key: &str) -> Option<String> {
875 run_gsettings_with_timeout(&["get", schema, key])
876}
877
878#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
880pub(crate) fn xft_dpi() -> Option<f32> {
881 read_xft_dpi()
882}
883
884#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
886pub(crate) fn physical_dpi() -> Option<f32> {
887 detect_physical_dpi()
888}
889
890pub(crate) fn system_font_dpi() -> f32 {
892 detect_system_font_dpi()
893}
894
895#[cfg(test)]
896#[allow(clippy::unwrap_used, clippy::expect_used)]
897mod reduced_motion_tests {
898 use super::*;
899
900 #[test]
901 fn prefers_reduced_motion_smoke_test() {
902 let _result = prefers_reduced_motion();
906 }
907
908 #[cfg(target_os = "linux")]
909 #[test]
910 fn detect_reduced_motion_inner_linux() {
911 let result = detect_reduced_motion_inner();
915 let _ = result;
917 }
918
919 #[cfg(target_os = "macos")]
920 #[test]
921 fn detect_reduced_motion_inner_macos() {
922 let result = detect_reduced_motion_inner();
923 let _ = result;
924 }
925
926 #[cfg(target_os = "windows")]
927 #[test]
928 fn detect_reduced_motion_inner_windows() {
929 let result = detect_reduced_motion_inner();
930 let _ = result;
931 }
932}
933
934#[cfg(test)]
935mod detection_context_tests {
936 use super::*;
937
938 #[test]
939 fn system_returns_same_instance() {
940 let a = system() as *const DetectionContext;
941 let b = system() as *const DetectionContext;
942 assert_eq!(a, b);
943 }
944
945 #[test]
946 fn is_dark_caches_result() {
947 let ctx = DetectionContext::new();
948 let first = ctx.is_dark();
949 let second = ctx.is_dark();
950 assert_eq!(first, second);
951 }
952
953 #[test]
954 fn invalidate_is_dark_clears_cache() {
955 let ctx = DetectionContext::new();
956 let _ = ctx.is_dark(); ctx.invalidate_is_dark();
958 let _ = ctx.is_dark();
960 }
961
962 #[test]
963 fn prefers_reduced_motion_caches_result() {
964 let ctx = DetectionContext::new();
965 let first = ctx.prefers_reduced_motion();
966 let second = ctx.prefers_reduced_motion();
967 assert_eq!(first, second);
968 }
969
970 #[test]
971 fn invalidate_all_clears_all_caches() {
972 let ctx = DetectionContext::new();
973 let _ = ctx.is_dark();
974 let _ = ctx.prefers_reduced_motion();
975 let _ = ctx.icon_theme();
976 ctx.invalidate_all();
977 let _ = ctx.is_dark();
979 let _ = ctx.prefers_reduced_motion();
980 let _ = ctx.icon_theme();
981 }
982
983 #[cfg(target_os = "linux")]
984 #[test]
985 fn linux_desktop_caches_result() {
986 let ctx = DetectionContext::new();
987 let first = ctx.linux_desktop();
988 let second = ctx.linux_desktop();
989 assert_eq!(first, second);
990 }
991
992 #[cfg(target_os = "linux")]
993 #[test]
994 fn invalidate_linux_desktop_clears_cache() {
995 let ctx = DetectionContext::new();
996 let _ = ctx.linux_desktop();
997 ctx.invalidate_linux_desktop();
998 let _ = ctx.linux_desktop(); }
1000}