1use 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
90pub const KIT_FILE: &str = "kit.yaml";
92
93pub const KIT_FILES: &[&str] = &["kit.yaml", "kit.yml", "kit.json"];
95
96pub const TOKEN_FILE_ENDINGS: &[&str] = &[".tokens.yaml", ".tokens.yml", ".tokens.json"];
98
99pub const KIT_EXTENSION: &str = "org.egui-pop.kit";
101
102pub const USER_KITS_DIR: &str = "kits";
105
106pub const STATES: [&str; 6] = ["rest", "selected", "hover", "focus", "active", "disabled"];
108
109pub 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
123pub 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
154pub const TONES: [&str; 7] = [
157 "accent", "info", "success", "warning", "danger", "muted", "record",
158];
159
160pub 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
186pub 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
202pub type Bytes = Cow<'static, [u8]>;
204
205#[derive(Clone, PartialEq)]
207pub struct KitFont {
208 pub file: String,
210 pub family: String,
212 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#[derive(Clone, Debug, PartialEq, Eq)]
230pub enum Origin {
231 Embedded(&'static str),
234 Dir(PathBuf),
236}
237
238#[derive(Clone, Debug, PartialEq)]
241#[non_exhaustive]
242pub enum Problem {
243 Io { file: String, message: String },
245 Tokens(Error),
249 Repeated { path: String, file: String },
252 Extends { file: String },
255 UnknownTerm { path: String, reason: String },
258 UnknownComponent { path: String, component: String },
260 TermType {
263 path: String,
264 expected: String,
265 found: String,
266 },
267 Manifest { reason: String },
270 Font { file: String, reason: String },
273 Name { asked: String, used: String },
276 NotCached { file: String, reason: String },
280 NotRead { what: String },
282 Format { file: String, warning: Warning },
288 Theme(Error),
290 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#[derive(Clone, Debug)]
352pub struct Embedded {
353 pub dir: &'static str,
355 pub kit: &'static str,
357 pub tokens: Vec<(String, &'static str)>,
359 pub fonts: Vec<(&'static str, &'static [u8])>,
361 pub license: Option<&'static str>,
362}
363
364#[derive(Clone, Debug, PartialEq)]
368pub struct KitData {
369 pub name: String,
371 pub label: Option<String>,
373 pub theme: TokenFile,
375 pub counterpart: Option<KitVariant>,
379 pub fonts: Vec<KitFont>,
380 pub license: Option<String>,
381 pub origin: Origin,
382 manifest_fonts: Vec<String>,
384 problems: Vec<Problem>,
385}
386
387impl KitData {
388 pub fn load(dir: impl AsRef<Path>) -> KitData {
394 KitData::load_with(dir, &crate::cache::default())
395 }
396
397 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 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 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 pub fn problems(&self) -> &[Problem] {
542 &self.problems
543 }
544
545 pub fn display_name(&self) -> &str {
547 self.label.as_deref().unwrap_or(&self.name)
548 }
549
550 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 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#[derive(Clone, Debug, PartialEq)]
582pub struct KitVariant {
583 pub name: String,
585 pub label: Option<String>,
587 pub theme: TokenFile,
589}
590
591impl KitVariant {
592 pub fn display_name(&self) -> &str {
594 self.label.as_deref().unwrap_or(&self.name)
595 }
596}
597
598#[derive(Clone, Debug, PartialEq, Eq)]
600pub struct KitInfo {
601 pub name: String,
603 pub label: String,
604 pub description: Option<String>,
606 pub origin: Origin,
607 pub problems: usize,
609}
610
611impl Themes {
612 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
624pub 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
669pub fn discover(dir: impl AsRef<Path>) -> Vec<KitData> {
674 discover_with(dir, &crate::cache::default())
675}
676
677pub 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
691pub(crate) fn built_in(files: &[(&str, &'static str)]) -> KitData {
694 KitData::embedded(Embedded {
695 dir: "themes/kit",
696 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
707pub 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 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
838fn 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
858fn 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
909pub(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
926struct 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
1041const 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
1064fn 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
1093fn 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#[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 for path in ["tab.shape", "button.rest.fill", "field.rest.fill"] {
1299 assert!(kit.theme.tokens.contains_key(path), "{path}");
1300 }
1301 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 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 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 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 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 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}