Skip to main content

native_theme/
pipeline.rs

1//! Theme pipeline: reader -> preset merge -> resolve -> validate.
2
3use std::fmt;
4
5#[cfg(target_os = "linux")]
6use crate::detect::{LinuxDesktop, parse_linux_desktop};
7
8#[cfg(any(target_os = "linux", test))]
9use crate::ReaderOutput;
10use crate::model::Theme;
11use crate::{OverlaySource, ReaderResult, SystemTheme};
12
13/// Run the OS-first pipeline: merge reader output onto a platform
14/// preset, resolve both light and dark variants, validate.
15///
16/// Accepts a [`ReaderResult`] containing the reader's variant data
17/// and metadata (name, icon_set, layout, font_dpi, accessibility).
18///
19/// `ReaderOutput::Single` readers provide one variant; the pipeline
20/// fills the other from the full platform preset. `ReaderOutput::Dual`
21/// readers provide both; the pipeline uses both after merging. Both kinds
22/// report which variant is OS-active through `is_dark`, which decides `mode`.
23pub(crate) fn run_pipeline(reader: ReaderResult, preset_name: &str) -> crate::Result<SystemTheme> {
24    let mode = reader.output.mode();
25    let ReaderResult {
26        output: reader_output,
27        name: reader_name,
28        icon_set: reader_icon_set,
29        layout: reader_layout,
30        font_dpi,
31        accessibility,
32    } = reader;
33
34    // Build ONE resolution-time context for this theme-build. The reader
35    // may have supplied its font_dpi (each platform reader does: 96 on Linux and
36    // Windows, 72 on macOS); when it does, the context takes it.
37    // button_order + icon_theme are platform-detected as from_system()'s.
38    let context = match font_dpi {
39        Some(dpi) => crate::resolve::ResolutionContext::with_font_dpi(
40            dpi,
41            crate::detect::system_icon_theme(),
42        ),
43        None => crate::resolve::ResolutionContext::from_system(),
44    };
45
46    let source = OverlaySource {
47        reader_output,
48        name: reader_name,
49        icon_set: reader_icon_set,
50        layout: reader_layout,
51        preset_name: preset_name.to_string(),
52        context,
53        overlay: None,
54    };
55    replay(source, mode, accessibility)
56}
57
58/// Merge and resolve what `source` holds: the platform preset provides the
59/// defaults, the reader output live OS data on top, the app's overlays (if
60/// any) their changes over both. Shared by [`run_pipeline`] and
61/// [`SystemTheme::with_overlay`], which replays its source with one more
62/// overlay.
63pub(crate) fn replay(
64    source: OverlaySource,
65    mode: crate::ColorMode,
66    accessibility: crate::AccessibilityPreferences,
67) -> crate::Result<SystemTheme> {
68    // A `Single` reader states no inactive variant, so the merge keeps the
69    // preset's own there; a `Dual` reader's two variants go over the preset's.
70    let mut merged = Theme::preset(&source.preset_name)?;
71    merged.merge(
72        &source
73            .reader_output
74            .to_theme(&source.name, source.icon_set, &source.layout),
75    );
76    if let Some(overlay) = &source.overlay {
77        merged.merge(overlay);
78    }
79
80    // Keep reader name if non-empty, else use preset name
81    let name = if source.name.is_empty() {
82        merged.name.clone()
83    } else {
84        source.name.clone()
85    };
86
87    // Resolve icon_set from Theme level (shared across variants)
88    let icon_set = merged
89        .icon_set
90        .unwrap_or_else(crate::detect::system_icon_set);
91
92    // Resolve icon_theme with three-tier precedence (per §G4 / doc 1 §20 Option C):
93    //   Tier 1: per-variant override (`ThemeMode::defaults.icon_theme`)
94    //   Tier 2: shared Theme-level value (`Theme::icon_theme`)
95    //   Tier 3: runtime system detect (from `context.icon_theme`)
96    // Must read before variants are consumed by unwrap_or_default().
97    // None where no tier names a theme: the TOML states none and detection
98    // failed (`context.icon_theme` is then None). No theme stands in for it.
99    // Both variants are resolved, kept by variant (`SystemTheme::icon_theme_for`);
100    // `icon_theme` is the active mode's copy.
101    let icon_theme_of =
102        |variant: &Option<crate::model::ThemeMode>| -> Option<std::borrow::Cow<'static, str>> {
103            variant
104                .as_ref()
105                .and_then(|v| v.defaults.icon_theme.clone()) // tier 1: per-variant override
106                .or_else(|| merged.icon_theme.clone()) // tier 2: Theme-level shared
107                .or_else(|| source.context.icon_theme.clone()) // tier 3: pre-detected system
108        };
109    let light_icon_theme = icon_theme_of(&merged.light);
110    let dark_icon_theme = icon_theme_of(&merged.dark);
111    let icon_theme = match mode {
112        crate::ColorMode::Light => light_icon_theme.clone(),
113        crate::ColorMode::Dark => dark_icon_theme.clone(),
114    };
115
116    // Shared across variants.
117    crate::resolve::validate_helpers::check_font_dpi(source.context.font_dpi)?;
118    crate::resolve::validate_helpers::check_layout(&merged.layout)?;
119
120    let light = merged
121        .light
122        .unwrap_or_default()
123        .into_resolved(&source.context)
124        .map_err(|e| e.in_variant(crate::ColorMode::Light))?;
125    let dark = merged
126        .dark
127        .unwrap_or_default()
128        .into_resolved(&source.context)
129        .map_err(|e| e.in_variant(crate::ColorMode::Dark))?;
130
131    Ok(SystemTheme {
132        name,
133        mode,
134        light,
135        dark,
136        preset: source.preset_name.clone(),
137        overlay_source: source,
138        version_match: None,
139        icon_set,
140        icon_theme,
141        light_icon_theme,
142        dark_icon_theme,
143        layout: merged.layout,
144        accessibility,
145    })
146}
147
148// =============================================================================
149// Structured return types
150// =============================================================================
151
152/// A single diagnostic observation about platform theme support.
153///
154/// Returned by [`diagnose_platform_support()`]. Each variant represents
155/// a specific category of diagnostic information. Use `Display` to get
156/// a human-readable string, or pattern-match for programmatic inspection.
157///
158/// For simple tabular output, use the [`name()`](Self::name),
159/// [`status()`](Self::status), and [`detail()`](Self::detail) accessors:
160///
161/// ```
162/// let diagnostics = native_theme::pipeline::diagnose_platform_support();
163/// for entry in &diagnostics {
164///     print!("{}: {}", entry.name(), entry.status());
165///     if let Some(detail) = entry.detail() {
166///         print!(" ({})", detail);
167///     }
168///     println!();
169/// }
170/// ```
171#[derive(Clone, Debug, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum DiagnosticEntry {
174    /// Platform identification (e.g. "Linux", "macOS", "Windows").
175    Platform(&'static str),
176    /// Detected desktop environment (Linux only).
177    #[cfg(target_os = "linux")]
178    DesktopEnv(crate::detect::LinuxDesktop),
179    /// An environment variable was read successfully.
180    EnvVar {
181        /// Variable name (e.g. `"XDG_CURRENT_DESKTOP"`).
182        name: &'static str,
183        /// Variable value as read from the environment.
184        value: String,
185    },
186    /// An environment variable was missing or empty.
187    EnvVarMissing(&'static str),
188    /// An external tool was found and operational.
189    ToolAvailable {
190        /// Tool binary name (e.g. `"gsettings"`).
191        name: &'static str,
192        /// Version string reported by the tool.
193        version: String,
194    },
195    /// An external tool was found but returned an error.
196    ToolError(&'static str),
197    /// An external tool was not found on PATH.
198    ToolMissing {
199        /// Tool binary name.
200        name: &'static str,
201        /// Human-readable description of what is lost.
202        impact: &'static str,
203    },
204    /// A config file was found at the given path.
205    ConfigFound {
206        /// Logical config name (e.g. `"KDE kdeglobals"`).
207        name: &'static str,
208        /// Filesystem path where the file was found.
209        path: std::path::PathBuf,
210    },
211    /// A config file was not found at the expected path.
212    ConfigMissing {
213        /// Logical config name.
214        name: &'static str,
215        /// Filesystem path that was checked.
216        path: std::path::PathBuf,
217    },
218    /// A cargo feature is enabled.
219    FeatureEnabled(&'static str),
220    /// A cargo feature is disabled.
221    FeatureDisabled {
222        /// Feature name (e.g. `"KDE"`, `"Portal"`).
223        feature: &'static str,
224        /// Human-readable description of what is lost.
225        impact: &'static str,
226    },
227    /// The running OS version and the preset of its generation (macOS and
228    /// Windows, with their reader feature).
229    OsGeneration {
230        /// The running OS version: macOS `major.minor.patch`, Windows `10.0.build`.
231        version: String,
232        /// The preset of that version's generation.
233        preset: &'static str,
234        /// How the version relates to the preset's generation.
235        version_match: VersionMatch,
236    },
237}
238
239impl DiagnosticEntry {
240    /// A short label identifying what is being diagnosed.
241    ///
242    /// Examples: `"Platform"`, `"XDG_CURRENT_DESKTOP"`, `"gsettings"`,
243    /// `"KDE kdeglobals"`, `"Portal support"`.
244    #[must_use]
245    pub fn name(&self) -> &str {
246        match self {
247            Self::Platform(_) => "Platform",
248            #[cfg(target_os = "linux")]
249            Self::DesktopEnv(_) => "Detected DE",
250            Self::EnvVar { name, .. } | Self::EnvVarMissing(name) => name,
251            Self::ToolAvailable { name, .. }
252            | Self::ToolError(name)
253            | Self::ToolMissing { name, .. } => name,
254            Self::ConfigFound { name, .. } | Self::ConfigMissing { name, .. } => name,
255            Self::FeatureEnabled(feature) | Self::FeatureDisabled { feature, .. } => feature,
256            Self::OsGeneration { .. } => "OS version",
257        }
258    }
259
260    /// A short status string: the detected value or a state like
261    /// `"not set"`, `"available"`, `"found"`, `"enabled"`, etc.
262    #[must_use]
263    pub fn status(&self) -> &str {
264        match self {
265            Self::Platform(p) => p,
266            #[cfg(target_os = "linux")]
267            Self::DesktopEnv(_) => "detected",
268            Self::EnvVar { value, .. } => value.as_str(),
269            Self::EnvVarMissing(_) => "not set",
270            Self::ToolAvailable { .. } => "available",
271            Self::ToolError(_) => "found but returned error",
272            Self::ToolMissing { .. } => "not found",
273            Self::ConfigFound { .. } => "found",
274            Self::ConfigMissing { .. } => "not found",
275            Self::FeatureEnabled(_) => "enabled",
276            Self::FeatureDisabled { .. } => "disabled",
277            Self::OsGeneration { version, .. } => version.as_str(),
278        }
279    }
280
281    /// Optional extra detail (version string, file path, impact note, DE variant).
282    #[must_use]
283    pub fn detail(&self) -> Option<String> {
284        match self {
285            #[cfg(target_os = "linux")]
286            Self::DesktopEnv(de) => Some(format!("{de:?}")),
287            Self::ToolAvailable { version, .. } => Some(version.clone()),
288            Self::ToolMissing { impact, .. } => Some((*impact).to_string()),
289            Self::FeatureDisabled { impact, .. } => Some((*impact).to_string()),
290            Self::ConfigFound { path, .. } | Self::ConfigMissing { path, .. } => {
291                Some(path.display().to_string())
292            }
293            Self::OsGeneration {
294                preset,
295                version_match,
296                ..
297            } => Some(format!("{preset}, {version_match}")),
298            _ => None,
299        }
300    }
301}
302
303impl fmt::Display for DiagnosticEntry {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        match self {
306            Self::Platform(p) => write!(f, "Platform: {p}"),
307            #[cfg(target_os = "linux")]
308            Self::DesktopEnv(de) => write!(f, "Detected DE: {de:?}"),
309            Self::EnvVar { name, value } => write!(f, "{name}: {value}"),
310            Self::EnvVarMissing(name) => write!(f, "{name}: not set"),
311            Self::ToolAvailable { name, version } => {
312                write!(f, "{name}: available ({version})")
313            }
314            Self::ToolError(name) => write!(f, "{name}: found but returned error"),
315            Self::ToolMissing { name, impact } => write!(f, "{name}: not found ({impact})"),
316            Self::ConfigFound { name, path } => {
317                write!(f, "{name}: found at {}", path.display())
318            }
319            Self::ConfigMissing { name, path } => {
320                write!(f, "{name}: not found at {}", path.display())
321            }
322            Self::FeatureEnabled(feature) => write!(f, "{feature} support: enabled"),
323            Self::FeatureDisabled { feature, impact } => {
324                write!(f, "{feature} support: disabled ({impact})")
325            }
326            Self::OsGeneration {
327                version,
328                preset,
329                version_match,
330            } => write!(f, "OS version: {version} ({preset}, {version_match})"),
331        }
332    }
333}
334
335/// Structured information about the platform's default preset.
336///
337/// Returned by [`platform_preset_name()`]. The `name` field is the
338/// user-facing preset name (e.g. `"macos-monterey"`), the preset the OS-first
339/// pipeline merges the platform reader's output over.
340///
341/// `Display` returns the user-facing name.
342#[derive(Clone, Debug, PartialEq, Eq)]
343pub struct PlatformPreset {
344    /// User-facing preset name (e.g. "kde-breeze", "adwaita", "macos-monterey").
345    pub name: &'static str,
346}
347
348impl fmt::Display for PlatformPreset {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        f.write_str(self.name)
351    }
352}
353
354// =============================================================================
355// OS generations (M1-T1-01)
356// =============================================================================
357
358/// How the running OS version relates to the generation of the preset the
359/// pipeline merged the platform reader's output over
360/// ([`SystemTheme::version_match`](crate::SystemTheme::version_match)).
361#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
362#[non_exhaustive]
363pub enum VersionMatch {
364    /// The running version lies between the first version of the preset's
365    /// generation and the newest version its values were verified on.
366    Exact,
367    /// The running OS is newer than any version the preset was verified on:
368    /// the preset may carry an older look than the OS draws (macOS 27 under
369    /// `macos-tahoe`).
370    PresetOlder,
371    /// The running OS predates the preset's generation: the preset carries a
372    /// newer look than the OS draws (Windows 10 under `windows-11`).
373    PresetNewer,
374}
375
376impl VersionMatch {
377    /// A short label: `"exact"`, `"preset older than the OS"` or
378    /// `"preset newer than the OS"`.
379    #[must_use]
380    pub fn as_str(self) -> &'static str {
381        match self {
382            Self::Exact => "exact",
383            Self::PresetOlder => "preset older than the OS",
384            Self::PresetNewer => "preset newer than the OS",
385        }
386    }
387}
388
389impl fmt::Display for VersionMatch {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        f.write_str(self.as_str())
392    }
393}
394
395/// An OS version as the generation tables compare it: macOS
396/// `major.minor.patch`, Windows `10.0.build`.
397#[cfg_attr(
398    not(any(
399        all(target_os = "macos", feature = "macos"),
400        all(target_os = "windows", feature = "windows")
401    )),
402    allow(dead_code)
403)]
404#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
405pub(crate) struct OsVersion {
406    pub(crate) major: u32,
407    pub(crate) minor: u32,
408    pub(crate) build: u32,
409}
410
411impl OsVersion {
412    #[cfg_attr(
413        not(any(
414            all(target_os = "macos", feature = "macos"),
415            all(target_os = "windows", feature = "windows")
416        )),
417        allow(dead_code)
418    )]
419    pub(crate) const fn new(major: u32, minor: u32, build: u32) -> Self {
420        Self {
421            major,
422            minor,
423            build,
424        }
425    }
426}
427
428impl fmt::Display for OsVersion {
429    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430        write!(f, "{}.{}.{}", self.major, self.minor, self.build)
431    }
432}
433
434/// One visual generation of a platform: the preset that carries its look,
435/// the first OS version of that look, and the newest version its values were
436/// verified on.
437#[cfg_attr(
438    not(any(
439        all(target_os = "macos", feature = "macos"),
440        all(target_os = "windows", feature = "windows")
441    )),
442    allow(dead_code)
443)]
444#[derive(Clone, Copy, Debug, PartialEq, Eq)]
445pub(crate) struct Generation {
446    pub(crate) preset: &'static str,
447    pub(crate) first: OsVersion,
448    pub(crate) last_verified: OsVersion,
449}
450
451/// A platform's generations, oldest first; never empty, `oldest` being a field.
452#[cfg_attr(
453    not(any(
454        all(target_os = "macos", feature = "macos"),
455        all(target_os = "windows", feature = "windows")
456    )),
457    allow(dead_code)
458)]
459#[derive(Clone, Copy, Debug)]
460pub(crate) struct GenerationTable {
461    pub(crate) oldest: Generation,
462    /// The newer generations, in ascending order of `first`.
463    pub(crate) newer: &'static [Generation],
464    /// Every row's preset, oldest first: the names
465    /// [`SystemTheme::from_system_with_preset`](crate::SystemTheme::from_system_with_preset)
466    /// accepts on the platform.
467    pub(crate) keys: &'static [&'static str],
468}
469
470#[cfg_attr(
471    not(any(
472        all(target_os = "macos", feature = "macos"),
473        all(target_os = "windows", feature = "windows")
474    )),
475    allow(dead_code)
476)]
477impl GenerationTable {
478    /// The rows, oldest first.
479    fn rows(&self) -> impl Iterator<Item = Generation> + '_ {
480        std::iter::once(self.oldest).chain(self.newer.iter().copied())
481    }
482
483    /// The row whose preset is `preset`.
484    fn row(&self, preset: &str) -> Option<Generation> {
485        self.rows().find(|g| g.preset == preset)
486    }
487}
488
489/// macOS. `macos-monterey`: the look from macOS 12, whose AppKit release notes
490/// end the accent highlight of a clicked button (M2a Step 7, plan D8), verified
491/// on 14.8.9 and 15.7.9 by the OS probe; `macos-tahoe`: Liquid Glass from 26
492/// (M2a Step 1's version map), verified on 26.6.2 (`docs/evidence/os-probe/
493/// 2026-10-11-run-38129819806`). Apple's generations change at a major version,
494/// so [`macos_generation`] compares majors. macOS 27 refines Liquid Glass and
495/// gets no row until a preset is verified on it (plan D4): it maps to
496/// `macos-tahoe`, reported as [`VersionMatch::PresetOlder`].
497///
498/// Major version 16: early macOS 26 betas reported 16 to a binary built
499/// against the macOS 15 SDK ("When built against the 15 SDK or earlier, Tahoe
500/// returns 16 for compatibility with previous numbering and all existing
501/// apps", <https://eclecticlight.co/2025/06/13/is-tahoe-really-macos-26-or-16/>,
502/// 2025-06-13). From beta 3, `NSOperatingSystemVersion` reports 26 even for
503/// such a build (that page's comments, 2025-07-28); Apple Developer Forums
504/// thread 791906 reports the same for the `kern.osproductversion` sysctl
505/// (<https://developer.apple.com/forums/thread/791906>). No
506/// source covers what the released OS reports. If a major version 16 is ever
507/// read, this table gives `macos-monterey` with [`VersionMatch::PresetOlder`]
508/// (no OS probe verified 16), which `generation_tests` pins.
509#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
510pub(crate) const MACOS_GENERATIONS: GenerationTable = GenerationTable {
511    oldest: Generation {
512        preset: "macos-monterey",
513        first: OsVersion::new(12, 0, 0),
514        last_verified: OsVersion::new(15, 0, 0),
515    },
516    newer: &[Generation {
517        preset: "macos-tahoe",
518        first: OsVersion::new(26, 0, 0),
519        last_verified: OsVersion::new(26, 0, 0),
520    }],
521    keys: &["macos-monterey", "macos-tahoe"],
522};
523
524/// Windows. `windows-11`: the Fluent / WinUI 3 look from build 22000 (21H2;
525/// M2b Step 1's version map), verified on build 26200 (25H2, the OS probe's
526/// `windows-11-arm` image). Windows 10 has no preset of its own (M2b Step 7,
527/// plan D9: a documented limit): it gets `windows-11`, reported as
528/// [`VersionMatch::PresetNewer`].
529#[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
530pub(crate) const WINDOWS_GENERATIONS: GenerationTable = GenerationTable {
531    oldest: Generation {
532        preset: "windows-11",
533        first: OsVersion::new(10, 0, 22000),
534        last_verified: OsVersion::new(10, 0, 26200),
535    },
536    newer: &[],
537    keys: &["windows-11"],
538};
539
540/// How `running` relates to `row`'s generation.
541#[cfg_attr(
542    not(any(
543        all(target_os = "macos", feature = "macos"),
544        all(target_os = "windows", feature = "windows")
545    )),
546    allow(dead_code)
547)]
548pub(crate) fn version_match(row: &Generation, running: OsVersion) -> VersionMatch {
549    if running < row.first {
550        VersionMatch::PresetNewer
551    } else if running > row.last_verified {
552        VersionMatch::PresetOlder
553    } else {
554        VersionMatch::Exact
555    }
556}
557
558/// The generation of `running` in `table`: the newest row whose first version
559/// is not newer than `running`, or the oldest row where `running` predates
560/// them all; with how `running` relates to it.
561#[cfg_attr(
562    not(any(
563        all(target_os = "macos", feature = "macos"),
564        all(target_os = "windows", feature = "windows")
565    )),
566    allow(dead_code)
567)]
568pub(crate) fn preset_for_version(
569    table: &GenerationTable,
570    running: OsVersion,
571) -> (PlatformPreset, VersionMatch) {
572    let row = table
573        .newer
574        .iter()
575        .rev()
576        .find(|g| g.first <= running)
577        .copied()
578        .unwrap_or(table.oldest);
579    (
580        PlatformPreset { name: row.preset },
581        version_match(&row, running),
582    )
583}
584
585/// `running` reduced to its major version, the macOS table's granularity.
586#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
587pub(crate) fn macos_major(running: OsVersion) -> OsVersion {
588    OsVersion::new(running.major, 0, 0)
589}
590
591/// The macOS generation of a running macOS version, by its major version.
592#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
593pub(crate) fn macos_generation(running: OsVersion) -> (PlatformPreset, VersionMatch) {
594    preset_for_version(&MACOS_GENERATIONS, macos_major(running))
595}
596
597/// The Windows generation of a running Windows build.
598#[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
599pub(crate) fn windows_generation(running: OsVersion) -> (PlatformPreset, VersionMatch) {
600    preset_for_version(&WINDOWS_GENERATIONS, running)
601}
602
603/// Map a Linux desktop environment to its matching platform preset.
604///
605/// [`select_reader`] and [`platform_preset_name()`] both map the refined
606/// desktop through it ([`crate::detect::refine_linux_desktop`]). For
607/// `Unknown`, [`select_reader`] first asks the portal backend (async D-Bus,
608/// with the `portal` feature) and uses its answer, KDE or GNOME, either way;
609/// only where no portal backend answers does it check for `kdeglobals`.
610/// [`platform_preset_name()`] cannot ask the portal: it takes the desktop a
611/// system read refined, and before one only the `kdeglobals` check, so with
612/// the `kde` and `portal` features the two can differ until then, in both
613/// directions where a portal backend answers: a KDE backend without
614/// `kdeglobals` gives `kde-breeze` in `from_system` and `adwaita` in
615/// [`platform_preset_name()`], a GNOME backend with `kdeglobals` gives
616/// `adwaita` in `from_system` and `kde-breeze` in [`platform_preset_name()`].
617///
618/// - KDE -> `PlatformPreset { name: "kde-breeze" }`
619/// - All others (GNOME, XFCE, Cinnamon, MATE, LXQt, Budgie, Unknown)
620///   -> `PlatformPreset { name: "adwaita" }`
621#[cfg(target_os = "linux")]
622pub(crate) fn linux_preset_for_de(de: LinuxDesktop) -> PlatformPreset {
623    match de {
624        LinuxDesktop::Kde => PlatformPreset { name: "kde-breeze" },
625        _ => PlatformPreset { name: "adwaita" },
626    }
627}
628
629/// Map the current platform to its matching platform preset.
630///
631/// The preset is the merge base in the OS-first pipeline: the platform
632/// reader's output is merged over it.
633///
634/// - macOS -> the running version's generation: `macos-monterey` on 12 to 15,
635///   `macos-tahoe` on 26 and later; `macos-monterey` without the `macos`
636///   feature, which reads the version
637/// - Windows -> `PlatformPreset { name: "windows-11" }`, the one Windows generation
638/// - Linux KDE -> `PlatformPreset { name: "kde-breeze" }`; an unrecognised
639///   desktop with a `kdeglobals` file counts as KDE (with the `kde` feature)
640/// - Linux other/GNOME -> `PlatformPreset { name: "adwaita" }`
641/// - Unknown platform -> `PlatformPreset { name: "adwaita" }`
642///
643/// On an unrecognised Linux desktop `from_system` first asks the portal
644/// backend over D-Bus (with the `portal` feature) and uses its answer, KDE
645/// or GNOME, either way; only where no portal backend answers does it check
646/// for `kdeglobals`. This synchronous function does not ask the portal: it
647/// takes the desktop the last system read (`from_system`, `from_system_async`,
648/// [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system))
649/// refined, until [`invalidate_caches()`](crate::detect::invalidate_caches);
650/// before one it runs only the `kdeglobals` check, so with the `kde` and
651/// `portal` features the two can then differ in both directions where a
652/// portal backend answers: a KDE backend without `kdeglobals` gives
653/// `kde-breeze` in `from_system` and `adwaita` here, a GNOME backend with
654/// `kdeglobals` gives `adwaita` in `from_system` and `kde-breeze` here.
655///
656/// Returns a [`PlatformPreset`] with the user-facing preset name. Showcase
657/// UIs use `preset.name` to build the "default (...)" label.
658///
659/// # Examples
660///
661/// ```
662/// let preset = native_theme::pipeline::platform_preset_name();
663/// println!("Platform preset: {}", preset.name);
664/// ```
665#[must_use]
666pub fn platform_preset_name() -> PlatformPreset {
667    #[cfg(all(target_os = "macos", feature = "macos"))]
668    {
669        macos_generation(crate::macos::os_version()).0
670    }
671    // Without the reader feature the version cannot be read: the oldest
672    // generation's preset.
673    #[cfg(all(target_os = "macos", not(feature = "macos")))]
674    {
675        PlatformPreset {
676            name: MACOS_GENERATIONS.oldest.preset,
677        }
678    }
679    #[cfg(all(target_os = "windows", feature = "windows"))]
680    {
681        windows_generation(crate::windows::os_version()).0
682    }
683    #[cfg(all(target_os = "windows", not(feature = "windows")))]
684    {
685        PlatformPreset {
686            name: WINDOWS_GENERATIONS.oldest.preset,
687        }
688    }
689    #[cfg(target_os = "linux")]
690    {
691        linux_preset_for_de(crate::detect::system().refined_linux_desktop_sync())
692    }
693    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
694    {
695        PlatformPreset { name: "adwaita" }
696    }
697}
698
699/// Check whether OS theme detection is available on this platform.
700///
701/// Returns a list of [`DiagnosticEntry`] values describing what detection
702/// capabilities are available and what might be missing. Useful for
703/// debugging theme detection failures in end-user applications.
704///
705/// Each entry can be printed directly via its `Display` impl, or
706/// inspected programmatically via [`DiagnosticEntry::name()`],
707/// [`DiagnosticEntry::status()`], and [`DiagnosticEntry::detail()`].
708///
709/// # Platform Behavior
710///
711/// - **Linux:** Reports detected desktop environment, `gsettings`
712///   availability, `XDG_CURRENT_DESKTOP` value, and KDE config file
713///   presence (when the `kde` feature is enabled).
714/// - **macOS:** Reports whether the `macos` feature is enabled and, with it,
715///   the running version and its generation's preset
716///   ([`DiagnosticEntry::OsGeneration`]).
717/// - **Windows:** Reports whether the `windows` feature is enabled and, with
718///   it, the running version and its generation's preset
719///   ([`DiagnosticEntry::OsGeneration`]).
720/// - **Other:** Reports that no platform detection is available.
721///
722/// # Examples
723///
724/// ```
725/// let diagnostics = native_theme::pipeline::diagnose_platform_support();
726/// for entry in &diagnostics {
727///     println!("{entry}");
728/// }
729/// ```
730#[must_use]
731pub fn diagnose_platform_support() -> Vec<DiagnosticEntry> {
732    let mut diagnostics = Vec::new();
733
734    #[cfg(target_os = "linux")]
735    {
736        diagnostics.push(DiagnosticEntry::Platform("Linux"));
737
738        // Check XDG_CURRENT_DESKTOP
739        match std::env::var("XDG_CURRENT_DESKTOP") {
740            Ok(val) if !val.is_empty() => {
741                let de = parse_linux_desktop(&val);
742                diagnostics.push(DiagnosticEntry::EnvVar {
743                    name: "XDG_CURRENT_DESKTOP",
744                    value: val,
745                });
746                diagnostics.push(DiagnosticEntry::DesktopEnv(de));
747            }
748            _ => {
749                diagnostics.push(DiagnosticEntry::EnvVarMissing("XDG_CURRENT_DESKTOP"));
750                diagnostics.push(DiagnosticEntry::DesktopEnv(LinuxDesktop::Unknown));
751            }
752        }
753
754        // Check gsettings availability
755        match crate::detect::run_with_timeout(
756            "gsettings",
757            &["--version"],
758            crate::detect::SUBPROCESS_TIMEOUT,
759        ) {
760            Ok(output) if output.status.success() => {
761                let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
762                diagnostics.push(DiagnosticEntry::ToolAvailable {
763                    name: "gsettings",
764                    version,
765                });
766            }
767            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
768                diagnostics.push(DiagnosticEntry::ToolMissing {
769                    name: "gsettings",
770                    impact: "dark mode and icon theme detection may be limited",
771                });
772            }
773            Ok(_) | Err(_) => {
774                diagnostics.push(DiagnosticEntry::ToolError("gsettings"));
775            }
776        }
777
778        // Check KDE config files
779        #[cfg(feature = "kde")]
780        {
781            match crate::kde::kdeglobals_path() {
782                Some(path) if path.exists() => {
783                    diagnostics.push(DiagnosticEntry::ConfigFound {
784                        name: "KDE kdeglobals",
785                        path,
786                    });
787                }
788                Some(path) => {
789                    diagnostics.push(DiagnosticEntry::ConfigMissing {
790                        name: "KDE kdeglobals",
791                        path,
792                    });
793                }
794                None => diagnostics.push(DiagnosticEntry::EnvVarMissing("HOME")),
795            }
796        }
797
798        #[cfg(not(feature = "kde"))]
799        {
800            diagnostics.push(DiagnosticEntry::FeatureDisabled {
801                feature: "KDE",
802                impact: "kde feature not enabled",
803            });
804        }
805
806        // Report portal feature status
807        #[cfg(feature = "portal")]
808        diagnostics.push(DiagnosticEntry::FeatureEnabled("Portal"));
809
810        #[cfg(not(feature = "portal"))]
811        diagnostics.push(DiagnosticEntry::FeatureDisabled {
812            feature: "Portal",
813            impact: "portal feature not enabled",
814        });
815    }
816
817    #[cfg(target_os = "macos")]
818    {
819        diagnostics.push(DiagnosticEntry::Platform("macOS"));
820
821        #[cfg(feature = "macos")]
822        {
823            diagnostics.push(DiagnosticEntry::FeatureEnabled("macOS theme detection"));
824            let running = crate::macos::os_version();
825            let (preset, version_match) = macos_generation(running);
826            diagnostics.push(DiagnosticEntry::OsGeneration {
827                version: running.to_string(),
828                preset: preset.name,
829                version_match,
830            });
831        }
832
833        #[cfg(not(feature = "macos"))]
834        diagnostics.push(DiagnosticEntry::FeatureDisabled {
835            feature: "macOS theme detection",
836            impact: "macos feature not enabled, using subprocess fallback",
837        });
838    }
839
840    #[cfg(target_os = "windows")]
841    {
842        diagnostics.push(DiagnosticEntry::Platform("Windows"));
843
844        #[cfg(feature = "windows")]
845        {
846            diagnostics.push(DiagnosticEntry::FeatureEnabled("Windows theme detection"));
847            let running = crate::windows::os_version();
848            let (preset, version_match) = windows_generation(running);
849            diagnostics.push(DiagnosticEntry::OsGeneration {
850                version: running.to_string(),
851                preset: preset.name,
852                version_match,
853            });
854        }
855
856        #[cfg(not(feature = "windows"))]
857        diagnostics.push(DiagnosticEntry::FeatureDisabled {
858            feature: "Windows theme detection",
859            impact: "windows feature not enabled",
860        });
861    }
862
863    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
864    {
865        diagnostics.push(DiagnosticEntry::Platform(
866            "unsupported (no native theme detection available)",
867        ));
868    }
869
870    diagnostics
871}
872
873/// Build a `ReaderResult` from a preset (for fallback paths where no
874/// platform reader is available).
875#[cfg(any(target_os = "linux", test))]
876fn preset_as_reader(preset_name: &str, mode: crate::ColorMode) -> crate::Result<ReaderResult> {
877    let theme = Theme::preset(preset_name)?;
878    let is_dark = mode == crate::ColorMode::Dark;
879    let output = if is_dark {
880        ReaderOutput::Single {
881            mode: Box::new(theme.dark.unwrap_or_default()),
882            is_dark: true,
883        }
884    } else {
885        ReaderOutput::Single {
886            mode: Box::new(theme.light.unwrap_or_default()),
887            is_dark: false,
888        }
889    };
890    Ok(ReaderResult {
891        output,
892        name: theme.name,
893        icon_set: theme.icon_set,
894        layout: theme.layout,
895        font_dpi: None,
896        accessibility: crate::AccessibilityPreferences::default(),
897    })
898}
899
900/// The platform reader [`select_reader`] picked, the preset its output merges
901/// over, and how the running OS version relates to that preset's generation.
902pub(crate) struct SelectedReader {
903    /// The platform reader.
904    pub(crate) reader: Box<dyn crate::reader::ThemeReader>,
905    /// The platform preset [`run_pipeline`] merges the reader's output over.
906    pub(crate) preset: &'static str,
907    /// `None` where the platform has no generation table (Linux).
908    pub(crate) version_match: Option<VersionMatch>,
909}
910
911impl SelectedReader {
912    /// A reader of a platform without a generation table (Linux).
913    #[cfg_attr(
914        not(all(target_os = "linux", any(feature = "kde", feature = "portal"))),
915        allow(dead_code)
916    )]
917    fn unversioned(reader: Box<dyn crate::reader::ThemeReader>, preset: &'static str) -> Self {
918        Self {
919            reader,
920            preset,
921            version_match: None,
922        }
923    }
924}
925
926/// Platform + DE + feature cascade that picks the appropriate
927/// [`crate::reader::ThemeReader`] impl for the current system.
928///
929/// Returns `None` when no reader is available and the caller must fall back
930/// to a preset-only pipeline (non-KDE/GNOME Linux, unsupported platforms, or
931/// platforms whose reader feature is disabled). When `Some`, the
932/// [`SelectedReader`] names the platform preset to pass to [`run_pipeline`] —
933/// the reader and the preset are tied because the preset is chosen from the
934/// detected DE on Linux and from the running version's generation on macOS
935/// and Windows ([`preset_for_version`]).
936///
937/// Per plan 94-03 §G8: the `Box<dyn ThemeReader>` trait object is object-safe
938/// only because the trait carries a `#[async_trait::async_trait]` annotation
939/// (see [`crate::reader`] module docs for the full rationale).
940#[allow(unreachable_code)]
941#[allow(clippy::unnecessary_wraps)] // Option is part of the public contract.
942#[allow(clippy::needless_return)] // Explicit returns clarify cfg-gated dispatch.
943pub(crate) async fn select_reader() -> Option<SelectedReader> {
944    #[cfg(target_os = "macos")]
945    {
946        #[cfg(feature = "macos")]
947        {
948            let (preset, matched) = macos_generation(crate::macos::os_version());
949            return Some(SelectedReader {
950                reader: Box::new(crate::macos::MacosReader),
951                preset: preset.name,
952                version_match: Some(matched),
953            });
954        }
955        #[cfg(not(feature = "macos"))]
956        return None;
957    }
958
959    #[cfg(target_os = "windows")]
960    {
961        #[cfg(feature = "windows")]
962        {
963            let (preset, matched) = windows_generation(crate::windows::os_version());
964            return Some(SelectedReader {
965                reader: Box::new(crate::windows::WindowsReader),
966                preset: preset.name,
967                version_match: Some(matched),
968            });
969        }
970        #[cfg(not(feature = "windows"))]
971        return None;
972    }
973
974    #[cfg(target_os = "linux")]
975    {
976        return linux_reader(crate::detect::system().refined_linux_desktop().await);
977    }
978
979    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
980    {
981        None
982    }
983}
984
985/// A Linux platform reader.
986#[cfg(target_os = "linux")]
987#[derive(Debug, Clone, Copy, PartialEq, Eq)]
988enum LinuxReader {
989    /// [`crate::kde::KdeReader`].
990    #[cfg(feature = "kde")]
991    Kde,
992    /// [`crate::gnome::GnomePortalKdeReader`]: the KDE reader with the
993    /// portal's accent colour.
994    #[cfg(all(feature = "kde", feature = "portal"))]
995    PortalKde,
996    /// [`crate::gnome::GnomeReader`].
997    #[cfg(feature = "portal")]
998    Gnome,
999}
1000
1001/// The reader of `refined`, the refined desktop
1002/// ([`crate::detect::refine_desktop`]) the watcher and the icon-theme
1003/// detection also decide by: KDE's, with the portal's accent colour where the
1004/// `portal` feature is on and `XDG_CURRENT_DESKTOP` or the portal backend
1005/// named KDE; GNOME's for GNOME and Budgie; `None` for the other desktops and
1006/// where the reader's feature is off. A KDE named by `kdeglobals` alone gets
1007/// the plain KDE reader: no portal backend answered, so an accent read would
1008/// ask a portal that is not KDE's, or wait out a second deadline.
1009#[cfg(target_os = "linux")]
1010fn linux_reader_kind(refined: crate::detect::RefinedDesktop) -> Option<LinuxReader> {
1011    match refined.desktop {
1012        #[cfg(all(feature = "kde", feature = "portal"))]
1013        LinuxDesktop::Kde if refined.by_kdeglobals => Some(LinuxReader::Kde),
1014        #[cfg(all(feature = "kde", feature = "portal"))]
1015        LinuxDesktop::Kde => Some(LinuxReader::PortalKde),
1016        #[cfg(all(feature = "kde", not(feature = "portal")))]
1017        LinuxDesktop::Kde => Some(LinuxReader::Kde),
1018        #[cfg(not(feature = "kde"))]
1019        LinuxDesktop::Kde => None,
1020        #[cfg(feature = "portal")]
1021        LinuxDesktop::Gnome | LinuxDesktop::Budgie => Some(LinuxReader::Gnome),
1022        #[cfg(not(feature = "portal"))]
1023        LinuxDesktop::Gnome | LinuxDesktop::Budgie => None,
1024        LinuxDesktop::Xfce
1025        | LinuxDesktop::Cinnamon
1026        | LinuxDesktop::Mate
1027        | LinuxDesktop::LxQt
1028        | LinuxDesktop::Hyprland
1029        | LinuxDesktop::Sway
1030        | LinuxDesktop::River
1031        | LinuxDesktop::Niri
1032        | LinuxDesktop::Wayfire
1033        | LinuxDesktop::CosmicDe
1034        | LinuxDesktop::Unknown => None,
1035    }
1036}
1037
1038/// [`linux_reader_kind`]'s reader, with the preset of `refined`'s desktop.
1039#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
1040fn linux_reader(refined: crate::detect::RefinedDesktop) -> Option<SelectedReader> {
1041    let reader: Box<dyn crate::reader::ThemeReader> = match linux_reader_kind(refined)? {
1042        #[cfg(feature = "kde")]
1043        LinuxReader::Kde => Box::new(crate::kde::KdeReader),
1044        #[cfg(all(feature = "kde", feature = "portal"))]
1045        LinuxReader::PortalKde => Box::new(crate::gnome::GnomePortalKdeReader),
1046        #[cfg(feature = "portal")]
1047        LinuxReader::Gnome => Box::new(crate::gnome::GnomeReader),
1048    };
1049    Some(SelectedReader::unversioned(
1050        reader,
1051        linux_preset_for_de(refined.desktop).name,
1052    ))
1053}
1054
1055/// [`linux_reader_kind`]'s reader: none without `kde` and `portal`, where
1056/// `LinuxReader` has no variant.
1057#[cfg(all(target_os = "linux", not(any(feature = "kde", feature = "portal"))))]
1058fn linux_reader(refined: crate::detect::RefinedDesktop) -> Option<SelectedReader> {
1059    match linux_reader_kind(refined)? {}
1060}
1061
1062/// Single async implementation for all platforms. On Linux this may contain
1063/// `.await` points (portal D-Bus calls); on macOS/Windows the future resolves
1064/// immediately (no `.await` points).
1065///
1066/// Called by:
1067/// - `from_system()` via `pollster::block_on`.
1068/// - `from_system_async()` via `.await`.
1069///
1070/// Delegates platform detection to [`select_reader`]: when a reader is
1071/// available, its output feeds [`run_pipeline`]; when no reader is available,
1072/// falls back to a preset-only pipeline or returns a feature/platform error.
1073#[allow(unreachable_code)]
1074#[allow(clippy::needless_return)] // Explicit returns clarify cfg-gated fallback.
1075pub(crate) async fn from_system_inner() -> crate::Result<SystemTheme> {
1076    if let Some(selected) = select_reader().await {
1077        let mut theme = read_through_pipeline(
1078            selected.reader.as_ref(),
1079            selected.preset,
1080            crate::detect::system(),
1081        )
1082        .await?;
1083        theme.version_match = selected.version_match;
1084        return Ok(theme);
1085    }
1086
1087    // Preset-only fallback paths — no reader available for this
1088    // platform+feature combination.
1089    #[cfg(target_os = "macos")]
1090    {
1091        return Err(crate::Error::FeatureDisabled {
1092            name: "macos",
1093            needed_for: "macOS theme detection",
1094        });
1095    }
1096    #[cfg(target_os = "windows")]
1097    {
1098        return Err(crate::Error::FeatureDisabled {
1099            name: "windows",
1100            needed_for: "Windows theme detection",
1101        });
1102    }
1103    #[cfg(target_os = "linux")]
1104    {
1105        return linux_fallback(
1106            platform_preset_name(),
1107            crate::detect::detect_is_dark(),
1108            readerless_accessibility(),
1109        );
1110    }
1111    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
1112    {
1113        Err(crate::Error::PlatformUnsupported {
1114            platform: std::env::consts::OS,
1115        })
1116    }
1117}
1118
1119/// The Linux theme where no reader is available: `preset` alone, as both
1120/// the reader's output and the base it merges over, in the mode `is_dark`
1121/// names, with `accessibility`. [`from_system_inner`] passes the uncached
1122/// [`crate::detect::detect_is_dark`], as the readers read the mode fresh, and
1123/// [`readerless_accessibility`], as [`reader_accessibility`] does.
1124#[cfg(target_os = "linux")]
1125fn linux_fallback(
1126    preset: PlatformPreset,
1127    is_dark: bool,
1128    accessibility: crate::AccessibilityPreferences,
1129) -> crate::Result<SystemTheme> {
1130    let mode = if is_dark {
1131        crate::ColorMode::Dark
1132    } else {
1133        crate::ColorMode::Light
1134    };
1135    let mut reader = preset_as_reader(preset.name, mode)?;
1136    reader.accessibility = accessibility;
1137    run_pipeline(reader, preset.name)
1138}
1139
1140/// Run `reader` and feed its output through [`run_pipeline`] onto `preset`.
1141/// The reader's accessibility block is stored in `detection`, so
1142/// [`crate::detect::accessibility_preferences`] need not run it again.
1143async fn read_through_pipeline(
1144    reader: &dyn crate::reader::ThemeReader,
1145    preset: &str,
1146    detection: &crate::detect::DetectionContext,
1147) -> crate::Result<SystemTheme> {
1148    let fill = detection.begin_reader_accessibility();
1149    let result = reader.read().await?;
1150    detection.store_reader_accessibility(fill, result.accessibility.clone());
1151    run_pipeline(result, preset)
1152}
1153
1154/// [`crate::SystemTheme::from_system_with_preset`]'s body: `preset` must be a
1155/// generation of the running platform's table (M1-T1-04).
1156#[allow(unreachable_code)]
1157#[allow(clippy::needless_return)]
1158// Explicit returns clarify cfg-gated dispatch.
1159// Without the reader feature the name is never read: the feature error comes first.
1160#[cfg_attr(
1161    any(
1162        all(target_os = "macos", not(feature = "macos")),
1163        all(target_os = "windows", not(feature = "windows"))
1164    ),
1165    allow(unused_variables)
1166)]
1167pub(crate) async fn from_system_with_preset_inner(preset: &str) -> crate::Result<SystemTheme> {
1168    #[cfg(all(target_os = "macos", feature = "macos"))]
1169    {
1170        return pinned_pipeline(
1171            &MACOS_GENERATIONS,
1172            macos_major(crate::macos::os_version()),
1173            preset,
1174            &crate::macos::MacosReader,
1175            crate::detect::system(),
1176        )
1177        .await;
1178    }
1179    #[cfg(all(target_os = "windows", feature = "windows"))]
1180    {
1181        return pinned_pipeline(
1182            &WINDOWS_GENERATIONS,
1183            crate::windows::os_version(),
1184            preset,
1185            &crate::windows::WindowsReader,
1186            crate::detect::system(),
1187        )
1188        .await;
1189    }
1190    #[cfg(all(target_os = "macos", not(feature = "macos")))]
1191    {
1192        return Err(crate::Error::FeatureDisabled {
1193            name: "macos",
1194            needed_for: "macOS theme detection",
1195        });
1196    }
1197    #[cfg(all(target_os = "windows", not(feature = "windows")))]
1198    {
1199        return Err(crate::Error::FeatureDisabled {
1200            name: "windows",
1201            needed_for: "Windows theme detection",
1202        });
1203    }
1204    // No generation table, so no OS generations to choose between: Linux,
1205    // whose readers read the installed style, BSD and other platforms.
1206    Err(crate::Error::UnknownPreset {
1207        name: preset.to_string(),
1208        known: &[],
1209    })
1210}
1211
1212/// Run `reader` through the pipeline onto `preset`, a row of `table`, and
1213/// report that row's generation against `running`.
1214#[cfg_attr(
1215    not(any(
1216        all(target_os = "macos", feature = "macos"),
1217        all(target_os = "windows", feature = "windows")
1218    )),
1219    allow(dead_code)
1220)]
1221async fn pinned_pipeline(
1222    table: &GenerationTable,
1223    running: OsVersion,
1224    preset: &str,
1225    reader: &dyn crate::reader::ThemeReader,
1226    detection: &crate::detect::DetectionContext,
1227) -> crate::Result<SystemTheme> {
1228    let Some(row) = table.row(preset) else {
1229        return Err(crate::Error::UnknownPreset {
1230            name: preset.to_string(),
1231            known: table.keys,
1232        });
1233    };
1234    let mut theme = read_through_pipeline(reader, row.preset, detection).await?;
1235    theme.version_match = Some(version_match(&row, running));
1236    Ok(theme)
1237}
1238
1239/// Runs the same platform reader `from_system_inner` would run and returns its
1240/// accessibility block without merging or resolving a theme. Where no reader
1241/// is available (or it fails) [`readerless_accessibility`] is used.
1242pub(crate) async fn reader_accessibility() -> crate::AccessibilityPreferences {
1243    match select_reader().await {
1244        Some(selected) => match selected.reader.read().await {
1245            Ok(result) => result.accessibility,
1246            Err(_) => readerless_accessibility(),
1247        },
1248        None => readerless_accessibility(),
1249    }
1250}
1251
1252/// The accessibility block where no reader supplies one: the defaults, with
1253/// `reduce_motion` the platform's reduced-motion read, the one the readers
1254/// make ([`crate::detect::detect_reduced_motion`]).
1255fn readerless_accessibility() -> crate::AccessibilityPreferences {
1256    crate::AccessibilityPreferences {
1257        reduce_motion: crate::detect::detect_reduced_motion(),
1258        ..Default::default()
1259    }
1260}
1261
1262// =============================================================================
1263// Tests
1264// =============================================================================
1265
1266#[cfg(all(test, target_os = "linux"))]
1267#[allow(clippy::unwrap_used, clippy::expect_used)]
1268mod dispatch_tests {
1269    use super::*;
1270
1271    // -- parse_linux_desktop() pure function tests --
1272
1273    #[test]
1274    fn detect_kde_simple() {
1275        assert_eq!(parse_linux_desktop("KDE"), LinuxDesktop::Kde);
1276    }
1277
1278    #[test]
1279    fn detect_kde_colon_separated_after() {
1280        assert_eq!(parse_linux_desktop("ubuntu:KDE"), LinuxDesktop::Kde);
1281    }
1282
1283    #[test]
1284    fn detect_kde_colon_separated_before() {
1285        assert_eq!(parse_linux_desktop("KDE:plasma"), LinuxDesktop::Kde);
1286    }
1287
1288    #[test]
1289    fn detect_gnome_simple() {
1290        assert_eq!(parse_linux_desktop("GNOME"), LinuxDesktop::Gnome);
1291    }
1292
1293    #[test]
1294    fn detect_gnome_ubuntu() {
1295        assert_eq!(parse_linux_desktop("ubuntu:GNOME"), LinuxDesktop::Gnome);
1296    }
1297
1298    #[test]
1299    fn detect_xfce() {
1300        assert_eq!(parse_linux_desktop("XFCE"), LinuxDesktop::Xfce);
1301    }
1302
1303    #[test]
1304    fn detect_cinnamon() {
1305        assert_eq!(parse_linux_desktop("X-Cinnamon"), LinuxDesktop::Cinnamon);
1306    }
1307
1308    #[test]
1309    fn detect_cinnamon_short() {
1310        assert_eq!(parse_linux_desktop("Cinnamon"), LinuxDesktop::Cinnamon);
1311    }
1312
1313    #[test]
1314    fn detect_mate() {
1315        assert_eq!(parse_linux_desktop("MATE"), LinuxDesktop::Mate);
1316    }
1317
1318    #[test]
1319    fn detect_lxqt() {
1320        assert_eq!(parse_linux_desktop("LXQt"), LinuxDesktop::LxQt);
1321    }
1322
1323    #[test]
1324    fn detect_budgie() {
1325        assert_eq!(parse_linux_desktop("Budgie:GNOME"), LinuxDesktop::Budgie);
1326    }
1327
1328    #[test]
1329    fn detect_empty_string() {
1330        assert_eq!(parse_linux_desktop(""), LinuxDesktop::Unknown);
1331    }
1332
1333    // -- Pure pipeline dispatch tests (no env var manipulation) --
1334
1335    #[test]
1336    fn from_linux_non_kde_returns_adwaita() -> crate::Result<()> {
1337        // GNOME desktop produces an Adwaita-named theme via the pure pipeline
1338        let preset = linux_preset_for_de(LinuxDesktop::Gnome);
1339        let result = preset_as_reader("adwaita", crate::ColorMode::Light)?;
1340        let theme = run_pipeline(result, preset.name)?;
1341        assert_eq!(theme.name, "Adwaita");
1342        Ok(())
1343    }
1344
1345    #[test]
1346    #[cfg(feature = "kde")]
1347    fn from_linux_unknown_de_with_kdeglobals_fallback() -> crate::Result<()> {
1348        // Unknown DE with a kdeglobals file uses KDE reader -- test the dispatch
1349        // branch by calling from_kde_content_pure directly with minimal fixture.
1350        const MINIMAL_KDE_FIXTURE: &str = "\
1351[General]
1352ColorScheme=TestTheme
1353
1354[Colors:Window]
1355BackgroundNormal=239,240,241
1356
1357[Colors:View]
1358BackgroundNormal=252,252,252
1359ForegroundNormal=35,38,41
1360DecorationFocus=61,174,233
1361BackgroundAlternate=239,240,241
1362ForegroundLink=41,128,185";
1363
1364        let (reader_theme, dpi, acc) =
1365            crate::kde::from_kde_content_pure(MINIMAL_KDE_FIXTURE, None)?;
1366        let is_dark = reader_theme.dark.is_some() && reader_theme.light.is_none();
1367        let output = if is_dark {
1368            ReaderOutput::Single {
1369                mode: Box::new(reader_theme.dark.unwrap_or_default()),
1370                is_dark: true,
1371            }
1372        } else {
1373            ReaderOutput::Single {
1374                mode: Box::new(reader_theme.light.unwrap_or_default()),
1375                is_dark: false,
1376            }
1377        };
1378        let result = ReaderResult {
1379            output,
1380            name: reader_theme.name,
1381            icon_set: reader_theme.icon_set,
1382            layout: reader_theme.layout,
1383            font_dpi: dpi,
1384            accessibility: acc,
1385        };
1386        let preset = linux_preset_for_de(LinuxDesktop::Kde);
1387        let theme = run_pipeline(result, preset.name)?;
1388        assert_eq!(
1389            theme.name, "TestTheme",
1390            "should use KDE theme name from reader output"
1391        );
1392        Ok(())
1393    }
1394
1395    #[test]
1396    fn from_linux_unknown_de_without_kdeglobals_returns_adwaita() -> crate::Result<()> {
1397        // Unknown DE without kdeglobals falls back to Adwaita preset
1398        let preset = linux_preset_for_de(LinuxDesktop::Unknown);
1399        let result = preset_as_reader("adwaita", crate::ColorMode::Light)?;
1400        let theme = run_pipeline(result, preset.name)?;
1401        assert_eq!(
1402            theme.name, "Adwaita",
1403            "should fall back to Adwaita without kdeglobals"
1404        );
1405        Ok(())
1406    }
1407
1408    /// The preset's own theme: both variants straight from the preset.
1409    fn preset_theme(preset: &str) -> SystemTheme {
1410        let theme = Theme::preset(preset).unwrap();
1411        let reader = ReaderResult {
1412            output: ReaderOutput::Dual {
1413                light: Box::new(theme.light.unwrap_or_default()),
1414                dark: Box::new(theme.dark.unwrap_or_default()),
1415                is_dark: false,
1416            },
1417            name: theme.name,
1418            icon_set: theme.icon_set,
1419            layout: theme.layout,
1420            font_dpi: None,
1421            accessibility: crate::AccessibilityPreferences::default(),
1422        };
1423        run_pipeline(reader, preset).unwrap()
1424    }
1425
1426    #[test]
1427    fn the_fallback_on_kde_is_the_whole_breeze_preset() {
1428        let expected = preset_theme("kde-breeze");
1429        for is_dark in [false, true] {
1430            let st = linux_fallback(
1431                linux_preset_for_de(LinuxDesktop::Kde),
1432                is_dark,
1433                crate::AccessibilityPreferences::default(),
1434            )
1435            .unwrap();
1436            assert_eq!(st.preset, "kde-breeze");
1437            assert_eq!(st.name, expected.name, "is_dark {is_dark}");
1438            assert_eq!(st.light, expected.light, "is_dark {is_dark}");
1439            assert_eq!(st.dark, expected.dark, "is_dark {is_dark}");
1440            assert_eq!(
1441                st.icon_theme_for(crate::ColorMode::Light),
1442                expected.icon_theme_for(crate::ColorMode::Light)
1443            );
1444            assert_eq!(
1445                st.icon_theme_for(crate::ColorMode::Dark),
1446                expected.icon_theme_for(crate::ColorMode::Dark)
1447            );
1448        }
1449    }
1450
1451    #[test]
1452    fn the_fallback_on_other_desktops_is_the_whole_adwaita_preset() {
1453        let expected = preset_theme("adwaita");
1454        let st = linux_fallback(
1455            linux_preset_for_de(LinuxDesktop::Xfce),
1456            true,
1457            crate::AccessibilityPreferences::default(),
1458        )
1459        .unwrap();
1460        assert_eq!(st.preset, "adwaita");
1461        assert_eq!(st.name, expected.name);
1462        assert_eq!(st.light, expected.light);
1463        assert_eq!(st.dark, expected.dark);
1464    }
1465
1466    #[test]
1467    fn the_fallback_mode_is_the_dark_reading_it_is_given() {
1468        let preset = || linux_preset_for_de(LinuxDesktop::Unknown);
1469        let none = crate::AccessibilityPreferences::default;
1470        assert_eq!(
1471            linux_fallback(preset(), true, none()).unwrap().mode,
1472            crate::ColorMode::Dark
1473        );
1474        assert_eq!(
1475            linux_fallback(preset(), false, none()).unwrap().mode,
1476            crate::ColorMode::Light
1477        );
1478    }
1479
1480    /// Without a reader the theme carries the accessibility block
1481    /// `AccessibilityPreferences::from_system` reads there
1482    /// (`readerless_accessibility`), so the two agree on reduced motion.
1483    #[test]
1484    fn the_fallback_carries_the_accessibility_it_is_given() {
1485        let reduced = crate::AccessibilityPreferences {
1486            reduce_motion: true,
1487            ..Default::default()
1488        };
1489        let st = linux_fallback(
1490            linux_preset_for_de(LinuxDesktop::Xfce),
1491            false,
1492            reduced.clone(),
1493        )
1494        .unwrap();
1495        assert_eq!(st.accessibility, reduced);
1496    }
1497
1498    #[test]
1499    fn an_unknown_desktop_with_kdeglobals_maps_to_breeze() {
1500        let preset = |de, exists| {
1501            linux_preset_for_de(crate::detect::refine_linux_desktop(de, None, || exists)).name
1502        };
1503        assert_eq!(preset(LinuxDesktop::Unknown, true), "kde-breeze");
1504        assert_eq!(preset(LinuxDesktop::Unknown, false), "adwaita");
1505        assert_eq!(preset(LinuxDesktop::Kde, false), "kde-breeze");
1506        assert_eq!(preset(LinuxDesktop::Gnome, true), "adwaita");
1507        assert_eq!(preset(LinuxDesktop::Xfce, true), "adwaita");
1508    }
1509
1510    /// The reader `linux_reader_kind` picks for an unrecognised desktop with
1511    /// `portal_backend` and, or without, `kdeglobals`.
1512    fn unknown_desktop_reader(
1513        portal_backend: Option<LinuxDesktop>,
1514        kdeglobals: bool,
1515    ) -> Option<LinuxReader> {
1516        linux_reader_kind(crate::detect::refine_desktop(
1517            LinuxDesktop::Unknown,
1518            portal_backend,
1519            || kdeglobals,
1520        ))
1521    }
1522
1523    /// A KDE portal backend gets the KDE reader with the portal's accent,
1524    /// `kdeglobals` or not, as `XDG_CURRENT_DESKTOP=KDE` does.
1525    #[test]
1526    #[cfg(all(feature = "kde", feature = "portal"))]
1527    fn an_unknown_desktop_with_a_kde_portal_gets_the_kde_reader() {
1528        for kdeglobals in [false, true] {
1529            assert_eq!(
1530                unknown_desktop_reader(Some(LinuxDesktop::Kde), kdeglobals),
1531                Some(LinuxReader::PortalKde)
1532            );
1533        }
1534        assert_eq!(
1535            linux_reader_kind(crate::detect::refine_desktop(
1536                LinuxDesktop::Kde,
1537                None,
1538                || false
1539            )),
1540            Some(LinuxReader::PortalKde)
1541        );
1542    }
1543
1544    /// A GNOME portal backend gets the GNOME reader, `kdeglobals` or not.
1545    #[test]
1546    #[cfg(feature = "portal")]
1547    fn an_unknown_desktop_with_a_gnome_portal_gets_the_gnome_reader() {
1548        for kdeglobals in [false, true] {
1549            assert_eq!(
1550                unknown_desktop_reader(Some(LinuxDesktop::Gnome), kdeglobals),
1551                Some(LinuxReader::Gnome)
1552            );
1553        }
1554    }
1555
1556    /// Without a portal answer, `kdeglobals` gets the plain KDE reader, with
1557    /// or without the `portal` feature; with neither there is no reader.
1558    #[test]
1559    fn an_unknown_desktop_without_a_portal_answer() {
1560        #[cfg(feature = "kde")]
1561        assert_eq!(unknown_desktop_reader(None, true), Some(LinuxReader::Kde));
1562        assert_eq!(unknown_desktop_reader(None, false), None);
1563    }
1564
1565    /// A KDE reader merges over kde-breeze, the GNOME reader over adwaita.
1566    #[test]
1567    #[cfg(all(feature = "kde", feature = "portal"))]
1568    fn the_linux_readers_presets() {
1569        let preset = |portal_backend, kdeglobals| {
1570            linux_reader(crate::detect::refine_desktop(
1571                LinuxDesktop::Unknown,
1572                portal_backend,
1573                || kdeglobals,
1574            ))
1575            .map(|selected| selected.preset)
1576        };
1577        assert_eq!(preset(Some(LinuxDesktop::Kde), false), Some("kde-breeze"));
1578        assert_eq!(preset(None, true), Some("kde-breeze"));
1579        assert_eq!(preset(Some(LinuxDesktop::Gnome), true), Some("adwaita"));
1580    }
1581
1582    // -- LNXDE-03: Hyprland, Sway, COSMIC, River, Niri map to their own variants --
1583
1584    #[test]
1585    fn detect_hyprland() {
1586        assert_eq!(parse_linux_desktop("Hyprland"), LinuxDesktop::Hyprland);
1587    }
1588
1589    #[test]
1590    fn detect_sway() {
1591        assert_eq!(parse_linux_desktop("sway"), LinuxDesktop::Sway);
1592    }
1593
1594    #[test]
1595    fn detect_cosmic() {
1596        assert_eq!(parse_linux_desktop("COSMIC"), LinuxDesktop::CosmicDe);
1597    }
1598
1599    #[test]
1600    fn detect_river() {
1601        assert_eq!(parse_linux_desktop("river"), LinuxDesktop::River);
1602    }
1603
1604    #[test]
1605    fn detect_niri() {
1606        assert_eq!(parse_linux_desktop("niri"), LinuxDesktop::Niri);
1607    }
1608
1609    #[test]
1610    fn parses_xdg_wayfire() {
1611        assert_eq!(parse_linux_desktop("Wayfire"), LinuxDesktop::Wayfire);
1612        assert_eq!(parse_linux_desktop("Wayfire:GNOME"), LinuxDesktop::Wayfire);
1613    }
1614
1615    #[test]
1616    fn parses_xdg_empty_is_unknown() {
1617        // Regression guard -- empty XDG_CURRENT_DESKTOP must keep mapping to Unknown
1618        // even after the Wayfire variant addition.
1619        assert_eq!(parse_linux_desktop(""), LinuxDesktop::Unknown);
1620    }
1621
1622    #[test]
1623    fn detect_cosmic_full_desktop() {
1624        assert_eq!(
1625            parse_linux_desktop("COSMIC:Freedesktop"),
1626            LinuxDesktop::CosmicDe
1627        );
1628    }
1629
1630    // -- Pure pipeline smoke test (replaces from_system env var test) --
1631
1632    #[test]
1633    fn from_system_returns_result() {
1634        // Test the pure pipeline directly instead of mocking env vars for from_system()
1635        let result = preset_as_reader("adwaita", crate::ColorMode::Light).unwrap();
1636        let theme = run_pipeline(result, "adwaita")
1637            .expect("run_pipeline should succeed with adwaita preset");
1638        assert_eq!(theme.name, "Adwaita");
1639    }
1640}
1641
1642/// Tests for run_pipeline() -- internal pipeline functions.
1643/// These test functions moved from system_theme_tests in lib.rs since they
1644/// directly test pipeline internals rather than the SystemTheme public API.
1645#[cfg(test)]
1646#[allow(
1647    clippy::unwrap_used,
1648    clippy::expect_used,
1649    clippy::field_reassign_with_default
1650)]
1651mod pipeline_tests {
1652    use crate::color::Rgba;
1653    use crate::model::{LayoutTheme, Theme, ThemeMode};
1654    use crate::{ReaderOutput, ReaderResult};
1655
1656    use super::{preset_as_reader, read_through_pipeline, run_pipeline};
1657
1658    /// Helper: build a ReaderResult from a preset for testing.
1659    fn reader_from_preset(preset_name: &str) -> ReaderResult {
1660        let preset = Theme::preset(preset_name).unwrap();
1661        ReaderResult {
1662            output: ReaderOutput::Dual {
1663                light: Box::new(preset.light.clone().unwrap_or_default()),
1664                dark: Box::new(preset.dark.clone().unwrap_or_default()),
1665                is_dark: false,
1666            },
1667            name: preset.name,
1668            icon_set: preset.icon_set,
1669            layout: preset.layout,
1670            font_dpi: None,
1671            accessibility: crate::AccessibilityPreferences::default(),
1672        }
1673    }
1674
1675    // --- run_pipeline() tests ---
1676
1677    /// The reader's font DPI goes into the context both variants share: one
1678    /// that is not finite and positive is one violation, on
1679    /// `context.font_dpi`, with no variant table.
1680    #[test]
1681    fn run_pipeline_rejects_a_bad_reader_font_dpi_once() {
1682        for font_dpi in [0.0, -1.0, f32::NAN] {
1683            let reader = ReaderResult {
1684                font_dpi: Some(font_dpi),
1685                ..reader_from_preset("kde-breeze")
1686            };
1687            let result = run_pipeline(reader, "kde-breeze");
1688            let Err(crate::Error::ResolutionInvalid { errors }) = result else {
1689                panic!("font_dpi {font_dpi}: expected ResolutionInvalid");
1690            };
1691            let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
1692            assert_eq!(paths, ["context.font_dpi"], "font_dpi {font_dpi}");
1693        }
1694    }
1695
1696    #[test]
1697    fn test_run_pipeline_produces_both_variants() {
1698        let reader = reader_from_preset("catppuccin-mocha");
1699        let result = run_pipeline(reader, "catppuccin-mocha");
1700        assert!(result.is_ok(), "run_pipeline should succeed");
1701        let st = result.unwrap();
1702        // Both light and dark exist as ResolvedTheme (non-Option)
1703        assert!(!st.name.is_empty(), "name should be populated");
1704        // If we get here, both variants validated successfully
1705    }
1706
1707    #[test]
1708    fn test_run_pipeline_reader_values_win() {
1709        // Create a reader output where the reader provides a custom accent
1710        // (simulating a platform reader that detected this accent from the OS)
1711        let custom_accent = Rgba::rgb(42, 100, 200);
1712        let mut variant = ThemeMode::default();
1713        variant.defaults.accent_color = Some(custom_accent);
1714
1715        let reader = ReaderResult {
1716            output: ReaderOutput::Single {
1717                mode: Box::new(variant),
1718                is_dark: false,
1719            },
1720            name: "CustomTheme".into(),
1721            icon_set: None,
1722            layout: LayoutTheme::default(),
1723            font_dpi: None,
1724            accessibility: crate::AccessibilityPreferences::default(),
1725        };
1726
1727        let result = run_pipeline(reader, "catppuccin-mocha");
1728        assert!(result.is_ok(), "run_pipeline should succeed");
1729        let st = result.unwrap();
1730        // The reader's accent should win over the preset's accent
1731        assert_eq!(
1732            st.light.defaults.accent_color, custom_accent,
1733            "reader accent should win over preset accent"
1734        );
1735        assert_eq!(st.name, "CustomTheme", "reader name should win");
1736    }
1737
1738    #[test]
1739    fn test_run_pipeline_single_variant() {
1740        // Simulate a real OS reader that provides a complete dark variant
1741        // (like KDE's from_kde() would) but no light variant.
1742        let full = Theme::preset("kde-breeze").unwrap();
1743        let mut dark_v = full.dark.clone().unwrap();
1744        // Override accent to prove reader values win (simulating OS-detected accent)
1745        dark_v.defaults.accent_color = Some(Rgba::rgb(200, 50, 50));
1746
1747        let reader = ReaderResult {
1748            output: ReaderOutput::Single {
1749                mode: Box::new(dark_v),
1750                is_dark: true,
1751            },
1752            name: std::borrow::Cow::Borrowed(""),
1753            icon_set: None,
1754            layout: LayoutTheme::default(),
1755            font_dpi: None,
1756            accessibility: crate::AccessibilityPreferences::default(),
1757        };
1758
1759        let result = run_pipeline(reader, "kde-breeze");
1760        assert!(
1761            result.is_ok(),
1762            "run_pipeline should succeed with single variant"
1763        );
1764        let st = result.unwrap();
1765        // Dark should have the reader's overridden accent
1766        assert_eq!(
1767            st.dark.defaults.accent_color,
1768            Rgba::rgb(200, 50, 50),
1769            "dark variant should have reader accent"
1770        );
1771        // Light should still exist (from full preset, which has colors)
1772        // If we get here, both variants validated successfully
1773        assert_eq!(st.preset, "kde-breeze");
1774    }
1775
1776    #[test]
1777    fn test_run_pipeline_inactive_variant_from_full_preset() {
1778        // When reader provides only dark, light must come from the full preset.
1779        let full = Theme::preset("kde-breeze").unwrap();
1780
1781        let reader = ReaderResult {
1782            output: ReaderOutput::Single {
1783                mode: Box::new(full.dark.clone().unwrap_or_default()),
1784                is_dark: true,
1785            },
1786            name: std::borrow::Cow::Borrowed(""),
1787            icon_set: None,
1788            layout: LayoutTheme::default(),
1789            font_dpi: None,
1790            accessibility: crate::AccessibilityPreferences::default(),
1791        };
1792
1793        let st = run_pipeline(reader, "kde-breeze").unwrap();
1794
1795        // The light variant should have colors from the full "kde-breeze" preset
1796        let full_light = full.light.unwrap();
1797        assert_eq!(
1798            st.light.defaults.accent_color,
1799            full_light.defaults.accent_color.unwrap(),
1800            "inactive light variant should get accent from full preset"
1801        );
1802        assert_eq!(
1803            st.light.defaults.background_color,
1804            full_light.defaults.background_color.unwrap(),
1805            "inactive light variant should get background from full preset"
1806        );
1807    }
1808
1809    // --- run_pipeline with preset-as-reader (GNOME double-merge test) ---
1810
1811    #[test]
1812    fn test_run_pipeline_with_preset_as_reader() {
1813        // Simulates GNOME sync fallback: adwaita used as both reader and preset.
1814        // Double-merge is harmless: merge is idempotent for matching values.
1815        let reader = reader_from_preset("adwaita");
1816        let result = run_pipeline(reader, "adwaita");
1817        assert!(
1818            result.is_ok(),
1819            "double-merge with same preset should succeed"
1820        );
1821        let st = result.unwrap();
1822        assert_eq!(st.name, "Adwaita");
1823    }
1824
1825    /// Overlays stack: a later `with_overlay` keeps what an earlier one
1826    /// stated (M3-10), and wins on a field both state.
1827    #[test]
1828    fn with_overlay_keeps_an_earlier_overlay() -> crate::Result<()> {
1829        let st = run_pipeline(reader_from_preset("adwaita"), "adwaita")?;
1830        let a = Theme::from_toml("[light.defaults]\naccent_color = \"#ff0000\"")?;
1831        let b = Theme::from_toml("[light.defaults]\nbackground_color = \"#00ff00\"")?;
1832        let both = st.with_overlay(&a)?.with_overlay(&b)?;
1833        assert_eq!(both.light.defaults.accent_color, Rgba::rgb(255, 0, 0));
1834        assert_eq!(both.light.defaults.background_color, Rgba::rgb(0, 255, 0));
1835
1836        let c = Theme::from_toml("[light.defaults]\naccent_color = \"#0000ff\"")?;
1837        let all = both.with_overlay(&c)?;
1838        assert_eq!(all.light.defaults.accent_color, Rgba::rgb(0, 0, 255));
1839        assert_eq!(all.light.defaults.background_color, Rgba::rgb(0, 255, 0));
1840        Ok(())
1841    }
1842
1843    // --- Single/Dual contract tests ---
1844
1845    #[test]
1846    fn test_single_variant_fills_inactive_from_preset() {
1847        // Simulate KDE-style single-variant reader: only dark variant provided.
1848        // The pipeline should fill light from the full preset.
1849        let full = Theme::preset("kde-breeze").unwrap();
1850        let dark_v = full.dark.clone().unwrap();
1851        let reader = ReaderResult {
1852            output: ReaderOutput::Single {
1853                mode: Box::new(dark_v),
1854                is_dark: true,
1855            },
1856            name: "Breeze Dark".into(),
1857            icon_set: full.icon_set,
1858            layout: full.layout.clone(),
1859            font_dpi: None,
1860            accessibility: crate::AccessibilityPreferences::default(),
1861        };
1862
1863        let st = run_pipeline(reader, "kde-breeze").unwrap();
1864
1865        // Dark variant should have reader's data (merged with preset).
1866        // Light variant should come from the full preset (kde-breeze).
1867        let full_light = Theme::preset("kde-breeze").unwrap().light.unwrap();
1868        assert_eq!(
1869            st.light.defaults.accent_color,
1870            full_light.defaults.accent_color.unwrap(),
1871            "Single: inactive light variant should come from full preset"
1872        );
1873        assert_eq!(st.mode, crate::ColorMode::Dark);
1874    }
1875
1876    #[test]
1877    fn test_dual_variant_uses_both_from_reader() {
1878        // Simulate macOS-style dual-variant reader: both variants provided.
1879        // The pipeline should use BOTH reader variants (merged with preset).
1880        let full = Theme::preset("macos-monterey").unwrap();
1881        let custom_light_accent = Rgba::rgb(42, 100, 200);
1882        let custom_dark_accent = Rgba::rgb(200, 50, 50);
1883
1884        let mut light_v = full.light.clone().unwrap();
1885        light_v.defaults.accent_color = Some(custom_light_accent);
1886        let mut dark_v = full.dark.clone().unwrap();
1887        dark_v.defaults.accent_color = Some(custom_dark_accent);
1888
1889        let reader = ReaderResult {
1890            output: ReaderOutput::Dual {
1891                light: Box::new(light_v),
1892                dark: Box::new(dark_v),
1893                is_dark: false,
1894            },
1895            name: "macOS Sonoma".into(),
1896            icon_set: full.icon_set,
1897            layout: full.layout.clone(),
1898            font_dpi: Some(72.0),
1899            accessibility: crate::AccessibilityPreferences::default(),
1900        };
1901
1902        let st = run_pipeline(reader, "macos-monterey").unwrap();
1903
1904        // Both variants should reflect the reader's custom accents (merged).
1905        assert_eq!(
1906            st.light.defaults.accent_color, custom_light_accent,
1907            "Dual: light variant should have reader's light accent"
1908        );
1909        assert_eq!(
1910            st.dark.defaults.accent_color, custom_dark_accent,
1911            "Dual: dark variant should have reader's dark accent"
1912        );
1913    }
1914
1915    /// A dual-variant reader in dark mode, standing in for the macOS reader
1916    /// on an OS set to dark: both variants from the preset, `is_dark` true.
1917    struct DarkDualReader;
1918
1919    #[async_trait::async_trait]
1920    impl crate::reader::ThemeReader for DarkDualReader {
1921        async fn read(&self) -> crate::Result<ReaderResult> {
1922            let mut reader = reader_from_preset("macos-monterey");
1923            if let ReaderOutput::Dual { is_dark, .. } = &mut reader.output {
1924                *is_dark = true;
1925            }
1926            Ok(reader)
1927        }
1928    }
1929
1930    #[test]
1931    fn dual_reader_mode_follows_is_dark() {
1932        let detection = crate::detect::DetectionContext::new();
1933        let st = pollster::block_on(read_through_pipeline(
1934            &DarkDualReader,
1935            "macos-monterey",
1936            &detection,
1937        ))
1938        .unwrap();
1939        assert_eq!(
1940            st.mode,
1941            crate::ColorMode::Dark,
1942            "a Dual reader reporting is_dark must give SystemTheme::mode Dark"
1943        );
1944    }
1945
1946    #[test]
1947    fn a_pinned_older_generation_reports_preset_older() {
1948        let detection = crate::detect::DetectionContext::new();
1949        let st = pollster::block_on(super::pinned_pipeline(
1950            &super::MACOS_GENERATIONS,
1951            super::OsVersion::new(26, 0, 0),
1952            "macos-monterey",
1953            &DarkDualReader,
1954            &detection,
1955        ))
1956        .unwrap();
1957        assert_eq!(st.preset, "macos-monterey");
1958        assert_eq!(st.version_match, Some(super::VersionMatch::PresetOlder));
1959        // with_overlay keeps the match (M1-T1-01 change 2)
1960        let overlaid = st
1961            .with_overlay(&Theme::from_toml("name = \"overlay\"").unwrap())
1962            .unwrap();
1963        assert_eq!(overlaid.version_match, st.version_match);
1964    }
1965
1966    #[test]
1967    fn a_pinned_name_outside_the_table_is_unknown() {
1968        let detection = crate::detect::DetectionContext::new();
1969        let result = pollster::block_on(super::pinned_pipeline(
1970            &super::MACOS_GENERATIONS,
1971            super::OsVersion::new(26, 0, 0),
1972            "kde-breeze",
1973            &DarkDualReader,
1974            &detection,
1975        ));
1976        assert!(matches!(
1977            result,
1978            Err(crate::Error::UnknownPreset { known, .. }) if known == super::MACOS_GENERATIONS.keys
1979        ));
1980    }
1981
1982    #[cfg(target_os = "linux")]
1983    #[test]
1984    fn linux_has_no_generation_to_pin() {
1985        let result = pollster::block_on(super::from_system_with_preset_inner("adwaita"));
1986        let err = result.err();
1987        assert!(matches!(
1988            err,
1989            Some(crate::Error::UnknownPreset { known: [], .. })
1990        ));
1991        assert!(
1992            err.is_some_and(|e| e
1993                .to_string()
1994                .contains("no OS generations to choose between")),
1995            "pinning a preset on Linux says the platform has no OS generations to choose between"
1996        );
1997    }
1998
1999    /// A reader reporting a text-scaling factor of 1.5, standing in for any
2000    /// platform reader.
2001    struct ScaledTextReader;
2002
2003    #[async_trait::async_trait]
2004    impl crate::reader::ThemeReader for ScaledTextReader {
2005        async fn read(&self) -> crate::Result<ReaderResult> {
2006            let mut reader = reader_from_preset("adwaita");
2007            reader.accessibility.text_scaling_factor = 1.5;
2008            Ok(reader)
2009        }
2010    }
2011
2012    #[test]
2013    fn the_system_read_fills_the_accessibility_cache() {
2014        let detection = crate::detect::DetectionContext::new();
2015        let st = pollster::block_on(read_through_pipeline(
2016            &ScaledTextReader,
2017            "adwaita",
2018            &detection,
2019        ))
2020        .unwrap();
2021        let runs = std::cell::Cell::new(0);
2022        let cached = detection.reader_accessibility_with(|| {
2023            runs.set(runs.get() + 1);
2024            crate::AccessibilityPreferences::default()
2025        });
2026        assert_eq!(runs.get(), 0, "the cache was empty after the system read");
2027        assert_eq!(cached, st.accessibility);
2028        assert_eq!(cached.text_scaling_factor, 1.5);
2029    }
2030
2031    /// [`ScaledTextReader`], with the accessibility cache invalidated while
2032    /// it reads, as a watcher does when the OS changes mid-read.
2033    struct InvalidatedReader<'a>(&'a crate::detect::DetectionContext);
2034
2035    #[async_trait::async_trait]
2036    impl crate::reader::ThemeReader for InvalidatedReader<'_> {
2037        async fn read(&self) -> crate::Result<ReaderResult> {
2038            self.0.invalidate_accessibility_preferences();
2039            ScaledTextReader.read().await
2040        }
2041    }
2042
2043    #[test]
2044    fn a_system_read_across_an_invalidation_leaves_the_cache_empty() {
2045        let detection = crate::detect::DetectionContext::new();
2046        pollster::block_on(read_through_pipeline(
2047            &InvalidatedReader(&detection),
2048            "adwaita",
2049            &detection,
2050        ))
2051        .unwrap();
2052        let runs = std::cell::Cell::new(0);
2053        let _ = detection.reader_accessibility_with(|| {
2054            runs.set(runs.get() + 1);
2055            crate::AccessibilityPreferences::default()
2056        });
2057        assert_eq!(
2058            runs.get(),
2059            1,
2060            "a block read before the invalidation was cached"
2061        );
2062    }
2063
2064    // --- Phase 93-04 G4: Theme.icon_theme + three-tier precedence ---
2065    //
2066    // Per docs/archive/v0.5.7_gaps.md §G4 and doc 1 §20 Option C:
2067    //   Tier 1 (highest): ThemeMode::defaults.icon_theme (per-variant override)
2068    //   Tier 2:           Theme::icon_theme (shared across variants)
2069    //   Tier 3 (fallback): system_icon_theme() (runtime detect), none where it fails
2070
2071    /// Helper: construct a ReaderResult that carries only the active variant
2072    /// (light) with no per-variant icon_theme. The pipeline must then consult
2073    /// the preset's Theme-level icon_theme (tier 2) or system detect (tier 3).
2074    fn reader_with_empty_variant(is_dark: bool) -> ReaderResult {
2075        ReaderResult {
2076            output: ReaderOutput::Single {
2077                mode: Box::new(ThemeMode::default()),
2078                is_dark,
2079            },
2080            name: std::borrow::Cow::Borrowed(""),
2081            icon_set: None,
2082            layout: LayoutTheme::default(),
2083            font_dpi: None,
2084            accessibility: crate::AccessibilityPreferences::default(),
2085        }
2086    }
2087
2088    #[test]
2089    fn icon_theme_tier2_theme_level_used_when_per_variant_none() {
2090        // Adwaita preset (after G4 migration) carries icon_theme = "Adwaita"
2091        // at the Theme level, and None on both variant defaults.
2092        // With a reader that provides an empty variant (no per-variant override),
2093        // the resolver must fall through to tier 2 and produce "Adwaita".
2094        let reader = reader_with_empty_variant(false);
2095        let st = run_pipeline(reader, "adwaita").unwrap();
2096        assert_eq!(
2097            st.icon_theme.as_deref(),
2098            Some("Adwaita"),
2099            "tier 2: Theme.icon_theme should be used when per-variant is None"
2100        );
2101    }
2102
2103    #[test]
2104    fn icon_theme_tier1_per_variant_wins_over_theme_level() {
2105        // Construct a reader whose active variant explicitly sets a per-variant
2106        // icon_theme override. Even with a preset that carries a Theme-level
2107        // icon_theme, the per-variant override must win.
2108        let mut variant = ThemeMode::default();
2109        variant.defaults.icon_theme = Some(std::borrow::Cow::Borrowed("custom-override"));
2110        let reader = ReaderResult {
2111            output: ReaderOutput::Single {
2112                mode: Box::new(variant),
2113                is_dark: false,
2114            },
2115            name: std::borrow::Cow::Borrowed(""),
2116            icon_set: None,
2117            layout: LayoutTheme::default(),
2118            font_dpi: None,
2119            accessibility: crate::AccessibilityPreferences::default(),
2120        };
2121        // Adwaita preset has Theme.icon_theme = "Adwaita" after migration.
2122        let st = run_pipeline(reader, "adwaita").unwrap();
2123        assert_eq!(
2124            st.icon_theme.as_deref(),
2125            Some("custom-override"),
2126            "tier 1: per-variant icon_theme override must win over Theme-level"
2127        );
2128    }
2129
2130    /// `with_overlay` replays the overlay through the same tiers and layout
2131    /// as `run_pipeline`: an icon theme or a layout gap the overlay states
2132    /// wins, and an overlay that states none keeps the base's.
2133    #[test]
2134    fn with_overlay_applies_the_overlays_icon_theme_and_layout() -> crate::Result<()> {
2135        let st = run_pipeline(reader_from_preset("adwaita"), "adwaita")?;
2136        let kept = st.with_overlay(&Theme::default())?;
2137        assert_eq!(kept.icon_theme, st.icon_theme);
2138        assert_eq!(kept.layout.widget_gap, st.layout.widget_gap);
2139
2140        let overlay =
2141            Theme::from_toml("icon_theme = \"custom-override\"\n[layout]\nwidget_gap_px = 9.0")?;
2142        let changed = st.with_overlay(&overlay)?;
2143        assert_eq!(changed.icon_theme.as_deref(), Some("custom-override"));
2144        assert_eq!(
2145            changed.icon_theme_for(crate::ColorMode::Dark),
2146            Some("custom-override")
2147        );
2148        assert_eq!(changed.layout.widget_gap, Some(9.0));
2149        Ok(())
2150    }
2151
2152    #[test]
2153    fn icon_theme_kde_per_variant_values_still_win() {
2154        // Regression guard for Phase 80-fix: KDE Breeze uses per-variant icon_theme
2155        // values ("breeze" light / "breeze-dark" dark) that MUST continue to win
2156        // over any Theme-level value. The kde-breeze preset keeps per-variant-only.
2157        let kde_full = Theme::preset("kde-breeze").unwrap();
2158        // Simulate KDE reader providing the dark variant with its per-variant value.
2159        let dark_v = kde_full.dark.clone().unwrap();
2160        assert_eq!(
2161            dark_v.defaults.icon_theme.as_deref(),
2162            Some("breeze-dark"),
2163            "precondition: kde-breeze dark variant must carry breeze-dark"
2164        );
2165        let reader = ReaderResult {
2166            output: ReaderOutput::Single {
2167                mode: Box::new(dark_v),
2168                is_dark: true,
2169            },
2170            name: std::borrow::Cow::Borrowed(""),
2171            icon_set: None,
2172            layout: LayoutTheme::default(),
2173            font_dpi: None,
2174            accessibility: crate::AccessibilityPreferences::default(),
2175        };
2176        let st = run_pipeline(reader, "kde-breeze").unwrap();
2177        assert_eq!(
2178            st.icon_theme.as_deref(),
2179            Some("breeze-dark"),
2180            "KDE per-variant icon_theme must still win (Phase 80-fix invariant)"
2181        );
2182    }
2183
2184    #[test]
2185    fn theme_icon_theme_round_trips_when_some() {
2186        // Serialize a Theme with icon_theme: Some(...) and assert the
2187        // deserialized round-trip preserves the value.
2188        let theme = Theme {
2189            name: std::borrow::Cow::Borrowed("RoundTrip"),
2190            light: Some(ThemeMode::default()),
2191            dark: None,
2192            layout: LayoutTheme::default(),
2193            icon_set: None,
2194            icon_theme: Some(std::borrow::Cow::Borrowed("lucide")),
2195        };
2196        let toml_str = theme.to_toml().expect("serialize");
2197        let reparsed = Theme::from_toml(&toml_str).expect("deserialize");
2198        assert_eq!(
2199            reparsed.icon_theme.as_deref(),
2200            Some("lucide"),
2201            "Theme.icon_theme must round-trip through TOML"
2202        );
2203        // Verify the serialized form contains the key at the top level.
2204        assert!(
2205            toml_str.contains("icon_theme = \"lucide\""),
2206            "serialized TOML should contain top-level icon_theme, got:\n{toml_str}"
2207        );
2208    }
2209
2210    #[test]
2211    fn theme_icon_theme_skipped_when_none() {
2212        // Serialize a Theme with icon_theme: None and assert the TOML does NOT
2213        // emit the key (skip_serializing_if = Option::is_none).
2214        let theme = Theme {
2215            name: std::borrow::Cow::Borrowed("NoIcon"),
2216            light: Some(ThemeMode::default()),
2217            dark: None,
2218            layout: LayoutTheme::default(),
2219            icon_set: None,
2220            icon_theme: None,
2221        };
2222        let toml_str = theme.to_toml().expect("serialize");
2223        assert!(
2224            !toml_str.contains("icon_theme"),
2225            "serialized TOML should NOT contain icon_theme when None, got:\n{toml_str}"
2226        );
2227    }
2228
2229    #[test]
2230    fn lint_toml_accepts_top_level_icon_theme() {
2231        // lint_toml() must NOT warn about icon_theme at the top level.
2232        // Raw string uses ##"..."## because the TOML body contains `"#` hex colors.
2233        let toml_str = r##"
2234name = "Test"
2235icon_theme = "lucide"
2236
2237[light.defaults]
2238accent_color = "#0066cc"
2239"##;
2240        let warnings = Theme::lint_toml(toml_str).expect("lint");
2241        assert!(
2242            !warnings.iter().any(|w| w.contains("icon_theme")),
2243            "lint_toml must not flag top-level icon_theme as unknown; warnings: {warnings:?}"
2244        );
2245    }
2246
2247    /// §11.1: `SystemTheme.layout` is the reader's layout merged field-wise over
2248    /// the preset's. On the preset-only path the reader *is* the full preset, so
2249    /// the result equals full ⊕ full.
2250    #[test]
2251    fn system_theme_layout_is_the_merged_preset_layout() -> crate::Result<()> {
2252        let reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
2253        let sys = run_pipeline(reader, "adwaita")?;
2254
2255        let mut expected = Theme::preset("adwaita")?.layout;
2256        expected.merge(&Theme::preset("adwaita")?.layout);
2257
2258        assert_eq!(sys.layout, expected);
2259        assert!(
2260            sys.layout.widget_gap.is_some(),
2261            "adwaita defines all four layout keys (spec §1.3)"
2262        );
2263        Ok(())
2264    }
2265
2266    /// A layout value out of range fails the build, in `run_pipeline` and in
2267    /// `with_overlay`. Layout is shared by both variants: the path has no
2268    /// variant table.
2269    #[test]
2270    fn system_theme_layout_out_of_range_is_invalid() -> crate::Result<()> {
2271        let mut reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
2272        reader.layout.widget_gap = Some(-8.0);
2273        let Err(crate::Error::ResolutionInvalid { errors }) = run_pipeline(reader, "adwaita")
2274        else {
2275            panic!("expected ResolutionInvalid");
2276        };
2277        let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
2278        assert_eq!(paths, ["layout.widget_gap_px"]);
2279
2280        let reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
2281        let mut sys = run_pipeline(reader, "adwaita")?;
2282        sys.overlay_source.layout.section_gap = Some(f32::NAN);
2283        let Err(crate::Error::ResolutionInvalid { errors }) = sys.with_overlay(&Theme::default())
2284        else {
2285            panic!("expected ResolutionInvalid");
2286        };
2287        let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
2288        assert_eq!(paths, ["layout.section_gap_px"]);
2289        Ok(())
2290    }
2291
2292    /// `SystemTheme::icon` and `icon_indicator` load a freedesktop icon from
2293    /// the asked mode's variant theme, not the active one's, and keep doing so
2294    /// when the public `mode` field is changed.
2295    #[test]
2296    fn icon_loads_from_the_modes_icon_theme() -> crate::Result<()> {
2297        let mut theme = run_pipeline(reader_from_preset("kde-breeze"), "kde-breeze")?;
2298        for active in [crate::ColorMode::Light, crate::ColorMode::Dark] {
2299            theme.mode = active;
2300            for (mode, expected) in [
2301                (crate::ColorMode::Light, "breeze"),
2302                (crate::ColorMode::Dark, "breeze-dark"),
2303            ] {
2304                let source =
2305                    theme.with_icon_source(mode, |set, theme| (set, theme.map(str::to_owned)));
2306                assert_eq!(
2307                    source,
2308                    (crate::IconSet::Freedesktop, Some(expected.to_owned())),
2309                    "kde-breeze.toml:16 and :601 (active mode {active:?}, asked {mode:?})"
2310                );
2311                assert_eq!(theme.icon_theme_for(mode), Some(expected));
2312            }
2313        }
2314        Ok(())
2315    }
2316
2317    /// `SystemTheme::icon` and `icon_indicator` hand the mode's icon theme to
2318    /// the freedesktop loader: under a light variant theme that is not
2319    /// installed both load nothing (the loader searches no other theme), and
2320    /// the dark mode loads what `breeze-dark` itself gives, installed or not.
2321    #[test]
2322    #[cfg(all(target_os = "linux", feature = "system-icons"))]
2323    fn icon_and_indicator_load_from_the_modes_freedesktop_theme() -> crate::Result<()> {
2324        use crate::icons::{FreedesktopLoader, IconRole, is_freedesktop_theme_available};
2325
2326        const MISSING: &str = "native-theme-no-such-theme";
2327        assert!(!is_freedesktop_theme_available(MISSING));
2328        let mut theme = run_pipeline(reader_from_preset("kde-breeze"), "kde-breeze")?;
2329        theme.light_icon_theme = Some(std::borrow::Cow::Borrowed(MISSING));
2330        let role = IconRole::ActionCopy;
2331        for active in [crate::ColorMode::Light, crate::ColorMode::Dark] {
2332            theme.mode = active;
2333            assert_eq!(
2334                theme.icon(role, crate::ColorMode::Light, None),
2335                None,
2336                "light icon from {MISSING} (active mode {active:?})"
2337            );
2338            assert_eq!(
2339                theme.icon_indicator(crate::ColorMode::Light),
2340                None,
2341                "light spinner from {MISSING} (active mode {active:?})"
2342            );
2343            assert_eq!(
2344                theme.icon(role, crate::ColorMode::Dark, None),
2345                FreedesktopLoader::new(role).theme("breeze-dark").load(),
2346                "dark icon from breeze-dark, kde-breeze.toml:601 (active mode {active:?})"
2347            );
2348            assert_eq!(
2349                theme.icon_indicator(crate::ColorMode::Dark),
2350                FreedesktopLoader::load_indicator(Some("breeze-dark")),
2351                "dark spinner from breeze-dark (active mode {active:?})"
2352            );
2353        }
2354        Ok(())
2355    }
2356
2357    /// A Material system theme's icon comes back with the colour in its bytes.
2358    #[test]
2359    #[cfg(feature = "material-icons")]
2360    fn icon_of_a_material_theme_comes_back_in_the_colour() -> crate::Result<()> {
2361        let theme = run_pipeline(reader_from_preset("material-3"), "material-3")?;
2362        assert_eq!(
2363            theme.icon_set,
2364            crate::IconSet::Material,
2365            "material-3.toml:9"
2366        );
2367        // Test fixture colour, not a theme value.
2368        let color = Rgba::rgb(0x12, 0x34, 0x56);
2369        for mode in [crate::ColorMode::Light, crate::ColorMode::Dark] {
2370            match theme.icon(crate::IconRole::ActionCopy, mode, Some(color)) {
2371                Some(crate::IconData::Svg(svg)) => {
2372                    let svg = String::from_utf8(svg.into_owned()).unwrap();
2373                    assert!(svg.contains("#123456"), "{mode:?}: {svg}");
2374                }
2375                other => panic!("expected an SVG for {mode:?}, got {other:?}"),
2376            }
2377            assert!(
2378                theme.icon_indicator(mode).is_some(),
2379                "Material's spinner ({mode:?})"
2380            );
2381        }
2382        Ok(())
2383    }
2384
2385    /// Both variants' icon themes are known whichever mode is active: the
2386    /// egui connector needs the name per `egui::Theme`, because egui draws
2387    /// either style after a scheme change (egui spec §4.2, §9).
2388    #[test]
2389    fn icon_theme_for_gives_each_variants_name() -> crate::Result<()> {
2390        for mode in [crate::ColorMode::Light, crate::ColorMode::Dark] {
2391            // A reader that names no icon theme: tier 1 (the reader's own
2392            // variant) is empty, so the preset's variants decide.
2393            let reader = ReaderResult {
2394                output: ReaderOutput::Single {
2395                    mode: Box::new(crate::model::ThemeMode::default()),
2396                    is_dark: mode == crate::ColorMode::Dark,
2397                },
2398                name: std::borrow::Cow::Borrowed(""),
2399                icon_set: None,
2400                layout: crate::theme::LayoutTheme::default(),
2401                font_dpi: None,
2402                accessibility: crate::AccessibilityPreferences::default(),
2403            };
2404            let theme = run_pipeline(reader, "kde-breeze")?;
2405            assert_eq!(
2406                theme.icon_theme_for(crate::ColorMode::Light),
2407                Some("breeze"),
2408                "kde-breeze.toml:16 names breeze for light (active mode {mode:?})"
2409            );
2410            assert_eq!(
2411                theme.icon_theme_for(crate::ColorMode::Dark),
2412                Some("breeze-dark"),
2413                "kde-breeze.toml:601 names breeze-dark for dark (active mode {mode:?})"
2414            );
2415            assert_eq!(
2416                theme.icon_theme_for(mode),
2417                theme.icon_theme.as_deref(),
2418                "the active mode's name is `icon_theme` itself"
2419            );
2420            // `mode` is a public field: changing it after the build must not swap the names.
2421            let mut flipped = theme;
2422            flipped.mode = match mode {
2423                crate::ColorMode::Light => crate::ColorMode::Dark,
2424                crate::ColorMode::Dark => crate::ColorMode::Light,
2425            };
2426            assert_eq!(
2427                flipped.icon_theme_for(crate::ColorMode::Light),
2428                Some("breeze"),
2429                "built in {mode:?}, mode flipped"
2430            );
2431            assert_eq!(
2432                flipped.icon_theme_for(crate::ColorMode::Dark),
2433                Some("breeze-dark"),
2434                "built in {mode:?}, mode flipped"
2435            );
2436        }
2437        Ok(())
2438    }
2439}
2440
2441// =============================================================================
2442// Plan 94-03 (G8): ThemeReader trait + select_reader regression tests
2443// =============================================================================
2444//
2445// These tests lock the contract of the G8 ThemeReader refactor:
2446// - the `ThemeReader` trait exists under `crate::reader` and is object-safe
2447// - `select_reader()` exists and returns the correct platform-specific impl
2448//
2449// Object-safety is the load-bearing property: `select_reader()` is declared
2450// to return `Option<Box<dyn ThemeReader>>`, which only compiles if the trait
2451// is object-safe. On current stable Rust (1.95), native `async fn` in traits
2452// is NOT object-safe for `dyn Trait`; the trait definition must use
2453// `#[async_trait::async_trait]` to produce a `Pin<Box<dyn Future + Send>>`
2454// return type that vtables can hold. If an implementer deviates from the
2455// async-trait strategy (e.g., tries native async-fn-in-trait), the coercion
2456// below fails to compile with "the trait cannot be made into an object" —
2457// this is the structural enforcement of Option A (see plan 94-03 objective).
2458#[cfg(test)]
2459#[allow(clippy::unwrap_used, clippy::expect_used)]
2460mod theme_reader_trait_tests {
2461    /// Trait object-safety probe. With `#[async_trait::async_trait]` on the
2462    /// trait definition, this coercion compiles because the macro rewrite
2463    /// produces `Pin<Box<dyn Future + Send + '_>>` return types
2464    /// (vtable-compatible).
2465    #[test]
2466    fn theme_reader_trait_exists_and_is_object_safe() {
2467        // Plain function that requires its argument to be ?Sized — compile-time
2468        // proof that `Box<dyn ThemeReader>` is a valid trait object.
2469        //
2470        // `#[allow(dead_code)]` is required because on cfg permutations that
2471        // exclude every concrete reader (e.g. linux without kde feature) the
2472        // function is only name-resolved by the compiler but never called.
2473        #[allow(dead_code)]
2474        fn assert_object_safe<T: ?Sized>(_: &T) {}
2475
2476        // Use one of the concrete readers to construct the trait object on
2477        // the platforms where one exists.
2478        #[cfg(all(target_os = "linux", feature = "kde"))]
2479        {
2480            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::kde::KdeReader);
2481            assert_object_safe(&r);
2482        }
2483        #[cfg(all(target_os = "macos", feature = "macos"))]
2484        {
2485            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::macos::MacosReader);
2486            assert_object_safe(&r);
2487        }
2488        #[cfg(all(target_os = "windows", feature = "windows"))]
2489        {
2490            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::windows::WindowsReader);
2491            assert_object_safe(&r);
2492        }
2493        // Without any active-platform feature we still want the test body to
2494        // compile; reference the trait path once so name resolution fires
2495        // regardless of cfg.
2496        let _: Option<&dyn crate::reader::ThemeReader> = None;
2497    }
2498
2499    /// `select_reader()` exists, is async, and returns an
2500    /// `Option<SelectedReader>`.
2501    ///
2502    /// On each platform with an available backend we expect `Some(selected)`;
2503    /// on platforms without one (non-Linux/macOS/Windows, or Linux with no
2504    /// compiled-in backend, or Linux-other-DE without portal) we expect `None`.
2505    ///
2506    /// The selected reader carries the platform preset name that `run_pipeline`
2507    /// should use — kept in the same return type because the preset is chosen
2508    /// from the DE detected by `select_reader` (KDE -> kde-breeze, GNOME ->
2509    /// adwaita, macOS -> the running version's generation, Windows -> windows-11).
2510    #[test]
2511    fn select_reader_returns_platform_specific_impl() {
2512        // Call select_reader and observe the Option. The structural invariant
2513        // is that the function exists, is callable from a sync context via
2514        // `pollster::block_on`, and returns the selected reader and its preset.
2515        let picked: Option<super::SelectedReader> = pollster::block_on(super::select_reader());
2516
2517        // Every cfg branch borrows `picked` (via `&picked`) rather than moving
2518        // it, so the final `drop(picked)` consumes it uniformly on all
2519        // permutations -- including linux-without-kde, which has no branch.
2520        #[cfg(all(target_os = "macos", feature = "macos"))]
2521        {
2522            assert!(
2523                picked.is_some(),
2524                "select_reader must return Some on macOS+macos"
2525            );
2526            if let Some(selected) = &picked {
2527                let (preset, matched) = super::macos_generation(crate::macos::os_version());
2528                assert_eq!(selected.preset, preset.name);
2529                assert_eq!(selected.version_match, Some(matched));
2530            }
2531        }
2532        #[cfg(all(target_os = "windows", feature = "windows"))]
2533        {
2534            assert!(
2535                picked.is_some(),
2536                "select_reader must return Some on windows+windows"
2537            );
2538            if let Some(selected) = &picked {
2539                let (preset, matched) = super::windows_generation(crate::windows::os_version());
2540                assert_eq!(selected.preset, preset.name);
2541                assert_eq!(selected.version_match, Some(matched));
2542            }
2543        }
2544        #[cfg(all(target_os = "linux", feature = "kde", feature = "portal"))]
2545        {
2546            // On linux+kde+portal, select_reader returns Some(GnomePortalKdeReader, "kde-breeze")
2547            // whenever the active DE is KDE; for non-KDE DEs it may legitimately
2548            // return None (preset fallback). Assert the tuple shape regardless.
2549            if let Some(selected) = &picked {
2550                assert!(
2551                    selected.preset == "kde-breeze" || selected.preset == "adwaita",
2552                    "select_reader on linux must return a known platform preset, got: {}",
2553                    selected.preset
2554                );
2555                assert_eq!(selected.version_match, None);
2556            }
2557        }
2558        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
2559        {
2560            assert!(
2561                picked.is_none(),
2562                "select_reader() must return None on unsupported platforms"
2563            );
2564        }
2565        drop(picked);
2566    }
2567}
2568
2569/// The generation tables (M1-T1-01): pure functions of the version, tested on
2570/// every platform; CI's macOS and Windows legs run the readers against them.
2571#[cfg(test)]
2572#[allow(clippy::unwrap_used, clippy::expect_used)]
2573mod generation_tests {
2574    use super::*;
2575
2576    /// The macOS preset of a running major version, as `select_reader` picks it.
2577    fn macos_preset_for_version(major: u32) -> &'static str {
2578        macos_generation(OsVersion::new(major, 0, 0)).0.name
2579    }
2580
2581    #[test]
2582    fn macos_preset_follows_the_os_generation() {
2583        assert_eq!(macos_preset_for_version(12), "macos-monterey");
2584        assert_eq!(macos_preset_for_version(14), "macos-monterey");
2585        assert_eq!(macos_preset_for_version(15), "macos-monterey");
2586        assert_eq!(macos_preset_for_version(26), "macos-tahoe");
2587        // macOS 27 until a macos-golden-gate preset exists (D4)
2588        assert_eq!(macos_preset_for_version(27), "macos-tahoe");
2589        assert_eq!(
2590            macos_generation(OsVersion::new(27, 0, 1)).1,
2591            VersionMatch::PresetOlder
2592        );
2593        // 16: what early macOS 26 betas reported to a macOS 15 SDK build
2594        assert_eq!(
2595            macos_generation(OsVersion::new(16, 0, 0)),
2596            (
2597                PlatformPreset {
2598                    name: "macos-monterey"
2599                },
2600                VersionMatch::PresetOlder
2601            )
2602        );
2603        // An unreadable version reads as 0.0.0
2604        assert_eq!(
2605            macos_generation(OsVersion::new(0, 0, 0)),
2606            (
2607                PlatformPreset {
2608                    name: "macos-monterey"
2609                },
2610                VersionMatch::PresetNewer
2611            )
2612        );
2613    }
2614
2615    #[test]
2616    fn macos_versions_inside_a_generation_match_exactly() {
2617        for v in [
2618            OsVersion::new(12, 0, 0),
2619            OsVersion::new(14, 8, 9),
2620            OsVersion::new(15, 7, 9),
2621            OsVersion::new(26, 6, 2),
2622        ] {
2623            assert_eq!(macos_generation(v).1, VersionMatch::Exact, "{v}");
2624        }
2625        // Big Sur began the look, before Monterey's change to a clicked button
2626        assert_eq!(
2627            macos_generation(OsVersion::new(11, 7, 10)),
2628            (
2629                PlatformPreset {
2630                    name: "macos-monterey"
2631                },
2632                VersionMatch::PresetNewer
2633            )
2634        );
2635    }
2636
2637    #[test]
2638    fn windows_preset_follows_the_build() {
2639        // Windows 10 22H2: no preset of its own (M2b Step 7, D9)
2640        assert_eq!(
2641            windows_generation(OsVersion::new(10, 0, 19045)),
2642            (
2643                PlatformPreset { name: "windows-11" },
2644                VersionMatch::PresetNewer
2645            )
2646        );
2647        assert_eq!(
2648            windows_generation(OsVersion::new(10, 0, 22000)).1,
2649            VersionMatch::Exact
2650        );
2651        assert_eq!(
2652            windows_generation(OsVersion::new(10, 0, 26200)).1,
2653            VersionMatch::Exact
2654        );
2655        // 26H2 (26300): newer than the build the preset was verified on
2656        assert_eq!(
2657            windows_generation(OsVersion::new(10, 0, 26300)).1,
2658            VersionMatch::PresetOlder
2659        );
2660        // 26H1 (28000)
2661        assert_eq!(
2662            windows_generation(OsVersion::new(10, 0, 28000)),
2663            (
2664                PlatformPreset { name: "windows-11" },
2665                VersionMatch::PresetOlder
2666            )
2667        );
2668        // A failed version read gives 0.0.0
2669        assert_eq!(
2670            windows_generation(OsVersion::new(0, 0, 0)),
2671            (
2672                PlatformPreset { name: "windows-11" },
2673                VersionMatch::PresetNewer
2674            )
2675        );
2676    }
2677
2678    #[test]
2679    fn every_table_is_ordered_and_lists_its_keys() {
2680        for table in [MACOS_GENERATIONS, WINDOWS_GENERATIONS] {
2681            let rows: Vec<Generation> = table.rows().collect();
2682            let keys: Vec<&str> = rows.iter().map(|g| g.preset).collect();
2683            assert_eq!(keys, table.keys);
2684            for g in &rows {
2685                assert!(g.first <= g.last_verified, "{}", g.preset);
2686            }
2687            for (older, newer) in rows.iter().zip(rows.iter().skip(1)) {
2688                assert!(
2689                    older.last_verified < newer.first,
2690                    "{} / {}",
2691                    older.preset,
2692                    newer.preset
2693                );
2694            }
2695        }
2696    }
2697
2698    #[test]
2699    fn every_generation_is_a_bundled_preset_of_its_platform() {
2700        for (table, platform) in [
2701            (MACOS_GENERATIONS, "macos"),
2702            (WINDOWS_GENERATIONS, "windows"),
2703        ] {
2704            for key in table.keys {
2705                assert!(crate::Theme::preset(key).is_ok(), "{key}");
2706                let offered = crate::Theme::list_presets()
2707                    .iter()
2708                    .any(|p| p.key == *key && p.platforms.contains(&platform));
2709                assert!(offered, "{key} is not offered on {platform}");
2710            }
2711        }
2712    }
2713
2714    #[test]
2715    fn the_diagnostic_names_the_version_and_its_preset() {
2716        let entry = DiagnosticEntry::OsGeneration {
2717            version: OsVersion::new(27, 0, 1).to_string(),
2718            preset: "macos-tahoe",
2719            version_match: VersionMatch::PresetOlder,
2720        };
2721        assert_eq!(entry.name(), "OS version");
2722        assert_eq!(entry.status(), "27.0.1");
2723        assert_eq!(
2724            entry.to_string(),
2725            "OS version: 27.0.1 (macos-tahoe, preset older than the OS)"
2726        );
2727    }
2728}