Skip to main content

egui_pop_tokens/
kit.rs

1//! Kits as packages (`docs/kit-packages.md`): a folder holding a kit's
2//! tokens, its fonts and its licence, read at run time or embedded in the
3//! binary.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! ```text
9//! underline-tabs/
10//!   kit.yaml            a DTCG token file, like a theme (`$extends`, tokens);
11//!                       `kit.json` is read too
12//!   *.tokens.yaml       optional: more tokens, one file per component
13//!                       (`.tokens.json` is read too)
14//!   fonts/*.ttf|otf     optional: faces for the families the tokens name
15//!   LICENSE             optional: the kit's licence (and its fonts')
16//!   icons/              reserved: not read yet
17//! ```
18//!
19//! `kit.yaml` is a theme: its name is the folder's, unless its manifest
20//! (`$extensions."org.egui-pop.kit"`) gives one, and it extends `pop-dark`
21//! unless it says otherwise. A face's family and weight come from its
22//! file name (`Inter-SemiBold.ttf` is `Inter` at 600), or from the
23//! manifest when given:
24//!
25//! ```yaml
26//! $extends: "pop-dark"
27//! $extensions:
28//!   org.egui-pop.kit:
29//!     name: "brand"
30//!     label: "Brand"
31//!     fonts:
32//!       - {file: "JetBrainsMono-Regular.ttf", family: "JetBrains Mono", weight: 400}
33//! ```
34//!
35//! A kit may hold both variants of its look, light and dark: the
36//! manifest's `counterpart` gives the other variant's name, label and
37//! tokens (a token tree, with its own `$extends`). It becomes a theme of
38//! its own, each naming the other as its counterpart
39//! ([`crate::VARIANT_OF_EXTENSION`]), so the light, dark or system
40//! setting switches between them. `kit.yaml`'s own tokens are its
41//! variant's only; the other token files (`*.tokens.yaml`) and the faces
42//! serve both.
43//!
44//! ```yaml
45//! $extends: "pop-dark"
46//! $extensions:
47//!   org.egui-pop.kit:
48//!     name: "brand-dark"
49//!     label: "Brand Dark"
50//!     counterpart:
51//!       name: "brand-light"
52//!       label: "Brand Light"
53//!       tokens:
54//!         $extends: "pop-light"
55//!         surface: {panel: {$type: "color", $value: "#fafafa"}}
56//! surface: {panel: {$type: "color", $value: "#101010"}}
57//! ```
58//!
59//! Reading a kit never fails: what is wrong (bad YAML or JSON, a term outside the
60//! vocabulary, a font file missing) is in [`KitData::problems`], and the
61//! kit is still usable with fallbacks (a kit whose `kit.yaml` cannot be
62//! read is `pop-dark` under the kit's name).
63//!
64//! ```
65//! let kit = egui_pop_tokens::kit::KitData::from_text(
66//!     "underline",
67//!     r#"
68//!     tab:
69//!       shape: {$type: "string", $value: "underline"}
70//!     "#,
71//! );
72//! assert!(egui_pop_tokens::kit::check(&kit).is_empty());
73//! let mut themes = egui_pop_tokens::Themes::default();
74//! themes.add_kit(&kit);
75//! assert!(themes.get("underline").is_some());
76//! ```
77
78use std::borrow::Cow;
79use std::collections::BTreeSet;
80use std::fmt;
81use std::path::{Path, PathBuf};
82
83use serde_json::Value as Json;
84
85use crate::cache::Cache;
86use crate::contract::{kit_contract, required};
87use crate::theme::{BUILT_IN_THEMES, FALLBACK_THEME, ThemeSpec, Themes};
88use crate::{Error, TokenFile, Warning};
89
90/// The file every kit folder has.
91pub const KIT_FILE: &str = "kit.yaml";
92
93/// The names a kit folder's [`KIT_FILE`] may have, the first found read.
94pub const KIT_FILES: &[&str] = &["kit.yaml", "kit.yml", "kit.json"];
95
96/// The endings of a kit's other token files.
97pub const TOKEN_FILE_ENDINGS: &[&str] = &[".tokens.yaml", ".tokens.yml", ".tokens.json"];
98
99/// Where a kit's manifest lives in `kit.yaml`'s root `$extensions`.
100pub const KIT_EXTENSION: &str = "org.egui-pop.kit";
101
102/// The folder under an application's configuration directory where the
103/// user's kits are found ([`discover`]).
104pub const USER_KITS_DIR: &str = "kits";
105
106/// The six states (`docs/kit.md`), in the order their boxes apply.
107pub const STATES: [&str; 6] = ["rest", "selected", "hover", "focus", "active", "disabled"];
108
109/// The terms a state gives (`component.state.term`), with their type.
110pub const STATE_TERMS: &[(&str, &str)] = &[
111    ("fill", "color"),
112    ("border-color", "color"),
113    ("border-width", "dimension"),
114    ("radius", "dimension"),
115    ("text", "color"),
116    ("indicator-color", "color"),
117    ("indicator-size", "dimension"),
118    ("ring-color", "color"),
119    ("ring-width", "dimension"),
120    ("ring-offset", "dimension"),
121];
122
123/// The terms that do not change with the state (`component.term`), with
124/// their type.
125pub const COMPONENT_TERMS: &[(&str, &str)] = &[
126    ("based-on", "string"),
127    ("shape", "string"),
128    ("padding-x", "dimension"),
129    ("padding-y", "dimension"),
130    ("height", "dimension"),
131    ("width", "dimension"),
132    ("font-size", "dimension"),
133    ("offset", "dimension"),
134    ("offset-x", "dimension"),
135    ("indicator-side", "string"),
136    ("align", "string"),
137    ("opacity", "number"),
138    ("buttons-side", "string"),
139    ("buttons-hover", "string"),
140    ("corners", "string"),
141    ("shadow-offset-x", "dimension"),
142    ("shadow-offset-y", "dimension"),
143    ("shadow-blur", "dimension"),
144    ("shadow-spread", "dimension"),
145    ("shadow-color", "color"),
146    ("margin", "dimension"),
147    ("margin-track", "dimension"),
148    ("separator-inset", "dimension"),
149    ("placement", "string"),
150    ("visibility", "string"),
151    ("track-fill", "color"),
152];
153
154/// The tones a component may give (`component.tone.<tone>.<term>` and
155/// `component.tone.<tone>.<state>.<term>`).
156pub const TONES: [&str; 7] = [
157    "accent", "info", "success", "warning", "danger", "muted", "record",
158];
159
160/// Glyph roles that must keep shapes of their own (`glyph.<role>`), so
161/// that colour never carries a state alone: no two roles of a pair may
162/// name the same icon. The LEDs off, on, warning and error differ from
163/// each other, a busy LED from all but the on one (it pulses, or shows a
164/// still ring under reduced motion), and the four named flags from each
165/// other. [`check`] reports a kit breaking it, and egui-pop draws its own
166/// shapes for those roles.
167pub const DISTINCT_GLYPHS: &[(&str, &str)] = &[
168    ("check", "indeterminate"),
169    ("led-off", "led-on"),
170    ("led-off", "led-warning"),
171    ("led-off", "led-error"),
172    ("led-on", "led-warning"),
173    ("led-on", "led-error"),
174    ("led-warning", "led-error"),
175    ("led-busy", "led-off"),
176    ("led-busy", "led-warning"),
177    ("led-busy", "led-error"),
178    ("flag-modified", "flag-pinned"),
179    ("flag-modified", "flag-required"),
180    ("flag-modified", "flag-invalid"),
181    ("flag-pinned", "flag-required"),
182    ("flag-pinned", "flag-invalid"),
183    ("flag-required", "flag-invalid"),
184];
185
186/// The pairs of [`DISTINCT_GLYPHS`] naming the same icon in a resolved
187/// theme, with that icon's name.
188pub fn same_glyphs(theme: &crate::ResolvedTokens) -> Vec<(&'static str, &'static str, String)> {
189    let name = |role: &str| match theme.value(&format!("glyph.{role}")) {
190        Some(crate::Value::Other(serde_json::Value::String(s))) => Some(s.clone()),
191        _ => None,
192    };
193    DISTINCT_GLYPHS
194        .iter()
195        .filter_map(|(a, b)| match (name(a), name(b)) {
196            (Some(x), Some(y)) if x == y => Some((*a, *b, x)),
197            _ => None,
198        })
199        .collect()
200}
201
202/// A font file's bytes: embedded in the binary or read at run time.
203pub type Bytes = Cow<'static, [u8]>;
204
205/// A face a kit ships, for the families its tokens name.
206#[derive(Clone, PartialEq)]
207pub struct KitFont {
208    /// Its file name under `fonts/`.
209    pub file: String,
210    /// The family a theme names it by (`font.family.ui`).
211    pub family: String,
212    /// 100 to 900, as CSS numbers weights.
213    pub weight: u16,
214    pub bytes: Bytes,
215}
216
217impl fmt::Debug for KitFont {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        f.debug_struct("KitFont")
220            .field("file", &self.file)
221            .field("family", &self.family)
222            .field("weight", &self.weight)
223            .field("bytes", &self.bytes.len())
224            .finish()
225    }
226}
227
228/// Where a kit was read from.
229#[derive(Clone, Debug, PartialEq, Eq)]
230pub enum Origin {
231    /// Embedded in the binary ([`kit!`](crate::kit!)); the folder it was
232    /// embedded from, as the macro named it.
233    Embedded(&'static str),
234    /// Read from a folder at run time.
235    Dir(PathBuf),
236}
237
238/// What is wrong with a kit. The kit is usable anyway: each problem says
239/// what is done instead.
240#[derive(Clone, Debug, PartialEq)]
241#[non_exhaustive]
242pub enum Problem {
243    /// A file could not be read.
244    Io { file: String, message: String },
245    /// A token file is not valid YAML or JSON, or not a token file: its
246    /// tokens are left out (all of them for `kit.yaml`: the kit is its
247    /// base theme).
248    Tokens(Error),
249    /// Two of the kit's files give the same token: the first one read
250    /// (`kit.yaml`, then the others by name) is kept.
251    Repeated { path: String, file: String },
252    /// A token file other than `kit.yaml` says what it extends: only
253    /// `kit.yaml` does.
254    Extends { file: String },
255    /// A token of a kit component with a term outside the vocabulary
256    /// (`docs/kit.md`): no component reads it.
257    UnknownTerm { path: String, reason: String },
258    /// A token shaped `component.state.term` for a component no kit has.
259    UnknownComponent { path: String, component: String },
260    /// A term given with another type than the vocabulary's: the
261    /// component reads nothing there.
262    TermType {
263        path: String,
264        expected: String,
265        found: String,
266    },
267    /// The manifest (`$extensions."org.egui-pop.kit"`) is not as expected:
268    /// that part of it is ignored.
269    Manifest { reason: String },
270    /// A face could not be used: it is left out, and the families naming
271    /// it fall back (`egui_pop_core::fonts`).
272    Font { file: String, reason: String },
273    /// The kit's name is a built-in theme's: it is used with `-kit`
274    /// added, so the built-in theme is not replaced.
275    Name { asked: String, used: String },
276    /// A token file's compiled form could not be kept in the cache
277    /// ([`crate::cache`]): it was read uncached, and is parsed again
278    /// next time.
279    NotCached { file: String, reason: String },
280    /// A part of the folder egui-pop does not read yet.
281    NotRead { what: String },
282    /// A token file of the kit was read otherwise than written, by its
283    /// format stamp ([`crate::FormatStamp`]): stamped newer than this
284    /// egui-pop (read best-effort), a stamp that cannot be read, or a
285    /// token renamed since the contract it was written for (read under
286    /// its new name). Kit files load as theme files do, with warnings.
287    Format { file: String, warning: Warning },
288    /// A problem of the theme the kit resolves to ([`check`]).
289    Theme(Error),
290    /// Two glyph roles of [`DISTINCT_GLYPHS`] name the same icon: two
291    /// states would differ by colour alone, so egui-pop draws its own
292    /// shapes for them.
293    SameGlyph {
294        roles: (String, String),
295        icon: String,
296    },
297}
298
299impl fmt::Display for Problem {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        match self {
302            Problem::Io { file, message } => write!(f, "`{file}`: cannot be read: {message}"),
303            Problem::Tokens(e) => write!(f, "{e}: its tokens are left out"),
304            Problem::Repeated { path, file } => {
305                write!(f, "`{file}` gives `{path}` again: the first value is kept")
306            }
307            Problem::Extends { file } => write!(
308                f,
309                "`{file}` has `$extends`: only the kit file says what the kit extends, ignored"
310            ),
311            Problem::UnknownTerm { path, reason } => {
312                write!(f, "`{path}`: {reason}; nothing reads it")
313            }
314            Problem::UnknownComponent { path, component } => write!(
315                f,
316                "`{path}`: no kit component is named `{component}`; nothing reads it"
317            ),
318            Problem::TermType {
319                path,
320                expected,
321                found,
322            } => write!(
323                f,
324                "`{path}` is a {found}, the vocabulary says {expected}; nothing reads it"
325            ),
326            Problem::Manifest { reason } => write!(f, "manifest: {reason}"),
327            Problem::Font { file, reason } => write!(f, "font `{file}`: {reason}; left out"),
328            Problem::Name { asked, used } => write!(
329                f,
330                "the kit's name `{asked}` is a built-in theme's: it is `{used}`"
331            ),
332            Problem::NotCached { file, reason } => {
333                write!(f, "`{file}`: read uncached: {reason}")
334            }
335            Problem::NotRead { what } => write!(f, "{what} is not read yet"),
336            Problem::Format { file, warning } => write!(f, "`{file}`: {warning}"),
337            Problem::Theme(e) => write!(f, "theme: {e}"),
338            Problem::SameGlyph { roles, icon } => write!(
339                f,
340                "`glyph.{}` and `glyph.{}` both name `{icon}`: their states would differ by colour alone; egui-pop's own shapes are drawn",
341                roles.0, roles.1
342            ),
343        }
344    }
345}
346
347impl std::error::Error for Problem {}
348
349/// What [`kit!`](crate::kit!) embeds: the folder's files, named as in the
350/// folder.
351#[derive(Clone, Debug)]
352pub struct Embedded {
353    /// The folder, as the macro named it.
354    pub dir: &'static str,
355    /// `kit.yaml` (or `kit.json`).
356    pub kit: &'static str,
357    /// Other token files: their name and text.
358    pub tokens: Vec<(String, &'static str)>,
359    /// Faces: their file name under `fonts/` and their bytes.
360    pub fonts: Vec<(&'static str, &'static [u8])>,
361    pub license: Option<&'static str>,
362}
363
364/// A kit's data: its tokens (a theme), its faces and its licence, with
365/// what was wrong reading them. A kit with code adds its handlers
366/// around it (`egui_pop_core::kit::KitSource`).
367#[derive(Clone, Debug, PartialEq)]
368pub struct KitData {
369    /// Its theme's name; the theme picker lists it under it.
370    pub name: String,
371    /// A name for people, from the manifest.
372    pub label: Option<String>,
373    /// The kit's tokens: a theme named [`KitData::name`].
374    pub theme: TokenFile,
375    /// The kit's other variant, light or dark, when its manifest gives
376    /// one (`counterpart`): a theme of its own, each naming the other as
377    /// its counterpart.
378    pub counterpart: Option<KitVariant>,
379    pub fonts: Vec<KitFont>,
380    pub license: Option<String>,
381    pub origin: Origin,
382    /// Fonts the manifest names, to check embedded kits against.
383    manifest_fonts: Vec<String>,
384    problems: Vec<Problem>,
385}
386
387impl KitData {
388    /// Reads a kit folder (see the module). Never fails: what could not
389    /// be read is in [`KitData::problems`].
390    ///
391    /// Its YAML files go through the default cache ([`crate::cache`]):
392    /// read again unchanged, they are not parsed again.
393    pub fn load(dir: impl AsRef<Path>) -> KitData {
394        KitData::load_with(dir, &crate::cache::default())
395    }
396
397    /// [`KitData::load`] through a given cache ([`crate::cache::Cache`]).
398    /// An entry that cannot be written is a [`Problem::NotCached`]: the
399    /// kit is read all the same.
400    pub fn load_with(dir: impl AsRef<Path>, cache: &Cache) -> KitData {
401        let dir = dir.as_ref();
402        let mut problems = Vec::new();
403        let read = |file: &Path| {
404            std::fs::read_to_string(file).map_err(|e| Problem::Io {
405                file: file.display().to_string(),
406                message: e.to_string(),
407            })
408        };
409        let mut not_cached = Vec::new();
410        let mut parse = |name: &str, path: &Path| {
411            let text = read(path)?;
412            let (file, unwritten) = TokenFile::parse_cached(name, &text, path, cache);
413            if let Some(e) = unwritten {
414                not_cached.push(Problem::NotCached {
415                    file: name.to_string(),
416                    reason: e.to_string(),
417                });
418            }
419            file.map_err(Problem::Tokens)
420        };
421        let kit = parse(
422            KIT_FILE,
423            &kit_file(dir).unwrap_or_else(|| dir.join(KIT_FILE)),
424        );
425        let mut tokens = Vec::new();
426        let mut fonts = Vec::new();
427        let mut license = None;
428        let mut icons = false;
429        match std::fs::read_dir(dir) {
430            Ok(entries) => {
431                let mut names: Vec<(String, PathBuf)> = entries
432                    .filter_map(Result::ok)
433                    .map(|e| (e.file_name().to_string_lossy().into_owned(), e.path()))
434                    .collect();
435                names.sort();
436                for (name, path) in names {
437                    if TOKEN_FILE_ENDINGS.iter().any(|e| name.ends_with(e)) {
438                        let file = parse(&name, &path);
439                        tokens.push((name, file));
440                    } else if license.is_none()
441                        && matches!(name.as_str(), "LICENSE" | "LICENSE.txt" | "LICENSE.md")
442                    {
443                        match read(&path) {
444                            Ok(text) => license = Some(text),
445                            Err(p) => problems.push(p),
446                        }
447                    } else if name == "icons" {
448                        icons = true;
449                    }
450                }
451            }
452            Err(e) => problems.push(Problem::Io {
453                file: dir.display().to_string(),
454                message: e.to_string(),
455            }),
456        }
457        let fonts_dir = dir.join("fonts");
458        if let Ok(entries) = std::fs::read_dir(&fonts_dir) {
459            let mut files: Vec<(String, PathBuf)> = entries
460                .filter_map(Result::ok)
461                .map(|e| (e.file_name().to_string_lossy().into_owned(), e.path()))
462                .filter(|(n, _)| is_font_file(n))
463                .collect();
464            files.sort();
465            for (name, path) in files {
466                match std::fs::read(&path) {
467                    Ok(bytes) => fonts.push((name, Bytes::Owned(bytes))),
468                    Err(e) => problems.push(Problem::Font {
469                        file: name,
470                        reason: e.to_string(),
471                    }),
472                }
473            }
474        }
475        problems.extend(not_cached);
476        if icons {
477            problems.push(Problem::NotRead {
478                what: "icons/".into(),
479            });
480        }
481        let folder = dir
482            .file_name()
483            .map_or_else(|| "kit".into(), |n| n.to_string_lossy().into_owned());
484        assemble(
485            &folder,
486            Origin::Dir(dir.to_path_buf()),
487            kit,
488            tokens,
489            fonts,
490            license,
491            problems,
492        )
493    }
494
495    /// A kit embedded in the binary (what [`kit!`](crate::kit!) gives).
496    pub fn embedded(e: Embedded) -> KitData {
497        let folder = e
498            .dir
499            .trim_end_matches(['/', '\\'])
500            .rsplit(['/', '\\'])
501            .next()
502            .filter(|n| !n.is_empty() && *n != "." && *n != "..")
503            .unwrap_or("kit")
504            .to_string();
505        assemble(
506            &folder,
507            Origin::Embedded(e.dir),
508            TokenFile::parse(KIT_FILE, e.kit).map_err(Problem::Tokens),
509            e.tokens
510                .into_iter()
511                .map(|(n, t)| {
512                    let file = TokenFile::parse(&n, t).map_err(Problem::Tokens);
513                    (n, file)
514                })
515                .collect(),
516            e.fonts
517                .into_iter()
518                .map(|(n, b)| (n.to_string(), Bytes::Borrowed(b)))
519                .collect(),
520            e.license.map(String::from),
521            Vec::new(),
522        )
523    }
524
525    /// A data-only kit from the text of its `kit.yaml` (or `kit.json`),
526    /// under a name (the manifest's wins).
527    pub fn from_text(name: &str, kit_text: &str) -> KitData {
528        assemble(
529            name,
530            Origin::Embedded(""),
531            TokenFile::parse(KIT_FILE, kit_text).map_err(Problem::Tokens),
532            Vec::new(),
533            Vec::new(),
534            None,
535            Vec::new(),
536        )
537    }
538
539    /// What was wrong reading the kit, in the order met; empty for a
540    /// clean kit. [`check`] adds the problems of the theme it resolves to.
541    pub fn problems(&self) -> &[Problem] {
542        &self.problems
543    }
544
545    /// The kit's name for people: its label, else its name.
546    pub fn display_name(&self) -> &str {
547        self.label.as_deref().unwrap_or(&self.name)
548    }
549
550    /// The kit and its other variant, if it has one, as a theme picker
551    /// lists them: a theme each.
552    pub fn infos(&self) -> Vec<KitInfo> {
553        let mut v = vec![self.info()];
554        if let Some(c) = &self.counterpart {
555            v.push(KitInfo {
556                name: c.name.clone(),
557                label: c.display_name().to_string(),
558                description: c.theme.description.clone(),
559                origin: self.origin.clone(),
560                problems: self.problems.len(),
561            });
562        }
563        v
564    }
565
566    /// The kit as a theme picker lists it (its own variant; see
567    /// [`KitData::infos`]).
568    pub fn info(&self) -> KitInfo {
569        KitInfo {
570            name: self.name.clone(),
571            label: self.display_name().to_string(),
572            description: self.theme.description.clone(),
573            origin: self.origin.clone(),
574            problems: self.problems.len(),
575        }
576    }
577}
578
579/// A kit's other variant ([`KitData::counterpart`]): the manifest's
580/// `counterpart`, with the kit's other token files merged in.
581#[derive(Clone, Debug, PartialEq)]
582pub struct KitVariant {
583    /// Its theme's name.
584    pub name: String,
585    /// A name for people, from the manifest.
586    pub label: Option<String>,
587    /// Its tokens: a theme named [`KitVariant::name`].
588    pub theme: TokenFile,
589}
590
591impl KitVariant {
592    /// The variant's name for people: its label, else its name.
593    pub fn display_name(&self) -> &str {
594        self.label.as_deref().unwrap_or(&self.name)
595    }
596}
597
598/// A kit as a theme picker shows it.
599#[derive(Clone, Debug, PartialEq, Eq)]
600pub struct KitInfo {
601    /// The theme's name, for `ThemeSpec::new`.
602    pub name: String,
603    pub label: String,
604    /// `kit.yaml`'s `$description`.
605    pub description: Option<String>,
606    pub origin: Origin,
607    /// How many problems reading it met.
608    pub problems: usize,
609}
610
611impl Themes {
612    /// Adds a kit's theme (replacing a theme of the same name, returned),
613    /// and its other variant's when it has one. Its faces and handlers
614    /// are installed by `egui_pop_core::kit::KitSource` or
615    /// `AppBuilder::kit`.
616    pub fn add_kit(&mut self, kit: &KitData) -> Option<TokenFile> {
617        if let Some(c) = &kit.counterpart {
618            self.add(c.theme.clone());
619        }
620        self.add(kit.theme.clone())
621    }
622}
623
624/// Every problem of a kit: reading it, and resolving its theme over the
625/// built-in ones. An application's tests call it on the kits it embeds,
626/// since [`kit!`](crate::kit!) checks nothing when compiling:
627///
628/// ```
629/// let kit = egui_pop_tokens::kit::KitData::from_text(
630///     "k",
631///     r##"
632///     tab:
633///       rest:
634///         fil: {$type: "color", $value: "#000000"}
635///     "##,
636/// );
637/// let problems = egui_pop_tokens::kit::check(&kit);
638/// assert_eq!(problems.len(), 1, "{problems:?}");
639/// ```
640pub fn check(kit: &KitData) -> Vec<Problem> {
641    let mut problems = kit.problems.clone();
642    if let Origin::Embedded(_) = kit.origin {
643        for file in &kit.manifest_fonts {
644            if !kit.fonts.iter().any(|f| &f.file == file) {
645                problems.push(Problem::Font {
646                    file: file.clone(),
647                    reason: "named by the manifest but not embedded (add it to kit!'s fonts)"
648                        .into(),
649                });
650            }
651        }
652    }
653    let mut themes = Themes::default();
654    themes.add_kit(kit);
655    let names = std::iter::once(&kit.name).chain(kit.counterpart.as_ref().map(|c| &c.name));
656    for name in names {
657        let resolved = themes.resolve(&ThemeSpec::new(name.clone()));
658        problems.extend(resolved.problems().iter().cloned().map(Problem::Theme));
659        problems.extend(same_glyphs(&resolved).into_iter().map(|(a, b, icon)| {
660            Problem::SameGlyph {
661                roles: (a.into(), b.into()),
662                icon,
663            }
664        }));
665    }
666    problems
667}
668
669/// The kits found in a folder: each sub-folder holding a `kit.yaml`, by
670/// name (anything else is not a kit and is skipped). An application's
671/// user kits are in `<config>/kits` ([`USER_KITS_DIR`]); a folder that
672/// does not exist has none.
673pub fn discover(dir: impl AsRef<Path>) -> Vec<KitData> {
674    discover_with(dir, &crate::cache::default())
675}
676
677/// [`discover`] through a given cache ([`KitData::load_with`]).
678pub fn discover_with(dir: impl AsRef<Path>, cache: &Cache) -> Vec<KitData> {
679    let Ok(entries) = std::fs::read_dir(dir) else {
680        return Vec::new();
681    };
682    let mut dirs: Vec<PathBuf> = entries
683        .filter_map(Result::ok)
684        .map(|e| e.path())
685        .filter(|p| kit_file(p).is_some())
686        .collect();
687    dirs.sort();
688    dirs.iter().map(|d| KitData::load_with(d, cache)).collect()
689}
690
691/// The default kit: `themes/kit/`, read by the same code as any kit
692/// folder. `Themes::default` layers its tokens into `pop-dark`.
693pub(crate) fn built_in(files: &[(&str, &'static str)]) -> KitData {
694    KitData::embedded(Embedded {
695        dir: "themes/kit",
696        // Compiled to JSON by `build.rs`, as the token files are.
697        kit: include_str!(concat!(env!("OUT_DIR"), "/themes/kit/kit.json")),
698        tokens: files
699            .iter()
700            .map(|(component, text)| (format!("{component}.tokens.yaml"), *text))
701            .collect(),
702        fonts: Vec::new(),
703        license: None,
704    })
705}
706
707/// A kit folder's [`KIT_FILE`], under the first of [`KIT_FILES`] found.
708pub fn kit_file(dir: impl AsRef<Path>) -> Option<PathBuf> {
709    let dir = dir.as_ref();
710    KIT_FILES
711        .iter()
712        .map(|name| dir.join(name))
713        .find(|p| p.is_file())
714}
715
716fn is_font_file(name: &str) -> bool {
717    let lower = name.to_ascii_lowercase();
718    [".ttf", ".otf", ".ttc"].iter().any(|e| lower.ends_with(e))
719}
720
721fn assemble(
722    folder: &str,
723    origin: Origin,
724    kit: Result<TokenFile, Problem>,
725    tokens: Vec<(String, Result<TokenFile, Problem>)>,
726    fonts: Vec<(String, Bytes)>,
727    license: Option<String>,
728    mut problems: Vec<Problem>,
729) -> KitData {
730    // Each file says what it was written for (one stamp per file), and
731    // is brought to the current contract before the files are merged.
732    let upgrade = |file: &str, part: &mut TokenFile, problems: &mut Vec<Problem>| {
733        problems.extend(part.upgrade().into_iter().map(|warning| Problem::Format {
734            file: file.to_string(),
735            warning,
736        }));
737    };
738    let mut theme = match kit {
739        Ok(mut file) => {
740            upgrade(KIT_FILE, &mut file, &mut problems);
741            file
742        }
743        Err(p) => {
744            problems.push(p);
745            TokenFile::new(KIT_FILE)
746        }
747    };
748    let mut parts = Vec::new();
749    for (file, part) in tokens {
750        match part {
751            Ok(mut part) => {
752                upgrade(&file, &mut part, &mut problems);
753                parts.push((file, part));
754            }
755            Err(p) => problems.push(p),
756        }
757    }
758    for (file, part) in &parts {
759        if part.extends.is_some() {
760            problems.push(Problem::Extends { file: file.clone() });
761        }
762    }
763    merge_parts(&mut theme, &parts, &mut problems);
764    let mut manifest = Manifest::read(&theme, &mut problems);
765    let asked = manifest.name.clone().unwrap_or_else(|| folder.to_string());
766    let name = if BUILT_IN_THEMES.contains(&asked.as_str()) {
767        let used = format!("{asked}-kit");
768        problems.push(Problem::Name {
769            asked,
770            used: used.clone(),
771        });
772        used
773    } else {
774        asked
775    };
776    theme.name = name.clone();
777    if theme.extends.is_none() {
778        theme.extends = Some(FALLBACK_THEME.to_string());
779    }
780    problems.extend(vocabulary(&theme));
781    let counterpart = manifest
782        .counterpart
783        .take()
784        .and_then(|c| counterpart(&mut theme, c, &parts, &mut problems));
785    let mut faces = Vec::new();
786    for entry in &manifest.fonts {
787        if !fonts.iter().any(|(f, _)| f == &entry.file) && matches!(origin, Origin::Dir(_)) {
788            problems.push(Problem::Font {
789                file: entry.file.clone(),
790                reason: "named by the manifest, not in fonts/".into(),
791            });
792        }
793    }
794    for (file, bytes) in fonts {
795        let (family, weight) = match manifest.fonts.iter().find(|e| e.file == file) {
796            Some(e) => (e.family.clone(), e.weight),
797            None => match face_from_file_name(&file) {
798                Ok(fw) => fw,
799                Err((fw, reason)) => {
800                    problems.push(Problem::Font {
801                        file: file.clone(),
802                        reason: format!(
803                            "{reason}: kept as `{}` at {} (name it in the manifest)",
804                            fw.0, fw.1
805                        ),
806                    });
807                    fw
808                }
809            },
810        };
811        if bytes.len() < 12 || !looks_like_font(&bytes) {
812            problems.push(Problem::Font {
813                file,
814                reason: "not a TrueType or OpenType file".into(),
815            });
816            continue;
817        }
818        faces.push(KitFont {
819            file,
820            family,
821            weight,
822            bytes,
823        });
824    }
825    KitData {
826        name,
827        label: manifest.label,
828        theme,
829        counterpart,
830        fonts: faces,
831        license,
832        origin,
833        manifest_fonts: manifest.fonts.into_iter().map(|e| e.file).collect(),
834        problems,
835    }
836}
837
838/// Merges the kit's other token files into a variant's tokens: what the
839/// variant gives itself is kept, and the repeat reported.
840fn merge_parts(theme: &mut TokenFile, parts: &[(String, TokenFile)], problems: &mut Vec<Problem>) {
841    for (file, part) in parts {
842        for (path, token) in &part.tokens {
843            match theme.tokens.entry(path.clone()) {
844                std::collections::btree_map::Entry::Occupied(e) => {
845                    problems.push(Problem::Repeated {
846                        path: e.key().clone(),
847                        file: file.clone(),
848                    });
849                }
850                std::collections::btree_map::Entry::Vacant(e) => {
851                    e.insert(token.clone());
852                }
853            }
854        }
855    }
856}
857
858/// The kit's other variant from its manifest's `counterpart`: its tokens
859/// with the kit's other token files merged in, both variants naming each
860/// other ([`crate::VARIANT_OF_EXTENSION`]). `None`, and a problem, when
861/// it cannot be used.
862fn counterpart(
863    theme: &mut TokenFile,
864    c: ManifestCounterpart,
865    parts: &[(String, TokenFile)],
866    problems: &mut Vec<Problem>,
867) -> Option<KitVariant> {
868    let refuse = |problems: &mut Vec<Problem>, reason: String| {
869        problems.push(Problem::Manifest {
870            reason: format!("`counterpart`: {reason}; the kit has one variant"),
871        });
872        None
873    };
874    if c.name == theme.name {
875        return refuse(problems, format!("`{}` is the kit's own name", c.name));
876    }
877    if BUILT_IN_THEMES.contains(&c.name.as_str()) {
878        return refuse(problems, format!("`{}` is a built-in theme's name", c.name));
879    }
880    let mut file = match TokenFile::from_tree(&c.name, &c.tokens) {
881        Ok(f) => f,
882        Err(e) => return refuse(problems, e.to_string()),
883    };
884    let label = format!("{KIT_FILE} (counterpart)");
885    problems.extend(file.upgrade().into_iter().map(|warning| Problem::Format {
886        file: label.clone(),
887        warning,
888    }));
889    merge_parts(&mut file, parts, problems);
890    if file.extends.is_none() {
891        file.extends = Some(FALLBACK_THEME.to_string());
892    }
893    problems.extend(vocabulary(&file));
894    file.set_extension(
895        crate::VARIANT_OF_EXTENSION,
896        Some(Json::String(theme.name.clone())),
897    );
898    theme.set_extension(
899        crate::VARIANT_OF_EXTENSION,
900        Some(Json::String(file.name.clone())),
901    );
902    Some(KitVariant {
903        name: c.name,
904        label: c.label,
905        theme: file,
906    })
907}
908
909/// The first bytes of a TrueType, OpenType or collection file.
910pub(crate) fn looks_like_font(bytes: &[u8]) -> bool {
911    bytes.len() >= 4
912        && matches!(
913            &bytes[..4],
914            [0, 1, 0, 0] | b"OTTO" | b"true" | b"ttcf" | b"typ1"
915        )
916}
917
918#[derive(Default)]
919struct Manifest {
920    name: Option<String>,
921    label: Option<String>,
922    fonts: Vec<ManifestFont>,
923    counterpart: Option<ManifestCounterpart>,
924}
925
926/// The manifest's `counterpart`: the other variant's name, label and
927/// token tree.
928struct ManifestCounterpart {
929    name: String,
930    label: Option<String>,
931    tokens: Json,
932}
933
934struct ManifestFont {
935    file: String,
936    family: String,
937    weight: u16,
938}
939
940impl Manifest {
941    fn read(theme: &TokenFile, problems: &mut Vec<Problem>) -> Manifest {
942        let mut m = Manifest::default();
943        let Some(raw) = theme.extensions.as_ref().and_then(|x| x.get(KIT_EXTENSION)) else {
944            return m;
945        };
946        let Some(obj) = raw.as_object() else {
947            problems.push(Problem::Manifest {
948                reason: "is not an object".into(),
949            });
950            return m;
951        };
952        let mut text = |key: &str| match obj.get(key) {
953            None => None,
954            Some(Json::String(s)) if !s.trim().is_empty() => Some(s.clone()),
955            Some(other) => {
956                problems.push(Problem::Manifest {
957                    reason: format!("`{key}`: `{other}` is not a name"),
958                });
959                None
960            }
961        };
962        m.name = text("name");
963        m.label = text("label");
964        if let Some(name) = &m.name
965            && name.contains(['/', '\\', '{', '}'])
966        {
967            problems.push(Problem::Manifest {
968                reason: format!("`name`: `{name}` may not contain `/`, `\\`, `{{` or `}}`"),
969            });
970            m.name = None;
971        }
972        match obj.get("fonts") {
973            None => {}
974            Some(Json::Array(entries)) => {
975                for (i, entry) in entries.iter().enumerate() {
976                    let file = entry.get("file").and_then(Json::as_str);
977                    let family = entry.get("family").and_then(Json::as_str);
978                    let weight = match entry.get("weight") {
979                        None => Some(400),
980                        Some(w) => w
981                            .as_u64()
982                            .filter(|w| (1..=1000).contains(w))
983                            .and_then(|w| u16::try_from(w).ok()),
984                    };
985                    match (file, family, weight) {
986                        (Some(file), Some(family), Some(weight)) => m.fonts.push(ManifestFont {
987                            file: file.into(),
988                            family: family.into(),
989                            weight,
990                        }),
991                        _ => problems.push(Problem::Manifest {
992                            reason: format!(
993                                "`fonts[{i}]` needs a `file`, a `family` and a `weight` from 1 to 1000"
994                            ),
995                        }),
996                    }
997                }
998            }
999            Some(_) => problems.push(Problem::Manifest {
1000                reason: "`fonts` is not a list".into(),
1001            }),
1002        }
1003        match obj.get("counterpart") {
1004            None => {}
1005            Some(Json::Object(c)) => {
1006                let text = |key: &str| {
1007                    c.get(key)
1008                        .and_then(Json::as_str)
1009                        .map(str::trim)
1010                        .filter(|s| !s.is_empty())
1011                        .map(String::from)
1012                };
1013                match (text("name"), c.get("tokens")) {
1014                    (Some(name), _) if name.contains(['/', '\\', '{', '}']) => {
1015                        problems.push(Problem::Manifest {
1016                            reason: format!(
1017                                "`counterpart.name`: `{name}` may not contain `/`, `\\`, `{{` or `}}`; the kit has one variant"
1018                            ),
1019                        });
1020                    }
1021                    (Some(name), Some(tokens)) if tokens.is_object() => {
1022                        m.counterpart = Some(ManifestCounterpart {
1023                            name,
1024                            label: text("label"),
1025                            tokens: tokens.clone(),
1026                        });
1027                    }
1028                    _ => problems.push(Problem::Manifest {
1029                        reason: "`counterpart` needs a `name` and its `tokens` (a map); the kit has one variant".into(),
1030                    }),
1031                }
1032            }
1033            Some(_) => problems.push(Problem::Manifest {
1034                reason: "`counterpart` is not a map; the kit has one variant".into(),
1035            }),
1036        }
1037        m
1038    }
1039}
1040
1041/// The weights a file name can end with, as CSS numbers them.
1042const WEIGHT_NAMES: &[(&str, u16)] = &[
1043    ("thin", 100),
1044    ("hairline", 100),
1045    ("extralight", 200),
1046    ("ultralight", 200),
1047    ("light", 300),
1048    ("regular", 400),
1049    ("normal", 400),
1050    ("book", 400),
1051    ("variable", 400),
1052    ("medium", 500),
1053    ("semibold", 600),
1054    ("demibold", 600),
1055    ("bold", 700),
1056    ("extrabold", 800),
1057    ("ultrabold", 800),
1058    ("black", 900),
1059    ("heavy", 900),
1060];
1061
1062type FamilyWeight = (String, u16);
1063
1064/// A face's family and weight from its file name: `Family-Weight.ext`
1065/// (`Inter-SemiBold.ttf`), `Family.ext` at 400, a variable font's axes in
1066/// brackets dropped (`Inter[wght].ttf`). A suffix that is not a weight is
1067/// an error, the whole name then taken as the family.
1068fn face_from_file_name(file: &str) -> Result<FamilyWeight, (FamilyWeight, String)> {
1069    let stem = file.rsplit_once('.').map_or(file, |(s, _)| s);
1070    let stem = stem.split_once('[').map_or(stem, |(s, _)| s).trim();
1071    let Some((family, suffix)) = stem.rsplit_once('-') else {
1072        return Ok((stem.to_string(), 400));
1073    };
1074    let key: String = suffix
1075        .chars()
1076        .filter(|c| c.is_ascii_alphanumeric())
1077        .collect::<String>()
1078        .to_ascii_lowercase();
1079    if let Ok(n) = key.parse::<u16>()
1080        && (1..=1000).contains(&n)
1081    {
1082        return Ok((family.to_string(), n));
1083    }
1084    match WEIGHT_NAMES.iter().find(|(name, _)| *name == key) {
1085        Some((_, w)) => Ok((family.to_string(), *w)),
1086        None => Err((
1087            (stem.to_string(), 400),
1088            format!("`{suffix}` is not a weight"),
1089        )),
1090    }
1091}
1092
1093/// The tokens of kit components that are outside the vocabulary.
1094fn vocabulary(theme: &TokenFile) -> Vec<Problem> {
1095    let components: BTreeSet<&str> = kit_contract()
1096        .filter_map(|r| r.path.split('.').next())
1097        .collect();
1098    let mut problems = Vec::new();
1099    let find = |list: &[(&str, &'static str)], term: &str| {
1100        list.iter().find(|(t, _)| *t == term).map(|(_, ty)| *ty)
1101    };
1102    for (path, token) in &theme.tokens {
1103        if required(path).is_some() {
1104            continue;
1105        }
1106        let segs: Vec<&str> = path.split('.').collect();
1107        let unknown = |reason: String| Problem::UnknownTerm {
1108            path: path.clone(),
1109            reason,
1110        };
1111        let expected = if components.contains(segs[0]) {
1112            match segs[..] {
1113                [_, term] => match find(COMPONENT_TERMS, term) {
1114                    Some(ty) => Some(ty),
1115                    None if find(STATE_TERMS, term).is_some() => {
1116                        problems.push(unknown(format!(
1117                            "`{term}` is given per state (`{}.rest.{term}`)",
1118                            segs[0]
1119                        )));
1120                        None
1121                    }
1122                    None => {
1123                        problems.push(unknown(format!("`{term}` is not a term of the vocabulary")));
1124                        None
1125                    }
1126                },
1127                [_, state, term] if STATES.contains(&state) => match find(STATE_TERMS, term) {
1128                    Some(ty) => Some(ty),
1129                    None => {
1130                        problems.push(unknown(format!("`{term}` is not a term a state gives")));
1131                        None
1132                    }
1133                },
1134                [_, "tone", tone, ..] if !TONES.contains(&tone) => {
1135                    problems.push(unknown(format!(
1136                        "`{tone}` is not a tone ({})",
1137                        TONES.join(", ")
1138                    )));
1139                    None
1140                }
1141                [_, "tone", _, term] => match find(STATE_TERMS, term) {
1142                    Some(ty) => Some(ty),
1143                    None => {
1144                        problems.push(unknown(format!("`{term}` is not a term a tone gives")));
1145                        None
1146                    }
1147                },
1148                [_, "tone", _, state, term] if STATES.contains(&state) => {
1149                    match find(STATE_TERMS, term) {
1150                        Some(ty) => Some(ty),
1151                        None => {
1152                            problems.push(unknown(format!("`{term}` is not a term a state gives")));
1153                            None
1154                        }
1155                    }
1156                }
1157                [_, state, _] => {
1158                    problems.push(unknown(format!(
1159                        "`{state}` is not a state ({})",
1160                        STATES.join(", ")
1161                    )));
1162                    None
1163                }
1164                _ => {
1165                    problems.push(unknown(
1166                        "a kit token is `component.term` or `component.state.term`".into(),
1167                    ));
1168                    None
1169                }
1170            }
1171        } else {
1172            if let [component, state, term] = segs[..]
1173                && STATES.contains(&state)
1174                && find(STATE_TERMS, term).is_some()
1175            {
1176                problems.push(Problem::UnknownComponent {
1177                    path: path.clone(),
1178                    component: component.into(),
1179                });
1180            }
1181            None
1182        };
1183        if let (Some(expected), Some(found)) = (expected, token.ty.as_deref())
1184            && expected != found
1185        {
1186            problems.push(Problem::TermType {
1187                path: path.clone(),
1188                expected: expected.into(),
1189                found: found.into(),
1190            });
1191        }
1192    }
1193    problems
1194}
1195
1196/// Embeds a kit folder in the binary: `kit.yaml` (or the kit file
1197/// `kit = "kit.json"` names), and the token files,
1198/// faces (under `fonts/`) and licence it is given. The path is relative
1199/// to the file calling the macro, as `include_str!`'s. Nothing is checked
1200/// when compiling: call [`kit::check`](crate::kit::check) from a test.
1201///
1202/// ```ignore
1203/// let kit = egui_pop_tokens::kit!("../kits/brand",
1204///     tokens = ["tab.tokens.yaml"],
1205///     fonts = ["Inter-Regular.ttf", "Inter-Bold.ttf"],
1206///     license = "LICENSE");
1207/// ```
1208#[macro_export]
1209macro_rules! kit {
1210    ($dir:literal $(, tokens = [$($part:literal),* $(,)?])?
1211        $(, fonts = [$($font:literal),* $(,)?])?
1212        $(, license = $license:literal)?
1213        $(,)?) => {
1214        $crate::kit!($dir, kit = "kit.yaml"
1215            $(, tokens = [$($part),*])?
1216            $(, fonts = [$($font),*])?
1217            $(, license = $license)?)
1218    };
1219    ($dir:literal, kit = $kit:literal
1220        $(, tokens = [$($part:literal),* $(,)?])?
1221        $(, fonts = [$($font:literal),* $(,)?])?
1222        $(, license = $license:literal)?
1223        $(,)?) => {
1224        $crate::kit::KitData::embedded($crate::kit::Embedded {
1225            dir: $dir,
1226            kit: include_str!(concat!($dir, "/", $kit)),
1227            tokens: vec![$($((
1228                ::std::string::String::from($part),
1229                include_str!(concat!($dir, "/", $part)),
1230            ),)*)?],
1231            fonts: vec![$($((
1232                $font,
1233                &include_bytes!(concat!($dir, "/fonts/", $font))[..],
1234            ),)*)?],
1235            license: {
1236                #[allow(unused_mut, reason = "the macro assigns it only when a licence is given")]
1237                let mut license: ::std::option::Option<&'static str> = None;
1238                $(license = Some(include_str!(concat!($dir, "/", $license)));)?
1239                license
1240            },
1241        })
1242    };
1243}
1244
1245#[cfg(test)]
1246mod tests {
1247    use super::*;
1248
1249    #[test]
1250    fn each_kit_file_is_read_by_its_own_stamp() {
1251        let kit = KitData::embedded(Embedded {
1252            dir: "kits/stamped",
1253            kit: r##"{
1254              "$extensions": { "org.egui-pop.format": { "version": 1, "contract": 99 } },
1255              "tab": { "shape": { "$type": "string", "$value": "underline" } }
1256            }"##,
1257            tokens: vec![
1258                (
1259                    "button.tokens.json".into(),
1260                    r##"{
1261                      "$extensions": { "org.egui-pop.format": { "version": "two" } },
1262                      "button": { "rest": { "fill": { "$type": "color", "$value": "#102030" } } }
1263                    }"##,
1264                ),
1265                (
1266                    "field.tokens.json".into(),
1267                    r##"{ "field": { "rest": { "fill": { "$type": "color", "$value": "#203040" } } } }"##,
1268                ),
1269            ],
1270            fonts: Vec::new(),
1271            license: None,
1272        });
1273        let format: Vec<(&str, &Warning)> = kit
1274            .problems()
1275            .iter()
1276            .filter_map(|p| match p {
1277                Problem::Format { file, warning } => Some((file.as_str(), warning)),
1278                _ => None,
1279            })
1280            .collect();
1281        assert_eq!(format.len(), 2, "{:?}", kit.problems());
1282        assert!(matches!(
1283            format[0],
1284            (KIT_FILE, Warning::Newer { found: 99, .. })
1285        ));
1286        assert!(matches!(
1287            format[1],
1288            ("button.tokens.json", Warning::BadStamp { .. })
1289        ));
1290        assert!(
1291            kit.problems()[0]
1292                .to_string()
1293                .starts_with("`kit.yaml`: `$extensions.org.egui-pop.format.contract`"),
1294            "{}",
1295            kit.problems()[0]
1296        );
1297        // Warnings, not errors: every file's tokens are there.
1298        for path in ["tab.shape", "button.rest.fill", "field.rest.fill"] {
1299            assert!(kit.theme.tokens.contains_key(path), "{path}");
1300        }
1301        // A stamp saying the current format and contract is no problem.
1302        let mut current = TokenFile::parse(KIT_FILE, "{}").unwrap();
1303        current.stamp();
1304        let text = current.to_json_pretty();
1305        let kit = KitData::from_text("current", &text);
1306        assert!(kit.problems().is_empty(), "{:?}", kit.problems());
1307    }
1308
1309    #[test]
1310    fn a_face_is_named_by_its_file() {
1311        assert_eq!(
1312            face_from_file_name("Inter-SemiBold.ttf"),
1313            Ok(("Inter".into(), 600))
1314        );
1315        assert_eq!(
1316            face_from_file_name("Inter[wght].ttf"),
1317            Ok(("Inter".into(), 400))
1318        );
1319        assert_eq!(face_from_file_name("Hack.otf"), Ok(("Hack".into(), 400)));
1320        assert_eq!(
1321            face_from_file_name("Brand-700.otf"),
1322            Ok(("Brand".into(), 700))
1323        );
1324        assert!(face_from_file_name("Inter-Italic.ttf").is_err());
1325    }
1326
1327    #[test]
1328    fn terms_outside_the_vocabulary_are_reported() {
1329        let kit = KitData::from_text(
1330            "k",
1331            r##"
1332            tab:
1333              rest:
1334                fil: {$type: "color", $value: "#000000"}
1335              pressed:
1336                fill: {$type: "color", $value: "#000000"}
1337              fill: {$type: "color", $value: "#000000"}
1338              hover:
1339                radius: {$type: "color", $value: "#000000"}
1340            tabz:
1341              hover:
1342                fill: {$type: "color", $value: "#000000"}
1343            gray:
1344              "1": {$type: "color", $value: "#000000"}
1345            "##,
1346        );
1347        let p = kit.problems();
1348        assert_eq!(p.len(), 5, "{p:?}");
1349        assert!(p.iter().any(
1350            |p| matches!(p, Problem::UnknownComponent { component, .. } if component == "tabz")
1351        ));
1352        assert!(
1353            p.iter()
1354                .any(|p| matches!(p, Problem::TermType { path, .. } if path == "tab.hover.radius"))
1355        );
1356    }
1357
1358    #[test]
1359    fn tones_are_in_the_vocabulary() {
1360        let kit = KitData::from_text(
1361            "k",
1362            r##"
1363            window-button:
1364              tone:
1365                warning:
1366                  fill: {$type: "color", $value: "#ffbb00"}
1367                  active:
1368                    fill: {$type: "color", $value: "#cc9900"}
1369                amber:
1370                  fill: {$type: "color", $value: "#ffbb00"}
1371                danger:
1372                  glow: {$type: "color", $value: "#ff0000"}
1373            title-bar:
1374              buttons-side: {$type: "string", $value: "start"}
1375            "##,
1376        );
1377        let p = kit.problems();
1378        assert_eq!(p.len(), 2, "{p:?}");
1379        assert!(
1380            p.iter()
1381                .any(|p| matches!(p, Problem::UnknownTerm { path, .. }
1382            if path == "window-button.tone.amber.fill"))
1383        );
1384        assert!(
1385            p.iter()
1386                .any(|p| matches!(p, Problem::UnknownTerm { path, .. }
1387            if path == "window-button.tone.danger.glow"))
1388        );
1389    }
1390
1391    #[test]
1392    fn a_kit_extends_pop_dark_and_keeps_built_in_names() {
1393        let kit = KitData::from_text("pop-light", "{}");
1394        assert_eq!(kit.name, "pop-light-kit");
1395        assert_eq!(kit.theme.extends.as_deref(), Some(FALLBACK_THEME));
1396        assert!(matches!(kit.problems()[0], Problem::Name { .. }));
1397    }
1398
1399    #[test]
1400    fn bad_json_gives_the_base_theme_under_the_kit_name() {
1401        let kit = KitData::from_text("broken", "{ nope");
1402        assert!(matches!(
1403            kit.problems()[0],
1404            Problem::Tokens(Error::Json { .. })
1405        ));
1406        let problems = check(&kit);
1407        assert_eq!(problems.len(), 1, "{problems:?}");
1408        let mut themes = Themes::default();
1409        themes.add_kit(&kit);
1410        let r = themes.resolve(&ThemeSpec::new("broken"));
1411        assert!(r.problems().is_empty());
1412    }
1413
1414    /// The cache of compiled files with user kits (`crate::cache`).
1415    mod cached {
1416        use super::*;
1417        use crate::TOKENS_COMPILER;
1418        use crate::cache::Compiler;
1419        use crate::yaml::parses;
1420
1421        const KIT: &str =
1422            "$extends: \"pop-light\"\ntab:\n  shape: {$type: \"string\", $value: \"underline\"}\n";
1423        const PART: &str = "tab:\n  rest:\n    fil: {$type: \"color\", $value: \"#000000\"}\n";
1424
1425        /// A kit folder and a cache folder, under a temporary directory
1426        /// (never the user's cache).
1427        fn setup(name: &str) -> (PathBuf, PathBuf) {
1428            let root = std::env::temp_dir()
1429                .join(format!("egui-pop-kit-cache-{name}-{}", std::process::id()));
1430            std::fs::remove_dir_all(&root).ok();
1431            let kit = root.join("mine");
1432            std::fs::create_dir_all(&kit).unwrap();
1433            std::fs::write(kit.join("kit.yaml"), KIT).unwrap();
1434            std::fs::write(kit.join("tab.tokens.yaml"), PART).unwrap();
1435            (kit, root.join("cache"))
1436        }
1437
1438        #[test]
1439        fn a_kit_loaded_twice_reads_its_yaml_once() {
1440            let (dir, cache) = setup("twice");
1441            let cache = Cache::at(cache);
1442            let before = parses();
1443            let first = KitData::load_with(&dir, &cache);
1444            assert_eq!(parses() - before, 2, "kit.yaml and tab.tokens.yaml");
1445            let second = KitData::load_with(&dir, &cache);
1446            assert_eq!(parses() - before, 2, "the second load reads the cache");
1447            assert_eq!(first, second, "the same kit, the same problems");
1448            assert!(
1449                first
1450                    .problems()
1451                    .iter()
1452                    .any(|p| matches!(p, Problem::UnknownTerm { .. })),
1453                "{:?}",
1454                first.problems()
1455            );
1456            assert_eq!(first.theme.extends.as_deref(), Some("pop-light"));
1457            std::fs::remove_dir_all(dir.parent().unwrap()).ok();
1458        }
1459
1460        #[test]
1461        fn a_changed_source_is_read_again() {
1462            let (dir, cache) = setup("changed");
1463            let cache = Cache::at(cache);
1464            KitData::load_with(&dir, &cache);
1465            std::fs::write(
1466                dir.join("kit.yaml"),
1467                KIT.replace("underline", "pill")
1468                    .replace("pop-light", "pop-dark"),
1469            )
1470            .unwrap();
1471            let before = parses();
1472            let kit = KitData::load_with(&dir, &cache);
1473            assert_eq!(parses() - before, 1, "only the changed file");
1474            assert_eq!(kit.theme.extends.as_deref(), Some("pop-dark"));
1475            assert_eq!(kit.theme.tokens["tab.shape"].value, "pill");
1476            std::fs::remove_dir_all(dir.parent().unwrap()).ok();
1477        }
1478
1479        #[test]
1480        fn an_unwritable_cache_still_loads_and_says_so() {
1481            let (dir, cache) = setup("unwritable");
1482            // A file where the cache's folder should be.
1483            std::fs::write(&cache, "").unwrap();
1484            let kit = KitData::load_with(&dir, &Cache::at(&cache));
1485            let clean = KitData::load_with(&dir, &Cache::off());
1486            assert_eq!(kit.theme, clean.theme);
1487            let not_cached: Vec<_> = kit
1488                .problems()
1489                .iter()
1490                .filter(|p| matches!(p, Problem::NotCached { .. }))
1491                .collect();
1492            assert_eq!(not_cached.len(), 2, "{:?}", kit.problems());
1493            assert!(not_cached[0].to_string().contains("read uncached"));
1494            std::fs::remove_dir_all(dir.parent().unwrap()).ok();
1495        }
1496
1497        #[test]
1498        fn a_new_compiler_version_ignores_old_entries() {
1499            let (dir, cache) = setup("version");
1500            let cache = Cache::at(cache);
1501            // An entry for kit.yaml from another version, which would
1502            // give another tree.
1503            let old = Compiler {
1504                version: "0.0.0",
1505                ..TOKENS_COMPILER
1506            };
1507            cache
1508                .put(&old, &dir.join("kit.yaml"), KIT.as_bytes(), b"{}")
1509                .unwrap();
1510            let before = parses();
1511            let kit = KitData::load_with(&dir, &cache);
1512            assert_eq!(parses() - before, 2, "the old entry is not read");
1513            assert_eq!(kit.theme.tokens["tab.shape"].value, "underline");
1514            // And replaced by this version's.
1515            let before = parses();
1516            KitData::load_with(&dir, &cache);
1517            assert_eq!(parses(), before);
1518            std::fs::remove_dir_all(dir.parent().unwrap()).ok();
1519        }
1520
1521        #[test]
1522        fn a_theme_file_keeps_its_warnings_on_a_hit() {
1523            let (dir, cache) = setup("theme");
1524            let cache = Cache::at(cache);
1525            let path = dir.join("mine.tokens.yaml");
1526            std::fs::write(
1527                &path,
1528                "surface:\n  panel: {$type: \"color\", $value: \"{nowhere.1}\"}\n",
1529            )
1530            .unwrap();
1531            let mut themes = Themes::default();
1532            let before = parses();
1533            let first = themes.add_path_with("mine", &path, &cache).unwrap();
1534            let second = themes.add_path_with("mine", &path, &cache).unwrap();
1535            assert_eq!(parses() - before, 1);
1536            assert!(
1537                first
1538                    .iter()
1539                    .any(|w| matches!(w, crate::Warning::Invalid { .. })),
1540                "{first:?}"
1541            );
1542            assert_eq!(first, second);
1543            assert!(themes.get("mine").is_some());
1544            let missing = themes.add_path_with("gone", &dir.join("gone.yaml"), &cache);
1545            assert!(matches!(missing, Err(Error::Io { .. })), "{missing:?}");
1546            std::fs::remove_dir_all(dir.parent().unwrap()).ok();
1547        }
1548    }
1549}