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 cursor-blink",
635 "org.gnome.desktop.interface cursor-blink",
636 ),
637 (
638 "gnome",
639 "org.gnome.desktop.interface cursor-blink-time",
640 "org.gnome.desktop.interface cursor-blink-time",
641 ),
642 (
643 "gnome",
644 "org.gnome.desktop.interface cursor-blink-timeout",
645 "org.gnome.desktop.interface cursor-blink-timeout",
646 ),
647 (
648 "gnome",
649 "org.gnome.desktop.interface icon-theme",
650 "org.gnome.desktop.interface icon-theme",
651 ),
652 (
653 "gnome",
654 "org.gnome.desktop.wm.preferences titlebar-font",
655 "org.gnome.desktop.wm.preferences titlebar-font",
656 ),
657 (
658 "gnome",
659 "org.gnome.desktop.a11y.interface high-contrast",
660 "org.gnome.desktop.a11y.interface high-contrast",
661 ),
662 (
663 "macos",
664 "AppleInterfaceStyle",
665 "AppleInterfaceThemeChangedNotification",
666 ),
667 ("macos", "NSColor", "NSSystemColorsDidChangeNotification"),
668 (
669 "macos",
670 "NSScroller.preferredScrollerStyle",
671 "NSPreferredScrollerStyleDidChangeNotification",
672 ),
673 (
674 "macos",
675 "NSWorkspace.accessibilityDisplayOptions",
676 "NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification",
677 ),
678 ("windows", "UISettings.GetColorValue", "ColorValuesChanged"),
679 (
680 "windows",
681 "UISettings.TextScaleFactor",
682 "TextScaleFactorChanged",
683 ),
684 // `UISettings.AnimationsEnabled` and SPI_GETCLIENTAREAANIMATION read
685 // the same on the three Windows probe images; no page says they are
686 // one setting.
687 (
688 "windows",
689 "SPI_GETCLIENTAREAANIMATION",
690 "AnimationsEnabledChanged",
691 ),
692 (
693 "windows",
694 "UISettings.AdvancedEffectsEnabled",
695 "AdvancedEffectsEnabledChanged",
696 ),
697 ];
698
699 /// Each reader's module source, whose docs list its sources.
700 const READER_MODULES: &[(&str, &str)] = &[
701 ("kde", include_str!("../kde/mod.rs")),
702 ("gnome", include_str!("../gnome/mod.rs")),
703 ("macos", include_str!("../macos.rs")),
704 ("windows", include_str!("../windows.rs")),
705 ];
706
707 /// The sources a reader module lists: the first code span of each item
708 /// of its `# Sources` doc section.
709 fn listed_sources(module: &'static str) -> Vec<&'static str> {
710 module
711 .lines()
712 .skip_while(|line| line.trim_end() != "//! # Sources")
713 .skip(1)
714 .take_while(|line| line.starts_with("//!") && !line.starts_with("//! #"))
715 .filter_map(|line| line.strip_prefix("//! - `"))
716 .filter_map(|item| item.split('`').next())
717 .collect()
718 }
719
720 /// The notifications the table gives for `reader`'s sources.
721 #[cfg(any(
722 all(target_os = "linux", any(feature = "kde", feature = "portal")),
723 all(target_os = "macos", feature = "macos"),
724 all(target_os = "windows", feature = "windows"),
725 ))]
726 fn table_notifications(reader: &str) -> impl Iterator<Item = &'static str> {
727 SOURCE_NOTIFICATIONS
728 .iter()
729 .filter(move |(row_reader, _, _)| *row_reader == reader)
730 .map(|(_, _, notification)| *notification)
731 }
732
733 /// Every source a reader lists has a row in [`SOURCE_NOTIFICATIONS`],
734 /// and every row names a listed source.
735 #[test]
736 fn every_listed_source_has_a_table_row() {
737 for (reader, module) in READER_MODULES {
738 let sources = listed_sources(module);
739 assert!(!sources.is_empty(), "{reader}: no `# Sources` list");
740 for source in &sources {
741 assert!(
742 SOURCE_NOTIFICATIONS
743 .iter()
744 .any(|(r, s, _)| r == reader && s == source),
745 "{reader}: the source `{source}` has no row in SOURCE_NOTIFICATIONS"
746 );
747 }
748 for (_, source, _) in SOURCE_NOTIFICATIONS.iter().filter(|(r, _, _)| r == reader) {
749 assert!(
750 sources.contains(source),
751 "{reader}: the row for `{source}` names a source the reader does not list"
752 );
753 }
754 }
755 }
756
757 /// The KDE watcher observes the file of every KDE row, and no other file.
758 #[cfg(all(target_os = "linux", feature = "kde"))]
759 #[test]
760 fn the_kde_watcher_observes_every_kde_source() {
761 for file in table_notifications("kde") {
762 assert!(
763 kde::WATCHED_FILES.contains(&file),
764 "the KDE watcher does not observe `{file}`"
765 );
766 }
767 for file in kde::WATCHED_FILES {
768 assert!(
769 table_notifications("kde").any(|n| n == *file),
770 "the KDE watcher observes `{file}`, which no KDE source row names"
771 );
772 }
773 }
774
775 /// The GNOME watcher fires on the `SettingChanged` of every GNOME row.
776 #[cfg(all(target_os = "linux", feature = "portal"))]
777 #[test]
778 fn the_gnome_watcher_observes_every_gnome_source() {
779 for setting in table_notifications("gnome") {
780 let (namespace, key) = setting.split_once(' ').unwrap();
781 assert!(
782 gnome::watches(namespace, key),
783 "the GNOME watcher ignores the SettingChanged of `{setting}`"
784 );
785 }
786 }
787
788 /// Every gsettings key the GNOME reader reads is a listed source.
789 #[cfg(all(target_os = "linux", feature = "portal"))]
790 #[test]
791 fn the_gnome_reader_lists_every_gsetting_it_reads() {
792 let sources = listed_sources(include_str!("../gnome/mod.rs"));
793 let mut read = Vec::new();
794 let _ = crate::gnome::build_theme(
795 None,
796 None,
797 ashpd::desktop::settings::Contrast::default(),
798 None,
799 None,
800 |schema, key| {
801 read.push(format!("{schema} {key}"));
802 None
803 },
804 );
805 assert!(!read.is_empty());
806 for setting in &read {
807 assert!(
808 sources.contains(&setting.as_str()),
809 "the GNOME reader reads `{setting}`, which its `# Sources` do not list"
810 );
811 }
812 }
813
814 /// The macOS watcher observes the notification of every macOS row.
815 #[cfg(all(target_os = "macos", feature = "macos"))]
816 #[test]
817 fn the_macos_watcher_observes_every_macos_source() {
818 let observed: Vec<&str> = macos::registrations().iter().map(|r| r.name_id).collect();
819 for notification in table_notifications("macos") {
820 assert!(
821 observed.contains(¬ification),
822 "the macOS watcher does not observe `{notification}`"
823 );
824 }
825 }
826
827 /// The Windows watcher subscribes to the event of every Windows row.
828 #[cfg(all(target_os = "windows", feature = "windows"))]
829 #[test]
830 fn the_windows_watcher_observes_every_windows_source() {
831 for event in table_notifications("windows") {
832 assert!(
833 windows::SUBSCRIBED_EVENTS.contains(&event),
834 "the Windows watcher does not subscribe to `{event}`"
835 );
836 }
837 }
838
839 #[test]
840 fn theme_change_event_is_debug_clone_eq() {
841 let event = ThemeChangeEvent::Changed;
842 let cloned = event.clone();
843 assert_eq!(event, cloned);
844 // Debug
845 let debug_str = format!("{:?}", event);
846 assert!(debug_str.contains("Changed"));
847 }
848
849 /// On unsupported platforms, on_theme_change() returns PlatformUnsupported.
850 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
851 #[test]
852 fn on_theme_change_returns_unsupported() {
853 let result = on_theme_change(|_| {});
854 assert!(result.is_err());
855 let err = result.unwrap_err();
856 assert!(
857 matches!(&err, crate::Error::PlatformUnsupported { .. }),
858 "expected PlatformUnsupported, got: {err:?}"
859 );
860 }
861
862 /// On Linux, on_theme_change() dispatches based on the detected DE.
863 /// In CI (no DE running), XDG_CURRENT_DESKTOP is usually empty/Unknown,
864 /// so we get WatchUnavailable. On a real DE it may succeed or return
865 /// ReaderFailed. All outcomes are valid.
866 #[cfg(target_os = "linux")]
867 #[test]
868 fn on_theme_change_dispatches_or_returns_error() {
869 let result = on_theme_change(|_| {});
870 assert!(
871 matches!(
872 &result,
873 Ok(_)
874 | Err(crate::Error::WatchUnavailable { .. })
875 | Err(crate::Error::PlatformUnsupported { .. })
876 | Err(crate::Error::ReaderFailed { .. })
877 ),
878 "unexpected result: {result:?}"
879 );
880 }
881
882 #[test]
883 fn theme_subscription_drop_signals_shutdown() {
884 use std::sync::mpsc;
885 use std::thread;
886
887 let (tx, rx) = mpsc::channel();
888 let thread_handle = thread::spawn(move || {
889 // Block until shutdown signal (channel disconnected)
890 let _ = rx.recv();
891 });
892
893 let watcher = ThemeSubscription::new(tx, thread_handle, None);
894 // Drop the watcher -- should signal shutdown and join thread
895 drop(watcher);
896 // If we get here, the thread was joined successfully (did not hang)
897 }
898
899 /// A panicking callback is contained: `fire` returns, and the next call
900 /// runs the callback again (M4-33).
901 #[test]
902 fn fire_contains_a_panicking_callback() {
903 use std::sync::atomic::{AtomicUsize, Ordering};
904
905 let calls = AtomicUsize::new(0);
906 let callback = |_| {
907 let call = calls.fetch_add(1, Ordering::SeqCst);
908 assert!(call > 0, "the first call panics");
909 };
910 fire(&callback);
911 fire(&callback);
912 assert_eq!(calls.load(Ordering::SeqCst), 2);
913 }
914
915 /// The instant `ms` milliseconds after `start`.
916 fn after(start: std::time::Instant, ms: u64) -> std::time::Instant {
917 start + std::time::Duration::from_millis(ms)
918 }
919
920 /// Messages closer together than [`DEBOUNCE`] are one burst, due once,
921 /// [`DEBOUNCE`] after the last of them, not after the first
922 /// (`docs/archive/todo_closed.md`, *Closed items from Theme watcher: OS
923 /// changes it does not report*, "KDE: the 300 ms throttle keeps the first
924 /// event of a burst").
925 #[test]
926 fn a_burst_is_due_once_after_its_last_message() {
927 let start = std::time::Instant::now();
928 let window = u64::from(DEBOUNCE_MS);
929 let mut debounce = Debounce::default();
930 for ms in [0, 50, 100, 150, 200, 250] {
931 assert!(
932 !debounce.take_due(after(start, ms)),
933 "due at {ms} ms, inside the burst"
934 );
935 debounce.note(after(start, ms));
936 }
937 assert!(!debounce.take_due(after(start, 250 + window - 1)));
938 assert!(debounce.take_due(after(start, 250 + window)));
939 assert!(
940 !debounce.take_due(after(start, 250 + 2 * window)),
941 "a burst is due once"
942 );
943 }
944
945 /// A gap of [`DEBOUNCE`] between two messages makes two bursts.
946 #[test]
947 fn a_gap_of_the_debounce_window_makes_two_bursts() {
948 let start = std::time::Instant::now();
949 let window = u64::from(DEBOUNCE_MS);
950 let mut debounce = Debounce::default();
951 assert!(!debounce.take_due(start), "nothing is due before a message");
952 debounce.note(start);
953 assert!(debounce.take_due(after(start, window)));
954 debounce.note(after(start, window));
955 assert!(!debounce.take_due(after(start, 2 * window - 1)));
956 assert!(debounce.take_due(after(start, 2 * window)));
957 }
958
959 /// The loop waits `poll` while no burst is pending, then no longer than
960 /// until the pending burst is due, and not at all once it is.
961 #[test]
962 fn the_wait_ends_when_the_burst_is_due() {
963 use std::time::Duration;
964
965 let start = std::time::Instant::now();
966 let window = u64::from(DEBOUNCE_MS);
967 let poll = Duration::from_millis(200);
968 let mut debounce = Debounce::default();
969 assert_eq!(debounce.wait(start, poll), poll);
970 debounce.note(start);
971 assert_eq!(debounce.wait(start, poll), poll);
972 assert_eq!(
973 debounce.wait(after(start, window - 50), poll),
974 Duration::from_millis(50)
975 );
976 assert_eq!(debounce.wait(after(start, window), poll), Duration::ZERO);
977 assert_eq!(
978 debounce.wait(after(start, 2 * window), poll),
979 Duration::ZERO
980 );
981 }
982
983 /// `fire_debounced` on the real clock: an irrelevant message fires
984 /// nothing; a burst of relevant ones fires [`DEBOUNCE`] after the last of
985 /// them, at most once per relevant message; it returns when its channel
986 /// disconnects. A loaded machine can stall a thread past [`DEBOUNCE`]
987 /// and split the burst, so that it fires exactly once is checked on
988 /// made-up instants ([`a_burst_is_due_once_after_its_last_message`]).
989 #[test]
990 fn fire_debounced_fires_after_the_last_relevant_message() {
991 use std::time::{Duration, Instant};
992
993 let (events_tx, events_rx) = mpsc::channel::<bool>();
994 let (_shutdown_tx, shutdown_rx) = mpsc::channel::<()>();
995 let (fired_tx, fired_rx) = mpsc::channel::<Instant>();
996 let watcher = std::thread::spawn(move || {
997 fire_debounced(&events_rx, &shutdown_rx, |relevant| relevant, &|_| {
998 let _ = fired_tx.send(Instant::now());
999 });
1000 });
1001
1002 let _ = events_tx.send(false);
1003 assert!(
1004 fired_rx.recv_timeout(DEBOUNCE * 2).is_err(),
1005 "an irrelevant message fired"
1006 );
1007
1008 let relevant_messages = [true, false, true, true];
1009 let mut before_last = Instant::now();
1010 for relevant in relevant_messages {
1011 std::thread::sleep(Duration::from_millis(50));
1012 if relevant {
1013 before_last = Instant::now();
1014 }
1015 let _ = events_tx.send(relevant);
1016 }
1017 // The last relevant message arrives after `before_last`, and its
1018 // burst fires DEBOUNCE after that.
1019 let due = before_last + DEBOUNCE;
1020 let deadline = Instant::now() + Duration::from_secs(5);
1021 let mut fires = 0;
1022 let mut fired_when_due = false;
1023 while !fired_when_due {
1024 match fired_rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
1025 Ok(fired) => {
1026 fires += 1;
1027 fired_when_due = fired >= due;
1028 }
1029 Err(_) => break,
1030 }
1031 }
1032 assert!(
1033 fired_when_due,
1034 "no fire DEBOUNCE after the last relevant message"
1035 );
1036
1037 drop(events_tx);
1038 watcher.join().unwrap();
1039 fires += fired_rx.try_iter().count();
1040 let relevant = relevant_messages.iter().filter(|&&r| r).count();
1041 assert!(
1042 fires <= relevant,
1043 "{fires} fires for {relevant} relevant messages"
1044 );
1045 }
1046
1047 #[test]
1048 fn theme_subscription_is_send() {
1049 fn assert_send<T: Send>() {}
1050 assert_send::<ThemeSubscription>();
1051 }
1052
1053 /// Start the platform watcher and drop it at once, `rounds` times. Each
1054 /// round subscribes and drops on a helper thread, with nothing between
1055 /// the two, so a drop that hangs fails the test after `per_drop_timeout`
1056 /// instead of blocking it. A platform or desktop without a watcher
1057 /// (`WatchUnavailable`) skips the test.
1058 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
1059 fn assert_subscribe_and_drop_returns(rounds: usize, per_drop_timeout: std::time::Duration) {
1060 for round in 0..rounds {
1061 let (done_tx, done_rx) = mpsc::channel();
1062 std::thread::spawn(move || {
1063 let result = on_theme_change(|_| {}).map(drop);
1064 let _ = done_tx.send(result);
1065 });
1066 match done_rx.recv_timeout(per_drop_timeout) {
1067 Ok(Ok(())) => {}
1068 Ok(Err(crate::Error::WatchUnavailable { .. })) => return,
1069 Ok(Err(err)) => panic!("round {round}: on_theme_change failed: {err:?}"),
1070 Err(_) => panic!(
1071 "round {round}: subscribing and dropping did not return within {per_drop_timeout:?}"
1072 ),
1073 }
1074 }
1075 }
1076
1077 #[cfg(all(target_os = "macos", feature = "watch"))]
1078 #[test]
1079 fn macos_subscribe_and_drop_returns() {
1080 assert_subscribe_and_drop_returns(1000, std::time::Duration::from_secs(5));
1081 }
1082
1083 #[cfg(all(target_os = "windows", feature = "watch"))]
1084 #[test]
1085 fn windows_subscribe_and_drop_returns() {
1086 assert_subscribe_and_drop_returns(1000, std::time::Duration::from_secs(5));
1087 }
1088
1089 /// The KDE watcher polls its shutdown channel every 200 ms, so a drop
1090 /// takes up to that long: a few rounds keep the test short.
1091 #[cfg(all(target_os = "linux", feature = "watch"))]
1092 #[test]
1093 fn linux_subscribe_and_drop_returns() {
1094 assert_subscribe_and_drop_returns(10, std::time::Duration::from_secs(5));
1095 }
1096}