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