#[cfg(all(feature = "watch", feature = "kde", target_os = "linux"))]
mod kde;
#[cfg(all(feature = "watch", feature = "portal", target_os = "linux"))]
mod gnome;
#[cfg(all(feature = "watch", feature = "macos", target_os = "macos"))]
mod macos;
#[cfg(all(feature = "watch", feature = "windows", target_os = "windows"))]
mod windows;
use std::sync::mpsc;
use std::thread::JoinHandle;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ThemeChangeEvent {
Changed,
}
#[must_use]
pub struct ThemeSubscription {
shutdown_tx: Option<mpsc::Sender<()>>,
thread: Option<JoinHandle<()>>,
platform_shutdown: Option<Box<dyn FnOnce() + Send>>,
}
impl std::fmt::Debug for ThemeSubscription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ThemeSubscription")
.field("shutdown_tx", &self.shutdown_tx)
.field("thread", &self.thread)
.field(
"platform_shutdown",
&self.platform_shutdown.as_ref().map(|_| "..."),
)
.finish()
}
}
impl ThemeSubscription {
#[cfg(any(
test,
all(target_os = "linux", any(feature = "kde", feature = "portal")),
all(target_os = "windows", feature = "windows"),
))]
pub(crate) fn new(
shutdown_tx: mpsc::Sender<()>,
thread: JoinHandle<()>,
platform_shutdown: Option<Box<dyn FnOnce() + Send>>,
) -> Self {
Self {
shutdown_tx: Some(shutdown_tx),
thread: Some(thread),
platform_shutdown,
}
}
#[cfg(all(target_os = "macos", feature = "macos"))]
pub(crate) fn from_platform_shutdown(platform_shutdown: Box<dyn FnOnce() + Send>) -> Self {
Self {
shutdown_tx: None,
thread: None,
platform_shutdown: Some(platform_shutdown),
}
}
}
impl Drop for ThemeSubscription {
fn drop(&mut self) {
if let Some(shutdown_fn) = self.platform_shutdown.take() {
shutdown_fn();
}
drop(self.shutdown_tx.take());
if let Some(handle) = self.thread.take()
&& handle.thread().id() != std::thread::current().id()
{
let _ = handle.join();
}
}
}
#[cfg(any(
test,
all(target_os = "linux", any(feature = "kde", feature = "portal")),
all(target_os = "macos", feature = "macos"),
all(target_os = "windows", feature = "windows"),
))]
fn fire(callback: &impl Fn(ThemeChangeEvent)) {
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
callback(ThemeChangeEvent::Changed)
}));
}
#[cfg(any(
test,
all(target_os = "linux", any(feature = "kde", feature = "portal")),
all(target_os = "macos", feature = "macos"),
all(target_os = "windows", feature = "windows"),
))]
const DEBOUNCE_MS: u32 = 300;
#[cfg(any(
test,
all(target_os = "linux", any(feature = "kde", feature = "portal")),
all(target_os = "macos", feature = "macos"),
))]
const DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(DEBOUNCE_MS as u64);
#[cfg(any(
test,
all(target_os = "linux", any(feature = "kde", feature = "portal"))
))]
fn fire_debounced<T>(
events: &mpsc::Receiver<T>,
shutdown: &mpsc::Receiver<()>,
mut is_relevant: impl FnMut(T) -> bool,
callback: &impl Fn(ThemeChangeEvent),
) {
use std::time::{Duration, Instant};
let poll = Duration::from_millis(200);
let mut debounce = Debounce::default();
loop {
match shutdown.try_recv() {
Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
Err(mpsc::TryRecvError::Empty) => {}
}
match events.recv_timeout(debounce.wait(Instant::now(), poll)) {
Ok(message) => {
if is_relevant(message) {
debounce.note(Instant::now());
}
}
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
if debounce.take_due(Instant::now()) {
fire(callback);
}
}
}
#[cfg(any(
test,
all(target_os = "linux", any(feature = "kde", feature = "portal"))
))]
#[derive(Debug, Default)]
struct Debounce {
last: Option<std::time::Instant>,
}
#[cfg(any(
test,
all(target_os = "linux", any(feature = "kde", feature = "portal"))
))]
impl Debounce {
fn note(&mut self, now: std::time::Instant) {
self.last = Some(now);
}
fn wait(&self, now: std::time::Instant, poll: std::time::Duration) -> std::time::Duration {
self.last.map_or(poll, |last| {
DEBOUNCE
.saturating_sub(now.saturating_duration_since(last))
.min(poll)
})
}
fn take_due(&mut self, now: std::time::Instant) -> bool {
let due = self
.last
.is_some_and(|last| now.saturating_duration_since(last) >= DEBOUNCE);
if due {
self.last = None;
}
due
}
}
pub fn on_theme_change(
callback: impl Fn(ThemeChangeEvent) + Send + 'static,
) -> crate::Result<ThemeSubscription> {
#[cfg(target_os = "linux")]
{
#[cfg(not(any(feature = "kde", feature = "portal")))]
let _ = callback;
match linux_backend(crate::detect::system().refined_linux_desktop_sync()) {
#[cfg(feature = "kde")]
Some(LinuxBackend::Kde) => kde::watch_kde(callback),
#[cfg(feature = "portal")]
Some(LinuxBackend::Gnome) => gnome::watch_gnome(callback),
_ => Err(crate::Error::WatchUnavailable {
reason: "theme watching not supported for this desktop environment",
}),
}
}
#[cfg(target_os = "macos")]
{
#[cfg(feature = "macos")]
{
macos::watch_macos(callback)
}
#[cfg(not(feature = "macos"))]
{
let _ = callback;
Err(crate::Error::WatchUnavailable {
reason: "enable the 'macos' feature for macOS theme watching",
})
}
}
#[cfg(target_os = "windows")]
{
#[cfg(feature = "windows")]
{
windows::watch_windows(callback)
}
#[cfg(not(feature = "windows"))]
{
let _ = callback;
Err(crate::Error::WatchUnavailable {
reason: "enable the 'windows' feature for Windows theme watching",
})
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
let _ = callback;
Err(crate::Error::PlatformUnsupported {
platform: std::env::consts::OS,
})
}
}
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LinuxBackend {
#[cfg(feature = "kde")]
Kde,
#[cfg(feature = "portal")]
Gnome,
}
#[cfg(target_os = "linux")]
fn linux_backend(desktop: crate::LinuxDesktop) -> Option<LinuxBackend> {
match desktop {
#[cfg(feature = "kde")]
crate::LinuxDesktop::Kde => Some(LinuxBackend::Kde),
#[cfg(feature = "portal")]
crate::LinuxDesktop::Gnome | crate::LinuxDesktop::Budgie => Some(LinuxBackend::Gnome),
_ => None,
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[cfg(all(target_os = "linux", feature = "kde"))]
#[test]
fn an_unknown_desktop_with_a_kde_portal_is_watched_as_kde() {
for kdeglobals in [false, true] {
let desktop = crate::detect::refine_linux_desktop(
crate::LinuxDesktop::Unknown,
Some(crate::LinuxDesktop::Kde),
|| kdeglobals,
);
assert_eq!(linux_backend(desktop), Some(LinuxBackend::Kde));
}
}
#[cfg(all(target_os = "linux", feature = "portal"))]
#[test]
fn an_unknown_desktop_with_a_gnome_portal_is_watched_as_gnome() {
for kdeglobals in [false, true] {
let desktop = crate::detect::refine_linux_desktop(
crate::LinuxDesktop::Unknown,
Some(crate::LinuxDesktop::Gnome),
|| kdeglobals,
);
assert_eq!(linux_backend(desktop), Some(LinuxBackend::Gnome));
}
}
#[cfg(target_os = "linux")]
#[test]
fn an_unknown_desktop_that_nothing_names_is_not_watched() {
let desktop =
crate::detect::refine_linux_desktop(crate::LinuxDesktop::Unknown, None, || false);
assert_eq!(linux_backend(desktop), None);
}
const SOURCE_NOTIFICATIONS: &[(&str, &str, &str)] = &[
("kde", "kdeglobals", "kdeglobals"),
("kde", "kdedefaults/kdeglobals", "kdedefaults/kdeglobals"),
(
"kde",
"org.freedesktop.appearance accent-color",
"kdeglobals",
),
(
"gnome",
"org.freedesktop.appearance color-scheme",
"org.freedesktop.appearance color-scheme",
),
(
"gnome",
"org.freedesktop.appearance accent-color",
"org.freedesktop.appearance accent-color",
),
(
"gnome",
"org.freedesktop.appearance contrast",
"org.freedesktop.appearance contrast",
),
(
"gnome",
"org.freedesktop.appearance reduced-motion",
"org.freedesktop.appearance reduced-motion",
),
(
"gnome",
"org.gnome.desktop.interface color-scheme",
"org.gnome.desktop.interface color-scheme",
),
(
"gnome",
"org.gnome.desktop.interface enable-animations",
"org.gnome.desktop.interface enable-animations",
),
(
"gnome",
"org.gnome.desktop.interface font-name",
"org.gnome.desktop.interface font-name",
),
(
"gnome",
"org.gnome.desktop.interface monospace-font-name",
"org.gnome.desktop.interface monospace-font-name",
),
(
"gnome",
"org.gnome.desktop.interface text-scaling-factor",
"org.gnome.desktop.interface text-scaling-factor",
),
(
"gnome",
"org.gnome.desktop.interface overlay-scrolling",
"org.gnome.desktop.interface overlay-scrolling",
),
(
"gnome",
"org.gnome.desktop.interface icon-theme",
"org.gnome.desktop.interface icon-theme",
),
(
"gnome",
"org.gnome.desktop.wm.preferences titlebar-font",
"org.gnome.desktop.wm.preferences titlebar-font",
),
(
"gnome",
"org.gnome.desktop.a11y.interface high-contrast",
"org.gnome.desktop.a11y.interface high-contrast",
),
(
"macos",
"AppleInterfaceStyle",
"AppleInterfaceThemeChangedNotification",
),
("macos", "NSColor", "NSSystemColorsDidChangeNotification"),
(
"macos",
"NSScroller.preferredScrollerStyle",
"NSPreferredScrollerStyleDidChangeNotification",
),
(
"macos",
"NSWorkspace.accessibilityDisplayOptions",
"NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification",
),
("windows", "UISettings.GetColorValue", "ColorValuesChanged"),
(
"windows",
"UISettings.TextScaleFactor",
"TextScaleFactorChanged",
),
(
"windows",
"SPI_GETCLIENTAREAANIMATION",
"AnimationsEnabledChanged",
),
(
"windows",
"UISettings.AdvancedEffectsEnabled",
"AdvancedEffectsEnabledChanged",
),
];
const READER_MODULES: &[(&str, &str)] = &[
("kde", include_str!("../kde/mod.rs")),
("gnome", include_str!("../gnome/mod.rs")),
("macos", include_str!("../macos.rs")),
("windows", include_str!("../windows.rs")),
];
fn listed_sources(module: &'static str) -> Vec<&'static str> {
module
.lines()
.skip_while(|line| line.trim_end() != "//! # Sources")
.skip(1)
.take_while(|line| line.starts_with("//!") && !line.starts_with("//! #"))
.filter_map(|line| line.strip_prefix("//! - `"))
.filter_map(|item| item.split('`').next())
.collect()
}
#[cfg(any(
all(target_os = "linux", any(feature = "kde", feature = "portal")),
all(target_os = "macos", feature = "macos"),
all(target_os = "windows", feature = "windows"),
))]
fn table_notifications(reader: &str) -> impl Iterator<Item = &'static str> {
SOURCE_NOTIFICATIONS
.iter()
.filter(move |(row_reader, _, _)| *row_reader == reader)
.map(|(_, _, notification)| *notification)
}
#[test]
fn every_listed_source_has_a_table_row() {
for (reader, module) in READER_MODULES {
let sources = listed_sources(module);
assert!(!sources.is_empty(), "{reader}: no `# Sources` list");
for source in &sources {
assert!(
SOURCE_NOTIFICATIONS
.iter()
.any(|(r, s, _)| r == reader && s == source),
"{reader}: the source `{source}` has no row in SOURCE_NOTIFICATIONS"
);
}
for (_, source, _) in SOURCE_NOTIFICATIONS.iter().filter(|(r, _, _)| r == reader) {
assert!(
sources.contains(source),
"{reader}: the row for `{source}` names a source the reader does not list"
);
}
}
}
#[cfg(all(target_os = "linux", feature = "kde"))]
#[test]
fn the_kde_watcher_observes_every_kde_source() {
for file in table_notifications("kde") {
assert!(
kde::WATCHED_FILES.contains(&file),
"the KDE watcher does not observe `{file}`"
);
}
for file in kde::WATCHED_FILES {
assert!(
table_notifications("kde").any(|n| n == *file),
"the KDE watcher observes `{file}`, which no KDE source row names"
);
}
}
#[cfg(all(target_os = "linux", feature = "portal"))]
#[test]
fn the_gnome_watcher_observes_every_gnome_source() {
for setting in table_notifications("gnome") {
let (namespace, key) = setting.split_once(' ').unwrap();
assert!(
gnome::watches(namespace, key),
"the GNOME watcher ignores the SettingChanged of `{setting}`"
);
}
}
#[cfg(all(target_os = "linux", feature = "portal"))]
#[test]
fn the_gnome_reader_lists_every_gsetting_it_reads() {
let sources = listed_sources(include_str!("../gnome/mod.rs"));
let mut read = Vec::new();
let _ = crate::gnome::build_theme(
None,
None,
ashpd::desktop::settings::Contrast::default(),
None,
None,
|schema, key| {
read.push(format!("{schema} {key}"));
None
},
);
assert!(!read.is_empty());
for setting in &read {
assert!(
sources.contains(&setting.as_str()),
"the GNOME reader reads `{setting}`, which its `# Sources` do not list"
);
}
}
#[cfg(all(target_os = "macos", feature = "macos"))]
#[test]
fn the_macos_watcher_observes_every_macos_source() {
let observed: Vec<&str> = macos::registrations().iter().map(|r| r.name_id).collect();
for notification in table_notifications("macos") {
assert!(
observed.contains(¬ification),
"the macOS watcher does not observe `{notification}`"
);
}
}
#[cfg(all(target_os = "windows", feature = "windows"))]
#[test]
fn the_windows_watcher_observes_every_windows_source() {
for event in table_notifications("windows") {
assert!(
windows::SUBSCRIBED_EVENTS.contains(&event),
"the Windows watcher does not subscribe to `{event}`"
);
}
}
#[test]
fn theme_change_event_is_debug_clone_eq() {
let event = ThemeChangeEvent::Changed;
let cloned = event.clone();
assert_eq!(event, cloned);
let debug_str = format!("{:?}", event);
assert!(debug_str.contains("Changed"));
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
#[test]
fn on_theme_change_returns_unsupported() {
let result = on_theme_change(|_| {});
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
matches!(&err, crate::Error::PlatformUnsupported { .. }),
"expected PlatformUnsupported, got: {err:?}"
);
}
#[cfg(target_os = "linux")]
#[test]
fn on_theme_change_dispatches_or_returns_error() {
let result = on_theme_change(|_| {});
assert!(
matches!(
&result,
Ok(_)
| Err(crate::Error::WatchUnavailable { .. })
| Err(crate::Error::PlatformUnsupported { .. })
| Err(crate::Error::ReaderFailed { .. })
),
"unexpected result: {result:?}"
);
}
#[test]
fn theme_subscription_drop_signals_shutdown() {
use std::sync::mpsc;
use std::thread;
let (tx, rx) = mpsc::channel();
let thread_handle = thread::spawn(move || {
let _ = rx.recv();
});
let watcher = ThemeSubscription::new(tx, thread_handle, None);
drop(watcher);
}
#[test]
fn fire_contains_a_panicking_callback() {
use std::sync::atomic::{AtomicUsize, Ordering};
let calls = AtomicUsize::new(0);
let callback = |_| {
let call = calls.fetch_add(1, Ordering::SeqCst);
assert!(call > 0, "the first call panics");
};
fire(&callback);
fire(&callback);
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
fn after(start: std::time::Instant, ms: u64) -> std::time::Instant {
start + std::time::Duration::from_millis(ms)
}
#[test]
fn a_burst_is_due_once_after_its_last_message() {
let start = std::time::Instant::now();
let window = u64::from(DEBOUNCE_MS);
let mut debounce = Debounce::default();
for ms in [0, 50, 100, 150, 200, 250] {
assert!(
!debounce.take_due(after(start, ms)),
"due at {ms} ms, inside the burst"
);
debounce.note(after(start, ms));
}
assert!(!debounce.take_due(after(start, 250 + window - 1)));
assert!(debounce.take_due(after(start, 250 + window)));
assert!(
!debounce.take_due(after(start, 250 + 2 * window)),
"a burst is due once"
);
}
#[test]
fn a_gap_of_the_debounce_window_makes_two_bursts() {
let start = std::time::Instant::now();
let window = u64::from(DEBOUNCE_MS);
let mut debounce = Debounce::default();
assert!(!debounce.take_due(start), "nothing is due before a message");
debounce.note(start);
assert!(debounce.take_due(after(start, window)));
debounce.note(after(start, window));
assert!(!debounce.take_due(after(start, 2 * window - 1)));
assert!(debounce.take_due(after(start, 2 * window)));
}
#[test]
fn the_wait_ends_when_the_burst_is_due() {
use std::time::Duration;
let start = std::time::Instant::now();
let window = u64::from(DEBOUNCE_MS);
let poll = Duration::from_millis(200);
let mut debounce = Debounce::default();
assert_eq!(debounce.wait(start, poll), poll);
debounce.note(start);
assert_eq!(debounce.wait(start, poll), poll);
assert_eq!(
debounce.wait(after(start, window - 50), poll),
Duration::from_millis(50)
);
assert_eq!(debounce.wait(after(start, window), poll), Duration::ZERO);
assert_eq!(
debounce.wait(after(start, 2 * window), poll),
Duration::ZERO
);
}
#[test]
fn fire_debounced_fires_after_the_last_relevant_message() {
use std::time::{Duration, Instant};
let (events_tx, events_rx) = mpsc::channel::<bool>();
let (_shutdown_tx, shutdown_rx) = mpsc::channel::<()>();
let (fired_tx, fired_rx) = mpsc::channel::<Instant>();
let watcher = std::thread::spawn(move || {
fire_debounced(&events_rx, &shutdown_rx, |relevant| relevant, &|_| {
let _ = fired_tx.send(Instant::now());
});
});
let _ = events_tx.send(false);
assert!(
fired_rx.recv_timeout(DEBOUNCE * 2).is_err(),
"an irrelevant message fired"
);
let relevant_messages = [true, false, true, true];
let mut before_last = Instant::now();
for relevant in relevant_messages {
std::thread::sleep(Duration::from_millis(50));
if relevant {
before_last = Instant::now();
}
let _ = events_tx.send(relevant);
}
let due = before_last + DEBOUNCE;
let deadline = Instant::now() + Duration::from_secs(5);
let mut fires = 0;
let mut fired_when_due = false;
while !fired_when_due {
match fired_rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
Ok(fired) => {
fires += 1;
fired_when_due = fired >= due;
}
Err(_) => break,
}
}
assert!(
fired_when_due,
"no fire DEBOUNCE after the last relevant message"
);
drop(events_tx);
watcher.join().unwrap();
fires += fired_rx.try_iter().count();
let relevant = relevant_messages.iter().filter(|&&r| r).count();
assert!(
fires <= relevant,
"{fires} fires for {relevant} relevant messages"
);
}
#[test]
fn theme_subscription_is_send() {
fn assert_send<T: Send>() {}
assert_send::<ThemeSubscription>();
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn assert_subscribe_and_drop_returns(rounds: usize, per_drop_timeout: std::time::Duration) {
for round in 0..rounds {
let (done_tx, done_rx) = mpsc::channel();
std::thread::spawn(move || {
let result = on_theme_change(|_| {}).map(drop);
let _ = done_tx.send(result);
});
match done_rx.recv_timeout(per_drop_timeout) {
Ok(Ok(())) => {}
Ok(Err(crate::Error::WatchUnavailable { .. })) => return,
Ok(Err(err)) => panic!("round {round}: on_theme_change failed: {err:?}"),
Err(_) => panic!(
"round {round}: subscribing and dropping did not return within {per_drop_timeout:?}"
),
}
}
}
#[cfg(all(target_os = "macos", feature = "watch"))]
#[test]
fn macos_subscribe_and_drop_returns() {
assert_subscribe_and_drop_returns(1000, std::time::Duration::from_secs(5));
}
#[cfg(all(target_os = "windows", feature = "watch"))]
#[test]
fn windows_subscribe_and_drop_returns() {
assert_subscribe_and_drop_returns(1000, std::time::Duration::from_secs(5));
}
#[cfg(all(target_os = "linux", feature = "watch"))]
#[test]
fn linux_subscribe_and_drop_returns() {
assert_subscribe_and_drop_returns(10, std::time::Duration::from_secs(5));
}
}