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