native-theme 0.6.1

Cross-platform native theme detection and loading for Rust GUI applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
//! # native-theme
//!
//! Cross-platform native theme detection and loading for Rust GUI applications.
//!
//! Any Rust GUI app can look native on any platform by loading a single theme
//! file or reading live OS settings, without coupling to any specific toolkit.

#![warn(missing_docs)]
#![deny(unsafe_code)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::expect_used)]

#[doc = include_str!("../README.md")]
#[cfg(doctest)]
pub struct ReadmeDoctests;

/// Generates `merge()` and `is_empty()` methods for theme structs.
///
/// Four field categories:
/// - `option { field1, field2, ... }` -- `Option<T>` leaf fields
/// - `soft_option { field1, field2, ... }` -- `Option<T>` leaf fields (same merge/is_empty as option)
/// - `nested { field1, field2, ... }` -- nested struct fields with their own `merge()`
/// - `optional_nested { field1, field2, ... }` -- `Option<T>` where T has its own `merge()`
///
/// For `option` and `soft_option` fields, `Some` values in the overlay replace the
/// corresponding fields in self; `None` fields are left unchanged.
/// For `nested` fields, merge is called recursively.
/// For `optional_nested` fields: if both base and overlay are `Some`, the inner values
/// are merged recursively. If base is `None` and overlay is `Some`, overlay is cloned.
/// If overlay is `None`, the base field is preserved unchanged.
///
/// # Examples
///
/// ```ignore
/// impl_merge!(MyColors {
///     option { accent, background }
/// });
/// ```
macro_rules! impl_merge {
    (
        $struct_name:ident {
            $(option { $($opt_field:ident),* $(,)? })?
            $(soft_option { $($so_field:ident),* $(,)? })?
            $(nested { $($nest_field:ident),* $(,)? })?
            $(optional_nested { $($on_field:ident),* $(,)? })*
        }
    ) => {
        impl $struct_name {
            /// Merge an overlay into this value. `Some` fields in the overlay
            /// replace the corresponding fields in self; `None` fields are
            /// left unchanged. Nested structs are merged recursively.
            pub fn merge(&mut self, overlay: &Self) {
                $($(
                    if overlay.$opt_field.is_some() {
                        self.$opt_field = overlay.$opt_field.clone();
                    }
                )*)?
                $($(
                    if overlay.$so_field.is_some() {
                        self.$so_field = overlay.$so_field.clone();
                    }
                )*)?
                $($(
                    self.$nest_field.merge(&overlay.$nest_field);
                )*)?
                $($(
                    match (&mut self.$on_field, &overlay.$on_field) {
                        (Some(base), Some(over)) => base.merge(over),
                        (None, Some(over)) => self.$on_field = Some(over.clone()),
                        _ => {}
                    }
                )*)*
            }

            /// Returns true if all fields are at their default (None/empty) state.
            pub fn is_empty(&self) -> bool {
                true
                $($(&& self.$opt_field.is_none())*)?
                $($(&& self.$so_field.is_none())*)?
                $($(&& self.$nest_field.is_empty())*)?
                $($(&& self.$on_field.as_ref().map_or(true, |v| v.is_empty()))*)*
            }
        }
    };
}

/// Color types and sRGB utilities.
pub mod color;
/// OS detection: dark mode, reduced motion, DPI, desktop environment.
pub mod detect;
/// Error types for theme operations.
pub mod error;
/// Font matching, and the platform's own typeface for a family (feature
/// `system-fonts`).
pub mod fonts;
/// GNOME portal theme reader.
///
/// Requires the `portal` feature, and Linux.
#[cfg(all(target_os = "linux", feature = "portal"))]
pub mod gnome;
/// Icon loading and dispatch.
pub mod icons;
/// KDE theme reader.
///
/// Requires the `kde` feature, and Linux.
#[cfg(all(target_os = "linux", feature = "kde"))]
pub mod kde;
/// Breeze widget sizing constants. Compiled on every target and feature set,
/// so the preset gate sees the values the KDE reader states.
#[path = "kde/metrics.rs"]
pub(crate) mod kde_metrics;
/// Theme data model types.
pub mod model;
/// Theme pipeline: reader -> preset merge -> resolve -> validate.
pub mod pipeline;
/// Bundled theme presets.
pub mod presets;
/// Internal `ThemeReader` trait (see module docs for Option A rationale).
///
/// Consumed by `pipeline::select_reader` as `Box<dyn ThemeReader>`; the
/// trait and every impl are `pub(crate)` — not part of the public API.
mod reader;
/// Theme resolution engine (inheritance + validation).
///
/// Public surface: [`resolve::ResolutionContext`] — the resolution-time
/// inputs struct consumed by
/// [`ThemeMode::into_resolved`](crate::theme::ThemeMode::into_resolved).
/// Inheritance rules, validation machinery, and the range-check helpers
/// are all crate-internal (no stability guarantee).
pub mod resolve;
#[cfg(any(
    feature = "material-icons",
    feature = "lucide-icons",
    feature = "system-icons"
))]
mod spinners;
/// Runtime theme change watching.
///
/// Requires the `watch` feature.
#[cfg(feature = "watch")]
pub mod watch;

/// Convenience re-exports for common usage.
///
/// `use native_theme::prelude::*` imports:
/// [`Theme`], [`ResolvedTheme`], [`SystemTheme`], [`AccessibilityPreferences`],
/// [`ResolutionContext`], [`Rgba`], [`Error`], and [`Result`].
pub mod prelude;

/// Theme data model: types, defaults, fonts, borders, widgets.
///
/// Core types: [`Theme`], [`ThemeMode`],
/// [`ResolvedTheme`], [`ResolvedDefaults`].
///
/// Re-exports from the internal model module.
pub mod theme {
    pub use crate::model::*;
    pub use crate::presets::PresetInfo;
}

/// Freedesktop icon theme lookup (Linux).
///
/// Requires the `system-icons` feature, and Linux.
#[cfg(all(target_os = "linux", feature = "system-icons"))]
pub mod freedesktop;
/// macOS platform helpers.
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(not(target_os = "macos"))]
pub(crate) mod macos;
/// SVG-to-RGBA rasterization utilities.
///
/// Requires the `svg-rasterize` feature.
#[cfg(feature = "svg-rasterize")]
pub mod rasterize;
/// SF Symbols icon loader (macOS).
///
/// Requires the `system-icons` feature, and macOS.
#[cfg(all(target_os = "macos", feature = "system-icons"))]
pub mod sficons;
/// Windows platform theme reader.
#[cfg(target_os = "windows")]
#[cfg_attr(not(feature = "windows"), allow(dead_code))]
pub mod windows;
#[cfg(not(target_os = "windows"))]
#[allow(dead_code, unused_variables)]
pub(crate) mod windows;
/// Windows Segoe Fluent / stock icon loader.
///
/// Requires the `system-icons` feature, and Windows.
#[cfg(all(target_os = "windows", feature = "system-icons"))]
pub mod winicons;
#[cfg(all(not(target_os = "windows"), feature = "system-icons"))]
#[allow(dead_code, unused_imports)]
pub(crate) mod winicons;

use std::borrow::Cow;

/// Convenience Result type alias for this crate.
pub type Result<T> = std::result::Result<T, error::Error>;

// Internal re-exports: keep crate::Type paths working for internal modules
// without exposing them in the public API. External users access types via
// native_theme::theme::*, native_theme::icons::*, native_theme::detect::*, etc.
#[allow(unused_imports)]
pub(crate) use color::{ParseColorError, Rgba};
#[cfg(target_os = "linux")]
#[allow(unused_imports)]
pub(crate) use detect::LinuxDesktop;
#[cfg(target_os = "linux")]
#[allow(unused_imports)]
pub(crate) use detect::detect_linux_desktop;
#[allow(unused_imports)]
pub(crate) use detect::{
    detect_is_dark, detect_reduced_motion, invalidate_caches, prefers_reduced_motion,
    system_is_dark,
};
#[allow(unused_imports)]
pub(crate) use error::{Error, ErrorKind, RangeViolation};
#[allow(unused_imports)]
pub(crate) use icons::{
    FreedesktopLoader, IconId, LucideLoader, MaterialLoader, SegoeIconsLoader, SfSymbolsLoader,
    is_freedesktop_theme_available, load_icon, load_icon_indicator,
};
pub use icons::{IconSetChoice, default_icon_choice, list_freedesktop_themes};
#[allow(unused_imports)]
pub(crate) use model::icons::{detect_icon_theme, icon_name, system_icon_set, system_icon_theme};
#[allow(unused_imports)]
pub(crate) use model::{
    AnimatedIcon, ButtonTheme, CardTheme, CheckboxTheme, ColorMode, ComboBoxTheme,
    DefaultsBorderSpec, DialogButtonOrder, DialogTheme, ExpanderTheme, FontSize, FontSpec,
    FontStyle, IconData, IconProvider, IconRole, IconSet, IconSizes, InputTheme, LayoutTheme,
    LinkTheme, ListTheme, MenuTheme, PopoverTheme, ProgressBarTheme, ResolvedDefaults,
    ResolvedDefaultsBorder, ResolvedFontSpec, ResolvedIconSizes, ResolvedPadding,
    ResolvedTextScale, ResolvedTextScaleEntry, ResolvedTheme, ResolvedWidgetBorder, ScrollbarTheme,
    SegmentedControlTheme, SeparatorTheme, SidebarTheme, SliderTheme, SpinnerTheme, SplitterTheme,
    StatusBarTheme, SwitchTheme, TabTheme, TextScale, TextScaleEntry, Theme, ThemeDefaults,
    ThemeMode, ToolbarTheme, TooltipTheme, TransformAnimation, WidgetBorderSpec, WindowTheme,
    bundled_icon_by_name, bundled_icon_svg,
};
pub use pipeline::{DiagnosticEntry, PlatformPreset};
#[allow(unused_imports)]
pub(crate) use pipeline::{diagnose_platform_support, platform_preset_name};
pub use resolve::ResolutionContext;

/// OS-detected accessibility preferences.
///
/// A single copy lives on [`SystemTheme`], shared across light and dark
/// variants. These are runtime values detected from the OS -- not stored
/// in TOML presets.
#[derive(Clone, Debug, PartialEq)]
pub struct AccessibilityPreferences {
    /// Text scaling factor (1.0 = no scaling). Multiply font sizes by
    /// this factor when honoring the user's preference for larger text.
    pub text_scaling_factor: f32,
    /// Whether the user has requested reduced motion.
    pub reduce_motion: bool,
    /// Whether a high-contrast mode is active.
    pub high_contrast: bool,
    /// Whether the user has requested reduced transparency.
    pub reduce_transparency: bool,
}

impl Default for AccessibilityPreferences {
    fn default() -> Self {
        Self {
            text_scaling_factor: 1.0,
            reduce_motion: false,
            high_contrast: false,
            reduce_transparency: false,
        }
    }
}

impl AccessibilityPreferences {
    /// Read the OS accessibility preferences without resolving a theme.
    ///
    /// Runs the same platform reader [`SystemTheme::from_system`] runs (KDE
    /// `kdeglobals`, GNOME portal + gsettings) and takes its accessibility
    /// block; `reduce_motion` is additionally read through
    /// [`crate::detect::detect_reduced_motion`] on every platform. Fields no
    /// reader supplies keep their defaults. Never fails: with no reader or a
    /// failing reader the defaults are returned.
    ///
    /// Use it on the preset path, where accessibility is orthogonal to the
    /// theme choice (a user with large text wants it under a preset too).
    #[must_use]
    #[cfg(target_os = "linux")]
    pub fn from_system() -> Self {
        pollster::block_on(pipeline::accessibility_from_system_inner())
    }

    /// Read the OS accessibility preferences without resolving a theme (non-Linux).
    ///
    /// The macOS reader (`NSWorkspace`) and the Windows reader (`UISettings`)
    /// fill the accessibility block on their platforms; `reduce_motion` is
    /// additionally read through [`crate::detect::detect_reduced_motion`].
    /// The inner future has no `.await` points off Linux, so a noop-waker
    /// single poll suffices, as in [`SystemTheme::from_system`].
    #[must_use]
    #[cfg(not(target_os = "linux"))]
    pub fn from_system() -> Self {
        let waker = std::task::Waker::noop();
        let mut cx = std::task::Context::from_waker(&waker);
        let mut fut = std::pin::pin!(pipeline::accessibility_from_system_inner());
        match fut.as_mut().poll(&mut cx) {
            std::task::Poll::Ready(prefs) => prefs,
            std::task::Poll::Pending => Self::default(),
        }
    }
}

/// Complete reader result for the pipeline.
///
/// Bundles the type-safe [`ReaderOutput`] with reader metadata
/// (name, icon_set, layout, font_dpi, accessibility) so that
/// `run_pipeline` accepts a single struct instead of many arguments.
#[derive(Clone, Debug)]
pub(crate) struct ReaderResult {
    /// The reader's variant data.
    pub(crate) output: ReaderOutput,
    /// Theme name from reader (e.g. "BreezeDark", "GNOME", "macOS").
    pub(crate) name: Cow<'static, str>,
    /// Shared icon_set from reader.
    pub(crate) icon_set: Option<IconSet>,
    /// Shared layout from reader.
    pub(crate) layout: LayoutTheme,
    /// Font DPI captured at detection time (None = auto-detect).
    pub(crate) font_dpi: Option<f32>,
    /// OS-detected accessibility preferences.
    pub(crate) accessibility: AccessibilityPreferences,
}

/// Output contract for platform readers.
///
/// Expresses single-vs-dual variant semantics explicitly:
/// - `Single`: KDE, GNOME, and Windows readers report only the OS-active mode.
///   The pipeline fills the inactive variant from the platform preset.
/// - `Dual`: macOS reads both light and dark appearances in a single call.
///   The pipeline uses both reader-provided variants directly.
#[derive(Clone, Debug)]
pub(crate) enum ReaderOutput {
    /// Reader provides only the OS-active variant. The pipeline fills the
    /// inactive variant from the platform preset.
    #[cfg_attr(all(target_os = "windows", not(feature = "windows")), allow(dead_code))]
    Single {
        /// The reader-provided variant (OS-active).
        mode: Box<ThemeMode>,
        /// Which color mode this variant represents.
        is_dark: bool,
    },
    /// Reader provides both light and dark variants (macOS).
    #[allow(dead_code)]
    Dual {
        /// The light variant from the reader.
        light: Box<ThemeMode>,
        /// The dark variant from the reader.
        dark: Box<ThemeMode>,
    },
}

impl ReaderOutput {
    /// Reconstruct a [`Theme`] from this reader output (for overlay replay
    /// and merge compatibility).
    pub(crate) fn to_theme(
        &self,
        name: &str,
        icon_set: Option<IconSet>,
        layout: &LayoutTheme,
    ) -> Theme {
        let (light, dark) = match self {
            ReaderOutput::Single { mode, is_dark } => {
                if *is_dark {
                    (None, Some(ThemeMode::clone(mode)))
                } else {
                    (Some(ThemeMode::clone(mode)), None)
                }
            }
            ReaderOutput::Dual { light, dark } => {
                (Some(ThemeMode::clone(light)), Some(ThemeMode::clone(dark)))
            }
        };
        Theme {
            name: std::borrow::Cow::Owned(name.to_string()),
            light,
            dark,
            layout: layout.clone(),
            icon_set,
            // Readers keep Theme-level icon_theme = None and rely on either
            // the preset's value (tier 2) or system detect (tier 3). Readers
            // that need to override per color mode use ThemeDefaults::icon_theme
            // on the variant (tier 1, e.g. the KDE reader for breeze/breeze-dark).
            icon_theme: None,
        }
    }
}

/// Data needed to replay the merge+resolve pipeline for overlay support.
///
/// Stores the original reader output and preset name so that
/// [`SystemTheme::with_overlay()`] can reconstruct pre-resolve variants
/// on demand instead of storing ~2KB of ThemeMode clones.
#[derive(Clone, Debug)]
pub(crate) struct OverlaySource {
    /// The reader's variant data for replay.
    pub(crate) reader_output: ReaderOutput,
    /// Theme name from reader.
    pub(crate) name: Cow<'static, str>,
    /// Shared icon_set from reader.
    pub(crate) icon_set: Option<IconSet>,
    /// Shared layout from reader.
    pub(crate) layout: LayoutTheme,
    /// The live preset name (e.g. "kde-breeze-live").
    pub(crate) preset_name: String,
    /// Resolution-time inputs captured at detection time. Replaces the
    /// old `font_dpi: Option<f32>` field; the context bundles
    /// `font_dpi` + `button_order` + detected `icon_theme` and is cloned
    /// into `with_overlay` replays so resolution is deterministic across
    /// overlay applications.
    pub(crate) context: crate::resolve::ResolutionContext,
}

/// Result of the OS-first pipeline. Holds both resolved variants.
///
/// Produced by [`SystemTheme::from_system()`] and [`SystemTheme::from_system_async()`].
/// Both light and dark are always populated: the OS-active variant
/// comes from the reader + preset + resolve, the inactive variant
/// comes from the preset + resolve.
#[derive(Clone, Debug)]
pub struct SystemTheme {
    /// Theme name (from reader or preset).
    ///
    /// # Ownership type
    ///
    /// This field uses `Cow<'static, str>`, not `Arc<str>`. The v0.5.7 API
    /// review recommended uniform `Arc<str>` across `name`, `icon_theme`,
    /// `ReaderOutput::name`, and `ResolvedFontSpec::family`. The audit in
    /// `docs/archive/v0.5.7_gaps.md` §G9 concluded that the
    /// uniform recommendation should be adopted ONLY for
    /// [`ResolvedFontSpec::family`](crate::model::font::ResolvedFontSpec)
    /// (where 26 widgets × connectors genuinely share font families), and
    /// should be REVERSED for `name` / `icon_theme` because:
    ///
    /// - Each resolved theme carries exactly ONE `name` — no dedup benefit.
    /// - Bundled preset names are `&'static str` literals; `Cow::Borrowed(static_lit)`
    ///   is zero allocation, zero refcount. `Arc<str>` would require at least one
    ///   allocation per unique string at construction time, paying allocation cost
    ///   for a dedup benefit that is structurally absent.
    ///
    /// The same reasoning applies symmetrically to
    /// [`SystemTheme::icon_theme`](Self::icon_theme),
    /// [`Theme::name`](crate::theme::Theme), and
    /// [`ThemeDefaults::icon_theme`](crate::model::defaults::ThemeDefaults).
    ///
    /// See `docs/archive/v0.5.7_gaps.md` §G9 for the full audit.
    pub name: Cow<'static, str>,
    /// The OS color mode preference (light or dark).
    pub mode: ColorMode,
    /// Resolved light variant (always populated).
    pub light: ResolvedTheme,
    /// Resolved dark variant (always populated).
    pub dark: ResolvedTheme,
    /// Data for replaying the pipeline on overlay (replaces light_variant/dark_variant).
    pub(crate) overlay_source: OverlaySource,
    /// The platform preset used (e.g., "kde-breeze", "adwaita", "macos-sonoma").
    pub preset: String,
    /// The live preset name used internally (e.g., "kde-breeze-live").
    pub(crate) live_preset: String,
    /// Which icon loading mechanism to use for this theme.
    pub icon_set: IconSet,
    /// The name of the visual icon theme (e.g. `"breeze"`, `"Adwaita"`):
    /// the active variant's, else the theme's, else the detected system
    /// icon theme. `None` where the theme states none and detection fails;
    /// [`system_icon_theme()`](crate::theme::system_icon_theme) gives the
    /// reason.
    ///
    /// # Ownership type
    ///
    /// `Cow<'static, str>` is used here per the same principled deviation
    /// documented on [`SystemTheme::name`](Self::name) — see `docs/archive/v0.5.7_gaps.md`
    /// §G9. Each resolved theme carries a single icon-theme name (KDE has
    /// exactly two across light/dark variants — `"breeze"` / `"breeze-dark"`;
    /// other platforms have one), so the `Arc<str>` dedup benefit does not apply.
    pub icon_theme: Option<Cow<'static, str>>,
    /// Each variant's icon theme, resolved by the same three tiers as
    /// [`icon_theme`](Self::icon_theme), kept by variant rather than relative
    /// to [`mode`](Self::mode), a public field a caller may change. Read
    /// through [`icon_theme_for`](Self::icon_theme_for).
    pub(crate) light_icon_theme: Option<Cow<'static, str>>,
    /// The dark variant's counterpart of [`light_icon_theme`](Self::light_icon_theme).
    pub(crate) dark_icon_theme: Option<Cow<'static, str>>,
    /// Layout spacing shared by both variants: the platform reader's values
    /// merged field-wise over the preset's, the same precedence the pipeline
    /// uses for colours. `None` in a field means neither the platform nor the
    /// preset specifies it (platform-facts §2.20); nothing is invented.
    pub layout: LayoutTheme,
    /// OS-detected accessibility preferences (shared across variants).
    pub accessibility: AccessibilityPreferences,
}

impl SystemTheme {
    /// Pick a resolved variant by color mode.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use native_theme::theme::ColorMode;
    ///
    /// let sys = native_theme::SystemTheme::from_system()?;
    /// let dark = sys.pick(ColorMode::Dark);
    /// let active = sys.pick(sys.mode);
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    #[must_use]
    pub fn pick(&self, mode: ColorMode) -> &ResolvedTheme {
        match mode {
            ColorMode::Light => &self.light,
            ColorMode::Dark => &self.dark,
        }
    }

    /// The icon-theme name for one colour mode, resolved for that mode's
    /// variant by the same three tiers as [`icon_theme`](Self::icon_theme)
    /// (its `defaults.icon_theme`, then the theme's, then the detected system
    /// theme); for the mode the theme was built in it equals `icon_theme` as
    /// built. KDE names one theme per variant (`breeze`, `breeze-dark`); a
    /// toolkit that keeps a style per colour scheme needs both. `None` where
    /// that variant states none and detection failed; nothing is invented.
    #[must_use]
    pub fn icon_theme_for(&self, mode: ColorMode) -> Option<&str> {
        match mode {
            ColorMode::Light => self.light_icon_theme.as_deref(),
            ColorMode::Dark => self.dark_icon_theme.as_deref(),
        }
    }

    /// Apply an app-level TOML overlay and re-resolve.
    ///
    /// Merges the overlay onto the pre-resolve [`ThemeMode`] (not the
    /// already-resolved [`ResolvedTheme`]) so that changed source fields
    /// propagate correctly through `resolve()`. For example, changing
    /// `defaults.accent_color` in the overlay will cause `button.primary_background`,
    /// `checkbox.checked_background`, `slider.fill`, etc. to be re-derived from
    /// the new accent color.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let system = native_theme::SystemTheme::from_system()?;
    /// let overlay = native_theme::theme::Theme::from_toml(r##"
    ///     [light.defaults]
    ///     accent_color = "#ff6600"
    ///     [dark.defaults]
    ///     accent_color = "#ff6600"
    /// "##)?;
    /// let customized = system.with_overlay(&overlay)?;
    /// // customized.pick(customized.mode).defaults.accent_color is now #ff6600
    /// // and all accent-derived fields are updated
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    pub fn with_overlay(&self, overlay: &Theme) -> crate::Result<Self> {
        // Reconstruct pre-resolve variants from overlay_source
        let src = &self.overlay_source;
        let live_preset = Theme::preset(&src.preset_name)?;
        let full_preset_name = src
            .preset_name
            .strip_suffix("-live")
            .unwrap_or(&src.preset_name);
        let full_preset = Theme::preset(full_preset_name)?;

        // Reconstruct a Theme from the type-safe ReaderOutput for merge
        let reader_as_theme = src
            .reader_output
            .to_theme(&src.name, src.icon_set, &src.layout);

        let mut merged = full_preset.clone();
        merged.merge(&live_preset);
        merged.merge(&reader_as_theme);

        // Shared across variants; read before the variants are moved out of `merged`.
        let layout = merged.layout.clone();

        // Match on ReaderOutput for type-safe variant selection
        let (mut light, mut dark) = match &src.reader_output {
            ReaderOutput::Single { is_dark, .. } => {
                if *is_dark {
                    (
                        full_preset.light.unwrap_or_default(),
                        merged.dark.unwrap_or_default(),
                    )
                } else {
                    (
                        merged.light.unwrap_or_default(),
                        full_preset.dark.unwrap_or_default(),
                    )
                }
            }
            ReaderOutput::Dual { .. } => (
                merged.light.unwrap_or_default(),
                merged.dark.unwrap_or_default(),
            ),
        };

        // Apply the user overlay on top
        if let Some(over) = &overlay.light {
            light.merge(over);
        }
        if let Some(over) = &overlay.dark {
            dark.merge(over);
        }

        // Re-resolve both variants using the captured context (avoids
        // re-detecting DPI / button_order / icon_theme on replay).
        let resolved_light = light.into_resolved(&src.context)?;
        let resolved_dark = dark.into_resolved(&src.context)?;

        Ok(SystemTheme {
            name: self.name.clone(),
            mode: self.mode,
            light: resolved_light,
            dark: resolved_dark,
            overlay_source: self.overlay_source.clone(),
            live_preset: self.live_preset.clone(),
            preset: self.preset.clone(),
            icon_set: self.icon_set,
            icon_theme: self.icon_theme.clone(),
            light_icon_theme: self.light_icon_theme.clone(),
            dark_icon_theme: self.dark_icon_theme.clone(),
            layout,
            accessibility: self.accessibility.clone(),
        })
    }

    /// Load the OS theme synchronously.
    ///
    /// Detects the platform and desktop environment, reads the current theme
    /// settings, merges with a platform preset, and returns a fully resolved
    /// [`SystemTheme`] with both light and dark variants.
    ///
    /// The return value goes through the full pipeline: reader output ->
    /// resolve -> validate -> [`SystemTheme`] with both light and dark
    /// [`ResolvedTheme`] variants.
    ///
    /// # Platform Behavior
    ///
    /// - **macOS:** with the `macos` feature, reads both light and dark
    ///   variants via NSAppearance and merges them with the `macos-sonoma`
    ///   preset.
    /// - **Linux:** Uses `pollster::block_on` to drive the async inner
    ///   implementation, which handles portal D-Bus calls when the `portal`
    ///   feature is enabled. Without a reader for the detected desktop
    ///   (feature disabled, or a desktop with no reader), returns the
    ///   `adwaita` preset resolved in the detected light/dark mode.
    /// - **Windows:** with the `windows` feature, reads the active variant and
    ///   merges it with the `windows-11` preset.
    /// - **Other platforms:** Returns `Error::PlatformUnsupported`.
    ///
    /// # Errors
    ///
    /// - `Error::FeatureDisabled` on macOS or Windows when the `macos` /
    ///   `windows` feature is not enabled.
    /// - `Error::PlatformUnsupported` if the platform has no reader at all.
    /// - `Error::ReaderFailed` if the platform reader cannot access theme data.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let sys = native_theme::SystemTheme::from_system()?;
    /// let theme = sys.pick(sys.mode);
    /// // Icon set and theme are on SystemTheme, shared across variants
    /// let _icon_set = sys.icon_set;
    /// let _icon_theme = &sys.icon_theme;
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    #[cfg(target_os = "linux")]
    pub fn from_system() -> crate::Result<Self> {
        pollster::block_on(pipeline::from_system_inner())
    }

    /// Load the OS theme synchronously (non-Linux).
    ///
    /// On macOS and Windows the async inner has zero `.await` points, so a
    /// noop-waker single-poll is sufficient -- no async runtime needed.
    #[cfg(not(target_os = "linux"))]
    pub fn from_system() -> crate::Result<Self> {
        let waker = std::task::Waker::noop();
        let mut cx = std::task::Context::from_waker(&waker);
        let mut fut = std::pin::pin!(pipeline::from_system_inner());
        match fut.as_mut().poll(&mut cx) {
            std::task::Poll::Ready(result) => result,
            std::task::Poll::Pending => Err(crate::Error::PlatformUnsupported {
                platform: "unexpected async suspension",
            }),
        }
    }

    /// Async version of [`from_system()`](Self::from_system).
    ///
    /// On Linux, this enables portal D-Bus calls (e.g. GNOME settings portal,
    /// KDE portal backend detection) via `.await`. On macOS and Windows, the
    /// future completes immediately -- no actual async operations occur.
    ///
    /// Returns a [`SystemTheme`] with both resolved light and dark variants,
    /// same as [`from_system()`](Self::from_system).
    pub async fn from_system_async() -> crate::Result<Self> {
        pipeline::from_system_inner().await
    }
}

// =============================================================================
// Tests -- SystemTheme public API (active, pick, platform_preset_name)
// =============================================================================

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::field_reassign_with_default
)]
mod system_theme_tests {
    use super::*;

    // --- SystemTheme::active() / pick() tests ---

    #[test]
    fn test_system_theme_pick_dark_mode() {
        let preset = Theme::preset("catppuccin-mocha").unwrap();
        let mut light_v = preset.light.clone().unwrap();
        let mut dark_v = preset.dark.clone().unwrap();
        // Give them distinct accents so we can tell them apart
        // (test fixture values -- not production hardcoded colors)
        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
        light_v.resolve_all();
        dark_v.resolve_all();
        let light_resolved = light_v.validate().unwrap();
        let dark_resolved = dark_v.validate().unwrap();

        let st = SystemTheme {
            name: "test".into(),
            mode: ColorMode::Dark,
            light: light_resolved.clone(),
            dark: dark_resolved.clone(),
            overlay_source: OverlaySource {
                reader_output: ReaderOutput::Dual {
                    light: Box::new(ThemeMode::default()),
                    dark: Box::new(ThemeMode::default()),
                },
                name: Cow::Borrowed(""),
                icon_set: None,
                layout: LayoutTheme::default(),
                preset_name: "catppuccin-mocha".into(),
                context: crate::resolve::ResolutionContext::for_tests(),
            },
            live_preset: "catppuccin-mocha".into(),
            preset: "catppuccin-mocha".into(),
            icon_set: IconSet::Lucide,
            icon_theme: Some("lucide".into()),
            light_icon_theme: None,
            dark_icon_theme: Some("lucide".into()),
            layout: LayoutTheme::default(),
            accessibility: AccessibilityPreferences::default(),
        };
        assert_eq!(
            st.pick(st.mode).defaults.accent_color,
            dark_resolved.defaults.accent_color
        );
    }

    #[test]
    fn test_system_theme_pick_light_mode() {
        let preset = Theme::preset("catppuccin-mocha").unwrap();
        let mut light_v = preset.light.clone().unwrap();
        let mut dark_v = preset.dark.clone().unwrap();
        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
        light_v.resolve_all();
        dark_v.resolve_all();
        let light_resolved = light_v.validate().unwrap();
        let dark_resolved = dark_v.validate().unwrap();

        let st = SystemTheme {
            name: "test".into(),
            mode: ColorMode::Light,
            light: light_resolved.clone(),
            dark: dark_resolved.clone(),
            overlay_source: OverlaySource {
                reader_output: ReaderOutput::Dual {
                    light: Box::new(ThemeMode::default()),
                    dark: Box::new(ThemeMode::default()),
                },
                name: Cow::Borrowed(""),
                icon_set: None,
                layout: LayoutTheme::default(),
                preset_name: "catppuccin-mocha".into(),
                context: crate::resolve::ResolutionContext::for_tests(),
            },
            live_preset: "catppuccin-mocha".into(),
            preset: "catppuccin-mocha".into(),
            icon_set: IconSet::Lucide,
            icon_theme: Some("lucide".into()),
            light_icon_theme: Some("lucide".into()),
            dark_icon_theme: None,
            layout: LayoutTheme::default(),
            accessibility: AccessibilityPreferences::default(),
        };
        assert_eq!(
            st.pick(st.mode).defaults.accent_color,
            light_resolved.defaults.accent_color
        );
    }

    #[test]
    fn test_system_theme_pick_explicit() {
        let preset = Theme::preset("catppuccin-mocha").unwrap();
        let mut light_v = preset.light.clone().unwrap();
        let mut dark_v = preset.dark.clone().unwrap();
        light_v.defaults.accent_color = Some(Rgba::rgb(0, 0, 255));
        dark_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
        light_v.resolve_all();
        dark_v.resolve_all();
        let light_resolved = light_v.validate().unwrap();
        let dark_resolved = dark_v.validate().unwrap();

        let st = SystemTheme {
            name: "test".into(),
            mode: ColorMode::Light,
            light: light_resolved.clone(),
            dark: dark_resolved.clone(),
            overlay_source: OverlaySource {
                reader_output: ReaderOutput::Dual {
                    light: Box::new(ThemeMode::default()),
                    dark: Box::new(ThemeMode::default()),
                },
                name: Cow::Borrowed(""),
                icon_set: None,
                layout: LayoutTheme::default(),
                preset_name: "catppuccin-mocha".into(),
                context: crate::resolve::ResolutionContext::for_tests(),
            },
            live_preset: "catppuccin-mocha".into(),
            preset: "catppuccin-mocha".into(),
            icon_set: IconSet::Lucide,
            icon_theme: Some("lucide".into()),
            light_icon_theme: Some("lucide".into()),
            dark_icon_theme: None,
            layout: LayoutTheme::default(),
            accessibility: AccessibilityPreferences::default(),
        };
        assert_eq!(
            st.pick(ColorMode::Dark).defaults.accent_color,
            dark_resolved.defaults.accent_color
        );
        assert_eq!(
            st.pick(ColorMode::Light).defaults.accent_color,
            light_resolved.defaults.accent_color
        );
    }

    // --- platform_preset_name() pure tests ---
    // Tests the same logic path (parse_linux_desktop -> linux_preset_for_de) without env var mocking.

    /// Prove that the sync `from_system()` API works without any async runtime.
    /// On Linux with KDE feature: exercises pollster::block_on(from_system_inner()).
    /// This acts as a compile-time and runtime gate that the sync path works.
    #[test]
    #[cfg(target_os = "linux")]
    #[cfg(feature = "kde")]
    fn sync_consumer_no_async_runtime() {
        // Call the actual from_system() entry point.
        // This exercises the pollster::block_on(pipeline::from_system_inner()) path.
        // We don't assert Ok because the test environment may lack KDE config files,
        // but the call must not panic and must return a Result (not hang or deadlock).
        let _result = SystemTheme::from_system();
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_platform_preset_name_kde() {
        let preset = pipeline::linux_preset_for_de(detect::parse_linux_desktop("KDE"));
        assert_eq!(preset.name, "kde-breeze");
        assert!(preset.is_live);
        assert_eq!(preset.live_name(), "kde-breeze-live");
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_platform_preset_name_gnome() {
        let preset = pipeline::linux_preset_for_de(detect::parse_linux_desktop("GNOME"));
        assert_eq!(preset.name, "adwaita");
        assert!(preset.is_live);
        assert_eq!(preset.live_name(), "adwaita-live");
    }

    /// §11.2: `from_system()` is an extraction of the reader path, so it must
    /// agree with `SystemTheme::from_system()` wherever both succeed, and it
    /// must never return a non-finite or non-positive text scale.
    #[test]
    fn accessibility_preferences_from_system_is_consistent_with_system_theme() {
        let prefs = AccessibilityPreferences::from_system();
        assert!(prefs.text_scaling_factor.is_finite());
        assert!(prefs.text_scaling_factor > 0.0);

        // CI has no desktop; only compare when the full pipeline also works.
        if let Ok(sys) = SystemTheme::from_system() {
            assert_eq!(
                prefs.text_scaling_factor,
                sys.accessibility.text_scaling_factor
            );
            assert_eq!(prefs.high_contrast, sys.accessibility.high_contrast);
            assert_eq!(
                prefs.reduce_transparency,
                sys.accessibility.reduce_transparency
            );
            // reduce_motion may additionally be true via detect::detect_reduced_motion().
            assert!(prefs.reduce_motion || !sys.accessibility.reduce_motion);
        }
    }
}

// =============================================================================
// Tests -- with_overlay
// =============================================================================

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod overlay_tests {
    use super::*;

    /// Helper: build a SystemTheme from a preset via pipeline::run_pipeline.
    /// Uses test-only Result handling (module has #[allow(clippy::unwrap_used)]).
    fn default_system_theme() -> crate::Result<SystemTheme> {
        let preset = Theme::preset("catppuccin-mocha")?;
        let reader = ReaderResult {
            output: ReaderOutput::Dual {
                light: Box::new(preset.light.clone().unwrap_or_default()),
                dark: Box::new(preset.dark.clone().unwrap_or_default()),
            },
            name: preset.name,
            icon_set: preset.icon_set,
            layout: preset.layout,
            font_dpi: None,
            accessibility: AccessibilityPreferences::default(),
        };
        pipeline::run_pipeline(reader, "catppuccin-mocha", ColorMode::Light)
    }

    #[test]
    fn test_overlay_accent_propagates() -> crate::Result<()> {
        let st = default_system_theme()?;
        let new_accent = Rgba::rgb(255, 0, 0);

        // Build overlay with accent on both light and dark
        let mut overlay = Theme::default();
        let mut light_v = ThemeMode::default();
        light_v.defaults.accent_color = Some(new_accent);
        let mut dark_v = ThemeMode::default();
        dark_v.defaults.accent_color = Some(new_accent);
        overlay.light = Some(light_v);
        overlay.dark = Some(dark_v);

        let result = st.with_overlay(&overlay)?;

        // Accent itself
        assert_eq!(result.light.defaults.accent_color, new_accent);
        // Accent-derived widget fields
        assert_eq!(result.light.button.primary_background, new_accent);
        assert_eq!(result.light.checkbox.checked_background, new_accent);
        assert_eq!(result.light.slider.fill_color, new_accent);
        assert_eq!(result.light.progress_bar.fill_color, new_accent);
        assert_eq!(result.light.switch.checked_background, new_accent);
        // Additional accent-derived fields re-resolved via safety nets
        assert_eq!(
            result.light.spinner.fill_color, new_accent,
            "spinner.fill should re-derive from new accent"
        );
        Ok(())
    }

    #[test]
    fn test_overlay_preserves_unrelated_fields() -> crate::Result<()> {
        let st = default_system_theme()?;
        let original_bg = st.light.defaults.background_color;

        // Apply overlay changing only accent
        let mut overlay = Theme::default();
        let mut light_v = ThemeMode::default();
        light_v.defaults.accent_color = Some(Rgba::rgb(255, 0, 0));
        overlay.light = Some(light_v);

        let result = st.with_overlay(&overlay)?;
        assert_eq!(
            result.light.defaults.background_color, original_bg,
            "background should be unchanged"
        );
        Ok(())
    }

    #[test]
    fn test_overlay_empty_noop() -> crate::Result<()> {
        let st = default_system_theme()?;
        let original_light_accent = st.light.defaults.accent_color;
        let original_dark_accent = st.dark.defaults.accent_color;
        let original_light_bg = st.light.defaults.background_color;

        // Empty overlay
        let overlay = Theme::default();
        let result = st.with_overlay(&overlay)?;

        assert_eq!(result.light.defaults.accent_color, original_light_accent);
        assert_eq!(result.dark.defaults.accent_color, original_dark_accent);
        assert_eq!(result.light.defaults.background_color, original_light_bg);
        Ok(())
    }

    #[test]
    fn test_overlay_both_variants() -> crate::Result<()> {
        let st = default_system_theme()?;
        let red = Rgba::rgb(255, 0, 0);
        let green = Rgba::rgb(0, 255, 0);

        let mut overlay = Theme::default();
        let mut light_v = ThemeMode::default();
        light_v.defaults.accent_color = Some(red);
        let mut dark_v = ThemeMode::default();
        dark_v.defaults.accent_color = Some(green);
        overlay.light = Some(light_v);
        overlay.dark = Some(dark_v);

        let result = st.with_overlay(&overlay)?;
        assert_eq!(
            result.light.defaults.accent_color, red,
            "light accent = red"
        );
        assert_eq!(
            result.dark.defaults.accent_color, green,
            "dark accent = green"
        );
        Ok(())
    }

    #[test]
    fn test_overlay_font_family() -> crate::Result<()> {
        let st = default_system_theme()?;

        let mut overlay = Theme::default();
        let mut light_v = ThemeMode::default();
        light_v.defaults.font.family = Some("Comic Sans".into());
        overlay.light = Some(light_v);

        let result = st.with_overlay(&overlay)?;
        assert_eq!(result.light.defaults.font.family.as_ref(), "Comic Sans");
        Ok(())
    }

    #[test]
    fn test_overlay_roundtrip_via_overlay_source() -> crate::Result<()> {
        let st = default_system_theme()?;
        // Apply overlay and verify accent propagates
        let new_accent = Rgba::rgb(255, 0, 0);
        let mut overlay = Theme::default();
        let mut light_v = ThemeMode::default();
        light_v.defaults.accent_color = Some(new_accent);
        overlay.light = Some(light_v);

        let result = st.with_overlay(&overlay)?;
        assert_eq!(result.light.defaults.accent_color, new_accent);
        // The dark variant should be unchanged from original
        assert_eq!(
            result.dark.defaults.accent_color,
            st.dark.defaults.accent_color
        );
        Ok(())
    }

    #[test]
    fn test_overlay_source_no_variant_fields() -> crate::Result<()> {
        // Verify overlay_source exists on SystemTheme (compile-time structural check).
        // If light_variant or dark_variant fields still existed, this test would
        // need updating -- documenting the structural change.
        let st = default_system_theme()?;
        let _ = &st.overlay_source; // overlay_source exists
        Ok(())
    }
}