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