Skip to main content

egui_pop_tokens/
package.rs

1//! Theme packages: a token file with the font files it uses, so that a
2//! theme naming its own faces travels whole.
3//!
4//! A theme that uses font files is written as a folder, or as a `.zip`
5//! archive holding the same files:
6//!
7//! ```text
8//! my-theme/
9//!   my-theme.tokens.json   the token file
10//!   fonts/Inter-Regular.ttf
11//!   fonts/Inter-Bold.ttf
12//! ```
13//!
14//! The token file lists its faces in its root `$extensions`, each by its
15//! path relative to the token file, with the family a theme names it by
16//! and its weight ([`FONTS_EXTENSION`]):
17//!
18//! ```json
19//! { "$extensions": { "org.egui-pop.fonts": [
20//!     { "file": "fonts/Inter-Regular.ttf", "family": "Inter", "weight": 400 }
21//! ] } }
22//! ```
23//!
24//! [`ThemePackage::read`] takes a folder, a `.zip` archive or a lone
25//! token file (its faces then found beside it, by the same relative
26//! paths). Only a package without a readable token file is an error; a
27//! face that is missing or not a font is a [`Warning::Font`], and the
28//! families naming it fall back.
29//!
30//! ```
31//! use egui_pop_tokens::TokenFile;
32//! use egui_pop_tokens::package::ThemePackage;
33//!
34//! let mut package = ThemePackage::new(TokenFile::new("mine"));
35//! package.add_font("Brand", 400, "Brand-Regular.ttf", b"\0\x01\0\0 a font".to_vec());
36//! let dir = std::env::temp_dir().join(format!("egui-pop-package-doc-{}", std::process::id()));
37//! let file = package.write_dir(&dir).unwrap();
38//! assert!(file.ends_with("mine.tokens.json"));
39//! let (back, warnings) = ThemePackage::read(&dir).unwrap();
40//! assert!(warnings.is_empty(), "{warnings:?}");
41//! assert_eq!(back.fonts[0].family, "Brand");
42//! # std::fs::remove_dir_all(&dir).unwrap();
43//! ```
44//!
45//! Archives need the `zip` feature (zip, MIT, with deflate only); without
46//! it, a folder or a lone file still reads and writes.
47
48use std::fmt;
49use std::path::{Component, Path, PathBuf};
50
51use serde_json::{Value as Json, json};
52
53use crate::kit::TOKEN_FILE_ENDINGS;
54use crate::{Error, TokenFile, Warning};
55
56/// The root `$extensions` key listing a token file's font files.
57pub const FONTS_EXTENSION: &str = "org.egui-pop.fonts";
58
59/// The folder of a package the faces are written to.
60pub const FONTS_DIR: &str = "fonts";
61
62/// The ending of the token file a package is written with.
63pub const PACKAGE_TOKEN_FILE: &str = ".tokens.json";
64
65/// The most an archive may hold once unpacked (256 MiB): an archive
66/// claiming more is refused, so a crafted file cannot fill memory.
67pub const MAX_UNPACKED: u64 = 256 * 1024 * 1024;
68
69/// A face a theme package ships.
70#[derive(Clone, PartialEq, Eq)]
71pub struct PackageFont {
72    /// Its path relative to the token file, with `/` (`fonts/Inter.ttf`).
73    pub file: String,
74    /// The family a theme names it by (`font.family.ui`).
75    pub family: String,
76    /// 100 to 900, as CSS numbers weights.
77    pub weight: u16,
78    pub bytes: Vec<u8>,
79}
80
81impl fmt::Debug for PackageFont {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.debug_struct("PackageFont")
84            .field("file", &self.file)
85            .field("family", &self.family)
86            .field("weight", &self.weight)
87            .field("bytes", &self.bytes.len())
88            .finish()
89    }
90}
91
92/// A token file and the faces it uses.
93#[derive(Clone, Debug, PartialEq)]
94pub struct ThemePackage {
95    pub file: TokenFile,
96    pub fonts: Vec<PackageFont>,
97}
98
99/// A face as the token file lists it.
100struct Entry {
101    file: String,
102    family: String,
103    weight: u16,
104}
105
106impl ThemePackage {
107    /// A package of a token file alone.
108    pub fn new(file: TokenFile) -> ThemePackage {
109        ThemePackage {
110            file,
111            fonts: Vec::new(),
112        }
113    }
114
115    /// Adds a face under [`FONTS_DIR`] (replacing one of the same file
116    /// name); the token file lists it when the package is written.
117    pub fn add_font(&mut self, family: &str, weight: u16, file_name: &str, bytes: Vec<u8>) {
118        let name = Path::new(file_name).file_name().map_or_else(
119            || file_name.to_string(),
120            |n| n.to_string_lossy().into_owned(),
121        );
122        let file = format!("{FONTS_DIR}/{name}");
123        self.fonts.retain(|f| f.file != file);
124        self.fonts.push(PackageFont {
125            file,
126            family: family.to_string(),
127            weight,
128            bytes,
129        });
130    }
131
132    /// The token file as written in the package: its faces listed under
133    /// [`FONTS_EXTENSION`] (the entry taken out when it has none), the
134    /// rest of its root `$extensions` kept.
135    pub fn token_file(&self) -> TokenFile {
136        let mut file = self.file.clone();
137        let mut root = match file.extensions.take() {
138            Some(Json::Object(m)) => m,
139            _ => serde_json::Map::new(),
140        };
141        root.remove(FONTS_EXTENSION);
142        if !self.fonts.is_empty() {
143            let list = self
144                .fonts
145                .iter()
146                .map(|f| json!({ "file": f.file, "family": f.family, "weight": f.weight }))
147                .collect();
148            root.insert(FONTS_EXTENSION.to_string(), Json::Array(list));
149        }
150        file.extensions = (!root.is_empty()).then_some(Json::Object(root));
151        file
152    }
153
154    /// The name of the token file in the package
155    /// (`<theme>.tokens.json`).
156    pub fn token_file_name(&self) -> String {
157        let name = if self.file.name.trim().is_empty() {
158            "theme"
159        } else {
160            self.file.name.as_str()
161        };
162        format!("{name}{PACKAGE_TOKEN_FILE}")
163    }
164
165    /// The package's files: the token file, then each face, by their
166    /// path in the package.
167    pub fn files(&self) -> Vec<(String, Vec<u8>)> {
168        let mut out = vec![(
169            self.token_file_name(),
170            self.token_file().to_json_pretty().into_bytes(),
171        )];
172        out.extend(self.fonts.iter().map(|f| (f.file.clone(), f.bytes.clone())));
173        out
174    }
175
176    /// Reads a package: a folder, a `.zip` archive (with the `zip`
177    /// feature), or a lone token file, its faces beside it. What was read
178    /// otherwise than written comes back as warnings: a face missing or
179    /// not a font, a second token file in a folder.
180    pub fn read(path: &Path) -> Result<(ThemePackage, Vec<Warning>), Error> {
181        if path.is_dir() {
182            return ThemePackage::read_dir(path);
183        }
184        if is_zip(path) {
185            let bytes = std::fs::read(path).map_err(|e| io(path, &e))?;
186            return ThemePackage::from_zip(&bytes);
187        }
188        let text = std::fs::read_to_string(path).map_err(|e| io(path, &e))?;
189        let name = theme_name(&path.file_name().unwrap_or_default().to_string_lossy());
190        let dir = path.parent().unwrap_or(Path::new("."));
191        from_parts(&name, &text, |rel| {
192            let p = dir.join(rel);
193            std::fs::read(&p).map_err(|e| e.to_string())
194        })
195    }
196
197    /// Reads a package folder: the token file at its top (the first by
198    /// name ending in `.tokens.json`, `.tokens.yaml` or `.tokens.yml`)
199    /// and the faces it lists.
200    pub fn read_dir(dir: &Path) -> Result<(ThemePackage, Vec<Warning>), Error> {
201        let entries = std::fs::read_dir(dir).map_err(|e| io(dir, &e))?;
202        let mut names: Vec<String> = entries
203            .filter_map(Result::ok)
204            .filter(|e| e.path().is_file())
205            .map(|e| e.file_name().to_string_lossy().into_owned())
206            .filter(|n| is_token_file(n))
207            .collect();
208        names.sort();
209        let Some(first) = names.first() else {
210            return Err(no_token_file(&dir.display().to_string()));
211        };
212        let path = dir.join(first);
213        let text = std::fs::read_to_string(&path).map_err(|e| io(&path, &e))?;
214        let (package, mut warnings) = from_parts(&theme_name(first), &text, |rel| {
215            std::fs::read(dir.join(rel)).map_err(|e| e.to_string())
216        })?;
217        warnings.extend(names.iter().skip(1).map(|n| Warning::Font {
218            file: n.clone(),
219            reason: format!(
220                "a second token file: `{first}` is the package's, this one is not read"
221            ),
222        }));
223        Ok((package, warnings))
224    }
225
226    /// Reads a package from the bytes of a `.zip` archive: the files at
227    /// its top, or in its one top folder (an archive of the package's
228    /// folder), as [`ThemePackage::read_dir`] reads a folder.
229    #[cfg(feature = "zip")]
230    pub fn from_zip(bytes: &[u8]) -> Result<(ThemePackage, Vec<Warning>), Error> {
231        let files = archive::unpack(bytes)?;
232        let mut names: Vec<&String> = files.keys().filter(|n| is_token_file(n)).collect();
233        // An archive of the folder: everything under one top folder.
234        let prefix = if names.iter().any(|n| !n.contains('/')) {
235            String::new()
236        } else {
237            let tops: std::collections::BTreeSet<&str> = files
238                .keys()
239                .filter_map(|n| n.split_once('/').map(|(t, _)| t))
240                .collect();
241            match tops.into_iter().collect::<Vec<_>>()[..] {
242                [top] => format!("{top}/"),
243                _ => String::new(),
244            }
245        };
246        names.retain(|n| {
247            n.strip_prefix(prefix.as_str())
248                .is_some_and(|rest| !rest.contains('/'))
249        });
250        let Some(first) = names.first() else {
251            return Err(no_token_file("the archive"));
252        };
253        let text = std::str::from_utf8(&files[*first]).map_err(|e| Error::Io {
254            file: (*first).clone(),
255            message: e.to_string(),
256        })?;
257        let short = first.strip_prefix(prefix.as_str()).unwrap_or(first);
258        let (package, mut warnings) = from_parts(&theme_name(short), text, |rel| {
259            files
260                .get(&format!("{prefix}{rel}"))
261                .cloned()
262                .ok_or_else(|| "not in the archive".to_string())
263        })?;
264        warnings.extend(names.iter().skip(1).map(|n| Warning::Font {
265            file: (*n).clone(),
266            reason: format!(
267                "a second token file: `{first}` is the package's, this one is not read"
268            ),
269        }));
270        Ok((package, warnings))
271    }
272
273    /// Without the `zip` feature, an archive cannot be read.
274    #[cfg(not(feature = "zip"))]
275    pub fn from_zip(_bytes: &[u8]) -> Result<(ThemePackage, Vec<Warning>), Error> {
276        Err(no_zip())
277    }
278
279    /// Writes the package as a folder (made if needed): the token file
280    /// at its top, the faces by their paths. The token file's path.
281    pub fn write_dir(&self, dir: &Path) -> Result<PathBuf, Error> {
282        for (name, bytes) in self.files() {
283            let path = dir.join(&name);
284            if let Some(parent) = path.parent() {
285                std::fs::create_dir_all(parent).map_err(|e| io(parent, &e))?;
286            }
287            std::fs::write(&path, bytes).map_err(|e| io(&path, &e))?;
288        }
289        Ok(dir.join(self.token_file_name()))
290    }
291
292    /// The package as the bytes of a `.zip` archive (deflated), its files
293    /// at its top, dated 1980-01-01 so the same package gives the same
294    /// bytes.
295    #[cfg(feature = "zip")]
296    pub fn to_zip(&self) -> Result<Vec<u8>, Error> {
297        archive::pack(&self.files())
298    }
299
300    /// Without the `zip` feature, an archive cannot be written.
301    #[cfg(not(feature = "zip"))]
302    pub fn to_zip(&self) -> Result<Vec<u8>, Error> {
303        Err(no_zip())
304    }
305
306    /// Writes the package where a user chose to save it: a path ending
307    /// in `.zip` becomes an archive; otherwise a package without faces is
308    /// the lone token file at `path`, and one with faces a folder named
309    /// after the theme beside `path` (`<dir>/<theme>/<theme>.tokens.json`
310    /// and its `fonts/`). The token file's path, or the archive's.
311    pub fn write(&self, path: &Path) -> Result<PathBuf, Error> {
312        if is_zip(path) {
313            let bytes = self.to_zip()?;
314            std::fs::write(path, bytes).map_err(|e| io(path, &e))?;
315            return Ok(path.to_path_buf());
316        }
317        if self.fonts.is_empty() {
318            let text = self.token_file().to_json_pretty();
319            std::fs::write(path, text).map_err(|e| io(path, &e))?;
320            return Ok(path.to_path_buf());
321        }
322        let parent = path.parent().unwrap_or(Path::new("."));
323        let name = self.token_file_name();
324        self.write_dir(&parent.join(name.trim_end_matches(PACKAGE_TOKEN_FILE)))
325    }
326}
327
328/// Whether a path names a `.zip` archive, by its ending.
329pub fn is_zip(path: &Path) -> bool {
330    path.extension()
331        .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
332}
333
334/// Whether a file name is a package's token file.
335fn is_token_file(name: &str) -> bool {
336    TOKEN_FILE_ENDINGS.iter().any(|e| name.ends_with(e))
337}
338
339/// A theme's name from its token file's name (`mine.tokens.json` is
340/// `mine`).
341fn theme_name(file: &str) -> String {
342    let mut name = file;
343    for ending in TOKEN_FILE_ENDINGS
344        .iter()
345        .chain([&".json", &".yaml", &".yml"])
346    {
347        if let Some(stem) = name.strip_suffix(ending) {
348            name = stem;
349            break;
350        }
351    }
352    if name.is_empty() {
353        "theme".into()
354    } else {
355        name.to_string()
356    }
357}
358
359fn io(path: &Path, e: &std::io::Error) -> Error {
360    Error::Io {
361        file: path.display().to_string(),
362        message: e.to_string(),
363    }
364}
365
366fn no_token_file(place: &str) -> Error {
367    Error::Malformed {
368        file: place.to_string(),
369        path: String::new(),
370        reason: "no token file (`*.tokens.json`, `*.tokens.yaml`) at its top".into(),
371    }
372}
373
374#[cfg(not(feature = "zip"))]
375fn no_zip() -> Error {
376    Error::Io {
377        file: "archive".into(),
378        message: "this build reads and writes no .zip archives (egui-pop-tokens' `zip` feature)"
379            .into(),
380    }
381}
382
383/// Whether a relative path stays inside the package (no `..`, not
384/// absolute).
385fn enclosed(rel: &str) -> bool {
386    !rel.is_empty()
387        && Path::new(rel)
388            .components()
389            .all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
390}
391
392/// A package from its token file's text, its faces read by `read` (a
393/// path relative to the token file).
394fn from_parts(
395    name: &str,
396    text: &str,
397    read: impl Fn(&str) -> Result<Vec<u8>, String>,
398) -> Result<(ThemePackage, Vec<Warning>), Error> {
399    let mut file = TokenFile::parse(name, text)?;
400    let mut warnings = Vec::new();
401    let entries = entries(&file, &mut warnings);
402    let mut fonts = Vec::new();
403    for e in entries {
404        if !enclosed(&e.file) {
405            warnings.push(Warning::Font {
406                file: e.file,
407                reason: "not a path inside the package; left out".into(),
408            });
409            continue;
410        }
411        match read(&e.file) {
412            Ok(bytes) if crate::kit::looks_like_font(&bytes) => fonts.push(PackageFont {
413                file: e.file,
414                family: e.family,
415                weight: e.weight,
416                bytes,
417            }),
418            Ok(_) => warnings.push(Warning::Font {
419                file: e.file,
420                reason: "not a TrueType or OpenType file; left out".into(),
421            }),
422            Err(reason) => warnings.push(Warning::Font {
423                file: e.file,
424                reason: format!("{reason}; left out"),
425            }),
426        }
427    }
428    // The list is the package's: written again from its faces.
429    if let Some(Json::Object(root)) = file.extensions.as_mut() {
430        root.remove(FONTS_EXTENSION);
431        if root.is_empty() {
432            file.extensions = None;
433        }
434    }
435    Ok((ThemePackage { file, fonts }, warnings))
436}
437
438/// The faces a token file lists ([`FONTS_EXTENSION`]); an entry that
439/// cannot be read is a warning.
440fn entries(file: &TokenFile, warnings: &mut Vec<Warning>) -> Vec<Entry> {
441    let Some(raw) = file
442        .extensions
443        .as_ref()
444        .and_then(|x| x.get(FONTS_EXTENSION))
445    else {
446        return Vec::new();
447    };
448    let Some(list) = raw.as_array() else {
449        warnings.push(Warning::Invalid {
450            path: format!("$extensions.{FONTS_EXTENSION}"),
451            reason: format!("`{raw}` is not a list of font files"),
452        });
453        return Vec::new();
454    };
455    let mut out = Vec::new();
456    for (i, item) in list.iter().enumerate() {
457        let text = |key: &str| {
458            item.get(key)
459                .and_then(Json::as_str)
460                .filter(|s| !s.trim().is_empty())
461                .map(String::from)
462        };
463        let weight = item
464            .get("weight")
465            .map_or(Some(400), |w| w.as_u64().filter(|w| (1..=1000).contains(w)));
466        match (text("file"), text("family"), weight) {
467            (Some(file), Some(family), Some(weight)) => out.push(Entry {
468                file,
469                family,
470                weight: weight as u16,
471            }),
472            _ => warnings.push(Warning::Invalid {
473                path: format!("$extensions.{FONTS_EXTENSION}.{i}"),
474                reason: format!(
475                    "`{item}` is not a font file (`file` and `family`, a `weight` from 1 to 1000)"
476                ),
477            }),
478        }
479    }
480    out
481}
482
483#[cfg(feature = "zip")]
484mod archive {
485    //! `.zip` archives through the zip crate (MIT), deflate only.
486
487    use std::collections::BTreeMap;
488    use std::io::{Cursor, Read as _, Write as _};
489
490    use super::MAX_UNPACKED;
491    use crate::Error;
492
493    fn error(e: impl std::fmt::Display) -> Error {
494        Error::Io {
495            file: "archive".into(),
496            message: e.to_string(),
497        }
498    }
499
500    /// The archive's files by their path (with `/`), folders left out;
501    /// an entry whose path leaves the archive is refused.
502    pub(super) fn unpack(bytes: &[u8]) -> Result<BTreeMap<String, Vec<u8>>, Error> {
503        let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(error)?;
504        let mut files = BTreeMap::new();
505        let mut total: u64 = 0;
506        for i in 0..zip.len() {
507            let entry = zip.by_index(i).map_err(error)?;
508            if entry.is_dir() {
509                continue;
510            }
511            let Some(path) = entry.enclosed_name() else {
512                return Err(error(format!(
513                    "`{}` is not a path inside the archive",
514                    entry.name().unwrap_or_default()
515                )));
516            };
517            let name = path
518                .components()
519                .map(|c| c.as_os_str().to_string_lossy())
520                .collect::<Vec<_>>()
521                .join("/");
522            total = total.saturating_add(entry.size());
523            if total > MAX_UNPACKED {
524                return Err(error(format!(
525                    "more than {} MiB once unpacked",
526                    MAX_UNPACKED / 1024 / 1024
527                )));
528            }
529            let mut data = Vec::new();
530            // Never more than the entry says (a lying header stops here).
531            entry
532                .take(MAX_UNPACKED + 1)
533                .read_to_end(&mut data)
534                .map_err(error)?;
535            if data.len() as u64 > MAX_UNPACKED {
536                return Err(error("an entry larger than it says"));
537            }
538            files.insert(name, data);
539        }
540        Ok(files)
541    }
542
543    /// An archive of `files` (path, bytes), deflated, dated 1980-01-01.
544    pub(super) fn pack(files: &[(String, Vec<u8>)]) -> Result<Vec<u8>, Error> {
545        let options = zip::write::SimpleFileOptions::default()
546            .compression_method(zip::CompressionMethod::Deflated)
547            .last_modified_time(zip::DateTime::default());
548        let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
549        for (name, bytes) in files {
550            zip.start_file(name.as_str(), options).map_err(error)?;
551            zip.write_all(bytes).map_err(error)?;
552        }
553        Ok(zip.finish().map_err(error)?.into_inner())
554    }
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560
561    /// The first bytes of a TrueType file, enough for the check.
562    fn font_bytes(tag: &str) -> Vec<u8> {
563        let mut b = vec![0, 1, 0, 0];
564        b.extend_from_slice(format!("a face: {tag}").as_bytes());
565        b
566    }
567
568    fn package() -> ThemePackage {
569        let mut file = TokenFile::parse(
570            "mine",
571            r##"{
572              "$extends": "pop-dark",
573              "$extensions": { "org.example": 1 },
574              "font": { "family": { "ui": { "$type": "fontFamily", "$value": ["Brand", "sans-serif"] } } }
575            }"##,
576        )
577        .unwrap();
578        file.stamp();
579        let mut p = ThemePackage::new(file);
580        p.add_font("Brand", 400, "Brand-Regular.ttf", font_bytes("regular"));
581        p.add_font(
582            "Brand",
583            700,
584            "/somewhere/Brand-Bold.ttf",
585            font_bytes("bold"),
586        );
587        p
588    }
589
590    fn temp(name: &str) -> PathBuf {
591        let dir =
592            std::env::temp_dir().join(format!("egui-pop-package-{name}-{}", std::process::id()));
593        let _ = std::fs::remove_dir_all(&dir);
594        std::fs::create_dir_all(&dir).unwrap();
595        dir
596    }
597
598    #[test]
599    fn a_package_lists_its_faces_by_relative_path() {
600        let p = package();
601        assert_eq!(p.fonts[1].file, "fonts/Brand-Bold.ttf");
602        let file = p.token_file();
603        let list = &file.extensions.as_ref().unwrap()[FONTS_EXTENSION];
604        assert_eq!(
605            list[1],
606            json!({ "file": "fonts/Brand-Bold.ttf", "family": "Brand", "weight": 700 })
607        );
608        // The rest of the root's extensions stays.
609        assert_eq!(file.extensions.as_ref().unwrap()["org.example"], json!(1));
610        let names: Vec<String> = p.files().into_iter().map(|(n, _)| n).collect();
611        assert_eq!(
612            names,
613            [
614                "mine.tokens.json",
615                "fonts/Brand-Regular.ttf",
616                "fonts/Brand-Bold.ttf"
617            ]
618        );
619    }
620
621    #[test]
622    fn a_folder_and_its_token_file_read_back_the_package() {
623        let dir = temp("folder");
624        let p = package();
625        let file = p.write_dir(&dir).unwrap();
626        assert_eq!(file, dir.join("mine.tokens.json"));
627        let (back, warnings) = ThemePackage::read(&dir).unwrap();
628        assert!(warnings.is_empty(), "{warnings:?}");
629        assert_eq!(back.file.name, "mine");
630        assert_eq!(back.fonts, p.fonts);
631        assert_eq!(back.token_file(), p.token_file());
632        // The token file alone finds its faces beside it.
633        let (alone, warnings) = ThemePackage::read(&file).unwrap();
634        assert!(warnings.is_empty(), "{warnings:?}");
635        assert_eq!(alone, back);
636        let _ = std::fs::remove_dir_all(&dir);
637    }
638
639    #[test]
640    fn a_face_missing_or_not_a_font_is_a_warning() {
641        let dir = temp("missing");
642        let p = package();
643        p.write_dir(&dir).unwrap();
644        std::fs::remove_file(dir.join("fonts/Brand-Bold.ttf")).unwrap();
645        std::fs::write(dir.join("fonts/Brand-Regular.ttf"), b"<html>").unwrap();
646        std::fs::write(dir.join("other.tokens.yaml"), "{}").unwrap();
647        let (back, warnings) = ThemePackage::read(&dir).unwrap();
648        assert!(back.fonts.is_empty());
649        assert_eq!(back.file.tokens.len(), 1);
650        let files: Vec<&str> = warnings
651            .iter()
652            .map(|w| match w {
653                Warning::Font { file, .. } => file.as_str(),
654                other => panic!("{other:?}"),
655            })
656            .collect();
657        assert_eq!(
658            files,
659            [
660                "fonts/Brand-Regular.ttf",
661                "fonts/Brand-Bold.ttf",
662                "other.tokens.yaml"
663            ]
664        );
665        let _ = std::fs::remove_dir_all(&dir);
666    }
667
668    #[test]
669    fn a_face_outside_the_package_is_not_read() {
670        let text = r##"{ "$extensions": { "org.egui-pop.fonts": [
671            { "file": "../secret.ttf", "family": "X" },
672            { "file": "/etc/x.ttf", "family": "X" },
673            { "file": "fonts/a.ttf" }
674        ] } }"##;
675        let (p, warnings) = from_parts("t", text, |_| Ok(font_bytes("x"))).unwrap();
676        assert!(p.fonts.is_empty());
677        assert_eq!(warnings.len(), 3, "{warnings:?}");
678        // The entry without a family is set aside while the list is read,
679        // before the two paths are checked.
680        assert!(matches!(warnings[0], Warning::Invalid { .. }));
681        assert!(matches!(warnings[1], Warning::Font { .. }));
682        assert!(matches!(warnings[2], Warning::Font { .. }));
683        // The list is not kept in the file: it is the package's.
684        assert_eq!(p.file.extensions, None);
685    }
686
687    #[test]
688    fn a_folder_without_a_token_file_is_an_error() {
689        let dir = temp("empty");
690        assert!(matches!(
691            ThemePackage::read(&dir),
692            Err(Error::Malformed { .. })
693        ));
694        let _ = std::fs::remove_dir_all(&dir);
695    }
696
697    #[test]
698    fn a_package_without_faces_is_written_as_its_token_file() {
699        let dir = temp("lone");
700        let p = ThemePackage::new(TokenFile::new("lone"));
701        let path = p.write(&dir.join("chosen.tokens.json")).unwrap();
702        assert_eq!(path, dir.join("chosen.tokens.json"));
703        assert!(path.is_file());
704        // With faces, a folder named after the theme beside the path.
705        let path = package().write(&dir.join("chosen.tokens.json")).unwrap();
706        assert_eq!(path, dir.join("mine").join("mine.tokens.json"));
707        assert!(dir.join("mine/fonts/Brand-Bold.ttf").is_file());
708        let _ = std::fs::remove_dir_all(&dir);
709    }
710
711    #[cfg(feature = "zip")]
712    #[test]
713    fn an_archive_reads_back_the_package() {
714        let p = package();
715        let bytes = p.to_zip().unwrap();
716        // The same package, the same bytes.
717        assert_eq!(p.to_zip().unwrap(), bytes);
718        let (back, warnings) = ThemePackage::from_zip(&bytes).unwrap();
719        assert!(warnings.is_empty(), "{warnings:?}");
720        assert_eq!(back.fonts, p.fonts);
721        assert_eq!(back.token_file(), p.token_file());
722        // Written to a `.zip` path, read from it.
723        let dir = temp("zip");
724        let path = p.write(&dir.join("mine.zip")).unwrap();
725        let (read, _) = ThemePackage::read(&path).unwrap();
726        assert_eq!(read, back);
727        let _ = std::fs::remove_dir_all(&dir);
728    }
729
730    #[cfg(feature = "zip")]
731    #[test]
732    fn an_archive_of_the_folder_is_read_under_its_top_folder() {
733        let p = package();
734        let files: Vec<(String, Vec<u8>)> = p
735            .files()
736            .into_iter()
737            .map(|(n, b)| (format!("mine/{n}"), b))
738            .collect();
739        let bytes = archive::pack(&files).unwrap();
740        let (back, warnings) = ThemePackage::from_zip(&bytes).unwrap();
741        assert!(warnings.is_empty(), "{warnings:?}");
742        assert_eq!(back.fonts.len(), 2);
743        assert_eq!(back.file.name, "mine");
744        // Nothing that is a zip: an error, not a panic.
745        assert!(ThemePackage::from_zip(b"not a zip").is_err());
746        // An archive without a token file.
747        let bytes = archive::pack(&[("fonts/a.ttf".into(), font_bytes("a"))]).unwrap();
748        assert!(matches!(
749            ThemePackage::from_zip(&bytes),
750            Err(Error::Malformed { .. })
751        ));
752    }
753
754    #[cfg(not(feature = "zip"))]
755    #[test]
756    fn without_the_zip_feature_an_archive_is_an_error() {
757        assert!(package().to_zip().is_err());
758        assert!(ThemePackage::from_zip(b"PK").is_err());
759    }
760}