native-theme 0.5.8

Cross-platform native theme detection and loading for Rust GUI applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
//! Theme pipeline: reader -> preset merge -> resolve -> validate.

use std::fmt;

#[cfg(target_os = "linux")]
use crate::detect::{LinuxDesktop, detect_linux_desktop, parse_linux_desktop, system_is_dark};

use crate::model::Theme;
use crate::{OverlaySource, ReaderOutput, ReaderResult, SystemTheme};

/// Run the OS-first pipeline: merge reader output onto a platform
/// preset, resolve both light and dark variants, validate.
///
/// Accepts a [`ReaderResult`] containing the reader's variant data
/// and metadata (name, icon_set, layout, font_dpi, accessibility).
///
/// `ReaderOutput::Single` readers provide one variant; the pipeline
/// fills the other from the full platform preset. `ReaderOutput::Dual`
/// readers provide both; the pipeline uses both after merging.
pub(crate) fn run_pipeline(
    reader: ReaderResult,
    preset_name: &str,
    mode: crate::ColorMode,
) -> crate::Result<SystemTheme> {
    let ReaderResult {
        output: reader_output,
        name: reader_name,
        icon_set: reader_icon_set,
        layout: reader_layout,
        font_dpi,
        accessibility,
    } = reader;

    let live_preset = Theme::preset(preset_name)?;

    // For the inactive variant, load the full preset (with colors).
    // Falls back to original name if not a live preset (e.g. user preset).
    let full_preset_name = preset_name.strip_suffix("-live").unwrap_or(preset_name);
    debug_assert!(
        full_preset_name != preset_name || !preset_name.ends_with("-live"),
        "live preset '{preset_name}' should have -live suffix stripped"
    );
    let full_preset = Theme::preset(full_preset_name)?;

    // Reconstruct a Theme from the type-safe ReaderOutput for merge
    let reader_as_theme = reader_output.to_theme(&reader_name, reader_icon_set, &reader_layout);

    // Merge: full preset provides color/font defaults, live preset overrides
    // geometry, reader output provides live OS data on top.
    let mut merged = full_preset.clone();
    merged.merge(&live_preset);
    merged.merge(&reader_as_theme);

    // Keep reader name if non-empty, else use preset name
    let name = if reader_name.is_empty() {
        merged.name.clone()
    } else {
        reader_name.clone()
    };

    // Resolve icon_set from Theme level (shared across variants)
    let icon_set = merged
        .icon_set
        .unwrap_or_else(crate::model::icons::system_icon_set);

    // Build ONE resolution-time context for this theme-build. The reader
    // may have supplied an authoritative font_dpi (e.g. KDE forceFontDPI);
    // when it does we override ctx.font_dpi. button_order + icon_theme
    // come from the from_system() defaults (platform-detected).
    let mut ctx = crate::resolve::ResolutionContext::from_system();
    if let Some(dpi) = font_dpi {
        ctx.font_dpi = dpi;
    }

    // Resolve icon_theme with three-tier precedence (per §G4 / doc 1 §20 Option C):
    //   Tier 1: per-variant override (`ThemeMode::defaults.icon_theme`)
    //   Tier 2: shared Theme-level value (`Theme::icon_theme`)
    //   Tier 3: runtime system detect (from `ctx.icon_theme`)
    // Must read before variants are consumed by unwrap_or_default().
    let icon_theme: std::borrow::Cow<'static, str> = {
        let active = if mode == crate::ColorMode::Dark {
            &merged.dark
        } else {
            &merged.light
        };
        active
            .as_ref()
            .and_then(|v| v.defaults.icon_theme.clone()) // tier 1: per-variant override
            .or_else(|| merged.icon_theme.clone()) // tier 2: Theme-level shared
            .or_else(|| ctx.icon_theme.clone()) // tier 3: pre-detected system
            .unwrap_or_else(|| std::borrow::Cow::Owned(crate::model::icons::system_icon_theme()))
    };

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

    // Match on ReaderOutput for type-safe variant selection:
    // Single: active variant from merged, inactive from full preset.
    // Dual: both variants from merged.
    let (light_variant, dark_variant) = match &reader_output {
        ReaderOutput::Single { is_dark, .. } => {
            if *is_dark {
                (
                    full_preset.light.unwrap_or_default(),
                    merged.dark.unwrap_or_default(),
                )
            } else {
                (
                    merged.light.unwrap_or_default(),
                    full_preset.dark.unwrap_or_default(),
                )
            }
        }
        ReaderOutput::Dual { .. } => (
            merged.light.unwrap_or_default(),
            merged.dark.unwrap_or_default(),
        ),
    };

    let light = light_variant.into_resolved(&ctx)?;
    let dark = dark_variant.into_resolved(&ctx)?;

    // Build OverlaySource from the original reader data + pipeline parameters
    let overlay_source = OverlaySource {
        reader_output,
        name: reader_name,
        icon_set: reader_icon_set,
        layout: reader_layout,
        preset_name: preset_name.to_string(),
        context: ctx,
    };

    Ok(SystemTheme {
        name,
        mode,
        light,
        dark,
        overlay_source,
        preset: full_preset_name.to_string(),
        live_preset: preset_name.to_string(),
        icon_set,
        icon_theme,
        layout,
        accessibility,
    })
}

// =============================================================================
// Structured return types
// =============================================================================

/// A single diagnostic observation about platform theme support.
///
/// Returned by [`diagnose_platform_support()`]. Each variant represents
/// a specific category of diagnostic information. Use `Display` to get
/// a human-readable string, or pattern-match for programmatic inspection.
///
/// For simple tabular output, use the [`name()`](Self::name),
/// [`status()`](Self::status), and [`detail()`](Self::detail) accessors:
///
/// ```
/// let diagnostics = native_theme::pipeline::diagnose_platform_support();
/// for entry in &diagnostics {
///     print!("{}: {}", entry.name(), entry.status());
///     if let Some(detail) = entry.detail() {
///         print!(" ({})", detail);
///     }
///     println!();
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DiagnosticEntry {
    /// Platform identification (e.g. "Linux", "macOS", "Windows").
    Platform(&'static str),
    /// Detected desktop environment (Linux only).
    #[cfg(target_os = "linux")]
    DesktopEnv(crate::detect::LinuxDesktop),
    /// An environment variable was read successfully.
    EnvVar {
        /// Variable name (e.g. `"XDG_CURRENT_DESKTOP"`).
        name: &'static str,
        /// Variable value as read from the environment.
        value: String,
    },
    /// An environment variable was missing or empty.
    EnvVarMissing(&'static str),
    /// An external tool was found and operational.
    ToolAvailable {
        /// Tool binary name (e.g. `"gsettings"`).
        name: &'static str,
        /// Version string reported by the tool.
        version: String,
    },
    /// An external tool was found but returned an error.
    ToolError(&'static str),
    /// An external tool was not found on PATH.
    ToolMissing {
        /// Tool binary name.
        name: &'static str,
        /// Human-readable description of what is lost.
        impact: &'static str,
    },
    /// A config file was found at the given path.
    ConfigFound {
        /// Logical config name (e.g. `"KDE kdeglobals"`).
        name: &'static str,
        /// Filesystem path where the file was found.
        path: std::path::PathBuf,
    },
    /// A config file was not found at the expected path.
    ConfigMissing {
        /// Logical config name.
        name: &'static str,
        /// Filesystem path that was checked.
        path: std::path::PathBuf,
    },
    /// A cargo feature is enabled.
    FeatureEnabled(&'static str),
    /// A cargo feature is disabled.
    FeatureDisabled {
        /// Feature name (e.g. `"KDE"`, `"Portal"`).
        feature: &'static str,
        /// Human-readable description of what is lost.
        impact: &'static str,
    },
}

impl DiagnosticEntry {
    /// A short label identifying what is being diagnosed.
    ///
    /// Examples: `"Platform"`, `"XDG_CURRENT_DESKTOP"`, `"gsettings"`,
    /// `"KDE kdeglobals"`, `"Portal support"`.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::Platform(_) => "Platform",
            #[cfg(target_os = "linux")]
            Self::DesktopEnv(_) => "Detected DE",
            Self::EnvVar { name, .. } | Self::EnvVarMissing(name) => name,
            Self::ToolAvailable { name, .. }
            | Self::ToolError(name)
            | Self::ToolMissing { name, .. } => name,
            Self::ConfigFound { name, .. } | Self::ConfigMissing { name, .. } => name,
            Self::FeatureEnabled(feature) | Self::FeatureDisabled { feature, .. } => feature,
        }
    }

    /// A short status string: the detected value or a state like
    /// `"not set"`, `"available"`, `"found"`, `"enabled"`, etc.
    #[must_use]
    pub fn status(&self) -> &str {
        match self {
            Self::Platform(p) => p,
            #[cfg(target_os = "linux")]
            Self::DesktopEnv(_) => "detected",
            Self::EnvVar { value, .. } => value.as_str(),
            Self::EnvVarMissing(_) => "not set",
            Self::ToolAvailable { .. } => "available",
            Self::ToolError(_) => "found but returned error",
            Self::ToolMissing { .. } => "not found",
            Self::ConfigFound { .. } => "found",
            Self::ConfigMissing { .. } => "not found",
            Self::FeatureEnabled(_) => "enabled",
            Self::FeatureDisabled { .. } => "disabled",
        }
    }

    /// Optional extra detail (version string, file path, impact note, DE variant).
    #[must_use]
    pub fn detail(&self) -> Option<String> {
        match self {
            #[cfg(target_os = "linux")]
            Self::DesktopEnv(de) => Some(format!("{de:?}")),
            Self::ToolAvailable { version, .. } => Some(version.clone()),
            Self::ToolMissing { impact, .. } => Some((*impact).to_string()),
            Self::FeatureDisabled { impact, .. } => Some((*impact).to_string()),
            Self::ConfigFound { path, .. } | Self::ConfigMissing { path, .. } => {
                Some(path.display().to_string())
            }
            _ => None,
        }
    }
}

impl fmt::Display for DiagnosticEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Platform(p) => write!(f, "Platform: {p}"),
            #[cfg(target_os = "linux")]
            Self::DesktopEnv(de) => write!(f, "Detected DE: {de:?}"),
            Self::EnvVar { name, value } => write!(f, "{name}: {value}"),
            Self::EnvVarMissing(name) => write!(f, "{name}: not set"),
            Self::ToolAvailable { name, version } => {
                write!(f, "{name}: available ({version})")
            }
            Self::ToolError(name) => write!(f, "{name}: found but returned error"),
            Self::ToolMissing { name, impact } => write!(f, "{name}: not found ({impact})"),
            Self::ConfigFound { name, path } => {
                write!(f, "{name}: found at {}", path.display())
            }
            Self::ConfigMissing { name, path } => {
                write!(f, "{name}: not found at {}", path.display())
            }
            Self::FeatureEnabled(feature) => write!(f, "{feature} support: enabled"),
            Self::FeatureDisabled { feature, impact } => {
                write!(f, "{feature} support: disabled ({impact})")
            }
        }
    }
}

/// Structured information about the platform's default preset.
///
/// Returned by [`platform_preset_name()`]. The `name` field is the
/// user-facing preset name (e.g. `"macos-sonoma"`). The `is_live` field
/// indicates whether the preset is a live (geometry-only) preset used
/// by the OS-first pipeline.
///
/// `Display` returns the user-facing name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlatformPreset {
    /// User-facing preset name (e.g. "kde-breeze", "adwaita", "macos-sonoma").
    pub name: &'static str,
    /// Whether this is a live preset (geometry-only merge base for OS readers).
    pub is_live: bool,
}

impl PlatformPreset {
    /// Returns the internal live preset name (e.g. `"kde-breeze-live"`)
    /// when `is_live` is true, or the plain name when not.
    ///
    /// This is used internally by the pipeline to look up the correct
    /// preset entry; callers should use [`name`](Self::name) for display.
    #[must_use]
    pub fn live_name(&self) -> String {
        if self.is_live {
            format!("{}-live", self.name)
        } else {
            self.name.to_string()
        }
    }
}

impl fmt::Display for PlatformPreset {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name)
    }
}

/// Map a Linux desktop environment to its matching platform preset.
///
/// This is the single source of truth for the DE-to-preset mapping used
/// by [`from_system_inner()`] and [`platform_preset_name()`].
///
/// - KDE -> `PlatformPreset { name: "kde-breeze", is_live: true }`
/// - All others (GNOME, XFCE, Cinnamon, MATE, LXQt, Budgie, Unknown)
///   -> `PlatformPreset { name: "adwaita", is_live: true }`
#[cfg(target_os = "linux")]
pub(crate) fn linux_preset_for_de(de: LinuxDesktop) -> PlatformPreset {
    match de {
        LinuxDesktop::Kde => PlatformPreset {
            name: "kde-breeze",
            is_live: true,
        },
        _ => PlatformPreset {
            name: "adwaita",
            is_live: true,
        },
    }
}

/// Map the current platform to its matching platform preset.
///
/// Live presets contain only geometry/metrics (no colors, fonts, or icons)
/// and are used as the merge base in the OS-first pipeline. Use
/// [`PlatformPreset::live_name()`] to get the internal live preset key.
///
/// - macOS -> `PlatformPreset { name: "macos-sonoma", is_live: true }`
/// - Windows -> `PlatformPreset { name: "windows-11", is_live: true }`
/// - Linux KDE -> `PlatformPreset { name: "kde-breeze", is_live: true }`
/// - Linux other/GNOME -> `PlatformPreset { name: "adwaita", is_live: true }`
/// - Unknown platform -> `PlatformPreset { name: "adwaita", is_live: true }`
///
/// Returns a [`PlatformPreset`] with the user-facing preset name and
/// whether it is a live (geometry-only) preset. Showcase UIs use
/// `preset.name` to build the "default (...)" label.
///
/// # Examples
///
/// ```
/// let preset = native_theme::pipeline::platform_preset_name();
/// println!("Platform preset: {}", preset.name);
/// assert!(!preset.name.contains("-live"));
/// ```
#[allow(unreachable_code)]
#[must_use]
pub fn platform_preset_name() -> PlatformPreset {
    #[cfg(target_os = "macos")]
    {
        return PlatformPreset {
            name: "macos-sonoma",
            is_live: true,
        };
    }
    #[cfg(target_os = "windows")]
    {
        return PlatformPreset {
            name: "windows-11",
            is_live: true,
        };
    }
    #[cfg(target_os = "linux")]
    {
        linux_preset_for_de(detect_linux_desktop())
    }
    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    {
        PlatformPreset {
            name: "adwaita",
            is_live: true,
        }
    }
}

/// Check whether OS theme detection is available on this platform.
///
/// Returns a list of [`DiagnosticEntry`] values describing what detection
/// capabilities are available and what might be missing. Useful for
/// debugging theme detection failures in end-user applications.
///
/// Each entry can be printed directly via its `Display` impl, or
/// inspected programmatically via [`DiagnosticEntry::name()`],
/// [`DiagnosticEntry::status()`], and [`DiagnosticEntry::detail()`].
///
/// # Platform Behavior
///
/// - **Linux:** Reports detected desktop environment, `gsettings`
///   availability, `XDG_CURRENT_DESKTOP` value, and KDE config file
///   presence (when the `kde` feature is enabled).
/// - **macOS:** Reports whether the `macos` feature is enabled.
/// - **Windows:** Reports whether the `windows` feature is enabled.
/// - **Other:** Reports that no platform detection is available.
///
/// # Examples
///
/// ```
/// let diagnostics = native_theme::pipeline::diagnose_platform_support();
/// for entry in &diagnostics {
///     println!("{entry}");
/// }
/// ```
#[must_use]
pub fn diagnose_platform_support() -> Vec<DiagnosticEntry> {
    let mut diagnostics = Vec::new();

    #[cfg(target_os = "linux")]
    {
        diagnostics.push(DiagnosticEntry::Platform("Linux"));

        // Check XDG_CURRENT_DESKTOP
        match std::env::var("XDG_CURRENT_DESKTOP") {
            Ok(val) if !val.is_empty() => {
                let de = parse_linux_desktop(&val);
                diagnostics.push(DiagnosticEntry::EnvVar {
                    name: "XDG_CURRENT_DESKTOP",
                    value: val,
                });
                diagnostics.push(DiagnosticEntry::DesktopEnv(de));
            }
            _ => {
                diagnostics.push(DiagnosticEntry::EnvVarMissing("XDG_CURRENT_DESKTOP"));
                diagnostics.push(DiagnosticEntry::DesktopEnv(LinuxDesktop::Unknown));
            }
        }

        // Check gsettings availability
        match std::process::Command::new("gsettings")
            .arg("--version")
            .output()
        {
            Ok(output) if output.status.success() => {
                let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
                diagnostics.push(DiagnosticEntry::ToolAvailable {
                    name: "gsettings",
                    version,
                });
            }
            Ok(_) => {
                diagnostics.push(DiagnosticEntry::ToolError("gsettings"));
            }
            Err(_) => {
                diagnostics.push(DiagnosticEntry::ToolMissing {
                    name: "gsettings",
                    impact: "dark mode and icon theme detection may be limited",
                });
            }
        }

        // Check KDE config files
        #[cfg(feature = "kde")]
        {
            let path = crate::kde::kdeglobals_path();
            if path.exists() {
                diagnostics.push(DiagnosticEntry::ConfigFound {
                    name: "KDE kdeglobals",
                    path,
                });
            } else {
                diagnostics.push(DiagnosticEntry::ConfigMissing {
                    name: "KDE kdeglobals",
                    path,
                });
            }
        }

        #[cfg(not(feature = "kde"))]
        {
            diagnostics.push(DiagnosticEntry::FeatureDisabled {
                feature: "KDE",
                impact: "kde feature not enabled",
            });
        }

        // Report portal feature status
        #[cfg(feature = "portal")]
        diagnostics.push(DiagnosticEntry::FeatureEnabled("Portal"));

        #[cfg(not(feature = "portal"))]
        diagnostics.push(DiagnosticEntry::FeatureDisabled {
            feature: "Portal",
            impact: "portal feature not enabled",
        });
    }

    #[cfg(target_os = "macos")]
    {
        diagnostics.push(DiagnosticEntry::Platform("macOS"));

        #[cfg(feature = "macos")]
        diagnostics.push(DiagnosticEntry::FeatureEnabled("macOS theme detection"));

        #[cfg(not(feature = "macos"))]
        diagnostics.push(DiagnosticEntry::FeatureDisabled {
            feature: "macOS theme detection",
            impact: "macos feature not enabled, using subprocess fallback",
        });
    }

    #[cfg(target_os = "windows")]
    {
        diagnostics.push(DiagnosticEntry::Platform("Windows"));

        #[cfg(feature = "windows")]
        diagnostics.push(DiagnosticEntry::FeatureEnabled("Windows theme detection"));

        #[cfg(not(feature = "windows"))]
        diagnostics.push(DiagnosticEntry::FeatureDisabled {
            feature: "Windows theme detection",
            impact: "windows feature not enabled",
        });
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        diagnostics.push(DiagnosticEntry::Platform(
            "unsupported (no native theme detection available)",
        ));
    }

    diagnostics
}

/// Build a `ReaderResult` from a preset (for fallback paths where no
/// platform reader is available).
fn preset_as_reader(preset_name: &str, mode: crate::ColorMode) -> crate::Result<ReaderResult> {
    let theme = Theme::preset(preset_name)?;
    let is_dark = mode == crate::ColorMode::Dark;
    let output = if is_dark {
        ReaderOutput::Single {
            mode: Box::new(theme.dark.unwrap_or_default()),
            is_dark: true,
        }
    } else {
        ReaderOutput::Single {
            mode: Box::new(theme.light.unwrap_or_default()),
            is_dark: false,
        }
    };
    Ok(ReaderResult {
        output,
        name: theme.name,
        icon_set: theme.icon_set,
        layout: theme.layout,
        font_dpi: None,
        accessibility: crate::AccessibilityPreferences::default(),
    })
}

/// Platform + DE + feature cascade that picks the appropriate
/// [`crate::reader::ThemeReader`] impl for the current system.
///
/// Returns `None` when no reader is available and the caller must fall back
/// to a preset-only pipeline (non-KDE/GNOME Linux, unsupported platforms, or
/// platforms whose reader feature is disabled). When `Some`, the companion
/// `&'static str` is the `-live` preset name that should be passed to
/// [`run_pipeline`] — the reader and the preset are tied because the preset
/// is chosen from the detected DE.
///
/// Per plan 94-03 §G8: the `Box<dyn ThemeReader>` trait object is object-safe
/// only because the trait carries a `#[async_trait::async_trait]` annotation
/// (see [`crate::reader`] module docs for the full rationale).
#[allow(unreachable_code)]
#[allow(clippy::unnecessary_wraps)] // Option is part of the public contract.
#[allow(clippy::needless_return)] // Explicit returns clarify cfg-gated dispatch.
async fn select_reader() -> Option<(Box<dyn crate::reader::ThemeReader>, &'static str)> {
    #[cfg(target_os = "macos")]
    {
        #[cfg(feature = "macos")]
        {
            return Some((Box::new(crate::macos::MacosReader), "macos-sonoma-live"));
        }
        #[cfg(not(feature = "macos"))]
        return None;
    }

    #[cfg(target_os = "windows")]
    {
        #[cfg(feature = "windows")]
        {
            return Some((Box::new(crate::windows::WindowsReader), "windows-11-live"));
        }
        #[cfg(not(feature = "windows"))]
        return None;
    }

    #[cfg(target_os = "linux")]
    {
        let de = detect_linux_desktop();
        match de {
            #[cfg(all(feature = "kde", feature = "portal"))]
            LinuxDesktop::Kde => {
                return Some((
                    Box::new(crate::gnome::GnomePortalKdeReader),
                    "kde-breeze-live",
                ));
            }
            #[cfg(all(feature = "kde", not(feature = "portal")))]
            LinuxDesktop::Kde => {
                return Some((Box::new(crate::kde::KdeReader), "kde-breeze-live"));
            }
            #[cfg(not(feature = "kde"))]
            LinuxDesktop::Kde => return None,
            #[cfg(feature = "portal")]
            LinuxDesktop::Gnome | LinuxDesktop::Budgie => {
                return Some((Box::new(crate::gnome::GnomeReader), "adwaita-live"));
            }
            #[cfg(not(feature = "portal"))]
            LinuxDesktop::Gnome | LinuxDesktop::Budgie => return None,
            LinuxDesktop::Xfce
            | LinuxDesktop::Cinnamon
            | LinuxDesktop::Mate
            | LinuxDesktop::LxQt
            | LinuxDesktop::Hyprland
            | LinuxDesktop::Sway
            | LinuxDesktop::River
            | LinuxDesktop::Niri
            | LinuxDesktop::Wayfire
            | LinuxDesktop::CosmicDe => return None,
            LinuxDesktop::Unknown => {
                // Refine heuristic via D-Bus portal backend detection
                #[cfg(feature = "portal")]
                {
                    if let Some(detected) = crate::gnome::detect_portal_backend().await {
                        return match detected {
                            #[cfg(feature = "kde")]
                            LinuxDesktop::Kde => Some((
                                Box::new(crate::gnome::GnomePortalKdeReader),
                                "kde-breeze-live",
                            )),
                            #[cfg(not(feature = "kde"))]
                            LinuxDesktop::Kde => None,
                            LinuxDesktop::Gnome => {
                                Some((Box::new(crate::gnome::GnomeReader), "adwaita-live"))
                            }
                            // detect_portal_backend only returns Kde or Gnome;
                            // any future extension falls back to Adwaita preset.
                            _ => None,
                        };
                    }
                }
                // Sync fallback: try kdeglobals, then Adwaita
                #[cfg(feature = "kde")]
                {
                    if crate::kde::kdeglobals_path().exists() {
                        return Some((Box::new(crate::kde::KdeReader), "kde-breeze-live"));
                    }
                }
                return None;
            }
        }
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    {
        None
    }
}

/// Single async implementation for all platforms. On Linux this may contain
/// `.await` points (portal D-Bus calls); on macOS/Windows the future resolves
/// immediately (no `.await` points).
///
/// Called by:
/// - `from_system()` via `pollster::block_on` on Linux, noop-waker single-poll
///   on non-Linux.
/// - `from_system_async()` via `.await`.
///
/// Delegates platform detection to [`select_reader`]: when a reader is
/// available, its output feeds [`run_pipeline`]; when no reader is available,
/// falls back to a preset-only pipeline or returns a feature/platform error.
#[allow(unreachable_code)]
#[allow(clippy::needless_return)] // Explicit returns clarify cfg-gated fallback.
pub(crate) async fn from_system_inner() -> crate::Result<SystemTheme> {
    if let Some((reader, preset_live)) = select_reader().await {
        let result = reader.read().await?;
        let mode = match &result.output {
            ReaderOutput::Single { is_dark, .. } => {
                if *is_dark {
                    crate::ColorMode::Dark
                } else {
                    crate::ColorMode::Light
                }
            }
            ReaderOutput::Dual { .. } => crate::ColorMode::Light,
        };
        return run_pipeline(result, preset_live, mode);
    }

    // Preset-only fallback paths — no reader available for this
    // platform+feature combination.
    #[cfg(target_os = "macos")]
    {
        return Err(crate::Error::FeatureDisabled {
            name: "macos",
            needed_for: "macOS theme detection",
        });
    }
    #[cfg(target_os = "windows")]
    {
        return Err(crate::Error::FeatureDisabled {
            name: "windows",
            needed_for: "Windows theme detection",
        });
    }
    #[cfg(target_os = "linux")]
    {
        let mode = if system_is_dark() {
            crate::ColorMode::Dark
        } else {
            crate::ColorMode::Light
        };
        let preset_live = linux_preset_for_de(detect_linux_desktop()).live_name();
        return run_pipeline(preset_as_reader("adwaita", mode)?, &preset_live, mode);
    }
    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    {
        Err(crate::Error::PlatformUnsupported {
            platform: "unsupported",
        })
    }
}

/// Reader-only extraction for [`crate::AccessibilityPreferences::from_system`]:
/// runs the same platform reader `from_system_inner` would run and returns its
/// accessibility block without merging or resolving a theme. Where no reader
/// is available (or it fails) the defaults are used. `reduce_motion` is OR-ed
/// with [`crate::detect::detect_reduced_motion`], a floor for the cases where
/// no reader supplies it and it stays at its default: Linux outside KDE and
/// GNOME, and macOS or Windows builds without their reader feature. A reader's
/// own `true` is never downgraded (spec §11.2).
pub(crate) async fn accessibility_from_system_inner() -> crate::AccessibilityPreferences {
    let mut prefs = match select_reader().await {
        Some((reader, _preset)) => match reader.read().await {
            Ok(result) => result.accessibility,
            Err(_) => crate::AccessibilityPreferences::default(),
        },
        None => crate::AccessibilityPreferences::default(),
    };
    if !prefs.reduce_motion {
        prefs.reduce_motion = crate::detect::detect_reduced_motion();
    }
    prefs
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(all(test, target_os = "linux"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod dispatch_tests {
    use super::*;

    // -- parse_linux_desktop() pure function tests --

    #[test]
    fn detect_kde_simple() {
        assert_eq!(parse_linux_desktop("KDE"), LinuxDesktop::Kde);
    }

    #[test]
    fn detect_kde_colon_separated_after() {
        assert_eq!(parse_linux_desktop("ubuntu:KDE"), LinuxDesktop::Kde);
    }

    #[test]
    fn detect_kde_colon_separated_before() {
        assert_eq!(parse_linux_desktop("KDE:plasma"), LinuxDesktop::Kde);
    }

    #[test]
    fn detect_gnome_simple() {
        assert_eq!(parse_linux_desktop("GNOME"), LinuxDesktop::Gnome);
    }

    #[test]
    fn detect_gnome_ubuntu() {
        assert_eq!(parse_linux_desktop("ubuntu:GNOME"), LinuxDesktop::Gnome);
    }

    #[test]
    fn detect_xfce() {
        assert_eq!(parse_linux_desktop("XFCE"), LinuxDesktop::Xfce);
    }

    #[test]
    fn detect_cinnamon() {
        assert_eq!(parse_linux_desktop("X-Cinnamon"), LinuxDesktop::Cinnamon);
    }

    #[test]
    fn detect_cinnamon_short() {
        assert_eq!(parse_linux_desktop("Cinnamon"), LinuxDesktop::Cinnamon);
    }

    #[test]
    fn detect_mate() {
        assert_eq!(parse_linux_desktop("MATE"), LinuxDesktop::Mate);
    }

    #[test]
    fn detect_lxqt() {
        assert_eq!(parse_linux_desktop("LXQt"), LinuxDesktop::LxQt);
    }

    #[test]
    fn detect_budgie() {
        assert_eq!(parse_linux_desktop("Budgie:GNOME"), LinuxDesktop::Budgie);
    }

    #[test]
    fn detect_empty_string() {
        assert_eq!(parse_linux_desktop(""), LinuxDesktop::Unknown);
    }

    // -- Pure pipeline dispatch tests (no env var manipulation) --

    #[test]
    fn from_linux_non_kde_returns_adwaita() -> crate::Result<()> {
        // GNOME desktop produces an Adwaita-named theme via the pure pipeline
        let preset = linux_preset_for_de(LinuxDesktop::Gnome);
        let result = preset_as_reader("adwaita", crate::ColorMode::Light)?;
        let theme = run_pipeline(result, &preset.live_name(), crate::ColorMode::Light)?;
        assert_eq!(theme.name, "Adwaita");
        Ok(())
    }

    #[test]
    #[cfg(feature = "kde")]
    fn from_linux_unknown_de_with_kdeglobals_fallback() -> crate::Result<()> {
        // Unknown DE with a kdeglobals file uses KDE reader -- test the dispatch
        // branch by calling from_kde_content_pure directly with minimal fixture.
        const MINIMAL_KDE_FIXTURE: &str = "\
[General]
ColorScheme=TestTheme

[Colors:Window]
BackgroundNormal=239,240,241

[Colors:View]
BackgroundNormal=252,252,252
ForegroundNormal=35,38,41
DecorationFocus=61,174,233
BackgroundAlternate=239,240,241
ForegroundLink=41,128,185";

        let (reader_theme, dpi, acc) =
            crate::kde::from_kde_content_pure(MINIMAL_KDE_FIXTURE, None)?;
        let is_dark = reader_theme.dark.is_some() && reader_theme.light.is_none();
        let output = if is_dark {
            ReaderOutput::Single {
                mode: Box::new(reader_theme.dark.unwrap_or_default()),
                is_dark: true,
            }
        } else {
            ReaderOutput::Single {
                mode: Box::new(reader_theme.light.unwrap_or_default()),
                is_dark: false,
            }
        };
        let result = ReaderResult {
            output,
            name: reader_theme.name,
            icon_set: reader_theme.icon_set,
            layout: reader_theme.layout,
            font_dpi: dpi,
            accessibility: acc,
        };
        let preset = linux_preset_for_de(LinuxDesktop::Kde);
        let theme = run_pipeline(result, &preset.live_name(), crate::ColorMode::Light)?;
        assert_eq!(
            theme.name, "TestTheme",
            "should use KDE theme name from reader output"
        );
        Ok(())
    }

    #[test]
    fn from_linux_unknown_de_without_kdeglobals_returns_adwaita() -> crate::Result<()> {
        // Unknown DE without kdeglobals falls back to Adwaita preset
        let preset = linux_preset_for_de(LinuxDesktop::Unknown);
        let result = preset_as_reader("adwaita", crate::ColorMode::Light)?;
        let theme = run_pipeline(result, &preset.live_name(), crate::ColorMode::Light)?;
        assert_eq!(
            theme.name, "Adwaita",
            "should fall back to Adwaita without kdeglobals"
        );
        Ok(())
    }

    // -- LNXDE-03: Hyprland, Sway, COSMIC, River, Niri map to their own variants --

    #[test]
    fn detect_hyprland() {
        assert_eq!(parse_linux_desktop("Hyprland"), LinuxDesktop::Hyprland);
    }

    #[test]
    fn detect_sway() {
        assert_eq!(parse_linux_desktop("sway"), LinuxDesktop::Sway);
    }

    #[test]
    fn detect_cosmic() {
        assert_eq!(parse_linux_desktop("COSMIC"), LinuxDesktop::CosmicDe);
    }

    #[test]
    fn detect_river() {
        assert_eq!(parse_linux_desktop("river"), LinuxDesktop::River);
    }

    #[test]
    fn detect_niri() {
        assert_eq!(parse_linux_desktop("niri"), LinuxDesktop::Niri);
    }

    #[test]
    fn parses_xdg_wayfire() {
        assert_eq!(parse_linux_desktop("Wayfire"), LinuxDesktop::Wayfire);
        assert_eq!(parse_linux_desktop("Wayfire:GNOME"), LinuxDesktop::Wayfire);
    }

    #[test]
    fn parses_xdg_empty_is_unknown() {
        // Regression guard -- empty XDG_CURRENT_DESKTOP must keep mapping to Unknown
        // even after the Wayfire variant addition.
        assert_eq!(parse_linux_desktop(""), LinuxDesktop::Unknown);
    }

    #[test]
    fn detect_cosmic_full_desktop() {
        assert_eq!(
            parse_linux_desktop("COSMIC:Freedesktop"),
            LinuxDesktop::CosmicDe
        );
    }

    // -- Pure pipeline smoke test (replaces from_system env var test) --

    #[test]
    fn from_system_returns_result() {
        // Test the pure pipeline directly instead of mocking env vars for from_system()
        let result = preset_as_reader("adwaita", crate::ColorMode::Light).unwrap();
        let theme = run_pipeline(result, "adwaita-live", crate::ColorMode::Light)
            .expect("run_pipeline should succeed with adwaita preset");
        assert_eq!(theme.name, "Adwaita");
    }
}

/// Tests for run_pipeline() -- internal pipeline functions.
/// These test functions moved from system_theme_tests in lib.rs since they
/// directly test pipeline internals rather than the SystemTheme public API.
#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::field_reassign_with_default
)]
mod pipeline_tests {
    use crate::color::Rgba;
    use crate::model::{LayoutTheme, Theme, ThemeMode};
    use crate::{ReaderOutput, ReaderResult};

    use super::{preset_as_reader, run_pipeline};

    /// Helper: build a ReaderResult from a preset for testing.
    fn reader_from_preset(preset_name: &str) -> ReaderResult {
        let preset = Theme::preset(preset_name).unwrap();
        ReaderResult {
            output: ReaderOutput::Dual {
                light: Box::new(preset.light.clone().unwrap_or_default()),
                dark: Box::new(preset.dark.clone().unwrap_or_default()),
            },
            name: preset.name,
            icon_set: preset.icon_set,
            layout: preset.layout,
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        }
    }

    // --- run_pipeline() tests ---

    #[test]
    fn test_run_pipeline_produces_both_variants() {
        let reader = reader_from_preset("catppuccin-mocha");
        let result = run_pipeline(reader, "catppuccin-mocha", crate::ColorMode::Light);
        assert!(result.is_ok(), "run_pipeline should succeed");
        let st = result.unwrap();
        // Both light and dark exist as ResolvedTheme (non-Option)
        assert!(!st.name.is_empty(), "name should be populated");
        // If we get here, both variants validated successfully
    }

    #[test]
    fn test_run_pipeline_reader_values_win() {
        // Create a reader output where the reader provides a custom accent
        // (simulating a platform reader that detected this accent from the OS)
        let custom_accent = Rgba::rgb(42, 100, 200);
        let mut variant = ThemeMode::default();
        variant.defaults.accent_color = Some(custom_accent);

        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(variant),
                is_dark: false,
            },
            name: "CustomTheme".into(),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let result = run_pipeline(reader, "catppuccin-mocha", crate::ColorMode::Light);
        assert!(result.is_ok(), "run_pipeline should succeed");
        let st = result.unwrap();
        // The reader's accent should win over the preset's accent
        assert_eq!(
            st.light.defaults.accent_color, custom_accent,
            "reader accent should win over preset accent"
        );
        assert_eq!(st.name, "CustomTheme", "reader name should win");
    }

    #[test]
    fn test_run_pipeline_single_variant() {
        // Simulate a real OS reader that provides a complete dark variant
        // (like KDE's from_kde() would) but no light variant.
        // Use a live preset so the inactive light variant gets the full preset.
        let full = Theme::preset("kde-breeze").unwrap();
        let mut dark_v = full.dark.clone().unwrap();
        // Override accent to prove reader values win (simulating OS-detected accent)
        dark_v.defaults.accent_color = Some(Rgba::rgb(200, 50, 50));

        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(dark_v),
                is_dark: true,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let result = run_pipeline(reader, "kde-breeze-live", crate::ColorMode::Dark);
        assert!(
            result.is_ok(),
            "run_pipeline should succeed with single variant"
        );
        let st = result.unwrap();
        // Dark should have the reader's overridden accent
        assert_eq!(
            st.dark.defaults.accent_color,
            Rgba::rgb(200, 50, 50),
            "dark variant should have reader accent"
        );
        // Light should still exist (from full preset, which has colors)
        // If we get here, both variants validated successfully
        assert_eq!(st.live_preset, "kde-breeze-live");
        assert_eq!(st.preset, "kde-breeze");
    }

    #[test]
    fn test_run_pipeline_inactive_variant_from_full_preset() {
        // When reader provides only dark, light must come from the full preset
        // (not the live preset, which has no colors and would fail validation).
        let full = Theme::preset("kde-breeze").unwrap();

        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(full.dark.clone().unwrap_or_default()),
                is_dark: true,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let st = run_pipeline(reader, "kde-breeze-live", crate::ColorMode::Dark).unwrap();

        // The light variant should have colors from the full "kde-breeze" preset
        let full_light = full.light.unwrap();
        assert_eq!(
            st.light.defaults.accent_color,
            full_light.defaults.accent_color.unwrap(),
            "inactive light variant should get accent from full preset"
        );
        assert_eq!(
            st.light.defaults.background_color,
            full_light.defaults.background_color.unwrap(),
            "inactive light variant should get background from full preset"
        );
    }

    // --- run_pipeline with preset-as-reader (GNOME double-merge test) ---

    #[test]
    fn test_run_pipeline_with_preset_as_reader() {
        // Simulates GNOME sync fallback: adwaita used as both reader and preset.
        // Double-merge is harmless: merge is idempotent for matching values.
        let reader = reader_from_preset("adwaita");
        let result = run_pipeline(reader, "adwaita", crate::ColorMode::Light);
        assert!(
            result.is_ok(),
            "double-merge with same preset should succeed"
        );
        let st = result.unwrap();
        assert_eq!(st.name, "Adwaita");
    }

    // --- Single/Dual contract tests ---

    #[test]
    fn test_single_variant_fills_inactive_from_preset() {
        // Simulate KDE-style single-variant reader: only dark variant provided.
        // The pipeline should fill light from the full preset.
        let full = Theme::preset("kde-breeze").unwrap();
        let dark_v = full.dark.clone().unwrap();
        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(dark_v),
                is_dark: true,
            },
            name: "Breeze Dark".into(),
            icon_set: full.icon_set,
            layout: full.layout.clone(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let st = run_pipeline(reader, "kde-breeze-live", crate::ColorMode::Dark).unwrap();

        // Dark variant should have reader's data (merged with preset).
        // Light variant should come from the full preset (kde-breeze, not live).
        let full_light = Theme::preset("kde-breeze").unwrap().light.unwrap();
        assert_eq!(
            st.light.defaults.accent_color,
            full_light.defaults.accent_color.unwrap(),
            "Single: inactive light variant should come from full preset"
        );
        assert_eq!(st.mode, crate::ColorMode::Dark);
    }

    #[test]
    fn test_dual_variant_uses_both_from_reader() {
        // Simulate macOS-style dual-variant reader: both variants provided.
        // The pipeline should use BOTH reader variants (merged with preset).
        let full = Theme::preset("macos-sonoma").unwrap();
        let custom_light_accent = Rgba::rgb(42, 100, 200);
        let custom_dark_accent = Rgba::rgb(200, 50, 50);

        let mut light_v = full.light.clone().unwrap();
        light_v.defaults.accent_color = Some(custom_light_accent);
        let mut dark_v = full.dark.clone().unwrap();
        dark_v.defaults.accent_color = Some(custom_dark_accent);

        let reader = ReaderResult {
            output: ReaderOutput::Dual {
                light: Box::new(light_v),
                dark: Box::new(dark_v),
            },
            name: "macOS Sonoma".into(),
            icon_set: full.icon_set,
            layout: full.layout.clone(),
            font_dpi: Some(72.0),
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let st = run_pipeline(reader, "macos-sonoma-live", crate::ColorMode::Light).unwrap();

        // Both variants should reflect the reader's custom accents (merged).
        assert_eq!(
            st.light.defaults.accent_color, custom_light_accent,
            "Dual: light variant should have reader's light accent"
        );
        assert_eq!(
            st.dark.defaults.accent_color, custom_dark_accent,
            "Dual: dark variant should have reader's dark accent"
        );
    }

    // --- Phase 93-04 G4: Theme.icon_theme + three-tier precedence ---
    //
    // Per docs/todo_v0.5.7_gaps.md §G4 and doc 1 §20 Option C:
    //   Tier 1 (highest): ThemeMode::defaults.icon_theme (per-variant override)
    //   Tier 2:           Theme::icon_theme (shared across variants)
    //   Tier 3 (fallback): system_icon_theme() (runtime detect)

    /// Helper: construct a ReaderResult that carries only the active variant
    /// (light) with no per-variant icon_theme. The pipeline must then consult
    /// the preset's Theme-level icon_theme (tier 2) or system detect (tier 3).
    fn reader_with_empty_variant(is_dark: bool) -> ReaderResult {
        ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(ThemeMode::default()),
                is_dark,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        }
    }

    #[test]
    fn icon_theme_tier2_theme_level_used_when_per_variant_none() {
        // Adwaita preset (after G4 migration) carries icon_theme = "Adwaita"
        // at the Theme level, and None on both variant defaults.
        // With a reader that provides an empty variant (no per-variant override),
        // the resolver must fall through to tier 2 and produce "Adwaita".
        let reader = reader_with_empty_variant(false);
        let st = run_pipeline(reader, "adwaita", crate::ColorMode::Light).unwrap();
        assert_eq!(
            st.icon_theme.as_ref(),
            "Adwaita",
            "tier 2: Theme.icon_theme should be used when per-variant is None"
        );
    }

    #[test]
    fn icon_theme_tier1_per_variant_wins_over_theme_level() {
        // Construct a reader whose active variant explicitly sets a per-variant
        // icon_theme override. Even with a preset that carries a Theme-level
        // icon_theme, the per-variant override must win.
        let mut variant = ThemeMode::default();
        variant.defaults.icon_theme = Some(std::borrow::Cow::Borrowed("custom-override"));
        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(variant),
                is_dark: false,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };
        // Adwaita preset has Theme.icon_theme = "Adwaita" after migration.
        let st = run_pipeline(reader, "adwaita", crate::ColorMode::Light).unwrap();
        assert_eq!(
            st.icon_theme.as_ref(),
            "custom-override",
            "tier 1: per-variant icon_theme override must win over Theme-level"
        );
    }

    #[test]
    fn icon_theme_kde_per_variant_values_still_win() {
        // Regression guard for Phase 80-fix: KDE Breeze uses per-variant icon_theme
        // values ("breeze" light / "breeze-dark" dark) that MUST continue to win
        // over any Theme-level value. The kde-breeze preset keeps per-variant-only.
        let kde_full = Theme::preset("kde-breeze").unwrap();
        // Simulate KDE reader providing the dark variant with its per-variant value.
        let dark_v = kde_full.dark.clone().unwrap();
        assert_eq!(
            dark_v.defaults.icon_theme.as_deref(),
            Some("breeze-dark"),
            "precondition: kde-breeze dark variant must carry breeze-dark"
        );
        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(dark_v),
                is_dark: true,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };
        let st = run_pipeline(reader, "kde-breeze-live", crate::ColorMode::Dark).unwrap();
        assert_eq!(
            st.icon_theme.as_ref(),
            "breeze-dark",
            "KDE per-variant icon_theme must still win (Phase 80-fix invariant)"
        );
    }

    #[test]
    fn theme_icon_theme_round_trips_when_some() {
        // Serialize a Theme with icon_theme: Some(...) and assert the
        // deserialized round-trip preserves the value.
        let theme = Theme {
            name: std::borrow::Cow::Borrowed("RoundTrip"),
            light: Some(ThemeMode::default()),
            dark: None,
            layout: LayoutTheme::default(),
            icon_set: None,
            icon_theme: Some(std::borrow::Cow::Borrowed("lucide")),
        };
        let toml_str = theme.to_toml().expect("serialize");
        let reparsed = Theme::from_toml(&toml_str).expect("deserialize");
        assert_eq!(
            reparsed.icon_theme.as_deref(),
            Some("lucide"),
            "Theme.icon_theme must round-trip through TOML"
        );
        // Verify the serialized form contains the key at the top level.
        assert!(
            toml_str.contains("icon_theme = \"lucide\""),
            "serialized TOML should contain top-level icon_theme, got:\n{toml_str}"
        );
    }

    #[test]
    fn theme_icon_theme_skipped_when_none() {
        // Serialize a Theme with icon_theme: None and assert the TOML does NOT
        // emit the key (skip_serializing_if = Option::is_none).
        let theme = Theme {
            name: std::borrow::Cow::Borrowed("NoIcon"),
            light: Some(ThemeMode::default()),
            dark: None,
            layout: LayoutTheme::default(),
            icon_set: None,
            icon_theme: None,
        };
        let toml_str = theme.to_toml().expect("serialize");
        assert!(
            !toml_str.contains("icon_theme"),
            "serialized TOML should NOT contain icon_theme when None, got:\n{toml_str}"
        );
    }

    #[test]
    fn lint_toml_accepts_top_level_icon_theme() {
        // lint_toml() must NOT warn about icon_theme at the top level.
        // Raw string uses ##"..."## because the TOML body contains `"#` hex colors.
        let toml_str = r##"
name = "Test"
icon_theme = "lucide"

[light.defaults]
accent_color = "#0066cc"
"##;
        let warnings = Theme::lint_toml(toml_str).expect("lint");
        assert!(
            !warnings.iter().any(|w| w.contains("icon_theme")),
            "lint_toml must not flag top-level icon_theme as unknown; warnings: {warnings:?}"
        );
    }

    /// §11.1: `SystemTheme.layout` is the reader's layout merged field-wise over
    /// the preset's. On the preset-only path the reader *is* the full preset, so
    /// the result equals full ⊕ live ⊕ full.
    #[test]
    fn system_theme_layout_is_the_merged_preset_layout() -> crate::Result<()> {
        let reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
        let sys = run_pipeline(reader, "adwaita-live", crate::ColorMode::Light)?;

        let mut expected = Theme::preset("adwaita")?.layout;
        expected.merge(&Theme::preset("adwaita-live")?.layout);
        expected.merge(&Theme::preset("adwaita")?.layout);

        assert_eq!(sys.layout, expected);
        assert!(
            sys.layout.widget_gap.is_some(),
            "adwaita defines all four layout keys (spec §1.3)"
        );
        Ok(())
    }
}

// =============================================================================
// Plan 94-03 (G8): ThemeReader trait + select_reader regression tests
// =============================================================================
//
// These tests lock the contract of the G8 ThemeReader refactor:
// - the `ThemeReader` trait exists under `crate::reader` and is object-safe
// - `select_reader()` exists and returns the correct platform-specific impl
//
// Object-safety is the load-bearing property: `select_reader()` is declared
// to return `Option<Box<dyn ThemeReader>>`, which only compiles if the trait
// is object-safe. On current stable Rust (1.95), native `async fn` in traits
// is NOT object-safe for `dyn Trait`; the trait definition must use
// `#[async_trait::async_trait]` to produce a `Pin<Box<dyn Future + Send>>`
// return type that vtables can hold. If an implementer deviates from the
// async-trait strategy (e.g., tries native async-fn-in-trait), the coercion
// below fails to compile with "the trait cannot be made into an object" —
// this is the structural enforcement of Option A (see plan 94-03 objective).
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod theme_reader_trait_tests {
    /// Trait object-safety probe. After Task 2 lands with
    /// `#[async_trait::async_trait]` on the trait definition, this coercion
    /// compiles because the macro rewrite produces `Pin<Box<dyn Future + Send + '_>>`
    /// return types (vtable-compatible).
    ///
    /// Before Task 2 lands: fails to compile (`unresolved module crate::reader`).
    #[test]
    fn theme_reader_trait_exists_and_is_object_safe() {
        // Plain function that requires its argument to be ?Sized — compile-time
        // proof that `Box<dyn ThemeReader>` is a valid trait object.
        //
        // `#[allow(dead_code)]` is required because on cfg permutations that
        // exclude every concrete reader (e.g. linux without kde feature) the
        // function is only name-resolved by the compiler but never called.
        #[allow(dead_code)]
        fn assert_object_safe<T: ?Sized>(_: &T) {}

        // Use one of the concrete readers to construct the trait object on
        // the platforms where one exists. If the trait or the reader struct
        // does not exist yet, this fails to compile before Task 2.
        #[cfg(all(target_os = "linux", feature = "kde"))]
        {
            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::kde::KdeReader);
            assert_object_safe(&r);
        }
        #[cfg(all(target_os = "macos", feature = "macos"))]
        {
            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::macos::MacosReader);
            assert_object_safe(&r);
        }
        #[cfg(all(target_os = "windows", feature = "windows"))]
        {
            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::windows::WindowsReader);
            assert_object_safe(&r);
        }
        // Without any active-platform feature we still want the test body to
        // compile; reference the trait path once so name resolution fires
        // regardless of cfg.
        let _: Option<&dyn crate::reader::ThemeReader> = None;
    }

    /// `select_reader()` exists, is async, and returns an
    /// `Option<(Box<dyn ThemeReader>, &'static str)>`.
    ///
    /// On each platform with an available backend we expect `Some((_, live_preset))`;
    /// on platforms without one (non-Linux/macOS/Windows, or Linux with no
    /// compiled-in backend, or Linux-other-DE without portal) we expect `None`.
    ///
    /// The companion `&'static str` is the `-live` preset name that `run_pipeline`
    /// should use — kept in the same return type because the preset is chosen
    /// from the DE detected by `select_reader` (KDE -> kde-breeze-live, GNOME ->
    /// adwaita-live, macOS -> macos-sonoma-live, Windows -> windows-11-live).
    #[test]
    fn select_reader_returns_platform_specific_impl() {
        // Call select_reader and observe the Option. The structural invariant
        // is that the function exists, is callable from a sync context via
        // `pollster::block_on`, and returns the (reader, preset_live) tuple.
        let picked: Option<(Box<dyn crate::reader::ThemeReader>, &'static str)> =
            pollster::block_on(super::select_reader());

        // Every cfg branch borrows `picked` (via `&picked`) rather than moving
        // it, so the final `drop(picked)` consumes it uniformly on all
        // permutations -- including linux-without-kde, which has no branch.
        #[cfg(all(target_os = "macos", feature = "macos"))]
        {
            assert!(
                picked.is_some(),
                "select_reader must return Some on macOS+macos"
            );
            if let Some((_reader, preset)) = &picked {
                assert_eq!(*preset, "macos-sonoma-live");
            }
        }
        #[cfg(all(target_os = "windows", feature = "windows"))]
        {
            assert!(
                picked.is_some(),
                "select_reader must return Some on windows+windows"
            );
            if let Some((_reader, preset)) = &picked {
                assert_eq!(*preset, "windows-11-live");
            }
        }
        #[cfg(all(target_os = "linux", feature = "kde", feature = "portal"))]
        {
            // On linux+kde+portal, select_reader returns Some(GnomePortalKdeReader, "kde-breeze-live")
            // whenever the active DE is KDE; for non-KDE DEs it may legitimately
            // return None (preset fallback). Assert the tuple shape regardless.
            if let Some((_reader, preset)) = &picked {
                assert!(
                    *preset == "kde-breeze-live" || *preset == "adwaita-live",
                    "select_reader on linux must return a known -live preset, got: {preset}"
                );
            }
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            assert!(
                picked.is_none(),
                "select_reader() must return None on unsupported platforms"
            );
        }
        drop(picked);
    }
}