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//! A [`Theme`] is sparse and TOML-shaped: every field is an `Option`, and it
9//! holds a light and a dark variant. Resolving one variant fills every field
10//! the model requires and checks its ranges, giving a [`ResolvedTheme`] that
11//! UI code reads without unwrapping. Most applications use a toolkit
12//! connector, which does this and converts the result:
13//! `native-theme-iced`, `native-theme-gpui` or `native-theme-egui`.
14//!
15//! # Quick start
16//!
17//! Read the OS theme and pick its active variant (the OS readers need the
18//! `native` feature, or `kde`, `portal`, `macos`, `windows`):
19//!
20//! ```no_run
21//! use native_theme::SystemTheme;
22//!
23//! let sys = SystemTheme::from_system()?;
24//! let active = sys.pick(sys.mode); // &ResolvedTheme
25//! let _accent = active.defaults.accent_color;
26//! # Ok::<(), native_theme::Error>(())
27//! ```
28//!
29//! Load a bundled preset and resolve one mode (no features needed):
30//!
31//! ```
32//! use native_theme::{ColorMode, Theme};
33//!
34//! let resolved = Theme::preset("nord")?.resolve(ColorMode::Dark)?;
35//! assert_eq!(resolved.mode, ColorMode::Dark);
36//! let _background = resolved.variant.defaults.background_color;
37//! # Ok::<(), native_theme::Error>(())
38//! ```
39//!
40//! Apply an overlay to the OS theme; the overlay states only what it changes:
41//!
42//! ```no_run
43//! use native_theme::{SystemTheme, Theme};
44//!
45//! let sys = SystemTheme::from_system()?;
46//! let overlay = Theme::from_toml(r##"
47//!     [light.defaults]
48//!     accent_color = "#ff6600"
49//!
50//!     [dark.defaults]
51//!     accent_color = "#ff6600"
52//! "##)?;
53//! let customised = sys.with_overlay(&overlay)?;
54//! # Ok::<(), native_theme::Error>(())
55//! ```
56//!
57//! Hand the result to a connector: `native-theme-iced`, `native-theme-gpui`
58//! and `native-theme-egui` each have `from_system` and `from_preset`, which do
59//! the steps above, and `to_theme`, which converts a [`ResolvedTheme`] you
60//! resolved yourself into the toolkit's theme.
61//!
62//! Watch for OS theme changes (the `watch` feature). The callback runs on a
63//! background thread and carries no theme: clear the detection caches, which
64//! hold the dark mode, reduced motion, accessibility preferences, icon theme
65//! and, on Linux, desktop detected before (the OS read takes its icon theme
66//! and desktop from them), and read the OS theme again. Keep the subscription
67//! alive; dropping it stops watching:
68//!
69//! ```no_run
70//! # #[cfg(feature = "watch")]
71//! # {
72//! let _subscription = native_theme::watch::on_theme_change(|_event| {
73//!     // Tell the UI thread to call `detect::invalidate_caches()`, then
74//!     // `SystemTheme::from_system()` again.
75//! })?;
76//! # }
77//! # Ok::<(), native_theme::Error>(())
78//! ```
79//!
80//! # Presets
81//!
82//! 17 presets are bundled, each a TOML file with a light and a dark variant,
83//! loaded by key with [`Theme::preset`] and listed by
84//! [`Theme::list_presets`] (or [`Theme::list_presets_for_platform`], the ones
85//! offered on the running platform):
86//!
87//! - Platform: `kde-breeze`, `adwaita`, `windows-11`, `macos-monterey`
88//!   (macOS 12 Monterey to 15 Sequoia), `macos-tahoe` (macOS 26 Tahoe),
89//!   `material-3` and `ios-13` (the flat look of iOS 13 to 18).
90//! - Community: `catppuccin-latte`, `catppuccin-frappe`,
91//!   `catppuccin-macchiato`, `catppuccin-mocha`, `nord`, `dracula`,
92//!   `gruvbox`, `solarized`, `tokyo-night` and `one-dark`.
93//!
94//! `material-3` and `ios-13` have no OS reader; an application chooses them
95//! as a look. `ios-13`'s SF Symbols icons load only on macOS (with
96//! `system-icons`); elsewhere its icons are `None`, never another set's.
97//!
98//! # Platform readers
99//!
100//! [`SystemTheme::from_system`] reads the OS theme with the running
101//! platform's reader and merges what it reads over that platform's preset; a
102//! field the reader does not supply keeps the preset's value. Both variants
103//! are resolved, so [`SystemTheme::pick`] serves either mode.
104//!
105//! | Platform | Feature | Reads | Preset |
106//! |---|---|---|---|
107//! | KDE Plasma | `kde` | `kdeglobals`; with `portal`, the portal's accent colour | `kde-breeze` |
108//! | GNOME, Budgie | `portal` | the XDG Desktop Portal settings and gsettings | `adwaita` |
109//! | macOS 11 and later | `macos` | `NSColor` under both appearances, `NSFont`, the scroller style and the accessibility options | `macos-monterey` before 26 (it covers 12 to 15), `macos-tahoe` from 26 |
110//! | Windows | `windows` | `UISettings`, the system metrics, the fonts and the caret's blink time | `windows-11` |
111//!
112//! The KDE, GNOME and Windows readers read the active variant only, and the
113//! other variant is the preset's; the macOS reader reads both. On another
114//! Linux desktop, or without the desktop's reader feature, `from_system`
115//! returns the desktop's preset (`kde-breeze` on KDE, `adwaita` elsewhere)
116//! with no live reading, in the mode [`detect::detect_is_dark`] reads. On macOS and Windows without the reader feature it returns
117//! [`Error::FeatureDisabled`], and on other platforms
118//! [`Error::PlatformUnsupported`].
119//!
120//! On macOS and Windows the preset is the one of the running OS version's
121//! visual generation. [`SystemTheme::version_match`] tells how the running
122//! version relates to it ([`VersionMatch`]): macOS 27, which has no preset of
123//! its own yet, gets `macos-tahoe` as [`VersionMatch::PresetOlder`], and
124//! Windows 10 gets `windows-11` as [`VersionMatch::PresetNewer`].
125//! [`SystemTheme::from_system_with_preset`] merges over another generation of
126//! the running platform instead. [`pipeline::platform_preset_name`] names the
127//! preset without reading the theme, and
128//! [`pipeline::diagnose_platform_support`] reports what detection can see.
129//!
130//! # Feature flags
131//!
132//! No feature is needed to load, merge and resolve presets and TOML files.
133//! Each OS-specific dependency is compiled only on its own target, so
134//! `native` on macOS pulls in only the macOS dependencies.
135//!
136//! | Feature | Enables |
137//! |---|---|
138//! | `kde`, `portal`, `macos`, `windows` | The platform readers above |
139//! | `linux-kde`, `linux-portal` | Aliases of `kde` and `portal` |
140//! | `linux` | `linux-kde` and `linux-portal` |
141//! | `native` | `linux`, `macos` and `windows`: every reader |
142//! | `watch` | `watch::on_theme_change`, for the platforms whose reader feature is on |
143//! | `material-icons`, `lucide-icons` | The bundled Material Symbols and Lucide icon sets |
144//! | `system-icons` | The platform icon sets: freedesktop icon themes (Linux), SF Symbols (macOS), Segoe Fluent Icons and stock icons (Windows); also enables `material-icons` |
145//! | `svg-rasterize` | `rasterize::rasterize_svg`, SVG icons to RGBA through resvg |
146//! | `system-fonts` | `fonts::system_face`, the platform's own typeface for a family; on macOS the system UI font's file through Core Text |
147//!
148//! The minimum supported Rust version is 1.88.0.
149//!
150//! # Modules
151//!
152//! - The crate root: [`Theme`], [`ColorMode`], [`SystemTheme`],
153//!   [`ResolvedTheme`], [`Resolved`], [`ResolutionContext`],
154//!   [`AccessibilityPreferences`], [`Rgba`], [`Error`] and [`Result`], and
155//!   from [`pipeline`] [`VersionMatch`], [`PlatformPreset`] and
156//!   [`DiagnosticEntry`].
157//! - [`prelude`]: the ten most-used items, for a glob import.
158//! - [`theme`]: the data model, the sparse types and their resolved
159//!   counterparts, widget by widget.
160//! - [`presets`]: [`PresetInfo`](presets::PresetInfo), the description of a
161//!   bundled preset that [`Theme::list_presets`] returns; [`Theme::preset`]
162//!   loads one.
163//! - [`resolve`]: the resolution-time inputs.
164//! - [`detect`]: OS detection: dark mode, reduced motion, accessibility
165//!   preferences, icon theme and set, desktop environment.
166//! - [`icons`]: the per-set icon loaders, the icon data types and the
167//!   icon-set choice.
168//! - [`fonts`]: font face matching; the platform's own typeface with the
169//!   `system-fonts` feature.
170//! - [`pipeline`]: the running platform's preset and a diagnosis of its
171//!   theme support.
172//! - [`error`] and [`color`]: the error and colour types.
173//! - `watch` (the `watch` feature): OS theme-change notifications.
174//! - `rasterize` (the `svg-rasterize` feature): SVG icons to RGBA.
175
176#![warn(missing_docs)]
177#![deny(unsafe_code)]
178#![deny(clippy::unwrap_used)]
179#![deny(clippy::expect_used)]
180
181/// The README's code blocks, compiled as doctests so they cannot drift from the API; the
182/// theme-change block needs feature `watch`.
183#[cfg(all(doctest, feature = "watch"))]
184#[doc = include_str!("../README.md")]
185pub struct ReadmeDoctests;
186
187/// Generates `merge()` and `is_empty()` methods for theme structs.
188///
189/// Three field categories:
190/// - `option { field1, field2, ... }` -- `Option<T>` leaf fields
191/// - `nested { field1, field2, ... }` -- nested struct fields with their own `merge()`
192/// - `optional_nested { field1, field2, ... }` -- `Option<T>` where T has its own `merge()`
193///
194/// For `option` fields, `Some` values in the overlay replace the
195/// corresponding fields in self; `None` fields are left unchanged.
196/// For `nested` fields, merge is called recursively.
197/// For `optional_nested` fields: if both base and overlay are `Some`, the inner values
198/// are merged recursively. If base is `None` and overlay is `Some`, overlay is cloned.
199/// If overlay is `None`, the base field is preserved unchanged.
200///
201/// # Examples
202///
203/// ```ignore
204/// impl_merge!(MyColors {
205///     option { accent, background }
206/// });
207/// ```
208macro_rules! impl_merge {
209    (
210        $struct_name:ident {
211            $(option { $($opt_field:ident),* $(,)? })?
212            $(nested { $($nest_field:ident),* $(,)? })?
213            $(optional_nested { $($on_field:ident),* $(,)? })*
214        }
215    ) => {
216        impl $struct_name {
217            /// Merge an overlay into this value. `Some` fields in the overlay
218            /// replace the corresponding fields in self; `None` fields are
219            /// left unchanged. Nested structs are merged recursively.
220            pub fn merge(&mut self, overlay: &Self) {
221                $($(
222                    if overlay.$opt_field.is_some() {
223                        self.$opt_field = overlay.$opt_field.clone();
224                    }
225                )*)?
226                $($(
227                    self.$nest_field.merge(&overlay.$nest_field);
228                )*)?
229                $($(
230                    match (&mut self.$on_field, &overlay.$on_field) {
231                        (Some(base), Some(over)) => base.merge(over),
232                        (None, Some(over)) => self.$on_field = Some(over.clone()),
233                        _ => {}
234                    }
235                )*)*
236            }
237
238            /// Returns true if all fields are at their default (None/empty) state.
239            pub fn is_empty(&self) -> bool {
240                true
241                $($(&& self.$opt_field.is_none())*)?
242                $($(&& self.$nest_field.is_empty())*)?
243                $($(&& self.$on_field.as_ref().map_or(true, |v| v.is_empty()))*)*
244            }
245        }
246    };
247}
248
249/// Color types and sRGB utilities.
250pub mod color;
251pub mod detect;
252/// Error types for theme operations.
253pub mod error;
254pub mod fonts;
255/// GNOME portal theme reader.
256///
257/// Requires the `portal` feature, and Linux.
258#[cfg(all(target_os = "linux", feature = "portal"))]
259pub(crate) mod gnome;
260/// Icon loading.
261///
262/// - The semantic roles, [`IconRole`], and the icon data, [`IconData`] and
263///   [`AnimatedIcon`].
264/// - A typed loader per icon set ([`IconSet`]): [`MaterialLoader`] and
265///   [`LucideLoader`] for the bundled sets, [`FreedesktopLoader`] (Linux),
266///   [`SfSymbolsLoader`] (macOS) and [`SegoeFluentLoader`] (Windows) for the
267///   platform sets. Each needs its set's feature, `material-icons`,
268///   `lucide-icons` or `system-icons`, and gives `None` without it.
269/// - [`load_icon`] and [`load_icon_indicator`], which load from whichever set
270///   they are given.
271/// - The icon-set choice of a settings UI,
272///   [`IconSetChoice`](icons::IconSetChoice).
273pub mod icons;
274#[cfg(all(target_os = "linux", feature = "kde"))]
275pub mod kde;
276/// Breeze widget sizing constants. Compiled on every target and feature set,
277/// so the preset gate sees the values the KDE reader states.
278#[path = "kde/metrics.rs"]
279pub(crate) mod kde_metrics;
280/// Theme data model types, public through [`theme`].
281mod model;
282pub mod pipeline;
283pub mod presets;
284/// Internal `ThemeReader` trait (see module docs for Option A rationale).
285///
286/// Consumed by `pipeline::select_reader` as `Box<dyn ThemeReader>`; the
287/// trait and every impl are `pub(crate)` — not part of the public API.
288mod reader;
289/// Theme resolution engine (inheritance + validation).
290///
291/// Public surface: [`resolve::ResolutionContext`] — the resolution-time
292/// inputs struct consumed by
293/// [`ThemeMode::into_resolved`](crate::theme::ThemeMode::into_resolved).
294/// Inheritance rules, validation machinery, and the range-check helpers
295/// are all crate-internal (no stability guarantee).
296pub mod resolve;
297#[cfg(any(
298    feature = "material-icons",
299    feature = "lucide-icons",
300    feature = "system-icons"
301))]
302mod spinners;
303#[cfg(feature = "watch")]
304pub mod watch;
305
306pub mod prelude;
307
308/// Theme data model: types, defaults, fonts, borders, widgets.
309///
310/// Core types: [`Theme`], [`ThemeMode`],
311/// [`ResolvedTheme`], [`ResolvedDefaults`].
312pub mod theme {
313    pub use crate::model::widgets::*;
314    pub use crate::model::{
315        ArrowSide, ColorMode, DefaultsBorderSpec, DialogButtonOrder, DialogEntranceStyle, FontSize,
316        FontSpec, FontStyle, IconSet, IconSizes, Resolved, ResolvedDefaults,
317        ResolvedDefaultsBorder, ResolvedFontSpec, ResolvedIconSizes, ResolvedPadding,
318        ResolvedTextScale, ResolvedTextScaleEntry, ResolvedTheme, ResolvedWidgetBorder,
319        TabIndicatorSide, TextScale, TextScaleEntry, Theme, ThemeDefaults, ThemeMode,
320        WidgetBorderSpec, intern_font_family,
321    };
322    pub use crate::presets::PresetInfo;
323}
324
325/// Freedesktop icon theme lookup (Linux).
326///
327/// Requires the `system-icons` feature, and Linux.
328#[cfg(all(target_os = "linux", feature = "system-icons"))]
329pub(crate) mod freedesktop;
330/// macOS platform helpers.
331pub(crate) mod macos;
332/// SVG-to-RGBA rasterization utilities.
333///
334/// Requires the `svg-rasterize` feature.
335#[cfg(feature = "svg-rasterize")]
336pub mod rasterize;
337/// SF Symbols icon loader (macOS).
338///
339/// Requires the `system-icons` feature, and macOS.
340#[cfg(all(target_os = "macos", feature = "system-icons"))]
341pub(crate) mod sficons;
342/// Windows platform theme reader.
343#[cfg(target_os = "windows")]
344#[cfg_attr(not(feature = "windows"), allow(dead_code))]
345pub(crate) mod windows;
346#[cfg(not(target_os = "windows"))]
347#[allow(dead_code, unused_variables)]
348pub(crate) mod windows;
349/// Windows Segoe Fluent / stock icon loader.
350///
351/// Requires the `system-icons` feature, and Windows.
352#[cfg(all(target_os = "windows", feature = "system-icons"))]
353pub(crate) mod winicons;
354#[cfg(all(not(target_os = "windows"), feature = "system-icons"))]
355#[allow(dead_code, unused_imports)]
356pub(crate) mod winicons;
357
358use std::borrow::Cow;
359
360/// Convenience Result type alias for this crate.
361pub type Result<T> = std::result::Result<T, error::Error>;
362
363// Internal re-exports: keep crate::Type paths working for internal modules
364// without exposing them in the public API. External users access types via
365// native_theme::theme::*, native_theme::icons::*, native_theme::detect::*, etc.
366#[allow(unused_imports)]
367pub(crate) use color::ParseColorError;
368pub use color::Rgba;
369#[cfg(target_os = "linux")]
370#[allow(unused_imports)]
371pub(crate) use detect::LinuxDesktop;
372#[cfg(target_os = "linux")]
373#[allow(unused_imports)]
374pub(crate) use detect::detect_linux_desktop;
375#[allow(unused_imports)]
376pub(crate) use detect::{detect_icon_theme, system_icon_set, system_icon_theme};
377#[allow(unused_imports)]
378pub(crate) use detect::{
379    detect_is_dark, detect_reduced_motion, invalidate_caches, prefers_reduced_motion,
380    system_is_dark,
381};
382pub use error::Error;
383#[allow(unused_imports)]
384pub(crate) use error::{ErrorKind, RangeViolation};
385#[allow(unused_imports)]
386pub(crate) use icons::{
387    FreedesktopLoader, IconId, LucideLoader, MaterialLoader, SegoeFluentLoader, SfSymbolsLoader,
388    is_freedesktop_theme_available, load_icon, load_icon_indicator,
389};
390#[allow(unused_imports)]
391pub(crate) use model::icons::icon_name;
392#[allow(unused_imports)]
393pub(crate) use model::{
394    AnimatedIcon, ButtonTheme, CardTheme, CheckboxTheme, ComboBoxTheme, DefaultsBorderSpec,
395    DialogButtonOrder, DialogTheme, ExpanderTheme, FontSize, FontSpec, FontStyle, IconData,
396    IconProvider, IconRole, IconSet, IconSizes, InputTheme, LayoutTheme, LinkTheme, ListTheme,
397    MenuTheme, PopoverTheme, ProgressBarTheme, ResolvedDefaults, ResolvedDefaultsBorder,
398    ResolvedFontSpec, ResolvedIconSizes, ResolvedPadding, ResolvedTextScale,
399    ResolvedTextScaleEntry, ResolvedWidgetBorder, ScrollbarTheme, SegmentedControlTheme,
400    SeparatorTheme, SidebarTheme, SliderTheme, SpinnerTheme, SplitterTheme, StatusBarTheme,
401    SwitchTheme, TabTheme, TextScale, TextScaleEntry, ThemeDefaults, ThemeMode, ToolbarTheme,
402    TooltipTheme, TransformAnimation, WidgetBorderSpec, WindowTheme, bundled_icon_by_name,
403    bundled_icon_svg,
404};
405pub use pipeline::{DiagnosticEntry, PlatformPreset, VersionMatch};
406#[allow(unused_imports)]
407pub(crate) use pipeline::{diagnose_platform_support, platform_preset_name};
408pub use resolve::ResolutionContext;
409pub use theme::{ColorMode, Resolved, ResolvedTheme, Theme};
410
411/// OS-detected accessibility preferences.
412///
413/// A single copy lives on [`SystemTheme`], shared across light and dark
414/// variants. These are runtime values detected from the OS -- not stored
415/// in TOML presets. Outside this crate, start from
416/// [`AccessibilityPreferences::DEFAULT`] (or `default()`) and set fields.
417#[derive(Clone, Debug, PartialEq)]
418#[non_exhaustive]
419pub struct AccessibilityPreferences {
420    /// Text scaling factor (1.0 = no scaling): the factor of the user's
421    /// preference for larger text that the toolkit has not applied. Multiply
422    /// font sizes by it ([`scaled`](Self::scaled)) to honour the preference.
423    /// Where the toolkit's own scale factor carries the preference, it is
424    /// 1.0: on a GNOME or Budgie X11 session, where winit and gpui take their
425    /// scale factor from the `Xft.dpi` gnome-settings-daemon writes as
426    /// 96 × `text-scaling-factor` × the window scale (gnome-settings-daemon
427    /// 51.0 `plugins/xsettings/gsd-xsettings-manager.c:666-668`, `:742`,
428    /// `:797-798`; winit 0.30.13 `src/platform_impl/linux/x11/util/randr.rs:41-53`,
429    /// `:145-146`; gpui-pre-linux 0.3.12 `src/linux/x11/client.rs:2674-2681`).
430    /// They do so only while `WINIT_X11_SCALE_FACTOR` and
431    /// `GPUI_X11_SCALE_FACTOR` are unset (`randr.rs:112-154`,
432    /// `client.rs:2623-2669`); with an override the application owns the
433    /// scale, and the factor is applied nowhere.
434    pub text_scaling_factor: f32,
435    /// Whether the user has requested reduced motion.
436    pub reduce_motion: bool,
437    /// Whether a high-contrast mode is active.
438    pub high_contrast: bool,
439    /// Whether the user has requested reduced transparency.
440    pub reduce_transparency: bool,
441}
442
443impl Default for AccessibilityPreferences {
444    fn default() -> Self {
445        Self::DEFAULT
446    }
447}
448
449impl AccessibilityPreferences {
450    /// No text scaling and no flag set: what [`Default::default`] returns,
451    /// usable in a `const` or `static`.
452    pub const DEFAULT: Self = Self {
453        text_scaling_factor: 1.0,
454        reduce_motion: false,
455        high_contrast: false,
456        reduce_transparency: false,
457    };
458
459    /// Read the OS accessibility preferences without resolving a theme.
460    ///
461    /// Runs the same platform reader [`SystemTheme::from_system`] runs (KDE
462    /// `kdeglobals`, GNOME portal + gsettings, macOS `NSWorkspace`, Windows
463    /// `UISettings`) and takes its accessibility block, blocking on it with
464    /// `pollster::block_on`. Fields no reader supplies keep their defaults.
465    /// Never fails: with no reader or a failing reader the defaults are
466    /// returned, with `reduce_motion` the platform's read
467    /// ([`crate::detect::detect_reduced_motion`], the one the readers make).
468    ///
469    /// Use it on the preset path, where accessibility is orthogonal to the
470    /// theme choice (a user with large text wants it under a preset too).
471    #[must_use]
472    pub fn from_system() -> Self {
473        pollster::block_on(pipeline::reader_accessibility())
474    }
475
476    /// The text-scaling multiplier the toolkit has not applied:
477    /// [`text_scaling_factor`](Self::text_scaling_factor) when it is finite
478    /// and positive, else `1.0`, so a factor no platform could mean (NaN,
479    /// zero, negative, infinite) leaves text at its size.
480    #[must_use]
481    pub fn text_scale_factor(&self) -> f32 {
482        let s = self.text_scaling_factor;
483        if s.is_finite() && s > 0.0 { s } else { 1.0 }
484    }
485
486    /// A text size times [`text_scale_factor`](Self::text_scale_factor).
487    ///
488    /// For every text size alike: a widget's font, a `text_scale` role's
489    /// size, the default fonts. No other length is scaled. Where the product
490    /// is not a normal positive number (a finite factor large enough to
491    /// overflow `f32`, or one small enough to make it subnormal or zero),
492    /// `size` is returned unscaled, as for a factor that is not finite and
493    /// positive.
494    #[must_use]
495    pub fn scaled(&self, size: f32) -> f32 {
496        let product = size * self.text_scale_factor();
497        if product.is_normal() && product > 0.0 {
498            product
499        } else {
500            size
501        }
502    }
503}
504
505/// Complete reader result for the pipeline.
506///
507/// Bundles the type-safe [`ReaderOutput`] with reader metadata
508/// (name, icon_set, layout, font_dpi, accessibility) so that
509/// `run_pipeline` accepts a single struct instead of many arguments.
510#[derive(Clone, Debug)]
511pub(crate) struct ReaderResult {
512    /// The reader's variant data.
513    pub(crate) output: ReaderOutput,
514    /// Theme name from reader (e.g. "BreezeDark", "GNOME", "macOS").
515    pub(crate) name: Cow<'static, str>,
516    /// Shared icon_set from reader.
517    pub(crate) icon_set: Option<IconSet>,
518    /// Shared layout from reader.
519    pub(crate) layout: LayoutTheme,
520    /// The reader's font DPI (None = `ResolutionContext::from_system()`'s).
521    pub(crate) font_dpi: Option<f32>,
522    /// OS-detected accessibility preferences.
523    pub(crate) accessibility: AccessibilityPreferences,
524}
525
526/// Output contract for platform readers.
527///
528/// Expresses single-vs-dual variant semantics explicitly:
529/// - `Single`: KDE, GNOME, and Windows readers report only the OS-active mode.
530///   The pipeline fills the inactive variant from the platform preset.
531/// - `Dual`: macOS reads both light and dark appearances in a single call.
532///   The pipeline uses both reader-provided variants directly.
533///
534/// Both carry `is_dark`, the OS-active mode, from which the pipeline sets
535/// [`SystemTheme::mode`].
536#[derive(Clone, Debug)]
537pub(crate) enum ReaderOutput {
538    /// Reader provides only the OS-active variant. The pipeline fills the
539    /// inactive variant from the platform preset.
540    #[cfg_attr(all(target_os = "windows", not(feature = "windows")), allow(dead_code))]
541    Single {
542        /// The reader-provided variant (OS-active).
543        mode: Box<ThemeMode>,
544        /// Which color mode this variant represents.
545        is_dark: bool,
546    },
547    /// Reader provides both light and dark variants (macOS).
548    #[allow(dead_code)]
549    Dual {
550        /// The light variant from the reader.
551        light: Box<ThemeMode>,
552        /// The dark variant from the reader.
553        dark: Box<ThemeMode>,
554        /// Whether the OS-active appearance is the dark one.
555        is_dark: bool,
556    },
557}
558
559impl ReaderOutput {
560    /// The OS-active color mode, as `is_dark` reports it.
561    pub(crate) fn mode(&self) -> ColorMode {
562        let (ReaderOutput::Single { is_dark, .. } | ReaderOutput::Dual { is_dark, .. }) = self;
563        if *is_dark {
564            ColorMode::Dark
565        } else {
566            ColorMode::Light
567        }
568    }
569
570    /// Reconstruct a [`Theme`] from this reader output (for overlay replay
571    /// and merge compatibility).
572    pub(crate) fn to_theme(
573        &self,
574        name: &str,
575        icon_set: Option<IconSet>,
576        layout: &LayoutTheme,
577    ) -> Theme {
578        let (light, dark) = match self {
579            ReaderOutput::Single { mode, is_dark } => {
580                if *is_dark {
581                    (None, Some(ThemeMode::clone(mode)))
582                } else {
583                    (Some(ThemeMode::clone(mode)), None)
584                }
585            }
586            ReaderOutput::Dual { light, dark, .. } => {
587                (Some(ThemeMode::clone(light)), Some(ThemeMode::clone(dark)))
588            }
589        };
590        Theme {
591            name: std::borrow::Cow::Owned(name.to_string()),
592            light,
593            dark,
594            layout: layout.clone(),
595            icon_set,
596            // Readers keep Theme-level icon_theme = None and rely on either
597            // the preset's value (tier 2) or system detect (tier 3). Readers
598            // that need to override per color mode use ThemeDefaults::icon_theme
599            // on the variant (tier 1, e.g. the KDE reader for breeze/breeze-dark).
600            icon_theme: None,
601        }
602    }
603}
604
605/// Data needed to replay the merge+resolve pipeline for overlay support.
606///
607/// Stores the reader's output, the preset name and every overlay applied so
608/// far (merged into one [`Theme`]), so that [`SystemTheme::with_overlay()`]
609/// rebuilds the pre-resolve variants (preset, then reader, then overlays)
610/// and resolves them again.
611#[derive(Clone, Debug)]
612pub(crate) struct OverlaySource {
613    /// The reader's variant data for replay.
614    pub(crate) reader_output: ReaderOutput,
615    /// Theme name from reader.
616    pub(crate) name: Cow<'static, str>,
617    /// Shared icon_set from reader.
618    pub(crate) icon_set: Option<IconSet>,
619    /// Shared layout from reader.
620    pub(crate) layout: LayoutTheme,
621    /// The platform preset name (e.g. "kde-breeze").
622    pub(crate) preset_name: String,
623    /// Resolution-time inputs captured at detection time: the context
624    /// bundles `font_dpi` + `button_order` + detected `icon_theme` and is cloned
625    /// into `with_overlay` replays so resolution is deterministic across
626    /// overlay applications.
627    pub(crate) context: crate::resolve::ResolutionContext,
628    /// Every overlay applied so far, merged in order; `None` before the
629    /// first [`SystemTheme::with_overlay()`].
630    pub(crate) overlay: Option<Theme>,
631}
632
633/// Result of the OS-first pipeline. Holds both resolved variants.
634///
635/// Produced by [`SystemTheme::from_system()`] and [`SystemTheme::from_system_async()`].
636/// Both light and dark are always populated: the OS-active variant
637/// comes from the reader + preset + resolve, the inactive variant
638/// comes from the preset + resolve.
639#[derive(Clone, Debug)]
640pub struct SystemTheme {
641    /// Theme name: the reader's (the KDE colour scheme's, such as
642    /// `"BreezeDark"`, or `"GNOME"`, `"macOS"`, `"Windows"`), or the preset's
643    /// where no reader ran.
644    //
645    // # Ownership type
646    //
647    // `Cow<'static, str>`, not `Arc<str>` (which `ResolvedFontSpec::family`
648    // uses, as 26 widgets share font families): each resolved theme carries
649    // one `name`, so sharing gains nothing, and a bundled preset's name is a
650    // `&'static str` literal that `Cow::Borrowed` holds with no allocation and
651    // no refcount. The same holds for `SystemTheme::icon_theme`, `Theme::name`
652    // and `ThemeDefaults::icon_theme` (`docs/archive/v0.5.7_gaps.md` §G9).
653    pub name: Cow<'static, str>,
654    /// The OS color mode preference (light or dark).
655    pub mode: ColorMode,
656    /// Resolved light variant (always populated).
657    pub light: ResolvedTheme,
658    /// Resolved dark variant (always populated).
659    pub dark: ResolvedTheme,
660    /// Data for replaying the pipeline on overlay.
661    pub(crate) overlay_source: OverlaySource,
662    /// The platform preset used (e.g., "kde-breeze", "adwaita", "macos-tahoe").
663    pub preset: String,
664    /// How the running OS version relates to the generation of
665    /// [`preset`](Self::preset): `None` where the platform has no generation
666    /// table (Linux, whose readers read the installed style) or no reader ran.
667    /// On macOS 27 under `macos-tahoe`, which no preset of its own covers yet,
668    /// it is `Some(VersionMatch::PresetOlder)`; on Windows 10 under
669    /// `windows-11`, `Some(VersionMatch::PresetNewer)`. Early macOS 26 betas
670    /// reported version 16 to a binary built against the macOS 15 SDK; a
671    /// major version 16 gets `macos-monterey` with
672    /// `Some(VersionMatch::PresetOlder)` (sources in the macOS generation
673    /// table, `pipeline.rs`).
674    pub version_match: Option<VersionMatch>,
675    /// Which icon loading mechanism to use for this theme.
676    pub icon_set: IconSet,
677    /// The name of the visual icon theme (e.g. `"breeze"`, `"Adwaita"`):
678    /// the active variant's, else the theme's, else the detected system
679    /// icon theme. `None` where the theme states none and detection fails;
680    /// [`system_icon_theme()`](crate::detect::system_icon_theme) gives the
681    /// reason.
682    //
683    // # Ownership type
684    //
685    // `Cow<'static, str>` is used here per the same principled deviation
686    // documented on `SystemTheme::name` — see `docs/archive/v0.5.7_gaps.md`
687    // §G9. Each resolved theme carries a single icon-theme name (KDE has
688    // exactly two across light/dark variants — `"breeze"` / `"breeze-dark"`;
689    // other platforms have one), so the `Arc<str>` dedup benefit does not apply.
690    pub icon_theme: Option<Cow<'static, str>>,
691    /// Each variant's icon theme, resolved by the same three tiers as
692    /// [`icon_theme`](Self::icon_theme), kept by variant rather than relative
693    /// to [`mode`](Self::mode), a public field a caller may change. Read
694    /// through [`icon_theme_for`](Self::icon_theme_for).
695    pub(crate) light_icon_theme: Option<Cow<'static, str>>,
696    /// The dark variant's counterpart of [`light_icon_theme`](Self::light_icon_theme).
697    pub(crate) dark_icon_theme: Option<Cow<'static, str>>,
698    /// Layout spacing shared by both variants: the platform reader's values
699    /// merged field-wise over the preset's, the same precedence the pipeline
700    /// uses for colours. `None` in a field means neither the platform nor the
701    /// preset specifies it (platform-facts §2.20); nothing is invented.
702    pub layout: LayoutTheme,
703    /// OS-detected accessibility preferences (shared across variants).
704    pub accessibility: AccessibilityPreferences,
705}
706
707impl SystemTheme {
708    /// Pick a resolved variant by color mode.
709    ///
710    /// # Examples
711    ///
712    /// ```no_run
713    /// use native_theme::theme::ColorMode;
714    ///
715    /// let sys = native_theme::SystemTheme::from_system()?;
716    /// let dark = sys.pick(ColorMode::Dark);
717    /// let active = sys.pick(sys.mode);
718    /// # Ok::<(), native_theme::error::Error>(())
719    /// ```
720    #[must_use]
721    pub fn pick(&self, mode: ColorMode) -> &ResolvedTheme {
722        match mode {
723            ColorMode::Light => &self.light,
724            ColorMode::Dark => &self.dark,
725        }
726    }
727
728    /// The icon-theme name for one colour mode, resolved for that mode's
729    /// variant by the same three tiers as [`icon_theme`](Self::icon_theme)
730    /// (its `defaults.icon_theme`, then the theme's, then the detected system
731    /// theme); for the mode the theme was built in it equals `icon_theme` as
732    /// built. KDE names one theme per variant (`breeze`, `breeze-dark`); a
733    /// toolkit that keeps a style per colour scheme needs both. `None` where
734    /// that variant states none and detection failed; nothing is invented.
735    #[must_use]
736    pub fn icon_theme_for(&self, mode: ColorMode) -> Option<&str> {
737        match mode {
738            ColorMode::Light => self.light_icon_theme.as_deref(),
739            ColorMode::Dark => self.dark_icon_theme.as_deref(),
740        }
741    }
742
743    /// Load an icon from this theme's [`icon_set`](Self::icon_set), in
744    /// `color`, for one colour mode's variant: a freedesktop icon comes from
745    /// that variant's theme, [`icon_theme_for(mode)`](Self::icon_theme_for)
746    /// (`breeze` or `breeze-dark` under `kde-breeze`), so an application can
747    /// draw the variant that is not the OS's.
748    ///
749    /// `color` is honoured as in
750    /// [`load_custom_icon`](crate::icons::load_custom_icon): an SF Symbol or
751    /// a Segoe glyph loads in it, and a Material or Lucide SVG (or a
752    /// provider's own SVG) is coloured through
753    /// [`colorize_monochrome_svg`](crate::icons::colorize_monochrome_svg). A
754    /// freedesktop icon takes it where it has a foreground left to the
755    /// caller: a symbolic icon's placeholders
756    /// ([`FreedesktopLoader::color`](crate::icons::FreedesktopLoader::color))
757    /// and a `currentColor` the document sets no `color` for
758    /// ([`fill_current_color`](crate::icons::fill_current_color)). An icon
759    /// whose own stylesheet sets the `color` its `currentColor` takes
760    /// (Breeze's `current-color-scheme`) keeps that colour, as it is not yet
761    /// rewritten from the theme as KDE's own icon loader does, and a
762    /// full-colour icon keeps its palette. `None` leaves each icon in the
763    /// colour it loads in. A system set's icon loads at its loader's default
764    /// size (a freedesktop icon looked up at 24
765    /// pixels, an SF Symbol at 24 points, a Segoe glyph at 32 pixels);
766    /// [`load_custom_icon`](crate::icons::load_custom_icon) takes a size.
767    ///
768    /// `None` where the set has no such icon, or without the set's feature
769    /// (see the loaders in [`icons`]).
770    ///
771    /// # Examples
772    ///
773    /// ```no_run
774    /// use native_theme::icons::IconRole;
775    ///
776    /// let sys = native_theme::SystemTheme::from_system()?;
777    /// let fg = sys.pick(sys.mode).defaults.text_color;
778    /// let _icon = sys.icon(IconRole::ActionCopy, sys.mode, Some(fg));
779    /// # Ok::<(), native_theme::Error>(())
780    /// ```
781    #[must_use]
782    pub fn icon<'a>(
783        &self,
784        id: impl Into<IconId<'a>>,
785        mode: ColorMode,
786        color: Option<Rgba>,
787    ) -> Option<IconData> {
788        self.with_icon_source(mode, |set, theme| {
789            icons::load_icon_in(id.into(), set, theme, color, None)
790        })
791    }
792
793    /// Load this theme's [`icon_set`](Self::icon_set) animated loading
794    /// indicator for one colour mode's variant: a freedesktop spinner comes
795    /// from [`icon_theme_for(mode)`](Self::icon_theme_for), as in
796    /// [`icon`](Self::icon). See
797    /// [`load_icon_indicator`].
798    #[must_use]
799    pub fn icon_indicator(&self, mode: ColorMode) -> Option<AnimatedIcon> {
800        self.with_icon_source(mode, icons::load_icon_indicator)
801    }
802
803    /// Run `load` on the set and the freedesktop theme that [`icon`](Self::icon)
804    /// and [`icon_indicator`](Self::icon_indicator) load from for `mode`.
805    fn with_icon_source<'s, R>(
806        &'s self,
807        mode: ColorMode,
808        load: impl FnOnce(IconSet, Option<&'s str>) -> R,
809    ) -> R {
810        load(self.icon_set, self.icon_theme_for(mode))
811    }
812
813    /// Apply an app-level TOML overlay and re-resolve.
814    ///
815    /// Merges the overlay onto the pre-resolve [`ThemeMode`] (not the
816    /// already-resolved [`ResolvedTheme`]) so that changed source fields
817    /// propagate correctly through `resolve()`. For example, changing
818    /// `defaults.accent_color` in the overlay will cause `button.primary_background`,
819    /// `checkbox.checked_background`, `slider.fill`, etc. to be re-derived from
820    /// the new accent color where the theme does not state them: windows-11
821    /// states its accent fills, `button.primary_background` among them, and
822    /// those keep their values.
823    ///
824    /// Overlays stack: each call applies its overlay over the ones applied
825    /// before it, so `sys.with_overlay(&a)?.with_overlay(&b)?` keeps what `a`
826    /// states unless `b` states it too.
827    ///
828    /// The overlay's `icon_set`, `icon_theme` and `[layout]` apply too, by
829    /// the precedence [`from_system()`](Self::from_system) uses: a variant's
830    /// `defaults.icon_theme`, then the theme's `icon_theme`, then the
831    /// detected one. So an overlay's top-level `icon_theme` loses to a
832    /// variant's own, such as the KDE reader's `breeze` and `breeze-dark`;
833    /// to replace those, state `[light.defaults] icon_theme` and
834    /// `[dark.defaults] icon_theme`.
835    ///
836    /// The result's `light`, `dark`, `layout`, `icon_set` and `icon_theme`
837    /// (with [`icon_theme_for`](Self::icon_theme_for)'s per-variant names)
838    /// are rebuilt from the theme's sources and the overlays, not copied
839    /// from `self`, so a change the caller made to one of those public fields
840    /// is lost. `name`, `mode`, `preset`, `version_match` and `accessibility`
841    /// are kept from `self`.
842    ///
843    /// # Errors
844    ///
845    /// Returns [`Error::ResolutionInvalid`] when a value the overlay states,
846    /// or one that inherits it, is out of range. Each path is the TOML key,
847    /// as [`Error::ResolutionIncomplete`] describes: a variant's value under
848    /// its variant table (`light.button.min_height_px`), a `[layout]` value
849    /// with no variant (`layout.widget_gap_px`).
850    ///
851    /// # Examples
852    ///
853    /// An overlay is a theme file that states only what it changes; it needs
854    /// no `name`:
855    ///
856    /// ```
857    /// let overlay = native_theme::Theme::from_toml(r##"
858    ///     [light.defaults]
859    ///     accent_color = "#ff6600"
860    ///     [dark.defaults]
861    ///     accent_color = "#ff6600"
862    /// "##)?;
863    /// # Ok::<(), native_theme::Error>(())
864    /// ```
865    ///
866    /// Then apply it to the live OS theme:
867    ///
868    /// ```no_run
869    /// # let overlay = native_theme::Theme::default();
870    /// let system = native_theme::SystemTheme::from_system()?;
871    /// let customized = system.with_overlay(&overlay)?;
872    /// // customized.pick(customized.mode).defaults.accent_color is now #ff6600
873    /// // and all accent-derived fields are updated
874    /// # Ok::<(), native_theme::Error>(())
875    /// ```
876    pub fn with_overlay(&self, overlay: &Theme) -> crate::Result<Self> {
877        let mut source = self.overlay_source.clone();
878        // The earlier overlays go under this one
879        source.overlay = Some(match source.overlay.take() {
880            Some(mut stacked) => {
881                stacked.merge(overlay);
882                stacked
883            }
884            None => overlay.clone(),
885        });
886        Ok(SystemTheme {
887            name: self.name.clone(),
888            preset: self.preset.clone(),
889            version_match: self.version_match,
890            ..pipeline::replay(source, self.mode, self.accessibility.clone())?
891        })
892    }
893
894    /// Load the OS theme synchronously.
895    ///
896    /// Detects the platform and desktop environment, reads the current theme
897    /// settings, merges with a platform preset, and returns a fully resolved
898    /// [`SystemTheme`] with both light and dark variants.
899    ///
900    /// The return value goes through the full pipeline: reader output ->
901    /// resolve -> validate -> [`SystemTheme`] with both light and dark
902    /// [`ResolvedTheme`] variants.
903    ///
904    /// On every platform `pollster::block_on` drives the async implementation
905    /// that [`from_system_async`](Self::from_system_async) awaits.
906    ///
907    /// # Platform Behavior
908    ///
909    /// - **macOS:** with the `macos` feature, reads both light and dark
910    ///   variants via NSAppearance and merges them with the preset of the
911    ///   running version's generation, `macos-monterey` on 12 to 15 and
912    ///   `macos-tahoe` on 26 and later ([`version_match`](Self::version_match)
913    ///   reports macOS 27 as `PresetOlder`); the active mode comes from
914    ///   [`detect::detect_is_dark`].
915    /// - **Linux:** the async implementation handles portal D-Bus calls when
916    ///   the `portal` feature is enabled. Without a reader for the detected
917    ///   desktop (feature disabled, or a desktop with no reader), returns the
918    ///   desktop's platform preset with no live reading (`kde-breeze` on KDE,
919    ///   `adwaita` elsewhere, as [`pipeline::platform_preset_name`] names
920    ///   it), resolved in the light/dark mode [`detect::detect_is_dark`]
921    ///   reads.
922    /// - **Windows:** with the `windows` feature, reads the active variant and
923    ///   merges it with the `windows-11` preset, the one Windows generation
924    ///   ([`version_match`](Self::version_match) reports Windows 10 as
925    ///   `PresetNewer`).
926    /// - **Other platforms:** Returns `Error::PlatformUnsupported`.
927    ///
928    /// # Errors
929    ///
930    /// - `Error::FeatureDisabled` on macOS or Windows when the `macos` /
931    ///   `windows` feature is not enabled.
932    /// - `Error::PlatformUnsupported` if the platform has no reader at all.
933    /// - `Error::ReaderFailed` if the platform reader cannot access theme data.
934    ///
935    /// # Examples
936    ///
937    /// ```no_run
938    /// let sys = native_theme::SystemTheme::from_system()?;
939    /// let theme = sys.pick(sys.mode);
940    /// // Icon set and theme are on SystemTheme, shared across variants
941    /// let _icon_set = sys.icon_set;
942    /// let _icon_theme = &sys.icon_theme;
943    /// # Ok::<(), native_theme::error::Error>(())
944    /// ```
945    pub fn from_system() -> crate::Result<Self> {
946        pollster::block_on(pipeline::from_system_inner())
947    }
948
949    /// Async version of [`from_system()`](Self::from_system).
950    ///
951    /// On Linux, this enables portal D-Bus calls (e.g. GNOME settings portal,
952    /// KDE portal backend detection) via `.await`. On macOS and Windows, the
953    /// future completes immediately -- no actual async operations occur.
954    ///
955    /// Returns a [`SystemTheme`] with both resolved light and dark variants,
956    /// same as [`from_system()`](Self::from_system).
957    pub async fn from_system_async() -> crate::Result<Self> {
958        pipeline::from_system_inner().await
959    }
960
961    /// Load the OS theme over a chosen generation's preset: the platform
962    /// reader runs as in [`from_system()`](Self::from_system), and its values
963    /// merge over `preset` instead of the running version's generation.
964    ///
965    /// `preset` must be a generation of the running platform: `macos-monterey`
966    /// or `macos-tahoe` on macOS, `windows-11` on Windows. Any other name, and
967    /// any name on a platform without a generation table (Linux, whose readers
968    /// read the installed style, BSD and other platforms), is
969    /// `Error::UnknownPreset`, where [`from_system()`](Self::from_system) may
970    /// return `Error::PlatformUnsupported` (BSD and other platforms).
971    ///
972    /// The result is a hybrid, not the older OS's look: the chosen
973    /// generation's geometry and design colours under the running OS's
974    /// colours, fonts and accessibility settings, which the reader reads live
975    /// (on macOS 26 with `macos-monterey`, `NSColor` gives macOS 26's
976    /// colours). [`version_match`](Self::version_match) reports the chosen
977    /// generation against the running OS: `PresetOlder` for an older one,
978    /// `PresetNewer` for a newer one.
979    ///
980    /// # Errors
981    ///
982    /// - `Error::UnknownPreset` for a name that is not a generation of the
983    ///   running platform, and for any name on a platform without a
984    ///   generation table.
985    /// - `Error::FeatureDisabled` on macOS or Windows when the `macos` /
986    ///   `windows` feature is not enabled.
987    /// - `Error::ReaderFailed` if the platform reader cannot access theme data.
988    ///
989    /// # Examples
990    ///
991    /// ```no_run
992    /// // Keep the Monterey-to-Sequoia look on a Mac running macOS 26.
993    /// let sys = native_theme::SystemTheme::from_system_with_preset("macos-monterey")?;
994    /// assert_eq!(sys.preset, "macos-monterey");
995    /// # Ok::<(), native_theme::error::Error>(())
996    /// ```
997    pub fn from_system_with_preset(preset: &str) -> crate::Result<Self> {
998        pollster::block_on(pipeline::from_system_with_preset_inner(preset))
999    }
1000
1001    /// Async version of
1002    /// [`from_system_with_preset()`](Self::from_system_with_preset).
1003    pub async fn from_system_with_preset_async(preset: &str) -> crate::Result<Self> {
1004        pipeline::from_system_with_preset_inner(preset).await
1005    }
1006}
1007
1008// =============================================================================
1009// Tests -- SystemTheme public API (active, pick, platform_preset_name)
1010// =============================================================================
1011
1012#[cfg(test)]
1013#[allow(
1014    clippy::unwrap_used,
1015    clippy::expect_used,
1016    clippy::field_reassign_with_default
1017)]
1018mod system_theme_tests {
1019    use super::*;
1020
1021    // --- SystemTheme::active() / pick() tests ---
1022
1023    #[test]
1024    fn test_system_theme_pick_dark_mode() {
1025        let preset = Theme::preset("catppuccin-mocha").unwrap();
1026        let mut light_v = preset.light.clone().unwrap();
1027        let mut dark_v = preset.dark.clone().unwrap();
1028        // Give them distinct accents so we can tell them apart
1029        // (test fixture values -- not production hardcoded colors)
1030        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
1031        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
1032        light_v.resolve_all();
1033        dark_v.resolve_all();
1034        let light_resolved = light_v.validate().unwrap();
1035        let dark_resolved = dark_v.validate().unwrap();
1036
1037        let st = SystemTheme {
1038            name: "test".into(),
1039            mode: ColorMode::Dark,
1040            light: light_resolved.clone(),
1041            dark: dark_resolved.clone(),
1042            overlay_source: OverlaySource {
1043                reader_output: ReaderOutput::Dual {
1044                    light: Box::new(ThemeMode::default()),
1045                    dark: Box::new(ThemeMode::default()),
1046                    is_dark: false,
1047                },
1048                name: Cow::Borrowed(""),
1049                icon_set: None,
1050                layout: LayoutTheme::default(),
1051                preset_name: "catppuccin-mocha".into(),
1052                context: crate::resolve::ResolutionContext::for_tests(),
1053                overlay: None,
1054            },
1055            preset: "catppuccin-mocha".into(),
1056            version_match: None,
1057            icon_set: IconSet::Lucide,
1058            icon_theme: Some("lucide".into()),
1059            light_icon_theme: None,
1060            dark_icon_theme: Some("lucide".into()),
1061            layout: LayoutTheme::default(),
1062            accessibility: AccessibilityPreferences::default(),
1063        };
1064        assert_eq!(
1065            st.pick(st.mode).defaults.accent_color,
1066            dark_resolved.defaults.accent_color
1067        );
1068    }
1069
1070    #[test]
1071    fn test_system_theme_pick_light_mode() {
1072        let preset = Theme::preset("catppuccin-mocha").unwrap();
1073        let mut light_v = preset.light.clone().unwrap();
1074        let mut dark_v = preset.dark.clone().unwrap();
1075        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
1076        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
1077        light_v.resolve_all();
1078        dark_v.resolve_all();
1079        let light_resolved = light_v.validate().unwrap();
1080        let dark_resolved = dark_v.validate().unwrap();
1081
1082        let st = SystemTheme {
1083            name: "test".into(),
1084            mode: ColorMode::Light,
1085            light: light_resolved.clone(),
1086            dark: dark_resolved.clone(),
1087            overlay_source: OverlaySource {
1088                reader_output: ReaderOutput::Dual {
1089                    light: Box::new(ThemeMode::default()),
1090                    dark: Box::new(ThemeMode::default()),
1091                    is_dark: false,
1092                },
1093                name: Cow::Borrowed(""),
1094                icon_set: None,
1095                layout: LayoutTheme::default(),
1096                preset_name: "catppuccin-mocha".into(),
1097                context: crate::resolve::ResolutionContext::for_tests(),
1098                overlay: None,
1099            },
1100            preset: "catppuccin-mocha".into(),
1101            version_match: None,
1102            icon_set: IconSet::Lucide,
1103            icon_theme: Some("lucide".into()),
1104            light_icon_theme: Some("lucide".into()),
1105            dark_icon_theme: None,
1106            layout: LayoutTheme::default(),
1107            accessibility: AccessibilityPreferences::default(),
1108        };
1109        assert_eq!(
1110            st.pick(st.mode).defaults.accent_color,
1111            light_resolved.defaults.accent_color
1112        );
1113    }
1114
1115    #[test]
1116    fn test_system_theme_pick_explicit() {
1117        let preset = Theme::preset("catppuccin-mocha").unwrap();
1118        let mut light_v = preset.light.clone().unwrap();
1119        let mut dark_v = preset.dark.clone().unwrap();
1120        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
1121        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
1122        light_v.resolve_all();
1123        dark_v.resolve_all();
1124        let light_resolved = light_v.validate().unwrap();
1125        let dark_resolved = dark_v.validate().unwrap();
1126
1127        let st = SystemTheme {
1128            name: "test".into(),
1129            mode: ColorMode::Light,
1130            light: light_resolved.clone(),
1131            dark: dark_resolved.clone(),
1132            overlay_source: OverlaySource {
1133                reader_output: ReaderOutput::Dual {
1134                    light: Box::new(ThemeMode::default()),
1135                    dark: Box::new(ThemeMode::default()),
1136                    is_dark: false,
1137                },
1138                name: Cow::Borrowed(""),
1139                icon_set: None,
1140                layout: LayoutTheme::default(),
1141                preset_name: "catppuccin-mocha".into(),
1142                context: crate::resolve::ResolutionContext::for_tests(),
1143                overlay: None,
1144            },
1145            preset: "catppuccin-mocha".into(),
1146            version_match: None,
1147            icon_set: IconSet::Lucide,
1148            icon_theme: Some("lucide".into()),
1149            light_icon_theme: Some("lucide".into()),
1150            dark_icon_theme: None,
1151            layout: LayoutTheme::default(),
1152            accessibility: AccessibilityPreferences::default(),
1153        };
1154        assert_eq!(
1155            st.pick(ColorMode::Dark).defaults.accent_color,
1156            dark_resolved.defaults.accent_color
1157        );
1158        assert_eq!(
1159            st.pick(ColorMode::Light).defaults.accent_color,
1160            light_resolved.defaults.accent_color
1161        );
1162    }
1163
1164    // --- platform_preset_name() pure tests ---
1165    // Tests the same logic path (parse_linux_desktop -> linux_preset_for_de) without env var mocking.
1166
1167    /// Prove that the sync `from_system()` API works without any async runtime.
1168    /// On Linux with KDE feature: exercises pollster::block_on(from_system_inner()).
1169    /// This acts as a compile-time and runtime gate that the sync path works.
1170    #[test]
1171    #[cfg(target_os = "linux")]
1172    #[cfg(feature = "kde")]
1173    fn sync_consumer_no_async_runtime() {
1174        // Call the actual from_system() entry point.
1175        // This exercises the pollster::block_on(pipeline::from_system_inner()) path.
1176        // We don't assert Ok because the test environment may lack KDE config files,
1177        // but the call must not panic and must return a Result (not hang or deadlock).
1178        let _result = SystemTheme::from_system();
1179    }
1180
1181    #[test]
1182    #[cfg(target_os = "linux")]
1183    fn test_platform_preset_name_kde() {
1184        let preset = pipeline::linux_preset_for_de(detect::parse_linux_desktop("KDE"));
1185        assert_eq!(preset.name, "kde-breeze");
1186    }
1187
1188    #[test]
1189    #[cfg(target_os = "linux")]
1190    fn test_platform_preset_name_gnome() {
1191        let preset = pipeline::linux_preset_for_de(detect::parse_linux_desktop("GNOME"));
1192        assert_eq!(preset.name, "adwaita");
1193    }
1194
1195    /// §11.2: `from_system()` is an extraction of the reader path, so it must
1196    /// agree with `SystemTheme::from_system()` wherever both succeed, and it
1197    /// must never return a non-finite or non-positive text scale.
1198    #[test]
1199    fn accessibility_preferences_from_system_is_consistent_with_system_theme() {
1200        let prefs = AccessibilityPreferences::from_system();
1201        assert!(prefs.text_scaling_factor.is_finite());
1202        assert!(prefs.text_scaling_factor > 0.0);
1203
1204        // CI has no desktop; only compare when the full pipeline also works.
1205        if let Ok(sys) = SystemTheme::from_system() {
1206            assert_eq!(
1207                prefs.text_scaling_factor,
1208                sys.accessibility.text_scaling_factor
1209            );
1210            assert_eq!(prefs.high_contrast, sys.accessibility.high_contrast);
1211            assert_eq!(
1212                prefs.reduce_transparency,
1213                sys.accessibility.reduce_transparency
1214            );
1215            assert_eq!(prefs.reduce_motion, sys.accessibility.reduce_motion);
1216        }
1217    }
1218}
1219
1220// =============================================================================
1221// Tests -- with_overlay
1222// =============================================================================
1223
1224#[cfg(test)]
1225#[allow(clippy::unwrap_used, clippy::expect_used)]
1226mod overlay_tests {
1227    use super::*;
1228
1229    /// Helper: build a SystemTheme from a preset via pipeline::run_pipeline.
1230    /// Uses test-only Result handling (module has #[allow(clippy::unwrap_used)]).
1231    fn default_system_theme() -> crate::Result<SystemTheme> {
1232        let preset = Theme::preset("catppuccin-mocha")?;
1233        let reader = ReaderResult {
1234            output: ReaderOutput::Dual {
1235                light: Box::new(preset.light.clone().unwrap_or_default()),
1236                dark: Box::new(preset.dark.clone().unwrap_or_default()),
1237                is_dark: false,
1238            },
1239            name: preset.name,
1240            icon_set: preset.icon_set,
1241            layout: preset.layout,
1242            font_dpi: None,
1243            accessibility: AccessibilityPreferences::default(),
1244        };
1245        pipeline::run_pipeline(reader, "catppuccin-mocha")
1246    }
1247
1248    /// The range-violation paths of `result`'s error.
1249    fn violation_paths(result: crate::Result<SystemTheme>) -> Vec<String> {
1250        let Err(crate::Error::ResolutionInvalid { errors }) = result else {
1251            panic!("expected ResolutionInvalid, got {:?}", result.err());
1252        };
1253        errors.into_iter().map(|rv| rv.path).collect()
1254    }
1255
1256    #[test]
1257    fn test_overlay_error_names_the_variant() -> crate::Result<()> {
1258        let st = default_system_theme()?;
1259        let overlay = Theme::from_toml("name = \"overlay\"\n[dark.button]\nmin_height_px = -1.0")?;
1260        assert_eq!(
1261            violation_paths(st.with_overlay(&overlay)),
1262            ["dark.button.min_height_px"]
1263        );
1264        Ok(())
1265    }
1266
1267    #[test]
1268    fn test_pipeline_error_names_the_variant() -> crate::Result<()> {
1269        let preset = Theme::preset("catppuccin-mocha")?;
1270        let mut light = preset.light.clone().unwrap_or_default();
1271        light.button.min_height = Some(-1.0);
1272        let reader = ReaderResult {
1273            output: ReaderOutput::Dual {
1274                light: Box::new(light),
1275                dark: Box::new(preset.dark.clone().unwrap_or_default()),
1276                is_dark: true,
1277            },
1278            name: preset.name,
1279            icon_set: preset.icon_set,
1280            layout: preset.layout,
1281            font_dpi: None,
1282            accessibility: AccessibilityPreferences::default(),
1283        };
1284        assert_eq!(
1285            violation_paths(pipeline::run_pipeline(reader, "catppuccin-mocha",)),
1286            ["light.button.min_height_px"]
1287        );
1288        Ok(())
1289    }
1290
1291    #[test]
1292    fn test_overlay_accent_propagates() -> crate::Result<()> {
1293        let st = default_system_theme()?;
1294        let new_accent = Rgba::rgb(255, 0, 0);
1295
1296        // Build overlay with accent on both light and dark
1297        let mut overlay = Theme::default();
1298        let mut light_v = ThemeMode::default();
1299        light_v.defaults.accent_color = Some(new_accent);
1300        let mut dark_v = ThemeMode::default();
1301        dark_v.defaults.accent_color = Some(new_accent);
1302        overlay.light = Some(light_v);
1303        overlay.dark = Some(dark_v);
1304
1305        let result = st.with_overlay(&overlay)?;
1306
1307        // Accent itself
1308        assert_eq!(result.light.defaults.accent_color, new_accent);
1309        // Accent-derived widget fields
1310        assert_eq!(result.light.button.primary_background, new_accent);
1311        assert_eq!(result.light.checkbox.checked_background, new_accent);
1312        assert_eq!(result.light.slider.fill_color, new_accent);
1313        assert_eq!(result.light.progress_bar.fill_color, new_accent);
1314        assert_eq!(result.light.switch.checked_background, new_accent);
1315        // Additional accent-derived fields re-resolved via safety nets
1316        assert_eq!(
1317            result.light.spinner.fill_color, new_accent,
1318            "spinner.fill should re-derive from new accent"
1319        );
1320        Ok(())
1321    }
1322
1323    #[test]
1324    fn test_overlay_preserves_unrelated_fields() -> crate::Result<()> {
1325        let st = default_system_theme()?;
1326        let original_bg = st.light.defaults.background_color;
1327
1328        // Apply overlay changing only accent
1329        let mut overlay = Theme::default();
1330        let mut light_v = ThemeMode::default();
1331        light_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
1332        overlay.light = Some(light_v);
1333
1334        let result = st.with_overlay(&overlay)?;
1335        assert_eq!(
1336            result.light.defaults.background_color, original_bg,
1337            "background should be unchanged"
1338        );
1339        Ok(())
1340    }
1341
1342    #[test]
1343    fn test_overlay_empty_noop() -> crate::Result<()> {
1344        let st = default_system_theme()?;
1345        let original_light_accent = st.light.defaults.accent_color;
1346        let original_dark_accent = st.dark.defaults.accent_color;
1347        let original_light_bg = st.light.defaults.background_color;
1348
1349        // Empty overlay
1350        let overlay = Theme::default();
1351        let result = st.with_overlay(&overlay)?;
1352
1353        assert_eq!(result.light.defaults.accent_color, original_light_accent);
1354        assert_eq!(result.dark.defaults.accent_color, original_dark_accent);
1355        assert_eq!(result.light.defaults.background_color, original_light_bg);
1356        Ok(())
1357    }
1358
1359    #[test]
1360    fn test_overlay_both_variants() -> crate::Result<()> {
1361        let st = default_system_theme()?;
1362        let red = Rgba::rgb(255, 0, 0);
1363        let green = Rgba::rgb(0, 255, 0);
1364
1365        let mut overlay = Theme::default();
1366        let mut light_v = ThemeMode::default();
1367        light_v.defaults.accent_color = Some(red);
1368        let mut dark_v = ThemeMode::default();
1369        dark_v.defaults.accent_color = Some(green);
1370        overlay.light = Some(light_v);
1371        overlay.dark = Some(dark_v);
1372
1373        let result = st.with_overlay(&overlay)?;
1374        assert_eq!(
1375            result.light.defaults.accent_color, red,
1376            "light accent = red"
1377        );
1378        assert_eq!(
1379            result.dark.defaults.accent_color, green,
1380            "dark accent = green"
1381        );
1382        Ok(())
1383    }
1384
1385    #[test]
1386    fn test_overlay_font_family() -> crate::Result<()> {
1387        let st = default_system_theme()?;
1388
1389        let mut overlay = Theme::default();
1390        let mut light_v = ThemeMode::default();
1391        light_v.defaults.font.family = Some("Comic Sans".into());
1392        overlay.light = Some(light_v);
1393
1394        let result = st.with_overlay(&overlay)?;
1395        assert_eq!(result.light.defaults.font.family.as_ref(), "Comic Sans");
1396        Ok(())
1397    }
1398
1399    #[test]
1400    fn test_overlay_roundtrip_via_overlay_source() -> crate::Result<()> {
1401        let st = default_system_theme()?;
1402        // Apply overlay and verify accent propagates
1403        let new_accent = Rgba::rgb(255, 0, 0);
1404        let mut overlay = Theme::default();
1405        let mut light_v = ThemeMode::default();
1406        light_v.defaults.accent_color = Some(new_accent);
1407        overlay.light = Some(light_v);
1408
1409        let result = st.with_overlay(&overlay)?;
1410        assert_eq!(result.light.defaults.accent_color, new_accent);
1411        // The dark variant should be unchanged from original
1412        assert_eq!(
1413            result.dark.defaults.accent_color,
1414            st.dark.defaults.accent_color
1415        );
1416        Ok(())
1417    }
1418
1419    #[test]
1420    fn test_overlay_source_no_variant_fields() -> crate::Result<()> {
1421        // Verify overlay_source exists on SystemTheme (compile-time structural check).
1422        let st = default_system_theme()?;
1423        let _ = &st.overlay_source; // overlay_source exists
1424        Ok(())
1425    }
1426}
1427
1428// =============================================================================
1429// Tests -- AccessibilityPreferences text scaling
1430// =============================================================================
1431
1432#[cfg(test)]
1433mod accessibility_tests {
1434    use super::*;
1435
1436    fn prefs(text_scaling_factor: f32) -> AccessibilityPreferences {
1437        AccessibilityPreferences {
1438            text_scaling_factor,
1439            ..AccessibilityPreferences::default()
1440        }
1441    }
1442
1443    #[test]
1444    fn text_scale_factor_keeps_a_finite_positive_factor() {
1445        assert_eq!(prefs(2.0).text_scale_factor(), 2.0);
1446        assert_eq!(prefs(2.0).scaled(10.0), 20.0);
1447        assert_eq!(AccessibilityPreferences::default().text_scale_factor(), 1.0);
1448    }
1449
1450    #[test]
1451    fn text_scale_factor_ignores_a_factor_that_is_not_finite_and_positive() {
1452        for f in [f32::NAN, 0.0, -0.0, -1.0, f32::INFINITY, f32::NEG_INFINITY] {
1453            assert_eq!(prefs(f).text_scale_factor(), 1.0, "{f}");
1454            assert_eq!(prefs(f).scaled(10.0), 10.0, "{f}");
1455        }
1456    }
1457
1458    #[test]
1459    fn scaled_keeps_a_size_whose_product_is_not_a_normal_positive_number() {
1460        // A finite factor whose product overflows f32, one whose product is
1461        // subnormal, and one whose product underflows to zero.
1462        assert_eq!(prefs(f32::MAX).scaled(13.0), 13.0);
1463        assert_eq!(prefs(3e37).scaled(13.0), 13.0);
1464        assert!((13.0 * 1e-45_f32).is_subnormal());
1465        assert_eq!(prefs(1e-45).scaled(13.0), 13.0);
1466        assert_eq!(
1467            prefs(f32::MIN_POSITIVE).scaled(f32::MIN_POSITIVE),
1468            f32::MIN_POSITIVE
1469        );
1470        // A product that stays finite and positive is scaled, however large.
1471        assert_eq!(prefs(2e37).scaled(13.0), 13.0 * 2e37);
1472    }
1473}