makeover 5.4.0

Shared theme loading for the make-family apps: TOML theme files parsed into intent-based color tokens, with perceptual derivations and WCAG contrast.
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
//! Loading and parsing theme files.

use crate::{
    BASE_INTENTS, COLOR_SECTIONS, Emphasis, Rgb, STEP_FLOOR, SemanticTokens, ThemeColors,
    ThemeDirs, ThemeMeta, Variant, find_theme_path, resolve, tonal, wcag_contrast,
};
use serde::Serialize;
use std::borrow::{Borrow, Cow};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};

// Names this module's prose links to, resolved for rustdoc.
#[allow(unused_imports)]
use crate::ansi_intent;

/// The longest theme id accepted, in bytes.
const MAX_THEME_ID: usize = 64;

/// Whether `id` is a theme id: 1 to 64 ASCII letters, digits, `-` or `_`.
const fn well_formed(id: &str) -> bool {
    let bytes = id.as_bytes();
    if bytes.is_empty() || bytes.len() > MAX_THEME_ID {
        return false;
    }
    let mut at = 0;
    while at < bytes.len() {
        let b = bytes[at];
        if !(b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
            return false;
        }
        at += 1;
    }
    true
}

/// A theme's id: the stem of its file, and the value a picker stores.
///
/// 1 to 64 ASCII letters, digits, `-` or `_`, checked once where the id is
/// made. ASCII rather than Unicode alphanumerics, because the id becomes a
/// file name and a CSS-adjacent token, and a filesystem that normalises `é`
/// two ways turns one id into two files. Empty is refused because `""` names
/// the file `.toml`. Holding one is holding an id that can name no path
/// outside its directory.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
#[serde(transparent)]
pub struct ThemeId(Cow<'static, str>);

impl ThemeId {
    /// An id from any string, if it is well formed.
    pub fn new(id: impl Into<String>) -> Result<Self, LoadError> {
        let id = id.into();
        if well_formed(&id) {
            Ok(Self(Cow::Owned(id)))
        } else {
            Err(LoadError::InvalidId(id))
        }
    }

    /// An id from a literal.
    ///
    /// # Panics
    ///
    /// If `id` is not well formed. In a `const` that is a compile error, which
    /// is how this is meant to be called:
    ///
    /// ```
    /// const HOUSE: makeover::ThemeId = makeover::ThemeId::from_static("akari-night");
    /// ```
    pub const fn from_static(id: &'static str) -> Self {
        assert!(well_formed(id), "not a theme id");
        Self(Cow::Borrowed(id))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

impl AsRef<str> for ThemeId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for ThemeId {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for ThemeId {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&str> for ThemeId {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

/// Why a theme could not be named, found, read or imported.
#[derive(Debug)]
#[non_exhaustive]
pub enum LoadError {
    /// Not a theme id. See [`ThemeId`].
    InvalidId(String),
    /// No theme by this id in the directories searched.
    NotFound(ThemeId),
    /// A filesystem operation failed.
    Io {
        /// What was being done: `read`, `create`, `copy`, `delete`.
        action: &'static str,
        path: PathBuf,
        source: std::io::Error,
    },
    /// The file is not TOML.
    Parse {
        /// The file, or the theme id for text with no file.
        origin: String,
        source: toml::de::Error,
    },
    /// An import with no colour section in it.
    NoColourSection,
    /// An import carrying a colour that does not parse.
    BadColour {
        /// `section.key`.
        key: String,
        value: String,
    },
    /// An import whose id is already a custom theme.
    AlreadyCustom(ThemeId),
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidId(id) => write!(f, "Invalid theme ID: {id:?}"),
            Self::NotFound(id) => write!(f, "Theme '{id}' not found"),
            Self::Io {
                action,
                path,
                source,
            } => write!(f, "Failed to {action} {}: {source}", path.display()),
            Self::Parse { origin, source } => write!(f, "Failed to parse {origin}: {source}"),
            Self::NoColourSection => write!(
                f,
                "Theme file must have at least one color section ({})",
                COLOR_SECTIONS.join(", ")
            ),
            Self::BadColour { key, value } => {
                write!(f, "Theme colour {key} is not a hex colour: {value:?}")
            }
            Self::AlreadyCustom(id) => write!(
                f,
                "A custom theme '{id}' already exists; delete it before importing a replacement"
            ),
        }
    }
}

impl std::error::Error for LoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::Parse { source, .. } => Some(source),
            _ => None,
        }
    }
}

fn io(action: &'static str, path: &Path) -> impl FnOnce(std::io::Error) -> LoadError {
    let path = path.to_path_buf();
    move |source| LoadError::Io {
        action,
        path,
        source,
    }
}

/// The largest theme file accepted, in bytes. Real themes are a few KiB; the
/// cap exists so a stray huge file or a device cannot stall a listing.
const MAX_THEME_BYTES: u64 = 16 * 1024 * 1024;

/// Read and parse one theme file. Every path that reads a theme goes through
/// here.
fn read_theme(path: &Path) -> Result<toml::Table, LoadError> {
    let content = read_theme_bytes(path)?;
    content.parse().map_err(|source| LoadError::Parse {
        origin: path.display().to_string(),
        source,
    })
}

/// Read one theme file with the guards every read path needs: the target must
/// be a regular file (a symlink to a device or a directory is refused) and no
/// larger than [`MAX_THEME_BYTES`].
fn read_theme_bytes(path: &Path) -> Result<String, LoadError> {
    let meta = std::fs::metadata(path).map_err(io("read", path))?;
    if !meta.is_file() {
        return Err(LoadError::Io {
            action: "read",
            path: path.to_path_buf(),
            source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a regular file"),
        });
    }
    if meta.len() > MAX_THEME_BYTES {
        return Err(LoadError::Io {
            action: "read",
            path: path.to_path_buf(),
            source: std::io::Error::new(std::io::ErrorKind::InvalidData, "theme file is too large"),
        });
    }
    std::fs::read_to_string(path).map_err(io("read", path))
}

/// The first value in `table` under a colour section that is not a colour, as
/// `section.key` and value.
///
/// What [`import_theme`] refuses on. A colour that does not parse is dropped by
/// [`resolve`] and the token falls back, and a non-string value under a colour
/// key never was a colour, so either would import, list and load, and then
/// quietly not look like the file.
fn unparseable_color(table: &toml::Table) -> Option<(String, String)> {
    COLOR_SECTIONS.iter().find_map(|section| {
        let sect = table.get(*section)?.as_table()?;
        sect.iter().find_map(|(key, val)| {
            let parses = val.as_str().and_then(Rgb::from_hex).is_some();
            (!parses).then(|| (format!("{section}.{key}"), val.to_string()))
        })
    })
}

/// Parse the `[meta]` section into `ThemeMeta`.
///
/// Falls back to the file ID as the name, and to dark for a variant that is
/// missing or names none of [`Variant`]'s.
pub fn parse_meta(id: &ThemeId, table: &toml::Table, is_custom: bool) -> ThemeMeta {
    let meta = table.get("meta").and_then(|m| m.as_table());
    let name = meta
        .and_then(|m| m.get("name"))
        .and_then(|v| v.as_str())
        .unwrap_or(id.as_str())
        .to_string();
    let variant = meta
        .and_then(|m| m.get("variant"))
        .and_then(|v| v.as_str())
        .map_or(Variant::Dark, Variant::from);

    ThemeMeta {
        id: id.clone(),
        name,
        variant,
        is_custom,
    }
}

/// Extract the intent color sections into a flat `HashMap` with dotted keys
/// like `"surface.page"`, `"status.danger"`, `"category.one"`.
///
/// The tonal steps of `content.primary` are filled in here rather than read, by
/// [`derive_tonal_steps`]. Anything a theme authored under those keys is
/// replaced.
pub fn extract_colors(table: &toml::Table) -> HashMap<String, String> {
    let mut colors = HashMap::new();
    for section in COLOR_SECTIONS {
        if let Some(sect) = table.get(*section).and_then(|s| s.as_table()) {
            for (key, val) in sect {
                if let Some(color) = val.as_str() {
                    colors.insert(format!("{section}.{key}"), color.to_string());
                }
            }
        }
    }
    derive_tonal_steps(&mut colors);
    colors
}

/// Fill in the tonal steps of `content.primary`, overwriting whatever the theme
/// authored under those keys.
///
/// # Why they are not authored
///
/// `content.secondary` and `content.muted` are not independent colours. They are
/// the ink, one step and two steps back, and a theme that names them separately
/// is stating three times something it stated once — which is how three of the
/// bundled themes came to author a `secondary` *lighter* than their own
/// `primary` (nord, solarized-dark) or identical to it (dracula), inverting the
/// emphasis ramp the whole vocabulary rests on. Deriving them makes
/// `content` > `content-secondary` > `content-muted` true by construction in
/// every theme, including one a user writes.
///
/// Applied at load rather than in [`resolve`] so that there is one answer: the
/// resolved token layer, the ANSI table ([`ansi_intent`] reads authored keys),
/// and every consumer holding a [`ThemeColors`] all see the same value. A
/// derivation visible from only one of those is how a terminal and a webview
/// come to disagree about what muted means.
///
/// Both keys need `content.primary` and `surface.page` to exist and parse. When
/// either is missing the step is skipped and anything authored is left where it
/// is, mirroring the skip-missing behaviour of the rest of the crate — a
/// half-written theme keeps whatever it has rather than losing it.
///
/// # The ratio is a starting point, not the answer
///
/// Each step is pushed further toward the page until it clears [`STEP_FLOOR`]
/// against the ink, so what the theme gets is a step that can be seen rather
/// than a step of the agreed size. The two are the same number in every bundled
/// theme but the two with a pure-black ink, where the ratio has no range to
/// travel in and the nominal step lands 3/255 from where it started.
pub fn derive_tonal_steps<S: std::hash::BuildHasher>(colors: &mut HashMap<String, String, S>) {
    let ink = colors.get("content.primary").and_then(|v| Rgb::from_hex(v));
    let page = colors.get("surface.page").and_then(|v| Rgb::from_hex(v));
    let (Some(ink), Some(page)) = (ink, page) else {
        return;
    };
    // Each step starts no nearer than the one before it landed, so pushing
    // secondary out cannot carry it past muted and invert the ramp.
    let mut reached = 0.0;
    for (key, step) in [
        ("content.secondary", Emphasis::Secondary),
        ("content.muted", Emphasis::Muted),
    ] {
        let (color, ratio) = step_clearing_floor(ink, page, step.ratio().max(reached));
        reached = ratio;
        colors.insert(key.to_string(), color.to_hex());
    }
}

/// The step `from` of the way from `ink` to `page`, pushed toward `page` until
/// it clears [`STEP_FLOOR`] against the ink it is a step of. Returns the colour
/// and the ratio it was found at.
///
/// A forward scan rather than a solve, because it wants the *first* ratio that
/// clears: contrast against the base rises with the distance travelled, but it
/// rises through sRGB's transfer curve and OKLab's chroma path, and a bisection
/// would trust a monotonicity nothing here guarantees.
///
/// Travel stops at the ground. A theme whose ink and page are the same colour
/// has no step to take, and the ground is the honest answer — nothing past it
/// is a step of the ink any more.
fn step_clearing_floor(ink: Rgb, page: Rgb, from: f32) -> (Rgb, f32) {
    // Finer than 8-bit sRGB can resolve on the shortest ramp in the corpus, so
    // the scan never steps over the first colour that clears.
    const PROBE: f32 = 0.005;
    let mut ratio = from.clamp(0.0, 1.0);
    loop {
        let color = tonal(ink, page, ratio);
        if wcag_contrast(color, ink) >= STEP_FLOOR || ratio >= 1.0 {
            return (color, ratio);
        }
        ratio = (ratio + PROBE).min(1.0);
    }
}

/// One theme file the scan kept: what it says about itself, and its contents.
pub(crate) struct Scanned {
    pub(crate) meta: ThemeMeta,
    pub(crate) table: toml::Table,
}

impl Scanned {
    pub(crate) fn colors(&self) -> ThemeColors {
        ThemeColors {
            meta: self.meta.clone(),
            colors: extract_colors(&self.table),
        }
    }
}

/// Every theme the search path offers, each file read and parsed once, by id.
///
/// The one walk over the directories. Later tiers override earlier ones by id,
/// the way [`find_theme_path`] resolves, so an id whose winning file is broken
/// is broken rather than served from a lower tier that [`load_theme`] would
/// never read.
pub(crate) fn scan(dirs: &ThemeDirs) -> (BTreeMap<ThemeId, Scanned>, Vec<(PathBuf, LoadError)>) {
    let mut seen: BTreeMap<ThemeId, Scanned> = BTreeMap::new();
    let mut broken_by_id: BTreeMap<ThemeId, (PathBuf, LoadError)> = BTreeMap::new();
    let mut broken: Vec<(PathBuf, LoadError)> = Vec::new();

    for (dir, is_custom) in dirs.search_path() {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        let mut paths: Vec<PathBuf> = entries
            .filter_map(|entry| Some(entry.ok()?.path()))
            .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("toml"))
            .collect();
        paths.sort();

        for path in paths {
            let stem = path
                .file_stem()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_default();
            let id = match ThemeId::new(stem) {
                Ok(id) => id,
                Err(error) => {
                    broken.push((path, error));
                    continue;
                }
            };
            match read_theme(&path) {
                Ok(table) => {
                    broken_by_id.remove(&id);
                    let meta = parse_meta(&id, &table, is_custom);
                    seen.insert(id, Scanned { meta, table });
                }
                Err(error) => {
                    seen.remove(&id);
                    broken_by_id.insert(id, (path, error));
                }
            }
        }
    }

    broken.extend(broken_by_id.into_values());
    broken.sort_by(|a, b| a.0.cmp(&b.0));
    (seen, broken)
}

/// What a scan of the theme directories found.
#[derive(Debug)]
pub struct Listed {
    /// Every theme that loads, sorted by name and then by id.
    pub themes: Vec<ThemeMeta>,
    /// Every `.toml` file that would not: an invalid stem, or a file that
    /// cannot be read or parsed. A user's custom directory is writable, and a
    /// theme that fails there is reported here rather than vanishing.
    pub broken: Vec<(PathBuf, LoadError)>,
}

/// Scan the search path for `.toml` theme files.
///
/// Later tiers override earlier ones by id. A file whose stem is not a valid
/// id, or which does not parse, is listed as [`Listed::broken`] rather than
/// offered: [`load_theme`] would refuse it.
pub fn list_themes_from_dirs(dirs: &ThemeDirs) -> Listed {
    let (seen, broken) = scan(dirs);
    let mut themes: Vec<ThemeMeta> = seen.into_values().map(|scanned| scanned.meta).collect();
    themes.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.id.cmp(&b.id)));
    Listed { themes, broken }
}

/// Parse a complete theme (metadata + colors) from raw TOML content, with no
/// filesystem access. For callers that embed themes at compile time.
pub fn parse_theme_str(
    id: &ThemeId,
    content: &str,
    is_custom: bool,
) -> Result<ThemeColors, LoadError> {
    let table: toml::Table = content.parse().map_err(|source| LoadError::Parse {
        origin: format!("theme '{id}'"),
        source,
    })?;
    let meta = parse_meta(id, &table, is_custom);
    let colors = extract_colors(&table);
    Ok(ThemeColors { meta, colors })
}

/// The file `id` resolves to, read and parsed, and whether it is custom.
fn read_by_id(dirs: &ThemeDirs, id: &ThemeId) -> Result<(toml::Table, bool), LoadError> {
    let (path, is_custom) =
        find_theme_path(dirs, id).ok_or_else(|| LoadError::NotFound(id.clone()))?;
    Ok((read_theme(&path)?, is_custom))
}

/// Load a complete theme (metadata + colors) by ID from the given directories.
pub fn load_theme(dirs: &ThemeDirs, id: &ThemeId) -> Result<ThemeColors, LoadError> {
    let (table, is_custom) = read_by_id(dirs, id)?;
    Ok(ThemeColors {
        meta: parse_meta(id, &table, is_custom),
        colors: extract_colors(&table),
    })
}

/// Load a theme and resolve it to the full intent token set in one step.
pub fn load_semantic(dirs: &ThemeDirs, id: &ThemeId) -> Result<SemanticTokens, LoadError> {
    Ok(resolve(&load_theme(dirs, id)?))
}

/// Import a theme TOML file into the custom themes directory.
///
/// Validates that the file is parseable TOML, that every value under a colour
/// section is a colour that parses, and that at least one of those colours
/// names an intent token, then writes it to `custom_dir/{id}.toml` atomically.
/// Returns the theme metadata.
///
/// Refuses an id that is already a custom theme rather than replacing it: an
/// import is not an edit, and a user importing a file that happens to share a
/// name with one they made would lose theirs without being asked. Deleting the
/// old one first is the way to replace it.
pub fn import_theme(source_path: &Path, custom_dir: &Path) -> Result<ThemeMeta, LoadError> {
    // Read the bytes once: what is validated below is what is written, so a
    // concurrent rewrite of the source cannot smuggle unvalidated content in.
    let content = read_theme_bytes(source_path)?;
    let table: toml::Table = content.parse().map_err(|source| LoadError::Parse {
        origin: source_path.display().to_string(),
        source,
    })?;

    // A non-string value under a colour key never was a colour, so it is as
    // wrong as one that does not parse.
    if let Some((key, value)) = unparseable_color(&table) {
        return Err(LoadError::BadColour { key, value });
    }
    // A theme that resolves to no intent colour is not a theme, however many
    // colour sections it declares: `extract_colors` keeps any string under a
    // colour section, including keys no token reads, so a file of only-unknown
    // keys would otherwise import, list and load and then render with none of
    // the colours it named.
    let colors = extract_colors(&table);
    let resolves = BASE_INTENTS
        .iter()
        .any(|(src, _)| colors.get(*src).and_then(|v| Rgb::from_hex(v)).is_some());
    if !resolves {
        return Err(LoadError::NoColourSection);
    }

    let stem = source_path
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    let id = ThemeId::new(stem)?;

    std::fs::create_dir_all(custom_dir).map_err(io("create", custom_dir))?;

    let dest = custom_dir.join(format!("{id}.toml"));
    if dest.exists() {
        return Err(LoadError::AlreadyCustom(id));
    }
    write_new_atomic(&dest, &content)?;

    Ok(parse_meta(&id, &table, true))
}

/// Delete a custom theme by ID.
///
/// Only operates on `custom_dir`: bundled themes are not deletable through
/// this entry point.
pub fn delete_theme(custom_dir: &Path, id: &ThemeId) -> Result<(), LoadError> {
    let path = custom_dir.join(format!("{id}.toml"));
    if !path.is_file() {
        return Err(LoadError::NotFound(id.clone()));
    }
    std::fs::remove_file(&path).map_err(io("delete", &path))
}

/// A four-color preview for theme thumbnails: the representative swatch from
/// each of the principal roles.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemePreview {
    pub meta: ThemeMeta,
    /// Page background (`surface.page`).
    pub background: Option<String>,
    /// Body text (`content.primary`).
    pub foreground: Option<String>,
    /// Brand/interactive color (`action.primary`).
    pub accent: Option<String>,
    /// Divider/outline color (`line.border`).
    pub border: Option<String>,
}

fn color_at(table: &toml::Table, section: &str, key: &str) -> Option<String> {
    table
        .get(section)
        .and_then(|s| s.as_table())
        .and_then(|s| s.get(key))
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string)
}

/// Load just the preview swatches for a theme, for UI thumbnails.
pub fn load_theme_preview(dirs: &ThemeDirs, id: &ThemeId) -> Result<ThemePreview, LoadError> {
    let (table, is_custom) = read_by_id(dirs, id)?;
    Ok(ThemePreview {
        meta: parse_meta(id, &table, is_custom),
        background: color_at(&table, "surface", "page"),
        foreground: color_at(&table, "content", "primary"),
        accent: color_at(&table, "action", "primary"),
        border: color_at(&table, "line", "border"),
    })
}

/// Export a theme to a user-chosen path.
pub fn export_theme(dirs: &ThemeDirs, id: &ThemeId, dest_path: &Path) -> Result<(), LoadError> {
    let (source, _) = find_theme_path(dirs, id).ok_or_else(|| LoadError::NotFound(id.clone()))?;
    // `fs::copy` truncates the destination before writing, so exporting a theme
    // onto its own file destroys it. Refuse rather than copy a file onto itself.
    if same_file(&source, dest_path) {
        return Err(LoadError::Io {
            action: "copy",
            path: dest_path.to_path_buf(),
            source: std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "source and destination are the same file",
            ),
        });
    }
    std::fs::copy(&source, dest_path).map_err(io("copy", dest_path))?;
    Ok(())
}

/// Whether `a` and `b` name the same file. False when either does not exist,
/// so an export destination that is not there yet never compares equal.
fn same_file(a: &Path, b: &Path) -> bool {
    std::fs::canonicalize(a)
        .ok()
        .zip(std::fs::canonicalize(b).ok())
        .is_some_and(|(a, b)| a == b)
}

/// Write `content` to `dest` without leaving a partial file or following a
/// symlink at the destination: the bytes go to a fresh temp file in the same
/// directory, which is then renamed over `dest`. A rename does not follow a
/// destination symlink, so a planted symlink cannot make the import write
/// outside the custom directory, and a partial write leaves nothing at `dest`
/// for a retry to trip over.
fn write_new_atomic(dest: &Path, content: &str) -> Result<(), LoadError> {
    use std::io::Write;
    let tmp = dest.with_extension(format!("tmp-{}", std::process::id()));
    let result = (|| -> std::io::Result<()> {
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp)?;
        file.write_all(content.as_bytes())?;
        file.sync_all()?;
        std::fs::rename(&tmp, dest)
    })();
    if let Err(source) = result {
        let _ = std::fs::remove_file(&tmp);
        return Err(LoadError::Io {
            action: "write",
            path: dest.to_path_buf(),
            source,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fixture::nord_toml;
    #[allow(unused_imports)]
    use crate::{ThemeDirs, ThemeId, Token};
    use crate::{bundled_themes_dir, embedded_themes};
    use std::fs;

    fn bundled(dir: &Path) -> ThemeDirs {
        ThemeDirs::new().bundled(Some(dir.to_path_buf()))
    }

    fn custom(dir: &Path) -> ThemeDirs {
        ThemeDirs::new().custom(Some(dir.to_path_buf()))
    }

    // ---- id validation ----

    #[test]
    fn a_theme_id_is_ascii_letters_digits_hyphens_and_underscores() {
        for good in ["darkmode", "Theme123", "dark-mode", "my_theme_v2"] {
            assert!(ThemeId::new(good).is_ok(), "{good}");
        }
        assert!(ThemeId::new("a".repeat(MAX_THEME_ID)).is_ok());
    }

    #[test]
    fn a_theme_id_cannot_name_a_path_or_be_empty_long_or_unicode() {
        for bad in [
            "../etc/passwd",
            "foo/bar",
            "theme.toml",
            "",
            "caf\u{e9}",
            "\u{65e5}\u{672c}",
            "my theme",
        ] {
            assert!(
                matches!(ThemeId::new(bad), Err(LoadError::InvalidId(_))),
                "{bad:?}"
            );
        }
        assert!(ThemeId::new("a".repeat(MAX_THEME_ID + 1)).is_err());
    }

    #[test]
    fn a_static_id_is_checked_at_compile_time() {
        const HOUSE: ThemeId = ThemeId::from_static("akari-night");
        assert_eq!(HOUSE, "akari-night");
        assert_eq!(HOUSE, ThemeId::new("akari-night").unwrap());
    }

    #[test]
    #[should_panic(expected = "not a theme id")]
    fn a_static_id_that_is_not_one_panics() {
        let _ = ThemeId::from_static("../evil");
    }

    #[test]
    fn listing_reports_what_cannot_load_and_orders_ties_by_id() {
        let dir = tempfile::tempdir().unwrap();
        let body = "[meta]\nname = \"Same\"\n[surface]\npage = \"#000000\"\n";
        for stem in ["zeta", "alpha", "my theme", "caf\u{e9}"] {
            fs::write(dir.path().join(format!("{stem}.toml")), body).unwrap();
        }
        fs::write(dir.path().join("torn.toml"), "this is not = = toml").unwrap();
        let dirs = custom(dir.path());
        let listed = list_themes_from_dirs(&dirs);
        let ids: Vec<&str> = listed.themes.iter().map(|m| m.id.as_str()).collect();
        assert_eq!(ids, ["alpha", "zeta"]);
        for meta in &listed.themes {
            load_theme(&dirs, &meta.id).unwrap();
        }

        // A user's broken theme is said, not dropped.
        let mut broken: Vec<(String, bool)> = listed
            .broken
            .iter()
            .map(|(path, error)| {
                (
                    path.file_name().unwrap().to_string_lossy().into_owned(),
                    matches!(error, LoadError::InvalidId(_)),
                )
            })
            .collect();
        broken.sort();
        assert_eq!(
            broken,
            [
                ("caf\u{e9}.toml".to_string(), true),
                ("my theme.toml".to_string(), true),
                ("torn.toml".to_string(), false),
            ]
        );
    }

    #[test]
    fn a_broken_override_is_broken_rather_than_served_from_below() {
        let low = tempfile::tempdir().unwrap();
        let high = tempfile::tempdir().unwrap();
        fs::write(low.path().join("mine.toml"), "[meta]\nname = \"Low\"\n").unwrap();
        fs::write(high.path().join("mine.toml"), "not = = toml").unwrap();
        let dirs = ThemeDirs::new()
            .bundled(Some(low.path().to_path_buf()))
            .custom(Some(high.path().to_path_buf()));
        let listed = list_themes_from_dirs(&dirs);
        assert!(
            listed.themes.is_empty(),
            "load_theme would read the broken one"
        );
        assert_eq!(listed.broken.len(), 1);
        assert!(load_theme(&dirs, &ThemeId::from_static("mine")).is_err());
    }

    #[test]
    fn a_load_error_keeps_its_cause() {
        use std::error::Error as _;
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("torn.toml"), "not = = toml").unwrap();
        let err = load_theme(&bundled(dir.path()), &ThemeId::from_static("torn")).unwrap_err();
        assert!(matches!(err, LoadError::Parse { .. }), "{err}");
        assert!(err.source().is_some());
        assert!(err.to_string().contains("torn.toml"), "{err}");
    }

    #[test]
    fn import_refuses_an_unparseable_colour_and_names_it() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();
        let src = src_dir.path().join("typo.toml");
        fs::write(&src, "[surface]\npage = \"#1a1b2g\"\n").unwrap();
        let err = import_theme(&src, custom_dir.path()).unwrap_err();
        assert!(
            matches!(&err, LoadError::BadColour { key, .. } if key == "surface.page"),
            "{err}"
        );
        assert!(!custom_dir.path().join("typo.toml").exists());
    }

    #[test]
    fn import_refuses_to_replace_an_existing_custom_theme() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();
        let mine = custom_dir.path().join("shared.toml");
        fs::write(&mine, "[surface]\npage = \"#111111\"\n").unwrap();
        let src = src_dir.path().join("shared.toml");
        fs::write(&src, "[surface]\npage = \"#222222\"\n").unwrap();
        let err = import_theme(&src, custom_dir.path()).unwrap_err();
        assert!(matches!(err, LoadError::AlreadyCustom(_)), "{err}");
        assert!(fs::read_to_string(&mine).unwrap().contains("#111111"));
    }

    #[test]
    fn every_embedded_theme_would_import() {
        for (id, content) in embedded_themes() {
            let table: toml::Table = content.parse().unwrap();
            assert_eq!(unparseable_color(&table), None, "{id}");
        }
    }

    // ---- meta ----

    #[test]
    fn parse_meta_with_name_and_variant() {
        let table: toml::Table = "[meta]\nname = \"Nord\"\nvariant = \"light\"\n"
            .parse()
            .unwrap();
        let meta = parse_meta(&ThemeId::from_static("nord"), &table, false);
        assert_eq!(meta.id, "nord");
        assert_eq!(meta.name, "Nord");
        assert_eq!(meta.variant, Variant::Light);
        assert!(!meta.is_custom);
    }

    #[test]
    fn parse_meta_defaults_to_id_and_dark() {
        let table: toml::Table = "".parse().unwrap();
        let meta = parse_meta(&ThemeId::from_static("fallback"), &table, true);
        assert_eq!(meta.name, "fallback");
        assert_eq!(meta.variant, Variant::Dark);
        assert!(meta.is_custom);
    }

    #[test]
    fn extract_colors_reads_intent_sections() {
        let table: toml::Table = nord_toml().parse().unwrap();
        let colors = extract_colors(&table);
        assert_eq!(colors.get("surface.page").unwrap(), "#2e3440");
        assert_eq!(colors.get("content.primary").unwrap(), "#d8dee9");
        assert_eq!(colors.get("action.primary").unwrap(), "#81a1c1");
        assert_eq!(colors.get("status.danger").unwrap(), "#bf616a");
        assert_eq!(colors.get("line.border").unwrap(), "#4c566a");
        assert_eq!(colors.get("category.five").unwrap(), "#b48ead");
        assert_eq!(colors.len(), 19);
    }

    #[test]
    fn every_shipped_theme_ramps_one_way() {
        // The property authoring the steps separately could not hold: three
        // themes had shipped a secondary lighter than their own primary, so a
        // renderer reading the emphasis order got the reverse of it.
        for (id, toml) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::new(id).unwrap(), toml, false).unwrap();
            let t = resolve(&theme);
            let page = t.color(Token::SurfacePage).unwrap();
            let steps = [Token::Content, Token::ContentSecondary, Token::ContentMuted]
                .map(|k| wcag_contrast(t.color(k).unwrap(), page));
            assert!(
                steps[0] > steps[1] && steps[1] > steps[2],
                "{id}: emphasis does not fall monotonically: {steps:?}"
            );
        }
    }

    #[test]
    fn every_shipped_theme_takes_a_visible_first_step() {
        // The property that was missing when 2.6.0 derived these, and the
        // reason a pure-black ink shipped a secondary 3/255 away from it: the
        // ramp falling monotonically says nothing about how far it falls, and
        // a step nobody can see is not a step.
        for (id, toml) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::new(id).unwrap(), toml, false).unwrap();
            let t = resolve(&theme);
            let ink = t.color(Token::Content).unwrap();
            let secondary = t.color(Token::ContentSecondary).unwrap();
            let step = wcag_contrast(ink, secondary);
            assert!(
                step >= STEP_FLOOR,
                "{id}: secondary is {step:.2} from its ink, under the {STEP_FLOOR} floor"
            );
        }
    }

    #[test]
    fn an_authored_emphasis_step_does_not_survive_loading() {
        // `nord_toml` still authors both, because a user's theme file might and
        // the answer has to be the same one.
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        assert_ne!(theme.colors.get("content.muted").unwrap(), "#616e88");
        assert_ne!(theme.colors.get("content.secondary").unwrap(), "#e5e9f0");
    }

    #[test]
    fn a_theme_with_no_page_keeps_what_it_authored() {
        // Skip-missing: there is nothing to read the step against, so the step
        // is not taken and a half-written theme does not lose a colour.
        let mut colors = HashMap::new();
        colors.insert("content.primary".to_string(), "#d8dee9".to_string());
        colors.insert("content.muted".to_string(), "#616e88".to_string());
        derive_tonal_steps(&mut colors);
        assert_eq!(colors.get("content.muted").unwrap(), "#616e88");
    }

    // ---- loading / fs ----

    #[test]
    fn load_and_resolve_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
        let t = load_semantic(&bundled(dir.path()), &ThemeId::from_static("nord")).unwrap();
        assert_eq!(t.meta.name, "Nord");
        assert_eq!(t.hex(Token::Action).as_deref(), Some("#81a1c1"));
    }

    #[test]
    fn load_theme_reports_an_id_it_cannot_find() {
        let err = load_theme(&ThemeDirs::new(), &ThemeId::from_static("ghost")).unwrap_err();
        assert!(matches!(err, LoadError::NotFound(_)), "{err}");
    }

    #[test]
    fn list_themes_from_dirs_finds_toml_files() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("t.toml"), "[meta]\nname = \"T\"\n").unwrap();
        fs::write(dir.path().join("x.txt"), "ignored").unwrap();
        let themes = list_themes_from_dirs(&bundled(dir.path())).themes;
        assert_eq!(themes.len(), 1);
        assert_eq!(themes[0].id, "t");
    }

    #[test]
    fn import_theme_valid_and_rejects_empty() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();

        let good = src_dir.path().join("my-theme.toml");
        fs::write(&good, "[surface]\npage = \"#1a1b26\"\n").unwrap();
        let meta = import_theme(&good, custom_dir.path()).unwrap();
        assert_eq!(meta.id, "my-theme");
        assert!(custom_dir.path().join("my-theme.toml").exists());

        let empty = src_dir.path().join("empty.toml");
        fs::write(&empty, "[meta]\nname = \"E\"\n").unwrap();
        assert!(import_theme(&empty, custom_dir.path()).is_err());
    }

    #[test]
    fn import_refuses_a_theme_that_resolves_to_no_colour() {
        // `extract_colors` keeps any string under a colour section, so a file
        // whose keys are all unknown parsed as having colours and imported
        // cleanly, then resolved to no intent token and rendered blank.
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();
        let src = src_dir.path().join("nokey.toml");
        fs::write(&src, "[surface]\nbanana = \"#ffffff\"\n").unwrap();
        let err = import_theme(&src, custom_dir.path()).unwrap_err();
        assert!(matches!(err, LoadError::NoColourSection), "{err}");
        assert!(!custom_dir.path().join("nokey.toml").exists());
    }

    #[test]
    fn import_accepts_a_theme_with_one_known_colour_among_unknowns() {
        // An unknown key beside a real one is the skip-missing behaviour the
        // rest of the crate has: the unknown key is ignored, not a refusal.
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();
        let src = src_dir.path().join("mixed-keys.toml");
        fs::write(
            &src,
            "[surface]\nbanana = \"#ffffff\"\n[content]\nprimary = \"#111111\"\n",
        )
        .unwrap();
        let meta = import_theme(&src, custom_dir.path()).unwrap();
        assert_eq!(meta.id, "mixed-keys");
    }

    #[test]
    fn import_theme_rejects_invalid_toml() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();
        let src = src_dir.path().join("bad.toml");
        fs::write(&src, "this is not [valid toml [[[").unwrap();
        assert!(import_theme(&src, custom_dir.path()).is_err());
    }

    #[test]
    fn import_refuses_a_non_string_colour_value() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();
        let src = src_dir.path().join("mixed.toml");
        fs::write(
            &src,
            "[surface]\npage = \"#1a1b26\"\n[content]\nprimary = 0xffffff\n",
        )
        .unwrap();
        let err = import_theme(&src, custom_dir.path()).unwrap_err();
        assert!(
            matches!(&err, LoadError::BadColour { key, .. } if key == "content.primary"),
            "{err}"
        );
        assert!(!custom_dir.path().join("mixed.toml").exists());
    }

    #[test]
    fn a_symlink_to_a_device_is_rejected_not_read() {
        let dir = tempfile::tempdir().unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::symlink;
            symlink("/dev/zero", dir.path().join("zero.toml")).unwrap();
            let listed = list_themes_from_dirs(&bundled(dir.path()));
            assert!(listed.themes.is_empty());
            assert_eq!(listed.broken.len(), 1);
        }
    }

    #[test]
    fn delete_theme_removes_and_guards() {
        let custom = tempfile::tempdir().unwrap();
        let path = custom.path().join("doomed.toml");
        fs::write(&path, "[surface]\npage = \"#000\"\n").unwrap();
        delete_theme(custom.path(), &ThemeId::from_static("doomed")).unwrap();
        assert!(!path.exists());
        assert!(delete_theme(custom.path(), &ThemeId::from_static("ghost")).is_err());
    }

    #[test]
    fn export_theme_copies_file() {
        let src_dir = tempfile::tempdir().unwrap();
        let dest_dir = tempfile::tempdir().unwrap();
        let content = "[meta]\nname = \"E\"\n[surface]\npage = \"#ffffff\"\n";
        fs::write(src_dir.path().join("e.toml"), content).unwrap();
        let dirs = bundled(src_dir.path());
        let dest = dest_dir.path().join("out.toml");
        export_theme(&dirs, &ThemeId::from_static("e"), &dest).unwrap();
        assert_eq!(fs::read_to_string(&dest).unwrap(), content);
        assert!(export_theme(&dirs, &ThemeId::from_static("missing"), &dest).is_err());
    }

    #[test]
    fn export_theme_refuses_to_copy_onto_itself() {
        let src_dir = tempfile::tempdir().unwrap();
        let content = "[surface]\npage = \"#ffffff\"\n";
        let path = src_dir.path().join("e.toml");
        fs::write(&path, content).unwrap();
        let dirs = bundled(src_dir.path());
        let err = export_theme(&dirs, &ThemeId::from_static("e"), &path).unwrap_err();
        assert!(matches!(err, LoadError::Io { .. }), "{err}");
        assert_eq!(fs::read_to_string(&path).unwrap(), content);
    }

    #[test]
    fn load_theme_preview_returns_role_swatches() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
        let p = load_theme_preview(&bundled(dir.path()), &ThemeId::from_static("nord")).unwrap();
        assert_eq!(p.background.as_deref(), Some("#2e3440")); // surface.page
        assert_eq!(p.foreground.as_deref(), Some("#d8dee9")); // content.primary
        assert_eq!(p.accent.as_deref(), Some("#81a1c1")); // action.primary
        assert_eq!(p.border.as_deref(), Some("#4c566a")); // line.border
    }

    #[test]
    fn every_shipped_theme_loads() {
        // Guards the data, not just the loader: a malformed or truncated
        // .toml in themes/ is a shipping bug, and it should fail here rather
        // than at a user's first launch.
        let dirs = ThemeDirs::new().bundled(bundled_themes_dir());
        let listed = list_themes_from_dirs(&dirs);
        assert!(listed.broken.is_empty(), "{:?}", listed.broken);
        let themes = listed.themes;
        assert!(
            themes.len() >= 30,
            "expected the full theme set, got {}",
            themes.len()
        );
        for meta in &themes {
            load_theme(&dirs, &meta.id)
                .unwrap_or_else(|e| panic!("shipped theme `{}` failed to load: {e}", meta.id));
        }
    }
}