Skip to main content

native_theme/
lib.rs

1//! # native-theme
2//!
3//! Cross-platform native theme detection and loading for Rust GUI applications.
4//!
5//! Any Rust GUI app can look native on any platform by loading a single theme
6//! file or reading live OS settings, without coupling to any specific toolkit.
7
8#![warn(missing_docs)]
9#![deny(unsafe_code)]
10#![deny(clippy::unwrap_used)]
11#![deny(clippy::expect_used)]
12
13#[doc = include_str!("../README.md")]
14#[cfg(doctest)]
15pub struct ReadmeDoctests;
16
17/// Generates `merge()` and `is_empty()` methods for theme structs.
18///
19/// Four field categories:
20/// - `option { field1, field2, ... }` -- `Option<T>` leaf fields
21/// - `soft_option { field1, field2, ... }` -- `Option<T>` leaf fields (same merge/is_empty as option)
22/// - `nested { field1, field2, ... }` -- nested struct fields with their own `merge()`
23/// - `optional_nested { field1, field2, ... }` -- `Option<T>` where T has its own `merge()`
24///
25/// For `option` and `soft_option` fields, `Some` values in the overlay replace the
26/// corresponding fields in self; `None` fields are left unchanged.
27/// For `nested` fields, merge is called recursively.
28/// For `optional_nested` fields: if both base and overlay are `Some`, the inner values
29/// are merged recursively. If base is `None` and overlay is `Some`, overlay is cloned.
30/// If overlay is `None`, the base field is preserved unchanged.
31///
32/// # Examples
33///
34/// ```ignore
35/// impl_merge!(MyColors {
36///     option { accent, background }
37/// });
38/// ```
39macro_rules! impl_merge {
40    (
41        $struct_name:ident {
42            $(option { $($opt_field:ident),* $(,)? })?
43            $(soft_option { $($so_field:ident),* $(,)? })?
44            $(nested { $($nest_field:ident),* $(,)? })?
45            $(optional_nested { $($on_field:ident),* $(,)? })*
46        }
47    ) => {
48        impl $struct_name {
49            /// Merge an overlay into this value. `Some` fields in the overlay
50            /// replace the corresponding fields in self; `None` fields are
51            /// left unchanged. Nested structs are merged recursively.
52            pub fn merge(&mut self, overlay: &Self) {
53                $($(
54                    if overlay.$opt_field.is_some() {
55                        self.$opt_field = overlay.$opt_field.clone();
56                    }
57                )*)?
58                $($(
59                    if overlay.$so_field.is_some() {
60                        self.$so_field = overlay.$so_field.clone();
61                    }
62                )*)?
63                $($(
64                    self.$nest_field.merge(&overlay.$nest_field);
65                )*)?
66                $($(
67                    match (&mut self.$on_field, &overlay.$on_field) {
68                        (Some(base), Some(over)) => base.merge(over),
69                        (None, Some(over)) => self.$on_field = Some(over.clone()),
70                        _ => {}
71                    }
72                )*)*
73            }
74
75            /// Returns true if all fields are at their default (None/empty) state.
76            pub fn is_empty(&self) -> bool {
77                true
78                $($(&& self.$opt_field.is_none())*)?
79                $($(&& self.$so_field.is_none())*)?
80                $($(&& self.$nest_field.is_empty())*)?
81                $($(&& self.$on_field.as_ref().map_or(true, |v| v.is_empty()))*)*
82            }
83        }
84    };
85}
86
87/// Color types and sRGB utilities.
88pub mod color;
89/// OS detection: dark mode, reduced motion, DPI, desktop environment.
90pub mod detect;
91/// Error types for theme operations.
92pub mod error;
93/// GNOME portal theme reader.
94#[cfg(all(target_os = "linux", feature = "portal"))]
95pub mod gnome;
96/// Icon loading and dispatch.
97pub mod icons;
98/// KDE theme reader.
99#[cfg(all(target_os = "linux", feature = "kde"))]
100pub mod kde;
101/// Theme data model types.
102pub mod model;
103/// Theme pipeline: reader -> preset merge -> resolve -> validate.
104pub mod pipeline;
105/// Bundled theme presets.
106pub mod presets;
107/// Internal `ThemeReader` trait (see module docs for Option A rationale).
108///
109/// Consumed by `pipeline::select_reader` as `Box<dyn ThemeReader>`; the
110/// trait and every impl are `pub(crate)` — not part of the public API.
111mod reader;
112/// Theme resolution engine (inheritance + validation).
113///
114/// Public surface: [`resolve::ResolutionContext`] — the resolution-time
115/// inputs struct consumed by
116/// [`ThemeMode::into_resolved`](crate::theme::ThemeMode::into_resolved).
117/// Inheritance rules, validation machinery, and the range-check helpers
118/// are all crate-internal (no stability guarantee).
119pub mod resolve;
120#[cfg(any(
121    feature = "material-icons",
122    feature = "lucide-icons",
123    feature = "system-icons"
124))]
125mod spinners;
126/// Runtime theme change watching.
127#[cfg(feature = "watch")]
128pub mod watch;
129
130/// Convenience re-exports for common usage.
131///
132/// `use native_theme::prelude::*` imports:
133/// [`Theme`](theme::Theme), [`ResolvedTheme`](theme::ResolvedTheme),
134/// [`SystemTheme`], [`AccessibilityPreferences`],
135/// [`Rgba`](color::Rgba), [`Error`](error::Error), and [`Result`].
136pub mod prelude;
137
138/// Theme data model: types, defaults, fonts, borders, widgets.
139///
140/// Core types: [`Theme`], [`ThemeMode`],
141/// [`ResolvedTheme`], [`ResolvedDefaults`].
142///
143/// Re-exports from the internal model module.
144pub mod theme {
145    pub use crate::model::*;
146    pub use crate::presets::PresetInfo;
147}
148
149/// Freedesktop icon theme lookup (Linux).
150#[cfg(all(target_os = "linux", feature = "system-icons"))]
151pub mod freedesktop;
152/// macOS platform helpers.
153#[cfg(target_os = "macos")]
154pub mod macos;
155#[cfg(not(target_os = "macos"))]
156pub(crate) mod macos;
157/// SVG-to-RGBA rasterization utilities.
158#[cfg(feature = "svg-rasterize")]
159pub mod rasterize;
160/// SF Symbols icon loader (macOS).
161#[cfg(all(target_os = "macos", feature = "system-icons"))]
162pub mod sficons;
163/// Windows platform theme reader.
164#[cfg(target_os = "windows")]
165pub mod windows;
166#[cfg(not(target_os = "windows"))]
167#[allow(dead_code, unused_variables)]
168pub(crate) mod windows;
169/// Windows Segoe Fluent / stock icon loader.
170#[cfg(all(target_os = "windows", feature = "system-icons"))]
171pub mod winicons;
172#[cfg(all(not(target_os = "windows"), feature = "system-icons"))]
173#[allow(dead_code, unused_imports)]
174pub(crate) mod winicons;
175
176use std::borrow::Cow;
177
178/// Convenience Result type alias for this crate.
179pub type Result<T> = std::result::Result<T, error::Error>;
180
181// Internal re-exports: keep crate::Type paths working for internal modules
182// without exposing them in the public API. External users access types via
183// native_theme::theme::*, native_theme::icons::*, native_theme::detect::*, etc.
184#[allow(unused_imports)]
185pub(crate) use color::{ParseColorError, Rgba};
186#[cfg(target_os = "linux")]
187#[allow(unused_imports)]
188pub(crate) use detect::LinuxDesktop;
189#[cfg(target_os = "linux")]
190#[allow(unused_imports)]
191pub(crate) use detect::detect_linux_desktop;
192#[allow(unused_imports)]
193pub(crate) use detect::{
194    detect_is_dark, detect_reduced_motion, invalidate_caches, prefers_reduced_motion,
195    system_is_dark,
196};
197#[allow(unused_imports)]
198pub(crate) use error::{Error, ErrorKind, RangeViolation};
199#[allow(unused_imports)]
200pub(crate) use icons::{
201    FreedesktopLoader, IconId, LucideLoader, MaterialLoader, SegoeIconsLoader, SfSymbolsLoader,
202    is_freedesktop_theme_available, load_icon, load_icon_indicator,
203};
204pub use icons::{IconSetChoice, default_icon_choice, list_freedesktop_themes};
205#[allow(unused_imports)]
206pub(crate) use model::icons::{detect_icon_theme, icon_name, system_icon_set, system_icon_theme};
207#[allow(unused_imports)]
208pub(crate) use model::{
209    AnimatedIcon, ButtonTheme, CardTheme, CheckboxTheme, ColorMode, ComboBoxTheme,
210    DefaultsBorderSpec, DialogButtonOrder, DialogTheme, ExpanderTheme, FontSize, FontSpec,
211    FontStyle, IconData, IconProvider, IconRole, IconSet, IconSizes, InputTheme, LayoutTheme,
212    LinkTheme, ListTheme, MenuTheme, PopoverTheme, ProgressBarTheme, ResolvedBorderSpec,
213    ResolvedDefaults, ResolvedFontSpec, ResolvedIconSizes, ResolvedTextScale,
214    ResolvedTextScaleEntry, ResolvedTheme, ScrollbarTheme, SegmentedControlTheme, SeparatorTheme,
215    SidebarTheme, SliderTheme, SpinnerTheme, SplitterTheme, StatusBarTheme, SwitchTheme, TabTheme,
216    TextScale, TextScaleEntry, Theme, ThemeDefaults, ThemeMode, ToolbarTheme, TooltipTheme,
217    TransformAnimation, WidgetBorderSpec, WindowTheme, bundled_icon_by_name, bundled_icon_svg,
218};
219pub use pipeline::{DiagnosticEntry, PlatformPreset};
220#[allow(unused_imports)]
221pub(crate) use pipeline::{diagnose_platform_support, platform_preset_name};
222pub use resolve::ResolutionContext;
223
224/// OS-detected accessibility preferences.
225///
226/// A single copy lives on [`SystemTheme`], shared across light and dark
227/// variants. These are runtime values detected from the OS -- not stored
228/// in TOML presets.
229#[derive(Clone, Debug, PartialEq)]
230pub struct AccessibilityPreferences {
231    /// Text scaling factor (1.0 = no scaling). Multiply font sizes by
232    /// this factor when honoring the user's preference for larger text.
233    pub text_scaling_factor: f32,
234    /// Whether the user has requested reduced motion.
235    pub reduce_motion: bool,
236    /// Whether a high-contrast mode is active.
237    pub high_contrast: bool,
238    /// Whether the user has requested reduced transparency.
239    pub reduce_transparency: bool,
240}
241
242impl Default for AccessibilityPreferences {
243    fn default() -> Self {
244        Self {
245            text_scaling_factor: 1.0,
246            reduce_motion: false,
247            high_contrast: false,
248            reduce_transparency: false,
249        }
250    }
251}
252
253/// Complete reader result for the pipeline.
254///
255/// Bundles the type-safe [`ReaderOutput`] with reader metadata
256/// (name, icon_set, layout, font_dpi, accessibility) so that
257/// `run_pipeline` accepts a single struct instead of many arguments.
258#[derive(Clone, Debug)]
259pub(crate) struct ReaderResult {
260    /// The reader's variant data.
261    pub(crate) output: ReaderOutput,
262    /// Theme name from reader (e.g. "BreezeDark", "GNOME", "macOS").
263    pub(crate) name: Cow<'static, str>,
264    /// Shared icon_set from reader.
265    pub(crate) icon_set: Option<IconSet>,
266    /// Shared layout from reader.
267    pub(crate) layout: LayoutTheme,
268    /// Font DPI captured at detection time (None = auto-detect).
269    pub(crate) font_dpi: Option<f32>,
270    /// OS-detected accessibility preferences.
271    pub(crate) accessibility: AccessibilityPreferences,
272}
273
274/// Output contract for platform readers.
275///
276/// Expresses single-vs-dual variant semantics explicitly:
277/// - `Single`: KDE, GNOME, and Windows readers report only the OS-active mode.
278///   The pipeline fills the inactive variant from the platform preset.
279/// - `Dual`: macOS reads both light and dark appearances in a single call.
280///   The pipeline uses both reader-provided variants directly.
281#[derive(Clone, Debug)]
282pub(crate) enum ReaderOutput {
283    /// Reader provides only the OS-active variant. The pipeline fills the
284    /// inactive variant from the platform preset.
285    Single {
286        /// The reader-provided variant (OS-active).
287        mode: Box<ThemeMode>,
288        /// Which color mode this variant represents.
289        is_dark: bool,
290    },
291    /// Reader provides both light and dark variants (macOS).
292    #[allow(dead_code)]
293    Dual {
294        /// The light variant from the reader.
295        light: Box<ThemeMode>,
296        /// The dark variant from the reader.
297        dark: Box<ThemeMode>,
298    },
299}
300
301impl ReaderOutput {
302    /// Reconstruct a [`Theme`] from this reader output (for overlay replay
303    /// and merge compatibility).
304    pub(crate) fn to_theme(
305        &self,
306        name: &str,
307        icon_set: Option<IconSet>,
308        layout: &LayoutTheme,
309    ) -> Theme {
310        let (light, dark) = match self {
311            ReaderOutput::Single { mode, is_dark } => {
312                if *is_dark {
313                    (None, Some(ThemeMode::clone(mode)))
314                } else {
315                    (Some(ThemeMode::clone(mode)), None)
316                }
317            }
318            ReaderOutput::Dual { light, dark } => {
319                (Some(ThemeMode::clone(light)), Some(ThemeMode::clone(dark)))
320            }
321        };
322        Theme {
323            name: std::borrow::Cow::Owned(name.to_string()),
324            light,
325            dark,
326            layout: layout.clone(),
327            icon_set,
328            // Readers keep Theme-level icon_theme = None and rely on either
329            // the preset's value (tier 2) or system detect (tier 3). Readers
330            // that need to override per color mode use ThemeDefaults::icon_theme
331            // on the variant (tier 1, e.g. the KDE reader for breeze/breeze-dark).
332            icon_theme: None,
333        }
334    }
335}
336
337/// Data needed to replay the merge+resolve pipeline for overlay support.
338///
339/// Stores the original reader output and preset name so that
340/// [`SystemTheme::with_overlay()`] can reconstruct pre-resolve variants
341/// on demand instead of storing ~2KB of ThemeMode clones.
342#[derive(Clone, Debug)]
343pub(crate) struct OverlaySource {
344    /// The reader's variant data for replay.
345    pub(crate) reader_output: ReaderOutput,
346    /// Theme name from reader.
347    pub(crate) name: Cow<'static, str>,
348    /// Shared icon_set from reader.
349    pub(crate) icon_set: Option<IconSet>,
350    /// Shared layout from reader.
351    pub(crate) layout: LayoutTheme,
352    /// The live preset name (e.g. "kde-breeze-live").
353    pub(crate) preset_name: String,
354    /// Resolution-time inputs captured at detection time. Replaces the
355    /// old `font_dpi: Option<f32>` field; the context bundles
356    /// `font_dpi` + `button_order` + `icon_theme` fallback and is cloned
357    /// into `with_overlay` replays so resolution is deterministic across
358    /// overlay applications.
359    pub(crate) context: crate::resolve::ResolutionContext,
360}
361
362/// Result of the OS-first pipeline. Holds both resolved variants.
363///
364/// Produced by [`SystemTheme::from_system()`] and [`SystemTheme::from_system_async()`].
365/// Both light and dark are always populated: the OS-active variant
366/// comes from the reader + preset + resolve, the inactive variant
367/// comes from the preset + resolve.
368#[derive(Clone, Debug)]
369pub struct SystemTheme {
370    /// Theme name (from reader or preset).
371    ///
372    /// # Ownership type — principled deviation from doc 2 §J.2 / §K.3
373    ///
374    /// This field uses `Cow<'static, str>`, not `Arc<str>`. Doc 2 §J.2
375    /// ("B3 refinement: use `Arc<str>` for `ReaderOutput::name`") and
376    /// §K.3 recommend uniform `Arc<str>` across `name`, `icon_theme`,
377    /// `ReaderOutput::name`, and `ResolvedFontSpec::family`. The audit in
378    /// `docs/todo_v0.5.7_gaps.md` §G9 (lines 449-506) concluded that the
379    /// uniform recommendation should be adopted ONLY for
380    /// [`ResolvedFontSpec::family`](crate::model::font::ResolvedFontSpec)
381    /// (where 26 widgets × connectors genuinely share font families), and
382    /// should be REVERSED for `name` / `icon_theme` because:
383    ///
384    /// - Each resolved theme carries exactly ONE `name` — no dedup benefit.
385    /// - Bundled preset names are `&'static str` literals; `Cow::Borrowed(static_lit)`
386    ///   is zero allocation, zero refcount. `Arc<str>` would require at least one
387    ///   allocation per unique string at construction time, paying allocation cost
388    ///   for a dedup benefit that is structurally absent.
389    ///
390    /// The same reasoning applies symmetrically to
391    /// [`SystemTheme::icon_theme`](Self::icon_theme),
392    /// [`Theme::name`](crate::theme::Theme), and
393    /// [`ThemeDefaults::icon_theme`](crate::model::defaults::ThemeDefaults).
394    ///
395    /// See `docs/todo_v0.5.7_gaps.md` §G9 for the full audit.
396    pub name: Cow<'static, str>,
397    /// The OS color mode preference (light or dark).
398    pub mode: ColorMode,
399    /// Resolved light variant (always populated).
400    pub light: ResolvedTheme,
401    /// Resolved dark variant (always populated).
402    pub dark: ResolvedTheme,
403    /// Data for replaying the pipeline on overlay (replaces light_variant/dark_variant).
404    pub(crate) overlay_source: OverlaySource,
405    /// The platform preset used (e.g., "kde-breeze", "adwaita", "macos-sonoma").
406    pub preset: String,
407    /// The live preset name used internally (e.g., "kde-breeze-live").
408    pub(crate) live_preset: String,
409    /// Which icon loading mechanism to use for this theme.
410    pub icon_set: IconSet,
411    /// The name of the visual icon theme (e.g. `"breeze"`, `"Adwaita"`).
412    ///
413    /// # Ownership type
414    ///
415    /// `Cow<'static, str>` is used here per the same principled deviation
416    /// documented on [`SystemTheme::name`](Self::name) — see `docs/todo_v0.5.7_gaps.md`
417    /// §G9. Each resolved theme carries a single icon-theme name (KDE has
418    /// exactly two across light/dark variants — `"breeze"` / `"breeze-dark"`;
419    /// other platforms have one), so the `Arc<str>` dedup benefit does not apply.
420    pub icon_theme: Cow<'static, str>,
421    /// OS-detected accessibility preferences (shared across variants).
422    pub accessibility: AccessibilityPreferences,
423}
424
425impl SystemTheme {
426    /// Pick a resolved variant by color mode.
427    ///
428    /// # Examples
429    ///
430    /// ```no_run
431    /// use native_theme::theme::ColorMode;
432    ///
433    /// let sys = native_theme::SystemTheme::from_system()?;
434    /// let dark = sys.pick(ColorMode::Dark);
435    /// let active = sys.pick(sys.mode);
436    /// # Ok::<(), native_theme::error::Error>(())
437    /// ```
438    #[must_use]
439    pub fn pick(&self, mode: ColorMode) -> &ResolvedTheme {
440        match mode {
441            ColorMode::Light => &self.light,
442            ColorMode::Dark => &self.dark,
443        }
444    }
445
446    /// Apply an app-level TOML overlay and re-resolve.
447    ///
448    /// Merges the overlay onto the pre-resolve [`ThemeMode`] (not the
449    /// already-resolved [`ResolvedTheme`]) so that changed source fields
450    /// propagate correctly through `resolve()`. For example, changing
451    /// `defaults.accent_color` in the overlay will cause `button.primary_background`,
452    /// `checkbox.checked_background`, `slider.fill`, etc. to be re-derived from
453    /// the new accent color.
454    ///
455    /// # Examples
456    ///
457    /// ```no_run
458    /// let system = native_theme::SystemTheme::from_system()?;
459    /// let overlay = native_theme::theme::Theme::from_toml(r##"
460    ///     [light.defaults]
461    ///     accent_color = "#ff6600"
462    ///     [dark.defaults]
463    ///     accent_color = "#ff6600"
464    /// "##)?;
465    /// let customized = system.with_overlay(&overlay)?;
466    /// // customized.pick(customized.mode).defaults.accent_color is now #ff6600
467    /// // and all accent-derived fields are updated
468    /// # Ok::<(), native_theme::error::Error>(())
469    /// ```
470    pub fn with_overlay(&self, overlay: &Theme) -> crate::Result<Self> {
471        // Reconstruct pre-resolve variants from overlay_source
472        let src = &self.overlay_source;
473        let live_preset = Theme::preset(&src.preset_name)?;
474        let full_preset_name = src
475            .preset_name
476            .strip_suffix("-live")
477            .unwrap_or(&src.preset_name);
478        let full_preset = Theme::preset(full_preset_name)?;
479
480        // Reconstruct a Theme from the type-safe ReaderOutput for merge
481        let reader_as_theme = src
482            .reader_output
483            .to_theme(&src.name, src.icon_set, &src.layout);
484
485        let mut merged = full_preset.clone();
486        merged.merge(&live_preset);
487        merged.merge(&reader_as_theme);
488
489        // Match on ReaderOutput for type-safe variant selection
490        let (mut light, mut dark) = match &src.reader_output {
491            ReaderOutput::Single { is_dark, .. } => {
492                if *is_dark {
493                    (
494                        full_preset.light.unwrap_or_default(),
495                        merged.dark.unwrap_or_default(),
496                    )
497                } else {
498                    (
499                        merged.light.unwrap_or_default(),
500                        full_preset.dark.unwrap_or_default(),
501                    )
502                }
503            }
504            ReaderOutput::Dual { .. } => (
505                merged.light.unwrap_or_default(),
506                merged.dark.unwrap_or_default(),
507            ),
508        };
509
510        // Apply the user overlay on top
511        if let Some(over) = &overlay.light {
512            light.merge(over);
513        }
514        if let Some(over) = &overlay.dark {
515            dark.merge(over);
516        }
517
518        // Re-resolve both variants using the captured context (avoids
519        // re-detecting DPI / button_order / icon_theme on replay).
520        let resolved_light = light.into_resolved(&src.context)?;
521        let resolved_dark = dark.into_resolved(&src.context)?;
522
523        Ok(SystemTheme {
524            name: self.name.clone(),
525            mode: self.mode,
526            light: resolved_light,
527            dark: resolved_dark,
528            overlay_source: self.overlay_source.clone(),
529            live_preset: self.live_preset.clone(),
530            preset: self.preset.clone(),
531            icon_set: self.icon_set,
532            icon_theme: self.icon_theme.clone(),
533            accessibility: self.accessibility.clone(),
534        })
535    }
536
537    /// Load the OS theme synchronously.
538    ///
539    /// Detects the platform and desktop environment, reads the current theme
540    /// settings, merges with a platform preset, and returns a fully resolved
541    /// [`SystemTheme`] with both light and dark variants.
542    ///
543    /// The return value goes through the full pipeline: reader output ->
544    /// resolve -> validate -> [`SystemTheme`] with both light and dark
545    /// [`ResolvedTheme`] variants.
546    ///
547    /// # Platform Behavior
548    ///
549    /// - **macOS:** Calls `from_macos()` when the `macos` feature is enabled.
550    ///   Reads both light and dark variants via NSAppearance, merges with
551    ///   `macos-sonoma` preset.
552    /// - **Linux:** Uses `pollster::block_on` to drive the async inner
553    ///   implementation, which handles portal D-Bus calls when the `portal`
554    ///   feature is enabled.
555    /// - **Windows:** Calls `from_windows()` when the `windows` feature is enabled,
556    ///   merges with `windows-11` preset.
557    /// - **Other platforms:** Returns `Error::PlatformUnsupported`.
558    ///
559    /// # Errors
560    ///
561    /// - `Error::FeatureDisabled` if the platform has a reader but the required feature
562    ///   is not enabled.
563    /// - `Error::PlatformUnsupported` if the platform has no reader at all.
564    /// - `Error::ReaderFailed` if the platform reader cannot access theme data.
565    ///
566    /// # Examples
567    ///
568    /// ```no_run
569    /// let sys = native_theme::SystemTheme::from_system()?;
570    /// let theme = sys.pick(sys.mode);
571    /// // Icon set and theme are on SystemTheme, shared across variants
572    /// let _icon_set = sys.icon_set;
573    /// let _icon_theme = &sys.icon_theme;
574    /// # Ok::<(), native_theme::error::Error>(())
575    /// ```
576    #[cfg(target_os = "linux")]
577    pub fn from_system() -> crate::Result<Self> {
578        pollster::block_on(pipeline::from_system_inner())
579    }
580
581    /// Load the OS theme synchronously (non-Linux).
582    ///
583    /// On macOS and Windows the async inner has zero `.await` points, so a
584    /// noop-waker single-poll is sufficient -- no async runtime needed.
585    #[cfg(not(target_os = "linux"))]
586    pub fn from_system() -> crate::Result<Self> {
587        let waker = std::task::Waker::noop();
588        let mut cx = std::task::Context::from_waker(&waker);
589        let mut fut = std::pin::pin!(pipeline::from_system_inner());
590        match fut.as_mut().poll(&mut cx) {
591            std::task::Poll::Ready(result) => result,
592            std::task::Poll::Pending => Err(crate::Error::PlatformUnsupported {
593                platform: "unexpected async suspension",
594            }),
595        }
596    }
597
598    /// Async version of [`from_system()`](Self::from_system).
599    ///
600    /// On Linux, this enables portal D-Bus calls (e.g. GNOME settings portal,
601    /// KDE portal backend detection) via `.await`. On macOS and Windows, the
602    /// future completes immediately -- no actual async operations occur.
603    ///
604    /// Returns a [`SystemTheme`] with both resolved light and dark variants,
605    /// same as [`from_system()`](Self::from_system).
606    pub async fn from_system_async() -> crate::Result<Self> {
607        pipeline::from_system_inner().await
608    }
609}
610
611// =============================================================================
612// Tests -- SystemTheme public API (active, pick, platform_preset_name)
613// =============================================================================
614
615#[cfg(test)]
616#[allow(
617    clippy::unwrap_used,
618    clippy::expect_used,
619    clippy::field_reassign_with_default
620)]
621mod system_theme_tests {
622    use super::*;
623
624    // --- SystemTheme::active() / pick() tests ---
625
626    #[test]
627    fn test_system_theme_pick_dark_mode() {
628        let preset = Theme::preset("catppuccin-mocha").unwrap();
629        let mut light_v = preset.light.clone().unwrap();
630        let mut dark_v = preset.dark.clone().unwrap();
631        // Give them distinct accents so we can tell them apart
632        // (test fixture values -- not production hardcoded colors)
633        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
634        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
635        light_v.resolve_all();
636        dark_v.resolve_all();
637        let light_resolved = light_v.validate().unwrap();
638        let dark_resolved = dark_v.validate().unwrap();
639
640        let st = SystemTheme {
641            name: "test".into(),
642            mode: ColorMode::Dark,
643            light: light_resolved.clone(),
644            dark: dark_resolved.clone(),
645            overlay_source: OverlaySource {
646                reader_output: ReaderOutput::Dual {
647                    light: Box::new(ThemeMode::default()),
648                    dark: Box::new(ThemeMode::default()),
649                },
650                name: Cow::Borrowed(""),
651                icon_set: None,
652                layout: LayoutTheme::default(),
653                preset_name: "catppuccin-mocha".into(),
654                context: crate::resolve::ResolutionContext::for_tests(),
655            },
656            live_preset: "catppuccin-mocha".into(),
657            preset: "catppuccin-mocha".into(),
658            icon_set: IconSet::Lucide,
659            icon_theme: "lucide".into(),
660            accessibility: AccessibilityPreferences::default(),
661        };
662        assert_eq!(
663            st.pick(st.mode).defaults.accent_color,
664            dark_resolved.defaults.accent_color
665        );
666    }
667
668    #[test]
669    fn test_system_theme_pick_light_mode() {
670        let preset = Theme::preset("catppuccin-mocha").unwrap();
671        let mut light_v = preset.light.clone().unwrap();
672        let mut dark_v = preset.dark.clone().unwrap();
673        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
674        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
675        light_v.resolve_all();
676        dark_v.resolve_all();
677        let light_resolved = light_v.validate().unwrap();
678        let dark_resolved = dark_v.validate().unwrap();
679
680        let st = SystemTheme {
681            name: "test".into(),
682            mode: ColorMode::Light,
683            light: light_resolved.clone(),
684            dark: dark_resolved.clone(),
685            overlay_source: OverlaySource {
686                reader_output: ReaderOutput::Dual {
687                    light: Box::new(ThemeMode::default()),
688                    dark: Box::new(ThemeMode::default()),
689                },
690                name: Cow::Borrowed(""),
691                icon_set: None,
692                layout: LayoutTheme::default(),
693                preset_name: "catppuccin-mocha".into(),
694                context: crate::resolve::ResolutionContext::for_tests(),
695            },
696            live_preset: "catppuccin-mocha".into(),
697            preset: "catppuccin-mocha".into(),
698            icon_set: IconSet::Lucide,
699            icon_theme: "lucide".into(),
700            accessibility: AccessibilityPreferences::default(),
701        };
702        assert_eq!(
703            st.pick(st.mode).defaults.accent_color,
704            light_resolved.defaults.accent_color
705        );
706    }
707
708    #[test]
709    fn test_system_theme_pick_explicit() {
710        let preset = Theme::preset("catppuccin-mocha").unwrap();
711        let mut light_v = preset.light.clone().unwrap();
712        let mut dark_v = preset.dark.clone().unwrap();
713        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
714        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
715        light_v.resolve_all();
716        dark_v.resolve_all();
717        let light_resolved = light_v.validate().unwrap();
718        let dark_resolved = dark_v.validate().unwrap();
719
720        let st = SystemTheme {
721            name: "test".into(),
722            mode: ColorMode::Light,
723            light: light_resolved.clone(),
724            dark: dark_resolved.clone(),
725            overlay_source: OverlaySource {
726                reader_output: ReaderOutput::Dual {
727                    light: Box::new(ThemeMode::default()),
728                    dark: Box::new(ThemeMode::default()),
729                },
730                name: Cow::Borrowed(""),
731                icon_set: None,
732                layout: LayoutTheme::default(),
733                preset_name: "catppuccin-mocha".into(),
734                context: crate::resolve::ResolutionContext::for_tests(),
735            },
736            live_preset: "catppuccin-mocha".into(),
737            preset: "catppuccin-mocha".into(),
738            icon_set: IconSet::Lucide,
739            icon_theme: "lucide".into(),
740            accessibility: AccessibilityPreferences::default(),
741        };
742        assert_eq!(
743            st.pick(ColorMode::Dark).defaults.accent_color,
744            dark_resolved.defaults.accent_color
745        );
746        assert_eq!(
747            st.pick(ColorMode::Light).defaults.accent_color,
748            light_resolved.defaults.accent_color
749        );
750    }
751
752    // --- platform_preset_name() pure tests ---
753    // Tests the same logic path (parse_linux_desktop -> linux_preset_for_de) without env var mocking.
754
755    /// Prove that the sync `from_system()` API works without any async runtime.
756    /// On Linux with KDE feature: exercises pollster::block_on(from_system_inner()).
757    /// This acts as a compile-time and runtime gate that the sync path works.
758    #[test]
759    #[cfg(target_os = "linux")]
760    #[cfg(feature = "kde")]
761    fn sync_consumer_no_async_runtime() {
762        // Call the actual from_system() entry point.
763        // This exercises the pollster::block_on(pipeline::from_system_inner()) path.
764        // We don't assert Ok because the test environment may lack KDE config files,
765        // but the call must not panic and must return a Result (not hang or deadlock).
766        let _result = SystemTheme::from_system();
767    }
768
769    #[test]
770    #[cfg(target_os = "linux")]
771    fn test_platform_preset_name_kde() {
772        let preset = pipeline::linux_preset_for_de(detect::parse_linux_desktop("KDE"));
773        assert_eq!(preset.name, "kde-breeze");
774        assert!(preset.is_live);
775        assert_eq!(preset.live_name(), "kde-breeze-live");
776    }
777
778    #[test]
779    #[cfg(target_os = "linux")]
780    fn test_platform_preset_name_gnome() {
781        let preset = pipeline::linux_preset_for_de(detect::parse_linux_desktop("GNOME"));
782        assert_eq!(preset.name, "adwaita");
783        assert!(preset.is_live);
784        assert_eq!(preset.live_name(), "adwaita-live");
785    }
786}
787
788// =============================================================================
789// Tests -- with_overlay
790// =============================================================================
791
792#[cfg(test)]
793#[allow(clippy::unwrap_used, clippy::expect_used)]
794mod overlay_tests {
795    use super::*;
796
797    /// Helper: build a SystemTheme from a preset via pipeline::run_pipeline.
798    /// Uses test-only Result handling (module has #[allow(clippy::unwrap_used)]).
799    fn default_system_theme() -> crate::Result<SystemTheme> {
800        let preset = Theme::preset("catppuccin-mocha")?;
801        let reader = ReaderResult {
802            output: ReaderOutput::Dual {
803                light: Box::new(preset.light.clone().unwrap_or_default()),
804                dark: Box::new(preset.dark.clone().unwrap_or_default()),
805            },
806            name: preset.name,
807            icon_set: preset.icon_set,
808            layout: preset.layout,
809            font_dpi: None,
810            accessibility: AccessibilityPreferences::default(),
811        };
812        pipeline::run_pipeline(reader, "catppuccin-mocha", ColorMode::Light)
813    }
814
815    #[test]
816    fn test_overlay_accent_propagates() -> crate::Result<()> {
817        let st = default_system_theme()?;
818        let new_accent = Rgba::rgb(255, 0, 0);
819
820        // Build overlay with accent on both light and dark
821        let mut overlay = Theme::default();
822        let mut light_v = ThemeMode::default();
823        light_v.defaults.accent_color = Some(new_accent);
824        let mut dark_v = ThemeMode::default();
825        dark_v.defaults.accent_color = Some(new_accent);
826        overlay.light = Some(light_v);
827        overlay.dark = Some(dark_v);
828
829        let result = st.with_overlay(&overlay)?;
830
831        // Accent itself
832        assert_eq!(result.light.defaults.accent_color, new_accent);
833        // Accent-derived widget fields
834        assert_eq!(result.light.button.primary_background, new_accent);
835        assert_eq!(result.light.checkbox.checked_background, new_accent);
836        assert_eq!(result.light.slider.fill_color, new_accent);
837        assert_eq!(result.light.progress_bar.fill_color, new_accent);
838        assert_eq!(result.light.switch.checked_background, new_accent);
839        // Additional accent-derived fields re-resolved via safety nets
840        assert_eq!(
841            result.light.spinner.fill_color, new_accent,
842            "spinner.fill should re-derive from new accent"
843        );
844        Ok(())
845    }
846
847    #[test]
848    fn test_overlay_preserves_unrelated_fields() -> crate::Result<()> {
849        let st = default_system_theme()?;
850        let original_bg = st.light.defaults.background_color;
851
852        // Apply overlay changing only accent
853        let mut overlay = Theme::default();
854        let mut light_v = ThemeMode::default();
855        light_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
856        overlay.light = Some(light_v);
857
858        let result = st.with_overlay(&overlay)?;
859        assert_eq!(
860            result.light.defaults.background_color, original_bg,
861            "background should be unchanged"
862        );
863        Ok(())
864    }
865
866    #[test]
867    fn test_overlay_empty_noop() -> crate::Result<()> {
868        let st = default_system_theme()?;
869        let original_light_accent = st.light.defaults.accent_color;
870        let original_dark_accent = st.dark.defaults.accent_color;
871        let original_light_bg = st.light.defaults.background_color;
872
873        // Empty overlay
874        let overlay = Theme::default();
875        let result = st.with_overlay(&overlay)?;
876
877        assert_eq!(result.light.defaults.accent_color, original_light_accent);
878        assert_eq!(result.dark.defaults.accent_color, original_dark_accent);
879        assert_eq!(result.light.defaults.background_color, original_light_bg);
880        Ok(())
881    }
882
883    #[test]
884    fn test_overlay_both_variants() -> crate::Result<()> {
885        let st = default_system_theme()?;
886        let red = Rgba::rgb(255, 0, 0);
887        let green = Rgba::rgb(0, 255, 0);
888
889        let mut overlay = Theme::default();
890        let mut light_v = ThemeMode::default();
891        light_v.defaults.accent_color = Some(red);
892        let mut dark_v = ThemeMode::default();
893        dark_v.defaults.accent_color = Some(green);
894        overlay.light = Some(light_v);
895        overlay.dark = Some(dark_v);
896
897        let result = st.with_overlay(&overlay)?;
898        assert_eq!(
899            result.light.defaults.accent_color, red,
900            "light accent = red"
901        );
902        assert_eq!(
903            result.dark.defaults.accent_color, green,
904            "dark accent = green"
905        );
906        Ok(())
907    }
908
909    #[test]
910    fn test_overlay_font_family() -> crate::Result<()> {
911        let st = default_system_theme()?;
912
913        let mut overlay = Theme::default();
914        let mut light_v = ThemeMode::default();
915        light_v.defaults.font.family = Some("Comic Sans".into());
916        overlay.light = Some(light_v);
917
918        let result = st.with_overlay(&overlay)?;
919        assert_eq!(result.light.defaults.font.family.as_ref(), "Comic Sans");
920        Ok(())
921    }
922
923    #[test]
924    fn test_overlay_roundtrip_via_overlay_source() -> crate::Result<()> {
925        let st = default_system_theme()?;
926        // Apply overlay and verify accent propagates
927        let new_accent = Rgba::rgb(255, 0, 0);
928        let mut overlay = Theme::default();
929        let mut light_v = ThemeMode::default();
930        light_v.defaults.accent_color = Some(new_accent);
931        overlay.light = Some(light_v);
932
933        let result = st.with_overlay(&overlay)?;
934        assert_eq!(result.light.defaults.accent_color, new_accent);
935        // The dark variant should be unchanged from original
936        assert_eq!(
937            result.dark.defaults.accent_color,
938            st.dark.defaults.accent_color
939        );
940        Ok(())
941    }
942
943    #[test]
944    fn test_overlay_source_no_variant_fields() -> crate::Result<()> {
945        // Verify overlay_source exists on SystemTheme (compile-time structural check).
946        // If light_variant or dark_variant fields still existed, this test would
947        // need updating -- documenting the structural change.
948        let st = default_system_theme()?;
949        let _ = &st.overlay_source; // overlay_source exists
950        Ok(())
951    }
952}