1use 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
56pub const FONTS_EXTENSION: &str = "org.egui-pop.fonts";
58
59pub const FONTS_DIR: &str = "fonts";
61
62pub const PACKAGE_TOKEN_FILE: &str = ".tokens.json";
64
65pub const MAX_UNPACKED: u64 = 256 * 1024 * 1024;
68
69#[derive(Clone, PartialEq, Eq)]
71pub struct PackageFont {
72 pub file: String,
74 pub family: String,
76 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#[derive(Clone, Debug, PartialEq)]
94pub struct ThemePackage {
95 pub file: TokenFile,
96 pub fonts: Vec<PackageFont>,
97}
98
99struct Entry {
101 file: String,
102 family: String,
103 weight: u16,
104}
105
106impl ThemePackage {
107 pub fn new(file: TokenFile) -> ThemePackage {
109 ThemePackage {
110 file,
111 fonts: Vec::new(),
112 }
113 }
114
115 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 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 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 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 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 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 #[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 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 #[cfg(not(feature = "zip"))]
275 pub fn from_zip(_bytes: &[u8]) -> Result<(ThemePackage, Vec<Warning>), Error> {
276 Err(no_zip())
277 }
278
279 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 #[cfg(feature = "zip")]
296 pub fn to_zip(&self) -> Result<Vec<u8>, Error> {
297 archive::pack(&self.files())
298 }
299
300 #[cfg(not(feature = "zip"))]
302 pub fn to_zip(&self) -> Result<Vec<u8>, Error> {
303 Err(no_zip())
304 }
305
306 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
328pub fn is_zip(path: &Path) -> bool {
330 path.extension()
331 .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
332}
333
334fn is_token_file(name: &str) -> bool {
336 TOKEN_FILE_ENDINGS.iter().any(|e| name.ends_with(e))
337}
338
339fn 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
383fn 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
392fn 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 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
438fn 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 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 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 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 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 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 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 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 assert!(matches!(warnings[0], Warning::Invalid { .. }));
681 assert!(matches!(warnings[1], Warning::Font { .. }));
682 assert!(matches!(warnings[2], Warning::Font { .. }));
683 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 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 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 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 assert!(ThemePackage::from_zip(b"not a zip").is_err());
746 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}