Skip to main content

native_theme/watch/
mod.rs

1//! Runtime theme change watching.
2//!
3//! Requires the `watch` feature.
4//!
5//! This module provides the public API for monitoring OS theme changes at
6//! runtime. Call [`on_theme_change()`](crate::watch::on_theme_change) with a callback to start watching;
7//! the returned [`ThemeSubscription`] keeps the watcher alive via RAII semantics
8//! -- dropping it stops the watcher and joins the background thread (macOS has
9//! no watcher thread: dropping it removes the notification observer).
10//!
11//! # RAII ownership model
12//!
13//! [`ThemeSubscription`] is an RAII guard. Dropping it stops the watcher and
14//! joins the background thread. You **must** bind it to a variable -- if
15//! you discard the return value, the watcher is dropped immediately and
16//! no events are ever delivered.
17//!
18//! # Shutdown mechanism
19//!
20//! When a `ThemeSubscription` is dropped, shutdown proceeds in three phases
21//! (on macOS only the first, which removes the observer):
22//!
23//! 1. **Platform-specific wakeup** -- where the backend has one, it runs
24//!    first (GNOME closes its D-Bus connection, Windows posts `WM_QUIT`).
25//!    This wakes the background thread's event loop so it can observe the
26//!    disconnect.
27//! 2. **Channel disconnect** -- the shutdown channel sender is dropped,
28//!    causing the receiver in the background thread to see `Disconnected`
29//!    on its next `recv()` or `try_recv()`.
30//! 3. **Thread join** -- `JoinHandle::join()` blocks until the background
31//!    thread exits, ensuring clean shutdown before the guard is gone.
32//!
33//! # Signal-only events
34//!
35//! [`ThemeChangeEvent`] carries no theme data. When you receive an event,
36//! call [`detect::invalidate_caches()`](crate::detect::invalidate_caches),
37//! then re-run [`SystemTheme::from_system()`](crate::SystemTheme::from_system)
38//! to get the updated theme: the detection values (dark mode, reduced
39//! motion, the accessibility preferences, the icon theme and, on Linux, the
40//! desktop) stay cached until the caches are cleared, and the OS read takes
41//! its icon theme and desktop from them.
42//!
43//! # Example
44//!
45//! ```no_run
46//! use std::sync::mpsc;
47//!
48//! let (tx, rx) = mpsc::channel();
49//! let _watcher = native_theme::watch::on_theme_change(move |event| {
50//!     let _ = tx.send(event);
51//! })?;
52//!
53//! // On your UI thread:
54//! // if let Ok(event) = rx.try_recv() {
55//! //     native_theme::detect::invalidate_caches();
56//! //     let theme = native_theme::SystemTheme::from_system()?;
57//! //     // re-apply theme ...
58//! // }
59//! # Ok::<(), native_theme::error::Error>(())
60//! ```
61
62#[cfg(all(feature = "watch", feature = "kde", target_os = "linux"))]
63mod kde;
64
65#[cfg(all(feature = "watch", feature = "portal", target_os = "linux"))]
66mod gnome;
67
68#[cfg(all(feature = "watch", feature = "macos", target_os = "macos"))]
69mod macos;
70
71#[cfg(all(feature = "watch", feature = "windows", target_os = "windows"))]
72mod windows;
73
74use std::sync::mpsc;
75use std::thread::JoinHandle;
76
77/// A signal that the OS theme has changed.
78///
79/// This enum carries no theme data -- it is a notification only.
80/// When you receive an event, call
81/// [`detect::invalidate_caches()`](crate::detect::invalidate_caches), then
82/// [`SystemTheme::from_system()`](crate::SystemTheme::from_system)
83/// to read the updated theme; without the first call, the detection values
84/// (dark mode, reduced motion, the accessibility preferences, the icon theme
85/// and, on Linux, the desktop) are the cached ones, and the OS read takes its
86/// icon theme and desktop from them.
87///
88/// # Non-exhaustive
89///
90/// Future versions may add new variants. Always include a wildcard arm:
91///
92/// ```ignore
93/// match event {
94///     ThemeChangeEvent::Changed => { /* ... */ }
95///     _ => { /* handle future variants */ }
96/// }
97/// ```
98#[derive(Debug, Clone, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum ThemeChangeEvent {
101    /// The OS theme changed.
102    Changed,
103}
104
105/// RAII guard that keeps a theme watcher alive.
106///
107/// Holds a background thread and a shutdown channel. When dropped, the
108/// channel sender is dropped (signaling shutdown via disconnection) and
109/// the background thread is joined. On macOS it holds the notification
110/// observer instead, and dropping it removes the observer.
111///
112/// Note: `ThemeSubscription` is `Send` but not `Sync`. The background thread
113/// handle and shutdown channel are not safe to share across threads, but the
114/// guard can be moved to a different thread if needed.
115///
116/// # Dropping
117///
118/// `Drop` joins the watcher thread: a callback that is running when the drop
119/// starts finishes before the drop returns, and none runs after it. A
120/// callback may drop its own subscription: the drop then runs on the watcher
121/// thread, so it does not join it but detaches it, and the thread exits once
122/// the callback returns. On macOS, where there is no watcher thread,
123/// dropping removes the observer and waits for a callback already queued to
124/// finish; dropped from inside the callback, it returns without waiting, and
125/// a notification already queued can still run the callback once.
126///
127/// Because the drop waits for the callback, it deadlocks if a callback waits
128/// on a lock the dropping thread holds, or, on macOS, dispatches
129/// synchronously to the main thread while the main thread drops the
130/// subscription.
131///
132/// # Important
133///
134/// You **must** bind this to a variable. If you discard it, the watcher
135/// stops immediately:
136///
137/// ```ignore
138/// // WRONG -- watcher is dropped immediately:
139/// on_theme_change(|e| println!("{e:?}"));
140///
141/// // RIGHT -- watcher lives as long as `_watcher`:
142/// let _watcher = on_theme_change(|e| println!("{e:?}")).unwrap();
143/// ```
144#[must_use]
145pub struct ThemeSubscription {
146    shutdown_tx: Option<mpsc::Sender<()>>,
147    thread: Option<JoinHandle<()>>,
148    platform_shutdown: Option<Box<dyn FnOnce() + Send>>,
149}
150
151impl std::fmt::Debug for ThemeSubscription {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("ThemeSubscription")
154            .field("shutdown_tx", &self.shutdown_tx)
155            .field("thread", &self.thread)
156            .field(
157                "platform_shutdown",
158                &self.platform_shutdown.as_ref().map(|_| "..."),
159            )
160            .finish()
161    }
162}
163
164impl ThemeSubscription {
165    /// Create a new `ThemeSubscription` from a shutdown channel, thread handle,
166    /// and optional platform-specific shutdown action.
167    ///
168    /// The `platform_shutdown` closure (if `Some`) is called **before** the
169    /// channel is dropped during `Drop`, allowing platform backends to wake
170    /// their blocked event loops so the thread can observe the disconnect.
171    /// Pass `None` on KDE, where the inotify loop polls the channel; GNOME's
172    /// backend closes its D-Bus connection here.
173    ///
174    /// Compiled where a backend exists to call it, and for tests.
175    #[cfg(any(
176        test,
177        all(target_os = "linux", any(feature = "kde", feature = "portal")),
178        all(target_os = "windows", feature = "windows"),
179    ))]
180    pub(crate) fn new(
181        shutdown_tx: mpsc::Sender<()>,
182        thread: JoinHandle<()>,
183        platform_shutdown: Option<Box<dyn FnOnce() + Send>>,
184    ) -> Self {
185        Self {
186            shutdown_tx: Some(shutdown_tx),
187            thread: Some(thread),
188            platform_shutdown,
189        }
190    }
191
192    /// Create a `ThemeSubscription` for a watcher without a thread: dropping
193    /// it only runs `platform_shutdown`.
194    #[cfg(all(target_os = "macos", feature = "macos"))]
195    pub(crate) fn from_platform_shutdown(platform_shutdown: Box<dyn FnOnce() + Send>) -> Self {
196        Self {
197            shutdown_tx: None,
198            thread: None,
199            platform_shutdown: Some(platform_shutdown),
200        }
201    }
202}
203
204impl Drop for ThemeSubscription {
205    fn drop(&mut self) {
206        // Run the platform-specific shutdown action first (PostThreadMessageW
207        // WM_QUIT on Windows, Connection::close on GNOME) to wake the blocked
208        // event loop so it can observe the channel disconnect; on macOS it
209        // removes the notification observer.
210        if let Some(shutdown_fn) = self.platform_shutdown.take() {
211            shutdown_fn();
212        }
213        // Drop the sender to signal shutdown (receiver sees Disconnected).
214        drop(self.shutdown_tx.take());
215        // Join the background thread so it finishes cleanly. A callback that
216        // drops its own subscription runs on that thread, and a thread that
217        // joins itself fails (EDEADLK): dropping the handle detaches the
218        // thread instead, which exits once the callback returns.
219        if let Some(handle) = self.thread.take()
220            && handle.thread().id() != std::thread::current().id()
221        {
222            let _ = handle.join();
223        }
224    }
225}
226
227/// Call `callback` with [`ThemeChangeEvent::Changed`], containing a panic:
228/// a callback that panics loses that one event, and the watcher keeps
229/// running. This holds with the default `panic = "unwind"`; under
230/// `panic = "abort"` a panicking callback aborts the process.
231#[cfg(any(
232    test,
233    all(target_os = "linux", any(feature = "kde", feature = "portal")),
234    all(target_os = "macos", feature = "macos"),
235    all(target_os = "windows", feature = "windows"),
236))]
237fn fire(callback: &impl Fn(ThemeChangeEvent)) {
238    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
239        callback(ThemeChangeEvent::Changed)
240    }));
241}
242
243/// How long a watcher waits after the last notification of a burst before
244/// it fires: one user action can raise several notifications (KDE writes its
245/// files in several steps, `QSaveFile`'s atomic writes; GNOME's portal sends
246/// a gsettings key and the `org.freedesktop.appearance` setting it maps to),
247/// and the callback fires once for all of them. The value is T20's KDE
248/// window, reused on every platform to keep one user action one event: a
249/// design value, not a platform fact.
250#[cfg(any(
251    test,
252    all(target_os = "linux", any(feature = "kde", feature = "portal")),
253    all(target_os = "macos", feature = "macos"),
254    all(target_os = "windows", feature = "windows"),
255))]
256const DEBOUNCE_MS: u32 = 300;
257
258/// [`DEBOUNCE_MS`] as a [`Duration`](std::time::Duration).
259#[cfg(any(
260    test,
261    all(target_os = "linux", any(feature = "kde", feature = "portal")),
262    all(target_os = "macos", feature = "macos"),
263))]
264const DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(DEBOUNCE_MS as u64);
265
266/// Fire `callback` once per burst of relevant messages from `events`,
267/// [`DEBOUNCE`] after the last of them; `is_relevant` sorts them. Returns
268/// when `events` disconnects or `shutdown` is signalled or disconnected,
269/// which is checked on every iteration, at least every 200ms.
270#[cfg(any(
271    test,
272    all(target_os = "linux", any(feature = "kde", feature = "portal"))
273))]
274fn fire_debounced<T>(
275    events: &mpsc::Receiver<T>,
276    shutdown: &mpsc::Receiver<()>,
277    mut is_relevant: impl FnMut(T) -> bool,
278    callback: &impl Fn(ThemeChangeEvent),
279) {
280    use std::time::{Duration, Instant};
281
282    let poll = Duration::from_millis(200);
283    let mut debounce = Debounce::default();
284
285    loop {
286        match shutdown.try_recv() {
287            Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
288            Err(mpsc::TryRecvError::Empty) => {}
289        }
290
291        match events.recv_timeout(debounce.wait(Instant::now(), poll)) {
292            Ok(message) => {
293                if is_relevant(message) {
294                    debounce.note(Instant::now());
295                }
296            }
297            Err(mpsc::RecvTimeoutError::Timeout) => {}
298            Err(mpsc::RecvTimeoutError::Disconnected) => break,
299        }
300
301        if debounce.take_due(Instant::now()) {
302            fire(callback);
303        }
304    }
305}
306
307/// [`fire_debounced`]'s decision: when the last relevant message not yet
308/// fired arrived, and whether its burst is due. Every method takes the time
309/// as an argument, so the tests drive it with made-up instants: what a
310/// burst fires does not depend on how the test machine schedules threads.
311#[cfg(any(
312    test,
313    all(target_os = "linux", any(feature = "kde", feature = "portal"))
314))]
315#[derive(Debug, Default)]
316struct Debounce {
317    /// When the last relevant message not yet fired arrived; `None` while
318    /// no burst is pending.
319    last: Option<std::time::Instant>,
320}
321
322#[cfg(any(
323    test,
324    all(target_os = "linux", any(feature = "kde", feature = "portal"))
325))]
326impl Debounce {
327    /// A relevant message arrived at `now`: the pending burst, or a new
328    /// one, is due [`DEBOUNCE`] after it.
329    fn note(&mut self, now: std::time::Instant) {
330        self.last = Some(now);
331    }
332
333    /// How long to wait at `now` for the next message: `poll`, or less when
334    /// the pending burst is due sooner.
335    fn wait(&self, now: std::time::Instant, poll: std::time::Duration) -> std::time::Duration {
336        self.last.map_or(poll, |last| {
337            DEBOUNCE
338                .saturating_sub(now.saturating_duration_since(last))
339                .min(poll)
340        })
341    }
342
343    /// Whether the pending burst is due at `now`, [`DEBOUNCE`] after its
344    /// last message. A due burst is cleared, so it fires once.
345    fn take_due(&mut self, now: std::time::Instant) -> bool {
346        let due = self
347            .last
348            .is_some_and(|last| now.saturating_duration_since(last) >= DEBOUNCE);
349        if due {
350            self.last = None;
351        }
352        due
353    }
354}
355
356/// Start watching for OS theme changes.
357///
358/// The `callback` is invoked on a **background thread** whenever the OS
359/// theme changes. To marshal events to your UI thread, send them through
360/// a channel:
361///
362/// ```no_run
363/// use std::sync::mpsc;
364/// use native_theme::watch::ThemeChangeEvent;
365///
366/// let (tx, rx) = mpsc::channel();
367/// let _watcher = native_theme::watch::on_theme_change(move |event| {
368///     let _ = tx.send(event);
369/// })?;
370///
371/// // On UI thread:
372/// // match rx.try_recv() {
373/// //     Ok(ThemeChangeEvent::Changed) => {
374/// //         native_theme::detect::invalidate_caches();
375/// //         let theme = native_theme::SystemTheme::from_system()?;
376/// //         // re-apply theme ...
377/// //     }
378/// //     _ => {}
379/// // }
380/// # Ok::<(), native_theme::error::Error>(())
381/// ```
382///
383/// Clear the detection caches before the re-read, as above: the detection
384/// values (dark mode, reduced motion, the accessibility preferences, the icon
385/// theme and, on Linux, the desktop) are cached until
386/// [`detect::invalidate_caches()`](crate::detect::invalidate_caches), and the
387/// OS read takes its icon theme and desktop from them.
388///
389/// On macOS the change arrives as a distributed notification, which is
390/// delivered through the process's main run loop, so the application must be
391/// running one in a common mode; every GUI toolkit's event loop does
392/// (AppKit's `NSApplication::run`). See Apple's Notification Programming
393/// Topics, ["Notification Centers"](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Notifications/Articles/NotificationCenters.html).
394/// The callback then runs on a private serial queue, never on the main
395/// thread and never twice at once.
396///
397/// The watcher observes what the platform's reader reads (each reader
398/// module lists its sources): on KDE `kdeglobals` and `kdedefaults/kdeglobals`
399/// in the config directory; on GNOME and Budgie the
400/// portal's `SettingChanged` for the `org.freedesktop.appearance` settings
401/// and the `org.gnome.desktop.interface`, `org.gnome.desktop.wm.preferences`
402/// and `org.gnome.desktop.a11y.interface` keys the reader reads; on macOS
403/// the appearance, system-colour, scroller-style and accessibility-display
404/// notifications; on Windows `UISettings::ColorValuesChanged`,
405/// `TextScaleFactorChanged`, `AnimationsEnabledChanged` and
406/// `AdvancedEffectsEnabledChanged` (a change of high contrast is announced to
407/// top-level windows only, and the watcher has none). One change can raise several of them, so the
408/// callback fires once per burst, 300 ms after the last.
409///
410/// A callback that panics loses that one event: the panic is contained, and
411/// the watcher keeps running (with the default `panic = "unwind"`; under
412/// `panic = "abort"` the process aborts). A callback may drop the returned
413/// [`ThemeSubscription`]; see its "Dropping" section for what a drop waits
414/// for.
415///
416/// On Linux the backend is the one of the desktop the reader is chosen by:
417/// KDE's for KDE (with the `kde` feature), GNOME's for GNOME and Budgie (with
418/// `portal`). An unrecognised `XDG_CURRENT_DESKTOP` counts as the desktop of
419/// its portal backend once a system read such as
420/// [`SystemTheme::from_system`](crate::SystemTheme::from_system) has asked
421/// it, else as KDE where the user's `kdeglobals` exists.
422///
423/// # Errors
424///
425/// Returns [`Error::WatchUnavailable`](crate::Error::WatchUnavailable) if no
426/// platform-specific backend is available for the current desktop
427/// environment or platform, and
428/// [`Error::ReaderFailed`](crate::Error::ReaderFailed) if the backend could
429/// not start: KDE, the config directory is unresolved (`$XDG_CONFIG_HOME` is
430/// not an absolute path and `$HOME` is unset or empty) or cannot be watched
431/// (it does not exist, or the inotify limits are reached); GNOME and Budgie,
432/// the watcher thread could not connect to the session bus or subscribe to
433/// the portal's `SettingChanged` signal; Windows, the watcher thread did not
434/// start or could not subscribe to `UISettings::ColorValuesChanged` or
435/// `TextScaleFactorChanged`. The KDE backend sets up its watch on the
436/// calling thread, and the GNOME and Windows backends return only once their
437/// thread is subscribed; the macOS backend registers its observer on the
438/// calling thread and does not fail.
439pub fn on_theme_change(
440    callback: impl Fn(ThemeChangeEvent) + Send + 'static,
441) -> crate::Result<ThemeSubscription> {
442    #[cfg(target_os = "linux")]
443    {
444        #[cfg(not(any(feature = "kde", feature = "portal")))]
445        let _ = callback;
446        match linux_backend(crate::detect::system().refined_linux_desktop_sync()) {
447            #[cfg(feature = "kde")]
448            Some(LinuxBackend::Kde) => kde::watch_kde(callback),
449
450            #[cfg(feature = "portal")]
451            Some(LinuxBackend::Gnome) => gnome::watch_gnome(callback),
452
453            _ => Err(crate::Error::WatchUnavailable {
454                reason: "theme watching not supported for this desktop environment",
455            }),
456        }
457    }
458
459    #[cfg(target_os = "macos")]
460    {
461        #[cfg(feature = "macos")]
462        {
463            macos::watch_macos(callback)
464        }
465        #[cfg(not(feature = "macos"))]
466        {
467            let _ = callback;
468            Err(crate::Error::WatchUnavailable {
469                reason: "enable the 'macos' feature for macOS theme watching",
470            })
471        }
472    }
473
474    #[cfg(target_os = "windows")]
475    {
476        #[cfg(feature = "windows")]
477        {
478            windows::watch_windows(callback)
479        }
480        #[cfg(not(feature = "windows"))]
481        {
482            let _ = callback;
483            Err(crate::Error::WatchUnavailable {
484                reason: "enable the 'windows' feature for Windows theme watching",
485            })
486        }
487    }
488
489    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
490    {
491        let _ = callback;
492        Err(crate::Error::PlatformUnsupported {
493            platform: std::env::consts::OS,
494        })
495    }
496}
497
498/// A Linux watcher backend.
499#[cfg(target_os = "linux")]
500#[derive(Debug, Clone, Copy, PartialEq, Eq)]
501enum LinuxBackend {
502    /// [`kde::watch_kde`].
503    #[cfg(feature = "kde")]
504    Kde,
505    /// [`gnome::watch_gnome`].
506    #[cfg(feature = "portal")]
507    Gnome,
508}
509
510/// The backend that watches `desktop`, the refined desktop the reader is
511/// chosen by ([`crate::detect::refine_linux_desktop`]); `None` where there is
512/// none.
513#[cfg(target_os = "linux")]
514fn linux_backend(desktop: crate::LinuxDesktop) -> Option<LinuxBackend> {
515    match desktop {
516        #[cfg(feature = "kde")]
517        crate::LinuxDesktop::Kde => Some(LinuxBackend::Kde),
518        #[cfg(feature = "portal")]
519        crate::LinuxDesktop::Gnome | crate::LinuxDesktop::Budgie => Some(LinuxBackend::Gnome),
520        _ => None,
521    }
522}
523
524#[cfg(test)]
525#[allow(clippy::unwrap_used)]
526mod tests {
527    use super::*;
528
529    /// The watcher follows the reader on an unrecognised desktop: a KDE
530    /// portal backend gets KDE's watcher (M4-36).
531    #[cfg(all(target_os = "linux", feature = "kde"))]
532    #[test]
533    fn an_unknown_desktop_with_a_kde_portal_is_watched_as_kde() {
534        for kdeglobals in [false, true] {
535            let desktop = crate::detect::refine_linux_desktop(
536                crate::LinuxDesktop::Unknown,
537                Some(crate::LinuxDesktop::Kde),
538                || kdeglobals,
539            );
540            assert_eq!(linux_backend(desktop), Some(LinuxBackend::Kde));
541        }
542    }
543
544    /// A GNOME portal backend gets GNOME's watcher, `kdeglobals` or not.
545    #[cfg(all(target_os = "linux", feature = "portal"))]
546    #[test]
547    fn an_unknown_desktop_with_a_gnome_portal_is_watched_as_gnome() {
548        for kdeglobals in [false, true] {
549            let desktop = crate::detect::refine_linux_desktop(
550                crate::LinuxDesktop::Unknown,
551                Some(crate::LinuxDesktop::Gnome),
552                || kdeglobals,
553            );
554            assert_eq!(linux_backend(desktop), Some(LinuxBackend::Gnome));
555        }
556    }
557
558    /// An unrecognised desktop that nothing names has no watcher.
559    #[cfg(target_os = "linux")]
560    #[test]
561    fn an_unknown_desktop_that_nothing_names_is_not_watched() {
562        let desktop =
563            crate::detect::refine_linux_desktop(crate::LinuxDesktop::Unknown, None, || false);
564        assert_eq!(linux_backend(desktop), None);
565    }
566
567    /// The source-to-notification table (M1-T6-08): for each reader, every
568    /// source its module lists under `# Sources`, and the notification its
569    /// watcher observes for it: a file in the config directory (KDE), a
570    /// `namespace key` of the portal's `SettingChanged` (GNOME), a
571    /// notification name (macOS) or a `UISettings` event (Windows).
572    const SOURCE_NOTIFICATIONS: &[(&str, &str, &str)] = &[
573        ("kde", "kdeglobals", "kdeglobals"),
574        ("kde", "kdedefaults/kdeglobals", "kdedefaults/kdeglobals"),
575        // xdg-desktop-portal-kde's accent is the palette's highlight, which
576        // the colour scheme in kdeglobals sets.
577        (
578            "kde",
579            "org.freedesktop.appearance accent-color",
580            "kdeglobals",
581        ),
582        (
583            "gnome",
584            "org.freedesktop.appearance color-scheme",
585            "org.freedesktop.appearance color-scheme",
586        ),
587        (
588            "gnome",
589            "org.freedesktop.appearance accent-color",
590            "org.freedesktop.appearance accent-color",
591        ),
592        (
593            "gnome",
594            "org.freedesktop.appearance contrast",
595            "org.freedesktop.appearance contrast",
596        ),
597        (
598            "gnome",
599            "org.freedesktop.appearance reduced-motion",
600            "org.freedesktop.appearance reduced-motion",
601        ),
602        (
603            "gnome",
604            "org.gnome.desktop.interface color-scheme",
605            "org.gnome.desktop.interface color-scheme",
606        ),
607        (
608            "gnome",
609            "org.gnome.desktop.interface enable-animations",
610            "org.gnome.desktop.interface enable-animations",
611        ),
612        (
613            "gnome",
614            "org.gnome.desktop.interface font-name",
615            "org.gnome.desktop.interface font-name",
616        ),
617        (
618            "gnome",
619            "org.gnome.desktop.interface monospace-font-name",
620            "org.gnome.desktop.interface monospace-font-name",
621        ),
622        (
623            "gnome",
624            "org.gnome.desktop.interface text-scaling-factor",
625            "org.gnome.desktop.interface text-scaling-factor",
626        ),
627        (
628            "gnome",
629            "org.gnome.desktop.interface overlay-scrolling",
630            "org.gnome.desktop.interface overlay-scrolling",
631        ),
632        (
633            "gnome",
634            "org.gnome.desktop.interface icon-theme",
635            "org.gnome.desktop.interface icon-theme",
636        ),
637        (
638            "gnome",
639            "org.gnome.desktop.wm.preferences titlebar-font",
640            "org.gnome.desktop.wm.preferences titlebar-font",
641        ),
642        (
643            "gnome",
644            "org.gnome.desktop.a11y.interface high-contrast",
645            "org.gnome.desktop.a11y.interface high-contrast",
646        ),
647        (
648            "macos",
649            "AppleInterfaceStyle",
650            "AppleInterfaceThemeChangedNotification",
651        ),
652        ("macos", "NSColor", "NSSystemColorsDidChangeNotification"),
653        (
654            "macos",
655            "NSScroller.preferredScrollerStyle",
656            "NSPreferredScrollerStyleDidChangeNotification",
657        ),
658        (
659            "macos",
660            "NSWorkspace.accessibilityDisplayOptions",
661            "NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification",
662        ),
663        ("windows", "UISettings.GetColorValue", "ColorValuesChanged"),
664        (
665            "windows",
666            "UISettings.TextScaleFactor",
667            "TextScaleFactorChanged",
668        ),
669        // `UISettings.AnimationsEnabled` and SPI_GETCLIENTAREAANIMATION read
670        // the same on the three Windows probe images; no page says they are
671        // one setting.
672        (
673            "windows",
674            "SPI_GETCLIENTAREAANIMATION",
675            "AnimationsEnabledChanged",
676        ),
677        (
678            "windows",
679            "UISettings.AdvancedEffectsEnabled",
680            "AdvancedEffectsEnabledChanged",
681        ),
682    ];
683
684    /// Each reader's module source, whose docs list its sources.
685    const READER_MODULES: &[(&str, &str)] = &[
686        ("kde", include_str!("../kde/mod.rs")),
687        ("gnome", include_str!("../gnome/mod.rs")),
688        ("macos", include_str!("../macos.rs")),
689        ("windows", include_str!("../windows.rs")),
690    ];
691
692    /// The sources a reader module lists: the first code span of each item
693    /// of its `# Sources` doc section.
694    fn listed_sources(module: &'static str) -> Vec<&'static str> {
695        module
696            .lines()
697            .skip_while(|line| line.trim_end() != "//! # Sources")
698            .skip(1)
699            .take_while(|line| line.starts_with("//!") && !line.starts_with("//! #"))
700            .filter_map(|line| line.strip_prefix("//! - `"))
701            .filter_map(|item| item.split('`').next())
702            .collect()
703    }
704
705    /// The notifications the table gives for `reader`'s sources.
706    #[cfg(any(
707        all(target_os = "linux", any(feature = "kde", feature = "portal")),
708        all(target_os = "macos", feature = "macos"),
709        all(target_os = "windows", feature = "windows"),
710    ))]
711    fn table_notifications(reader: &str) -> impl Iterator<Item = &'static str> {
712        SOURCE_NOTIFICATIONS
713            .iter()
714            .filter(move |(row_reader, _, _)| *row_reader == reader)
715            .map(|(_, _, notification)| *notification)
716    }
717
718    /// Every source a reader lists has a row in [`SOURCE_NOTIFICATIONS`],
719    /// and every row names a listed source.
720    #[test]
721    fn every_listed_source_has_a_table_row() {
722        for (reader, module) in READER_MODULES {
723            let sources = listed_sources(module);
724            assert!(!sources.is_empty(), "{reader}: no `# Sources` list");
725            for source in &sources {
726                assert!(
727                    SOURCE_NOTIFICATIONS
728                        .iter()
729                        .any(|(r, s, _)| r == reader && s == source),
730                    "{reader}: the source `{source}` has no row in SOURCE_NOTIFICATIONS"
731                );
732            }
733            for (_, source, _) in SOURCE_NOTIFICATIONS.iter().filter(|(r, _, _)| r == reader) {
734                assert!(
735                    sources.contains(source),
736                    "{reader}: the row for `{source}` names a source the reader does not list"
737                );
738            }
739        }
740    }
741
742    /// The KDE watcher observes the file of every KDE row, and no other file.
743    #[cfg(all(target_os = "linux", feature = "kde"))]
744    #[test]
745    fn the_kde_watcher_observes_every_kde_source() {
746        for file in table_notifications("kde") {
747            assert!(
748                kde::WATCHED_FILES.contains(&file),
749                "the KDE watcher does not observe `{file}`"
750            );
751        }
752        for file in kde::WATCHED_FILES {
753            assert!(
754                table_notifications("kde").any(|n| n == *file),
755                "the KDE watcher observes `{file}`, which no KDE source row names"
756            );
757        }
758    }
759
760    /// The GNOME watcher fires on the `SettingChanged` of every GNOME row.
761    #[cfg(all(target_os = "linux", feature = "portal"))]
762    #[test]
763    fn the_gnome_watcher_observes_every_gnome_source() {
764        for setting in table_notifications("gnome") {
765            let (namespace, key) = setting.split_once(' ').unwrap();
766            assert!(
767                gnome::watches(namespace, key),
768                "the GNOME watcher ignores the SettingChanged of `{setting}`"
769            );
770        }
771    }
772
773    /// Every gsettings key the GNOME reader reads is a listed source.
774    #[cfg(all(target_os = "linux", feature = "portal"))]
775    #[test]
776    fn the_gnome_reader_lists_every_gsetting_it_reads() {
777        let sources = listed_sources(include_str!("../gnome/mod.rs"));
778        let mut read = Vec::new();
779        let _ = crate::gnome::build_theme(
780            None,
781            None,
782            ashpd::desktop::settings::Contrast::default(),
783            None,
784            None,
785            |schema, key| {
786                read.push(format!("{schema} {key}"));
787                None
788            },
789        );
790        assert!(!read.is_empty());
791        for setting in &read {
792            assert!(
793                sources.contains(&setting.as_str()),
794                "the GNOME reader reads `{setting}`, which its `# Sources` do not list"
795            );
796        }
797    }
798
799    /// The macOS watcher observes the notification of every macOS row.
800    #[cfg(all(target_os = "macos", feature = "macos"))]
801    #[test]
802    fn the_macos_watcher_observes_every_macos_source() {
803        let observed: Vec<&str> = macos::registrations().iter().map(|r| r.name_id).collect();
804        for notification in table_notifications("macos") {
805            assert!(
806                observed.contains(&notification),
807                "the macOS watcher does not observe `{notification}`"
808            );
809        }
810    }
811
812    /// The Windows watcher subscribes to the event of every Windows row.
813    #[cfg(all(target_os = "windows", feature = "windows"))]
814    #[test]
815    fn the_windows_watcher_observes_every_windows_source() {
816        for event in table_notifications("windows") {
817            assert!(
818                windows::SUBSCRIBED_EVENTS.contains(&event),
819                "the Windows watcher does not subscribe to `{event}`"
820            );
821        }
822    }
823
824    #[test]
825    fn theme_change_event_is_debug_clone_eq() {
826        let event = ThemeChangeEvent::Changed;
827        let cloned = event.clone();
828        assert_eq!(event, cloned);
829        // Debug
830        let debug_str = format!("{:?}", event);
831        assert!(debug_str.contains("Changed"));
832    }
833
834    /// On unsupported platforms, on_theme_change() returns PlatformUnsupported.
835    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
836    #[test]
837    fn on_theme_change_returns_unsupported() {
838        let result = on_theme_change(|_| {});
839        assert!(result.is_err());
840        let err = result.unwrap_err();
841        assert!(
842            matches!(&err, crate::Error::PlatformUnsupported { .. }),
843            "expected PlatformUnsupported, got: {err:?}"
844        );
845    }
846
847    /// On Linux, on_theme_change() dispatches based on the detected DE.
848    /// In CI (no DE running), XDG_CURRENT_DESKTOP is usually empty/Unknown,
849    /// so we get WatchUnavailable. On a real DE it may succeed or return
850    /// ReaderFailed. All outcomes are valid.
851    #[cfg(target_os = "linux")]
852    #[test]
853    fn on_theme_change_dispatches_or_returns_error() {
854        let result = on_theme_change(|_| {});
855        assert!(
856            matches!(
857                &result,
858                Ok(_)
859                    | Err(crate::Error::WatchUnavailable { .. })
860                    | Err(crate::Error::PlatformUnsupported { .. })
861                    | Err(crate::Error::ReaderFailed { .. })
862            ),
863            "unexpected result: {result:?}"
864        );
865    }
866
867    #[test]
868    fn theme_subscription_drop_signals_shutdown() {
869        use std::sync::mpsc;
870        use std::thread;
871
872        let (tx, rx) = mpsc::channel();
873        let thread_handle = thread::spawn(move || {
874            // Block until shutdown signal (channel disconnected)
875            let _ = rx.recv();
876        });
877
878        let watcher = ThemeSubscription::new(tx, thread_handle, None);
879        // Drop the watcher -- should signal shutdown and join thread
880        drop(watcher);
881        // If we get here, the thread was joined successfully (did not hang)
882    }
883
884    /// A panicking callback is contained: `fire` returns, and the next call
885    /// runs the callback again (M4-33).
886    #[test]
887    fn fire_contains_a_panicking_callback() {
888        use std::sync::atomic::{AtomicUsize, Ordering};
889
890        let calls = AtomicUsize::new(0);
891        let callback = |_| {
892            let call = calls.fetch_add(1, Ordering::SeqCst);
893            assert!(call > 0, "the first call panics");
894        };
895        fire(&callback);
896        fire(&callback);
897        assert_eq!(calls.load(Ordering::SeqCst), 2);
898    }
899
900    /// The instant `ms` milliseconds after `start`.
901    fn after(start: std::time::Instant, ms: u64) -> std::time::Instant {
902        start + std::time::Duration::from_millis(ms)
903    }
904
905    /// Messages closer together than [`DEBOUNCE`] are one burst, due once,
906    /// [`DEBOUNCE`] after the last of them, not after the first
907    /// (`docs/archive/todo_closed.md`, *Closed items from Theme watcher: OS
908    /// changes it does not report*, "KDE: the 300 ms throttle keeps the first
909    /// event of a burst").
910    #[test]
911    fn a_burst_is_due_once_after_its_last_message() {
912        let start = std::time::Instant::now();
913        let window = u64::from(DEBOUNCE_MS);
914        let mut debounce = Debounce::default();
915        for ms in [0, 50, 100, 150, 200, 250] {
916            assert!(
917                !debounce.take_due(after(start, ms)),
918                "due at {ms} ms, inside the burst"
919            );
920            debounce.note(after(start, ms));
921        }
922        assert!(!debounce.take_due(after(start, 250 + window - 1)));
923        assert!(debounce.take_due(after(start, 250 + window)));
924        assert!(
925            !debounce.take_due(after(start, 250 + 2 * window)),
926            "a burst is due once"
927        );
928    }
929
930    /// A gap of [`DEBOUNCE`] between two messages makes two bursts.
931    #[test]
932    fn a_gap_of_the_debounce_window_makes_two_bursts() {
933        let start = std::time::Instant::now();
934        let window = u64::from(DEBOUNCE_MS);
935        let mut debounce = Debounce::default();
936        assert!(!debounce.take_due(start), "nothing is due before a message");
937        debounce.note(start);
938        assert!(debounce.take_due(after(start, window)));
939        debounce.note(after(start, window));
940        assert!(!debounce.take_due(after(start, 2 * window - 1)));
941        assert!(debounce.take_due(after(start, 2 * window)));
942    }
943
944    /// The loop waits `poll` while no burst is pending, then no longer than
945    /// until the pending burst is due, and not at all once it is.
946    #[test]
947    fn the_wait_ends_when_the_burst_is_due() {
948        use std::time::Duration;
949
950        let start = std::time::Instant::now();
951        let window = u64::from(DEBOUNCE_MS);
952        let poll = Duration::from_millis(200);
953        let mut debounce = Debounce::default();
954        assert_eq!(debounce.wait(start, poll), poll);
955        debounce.note(start);
956        assert_eq!(debounce.wait(start, poll), poll);
957        assert_eq!(
958            debounce.wait(after(start, window - 50), poll),
959            Duration::from_millis(50)
960        );
961        assert_eq!(debounce.wait(after(start, window), poll), Duration::ZERO);
962        assert_eq!(
963            debounce.wait(after(start, 2 * window), poll),
964            Duration::ZERO
965        );
966    }
967
968    /// `fire_debounced` on the real clock: an irrelevant message fires
969    /// nothing; a burst of relevant ones fires [`DEBOUNCE`] after the last of
970    /// them, at most once per relevant message; it returns when its channel
971    /// disconnects. A loaded machine can stall a thread past [`DEBOUNCE`]
972    /// and split the burst, so that it fires exactly once is checked on
973    /// made-up instants ([`a_burst_is_due_once_after_its_last_message`]).
974    #[test]
975    fn fire_debounced_fires_after_the_last_relevant_message() {
976        use std::time::{Duration, Instant};
977
978        let (events_tx, events_rx) = mpsc::channel::<bool>();
979        let (_shutdown_tx, shutdown_rx) = mpsc::channel::<()>();
980        let (fired_tx, fired_rx) = mpsc::channel::<Instant>();
981        let watcher = std::thread::spawn(move || {
982            fire_debounced(&events_rx, &shutdown_rx, |relevant| relevant, &|_| {
983                let _ = fired_tx.send(Instant::now());
984            });
985        });
986
987        let _ = events_tx.send(false);
988        assert!(
989            fired_rx.recv_timeout(DEBOUNCE * 2).is_err(),
990            "an irrelevant message fired"
991        );
992
993        let relevant_messages = [true, false, true, true];
994        let mut before_last = Instant::now();
995        for relevant in relevant_messages {
996            std::thread::sleep(Duration::from_millis(50));
997            if relevant {
998                before_last = Instant::now();
999            }
1000            let _ = events_tx.send(relevant);
1001        }
1002        // The last relevant message arrives after `before_last`, and its
1003        // burst fires DEBOUNCE after that.
1004        let due = before_last + DEBOUNCE;
1005        let deadline = Instant::now() + Duration::from_secs(5);
1006        let mut fires = 0;
1007        let mut fired_when_due = false;
1008        while !fired_when_due {
1009            match fired_rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
1010                Ok(fired) => {
1011                    fires += 1;
1012                    fired_when_due = fired >= due;
1013                }
1014                Err(_) => break,
1015            }
1016        }
1017        assert!(
1018            fired_when_due,
1019            "no fire DEBOUNCE after the last relevant message"
1020        );
1021
1022        drop(events_tx);
1023        watcher.join().unwrap();
1024        fires += fired_rx.try_iter().count();
1025        let relevant = relevant_messages.iter().filter(|&&r| r).count();
1026        assert!(
1027            fires <= relevant,
1028            "{fires} fires for {relevant} relevant messages"
1029        );
1030    }
1031
1032    #[test]
1033    fn theme_subscription_is_send() {
1034        fn assert_send<T: Send>() {}
1035        assert_send::<ThemeSubscription>();
1036    }
1037
1038    /// Start the platform watcher and drop it at once, `rounds` times. Each
1039    /// round subscribes and drops on a helper thread, with nothing between
1040    /// the two, so a drop that hangs fails the test after `per_drop_timeout`
1041    /// instead of blocking it. A platform or desktop without a watcher
1042    /// (`WatchUnavailable`) skips the test.
1043    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
1044    fn assert_subscribe_and_drop_returns(rounds: usize, per_drop_timeout: std::time::Duration) {
1045        for round in 0..rounds {
1046            let (done_tx, done_rx) = mpsc::channel();
1047            std::thread::spawn(move || {
1048                let result = on_theme_change(|_| {}).map(drop);
1049                let _ = done_tx.send(result);
1050            });
1051            match done_rx.recv_timeout(per_drop_timeout) {
1052                Ok(Ok(())) => {}
1053                Ok(Err(crate::Error::WatchUnavailable { .. })) => return,
1054                Ok(Err(err)) => panic!("round {round}: on_theme_change failed: {err:?}"),
1055                Err(_) => panic!(
1056                    "round {round}: subscribing and dropping did not return within {per_drop_timeout:?}"
1057                ),
1058            }
1059        }
1060    }
1061
1062    #[cfg(all(target_os = "macos", feature = "watch"))]
1063    #[test]
1064    fn macos_subscribe_and_drop_returns() {
1065        assert_subscribe_and_drop_returns(1000, std::time::Duration::from_secs(5));
1066    }
1067
1068    #[cfg(all(target_os = "windows", feature = "watch"))]
1069    #[test]
1070    fn windows_subscribe_and_drop_returns() {
1071        assert_subscribe_and_drop_returns(1000, std::time::Duration::from_secs(5));
1072    }
1073
1074    /// The KDE watcher polls its shutdown channel every 200 ms, so a drop
1075    /// takes up to that long: a few rounds keep the test short.
1076    #[cfg(all(target_os = "linux", feature = "watch"))]
1077    #[test]
1078    fn linux_subscribe_and_drop_returns() {
1079        assert_subscribe_and_drop_returns(10, std::time::Duration::from_secs(5));
1080    }
1081}