1use std::collections::{BTreeMap, BTreeSet};
5use std::fmt;
6use std::path::Path;
7use std::str::FromStr;
8
9use serde_json::{Map, Value as Json, json};
10
11use crate::cache::Cache;
12use crate::contract::{Tier, contract, required};
13use crate::file::{RawToken, TokenFile, alias_target};
14use crate::palette::{Backdrop, Ramp, Scheme, Seed};
15use crate::{Color, Error, Value, Warning};
16
17pub const FALLBACK_THEME: &str = "pop-dark";
19
20pub const ALPHA_EXTENSION: &str = "org.egui-pop.alpha";
26
27pub const VARIANT_OF_EXTENSION: &str = "org.egui-pop.variant-of";
34
35pub const COUNTERPART_EXTENSION: &str = "org.egui-pop.counterpart";
54
55impl TokenFile {
56 pub fn set_extension(&mut self, key: &str, value: Option<Json>) {
59 let mut root = match self.extensions.take() {
60 Some(Json::Object(m)) => m,
61 _ => Map::new(),
62 };
63 match value {
64 Some(v) => {
65 root.insert(key.to_string(), v);
66 }
67 None => {
68 root.remove(key);
69 }
70 }
71 self.extensions = (!root.is_empty()).then_some(Json::Object(root));
72 }
73
74 pub fn counterpart_file(&self) -> Option<Result<TokenFile, Error>> {
78 let raw = self.extensions.as_ref()?.get(COUNTERPART_EXTENSION)?;
79 let malformed = |reason: &str| Error::Malformed {
80 file: self.name.clone(),
81 path: format!("$extensions.{COUNTERPART_EXTENSION}"),
82 reason: reason.to_string(),
83 };
84 let Some(name) = raw
85 .get("name")
86 .and_then(Json::as_str)
87 .filter(|n| !n.is_empty())
88 else {
89 return Some(Err(malformed("no `name` naming the counterpart")));
90 };
91 if name == self.name {
92 return Some(Err(malformed("the counterpart has the file's own name")));
93 }
94 let Some(file) = raw.get("file").filter(|f| f.is_object()) else {
95 return Some(Err(malformed("no `file` giving the counterpart's tokens")));
96 };
97 Some(TokenFile::from_tree(name, file))
98 }
99
100 pub fn set_counterpart_file(&mut self, counterpart: Option<TokenFile>) {
104 match counterpart {
105 Some(mut other) => {
106 other.set_extension(VARIANT_OF_EXTENSION, Some(json!(self.name)));
107 self.set_extension(VARIANT_OF_EXTENSION, Some(json!(other.name)));
108 self.set_extension(
109 COUNTERPART_EXTENSION,
110 Some(json!({ "name": other.name, "file": other.to_json() })),
111 );
112 }
113 None => self.set_extension(COUNTERPART_EXTENSION, None),
114 }
115 }
116}
117
118pub const POP_THEMES: &[&str] = &["pop-dark", "pop-light", "pop-high-contrast"];
120
121pub const BUILT_IN_THEMES: &[&str] = &[
125 "pop-dark",
126 "pop-light",
127 "pop-high-contrast",
128 "github-light",
129 "github-dark",
130 "github-light-high-contrast",
131 "github-dark-high-contrast",
132 "catppuccin-latte",
133 "catppuccin-mocha",
134 "one-light",
135 "one-dark-pro",
136 "solarized-light",
137 "solarized-dark",
138 "gruvbox-light",
139 "gruvbox-dark",
140];
141
142const BUILT_IN_LABELS: &[(&str, &str)] = &[
146 ("pop-dark", "Pop dark"),
147 ("pop-light", "Pop light"),
148 ("pop-high-contrast", "Pop high contrast"),
149 ("github-light", "GitHub-inspired Light"),
150 ("github-dark", "GitHub-inspired Dark"),
151 (
152 "github-light-high-contrast",
153 "GitHub-inspired Light High Contrast",
154 ),
155 (
156 "github-dark-high-contrast",
157 "GitHub-inspired Dark High Contrast",
158 ),
159 ("catppuccin-latte", "Catppuccin-inspired Latte"),
160 ("catppuccin-mocha", "Catppuccin-inspired Mocha"),
161 ("one-light", "One Light-inspired"),
162 ("one-dark-pro", "One Dark Pro-inspired"),
163 ("solarized-light", "Solarized-inspired Light"),
164 ("solarized-dark", "Solarized-inspired Dark"),
165 ("gruvbox-light", "Gruvbox-inspired Light"),
166 ("gruvbox-dark", "Gruvbox-inspired Dark"),
167];
168
169pub fn theme_label(name: &str) -> String {
171 BUILT_IN_LABELS
172 .iter()
173 .find(|(id, _)| *id == name)
174 .map_or_else(|| name.to_string(), |(_, label)| (*label).to_string())
175}
176
177pub const BUILT_IN_ACCENTS: &[&str] = &["gold", "blue", "green", "amber", "red"];
179
180pub(crate) const KIT_FILES: &[(&str, &str)] = include!(concat!(env!("OUT_DIR"), "/kit_files.rs"));
184
185macro_rules! shipped {
188 ($name:literal) => {
189 include_str!(concat!(env!("OUT_DIR"), "/themes/", $name, ".tokens.json"))
190 };
191}
192
193const BUILT_IN_FILES: &[(&str, &str)] = &[
194 ("pop-dark", shipped!("pop-dark")),
195 ("pop-light", shipped!("pop-light")),
196 ("pop-high-contrast", shipped!("pop-high-contrast")),
197 ("github-light", shipped!("github-light")),
198 ("github-dark", shipped!("github-dark")),
199 (
200 "github-light-high-contrast",
201 shipped!("github-light-high-contrast"),
202 ),
203 (
204 "github-dark-high-contrast",
205 shipped!("github-dark-high-contrast"),
206 ),
207 ("catppuccin-latte", shipped!("catppuccin-latte")),
208 ("catppuccin-mocha", shipped!("catppuccin-mocha")),
209 ("one-light", shipped!("one-light")),
210 ("one-dark-pro", shipped!("one-dark-pro")),
211 ("solarized-light", shipped!("solarized-light")),
212 ("solarized-dark", shipped!("solarized-dark")),
213 ("gruvbox-light", shipped!("gruvbox-light")),
214 ("gruvbox-dark", shipped!("gruvbox-dark")),
215];
216
217pub const SEED_SCALE: &str = "custom";
221
222const ACCENT_ROLES: &[(&str, &str)] = &[
224 ("accent.default", "9"),
225 ("accent.hover", "10"),
226 ("accent.active", "8"),
227 ("accent.subtle", "3"),
228 ("text.on-accent", "contrast"),
229 ("selection", "5"),
230];
231
232#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
235pub enum Density {
236 #[default]
238 Comfortable,
239 Compact,
241}
242
243impl Density {
244 pub const ALL: [Density; 2] = [Density::Comfortable, Density::Compact];
245
246 pub fn name(self) -> &'static str {
247 match self {
248 Density::Comfortable => "comfortable",
249 Density::Compact => "compact",
250 }
251 }
252
253 pub fn built_in_file(self) -> TokenFile {
255 let text = match self {
256 Density::Comfortable => shipped!("density-comfortable"),
257 Density::Compact => shipped!("density-compact"),
258 };
259 TokenFile::parse(&format!("density-{}", self.name()), text)
260 .expect("built-in density files parse")
261 }
262}
263
264impl fmt::Display for Density {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 f.write_str(self.name())
267 }
268}
269
270impl FromStr for Density {
271 type Err = String;
272
273 fn from_str(s: &str) -> Result<Self, Self::Err> {
274 Density::ALL
275 .into_iter()
276 .find(|d| d.name() == s)
277 .ok_or_else(|| format!("`{s}` is not a density (comfortable, compact)"))
278 }
279}
280
281#[derive(Clone, Debug, Default, PartialEq, Eq)]
286#[non_exhaustive]
287pub enum Counterpart {
288 #[default]
291 Auto,
292 Theme(String),
294 None,
296}
297
298#[derive(Clone, Debug, PartialEq)]
314#[non_exhaustive]
315pub struct ThemeSpec {
316 pub base: String,
318 pub density: Density,
319 pub accent: Option<String>,
322 pub reduced_motion: bool,
324 pub overrides: BTreeMap<String, Json>,
326 pub counterpart: Counterpart,
328 pub counterpart_overrides: Option<BTreeMap<String, Json>>,
332 pub text_size: f32,
336 pub font_ui: Option<String>,
339 pub font_mono: Option<String>,
341 pub scroll_bars: ScrollBars,
344}
345
346#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
350pub enum ScrollBars {
351 #[default]
353 Auto,
354 Always,
357 Hover,
360}
361
362impl ScrollBars {
363 pub const CHOICES: [&'static str; 3] = ["auto", "always", "hover"];
365
366 pub fn as_str(self) -> &'static str {
367 match self {
368 ScrollBars::Auto => "auto",
369 ScrollBars::Always => "always",
370 ScrollBars::Hover => "hover",
371 }
372 }
373
374 pub fn parse(s: &str) -> Option<ScrollBars> {
375 [ScrollBars::Auto, ScrollBars::Always, ScrollBars::Hover]
376 .into_iter()
377 .find(|c| c.as_str() == s)
378 }
379}
380
381pub const TEXT_SIZES: [f32; 7] = [0.85, 1.0, 1.15, 1.3, 1.5, 1.75, 2.0];
384
385pub fn text_size_step(factor: f32) -> f32 {
387 TEXT_SIZES
388 .iter()
389 .copied()
390 .min_by(|a, b| (a - factor).abs().total_cmp(&(b - factor).abs()))
391 .unwrap_or(1.0)
392}
393
394const SIZE_SCALE: [&str; 5] = [
396 "font.size.xs",
397 "font.size.s",
398 "font.size.m",
399 "font.size.l",
400 "font.size.xl",
401];
402
403impl Default for ThemeSpec {
404 fn default() -> Self {
405 ThemeSpec::new(FALLBACK_THEME)
406 }
407}
408
409impl ThemeSpec {
410 pub fn new(base: impl Into<String>) -> ThemeSpec {
411 ThemeSpec {
412 base: base.into(),
413 density: Density::default(),
414 accent: None,
415 reduced_motion: false,
416 overrides: BTreeMap::new(),
417 counterpart: Counterpart::Auto,
418 counterpart_overrides: None,
419 text_size: 1.0,
420 font_ui: None,
421 font_mono: None,
422 scroll_bars: ScrollBars::Auto,
423 }
424 }
425
426 pub fn pair(dark: impl Into<String>, light: impl Into<String>) -> ThemeSpec {
438 ThemeSpec::new(dark).counterpart(light)
439 }
440
441 pub fn counterpart(mut self, theme: impl Into<String>) -> Self {
443 self.counterpart = Counterpart::Theme(theme.into());
444 self
445 }
446
447 pub fn alone(mut self) -> Self {
449 self.counterpart = Counterpart::None;
450 self
451 }
452
453 pub fn variant(&self, base: impl Into<String>) -> ThemeSpec {
456 let mut spec = self.clone();
457 spec.base = base.into();
458 spec.counterpart = Counterpart::None;
459 spec.counterpart_overrides = None;
460 spec
461 }
462
463 pub fn counterpart_variant(&self, other: impl Into<String>) -> ThemeSpec {
480 let mut spec = self.variant(other);
481 if let Some(own) = &self.counterpart_overrides {
482 spec.overrides = own.clone();
483 }
484 spec
485 }
486
487 pub fn density(mut self, density: Density) -> Self {
488 self.density = density;
489 self
490 }
491
492 pub fn accent(mut self, scale: impl Into<String>) -> Self {
496 self.accent = Some(scale.into());
497 self
498 }
499
500 pub fn accent_color(mut self, seed: Color) -> Self {
515 self.accent = Some(Color { a: 1.0, ..seed }.to_hex());
516 self
517 }
518
519 pub fn accent_seed(&self) -> Option<Color> {
521 self.accent
522 .as_deref()
523 .filter(|a| a.starts_with('#'))
524 .and_then(Color::from_hex)
525 }
526
527 pub fn reduced_motion(mut self, reduced: bool) -> Self {
528 self.reduced_motion = reduced;
529 self
530 }
531
532 pub fn text_size(mut self, factor: f32) -> Self {
552 self.text_size = text_size_step(factor);
553 self
554 }
555
556 pub fn scroll_bars(mut self, choice: ScrollBars) -> Self {
569 self.scroll_bars = choice;
570 self
571 }
572
573 pub fn font_ui(mut self, family: Option<String>) -> Self {
576 self.font_ui = family.filter(|f| !f.trim().is_empty());
577 self
578 }
579
580 pub fn font_mono(mut self, family: Option<String>) -> Self {
582 self.font_mono = family.filter(|f| !f.trim().is_empty());
583 self
584 }
585
586 pub fn override_token(mut self, path: impl Into<String>, value: Json) -> Self {
589 self.overrides.insert(path.into(), value);
590 self
591 }
592
593 pub fn counterpart_override(mut self, path: impl Into<String>, value: Json) -> Self {
597 self.counterpart_overrides
598 .get_or_insert_with(BTreeMap::new)
599 .insert(path.into(), value);
600 self
601 }
602
603 pub fn label(&self) -> String {
605 let mut parts = vec![self.base.clone(), self.density.name().to_string()];
606 if let Some(accent) = &self.accent {
607 parts.push(accent.clone());
608 }
609 if self.reduced_motion {
610 parts.push("reduced motion".into());
611 }
612 if (self.text_size - 1.0).abs() > f32::EPSILON {
613 parts.push(format!("text {}%", (self.text_size * 100.0).round()));
614 }
615 if self.scroll_bars != ScrollBars::Auto {
616 parts.push(format!("scroll bars {}", self.scroll_bars.as_str()));
617 }
618 for f in [&self.font_ui, &self.font_mono].into_iter().flatten() {
619 parts.push(f.clone());
620 }
621 if !self.overrides.is_empty() {
622 parts.push(format!("{} overrides", self.overrides.len()));
623 }
624 parts.join(" · ")
625 }
626}
627
628#[derive(Clone, Debug, PartialEq)]
630pub struct Token {
631 pub path: String,
632 pub ty: String,
634 pub value: Value,
635 pub alias: Option<String>,
637 pub description: Option<String>,
638 pub extensions: Option<Json>,
640 pub fallback: bool,
642}
643
644impl Token {
645 pub fn tier(&self) -> Tier {
647 required(&self.path).map_or(Tier::Reference, |r| r.tier)
648 }
649}
650
651#[derive(Clone, Debug, PartialEq)]
653pub struct ResolvedTokens {
654 spec: ThemeSpec,
655 tokens: BTreeMap<String, Token>,
656 problems: Vec<Error>,
657}
658
659impl ResolvedTokens {
660 pub fn spec(&self) -> &ThemeSpec {
661 &self.spec
662 }
663
664 pub fn problems(&self) -> &[Error] {
666 &self.problems
667 }
668
669 pub fn get(&self, path: &str) -> Option<&Token> {
670 self.tokens.get(path)
671 }
672
673 pub fn value(&self, path: &str) -> Option<&Value> {
674 self.tokens.get(path).map(|t| &t.value)
675 }
676
677 pub fn color(&self, path: &str) -> Option<Color> {
678 match self.value(path)? {
679 Value::Color(c) => Some(*c),
680 _ => None,
681 }
682 }
683
684 pub fn dimension(&self, path: &str) -> Option<f32> {
686 match self.value(path)? {
687 Value::Dimension(d) | Value::Number(d) => Some(*d),
688 _ => None,
689 }
690 }
691
692 pub fn duration_ms(&self, path: &str) -> Option<f32> {
694 match self.value(path)? {
695 Value::Duration(ms) => Some(*ms),
696 _ => None,
697 }
698 }
699
700 pub fn font_family(&self, path: &str) -> Option<&[String]> {
701 match self.value(path)? {
702 Value::FontFamily(f) => Some(f),
703 _ => None,
704 }
705 }
706
707 pub fn iter(&self) -> impl Iterator<Item = &Token> {
709 self.tokens.values()
710 }
711
712 pub fn len(&self) -> usize {
713 self.tokens.len()
714 }
715
716 pub fn is_empty(&self) -> bool {
717 self.tokens.is_empty()
718 }
719
720 pub fn is_dark(&self) -> bool {
722 self.color("surface.panel").is_some_and(Color::is_dark)
723 }
724
725 pub fn to_dtcg(&self) -> Json {
728 let mut root = Map::new();
729 root.insert("$description".into(), json!(self.spec.label()));
730 for token in self.tokens.values() {
731 let mut node = &mut root;
732 let parts: Vec<&str> = token.path.split('.').collect();
733 let (leaf, groups) = parts.split_last().expect("paths are not empty");
734 for part in groups {
735 node = node
736 .entry(part.to_string())
737 .or_insert_with(|| json!({}))
738 .as_object_mut()
739 .expect("groups are objects");
740 }
741 let mut entry = Map::new();
742 entry.insert("$type".into(), json!(token.ty));
743 entry.insert("$value".into(), token.value.to_json());
744 if let Some(d) = &token.description {
745 entry.insert("$description".into(), json!(d));
746 }
747 if let Some(e) = without_alpha(token.extensions.as_ref()) {
750 entry.insert("$extensions".into(), e);
751 }
752 node.insert(leaf.to_string(), Json::Object(entry));
753 }
754 Json::Object(root)
755 }
756}
757
758#[derive(Clone, Debug)]
760pub struct Themes {
761 themes: BTreeMap<String, TokenFile>,
762 densities: BTreeMap<Density, TokenFile>,
763}
764
765impl Default for Themes {
766 fn default() -> Self {
768 let mut themes = Themes {
769 themes: BTreeMap::new(),
770 densities: Density::ALL
771 .into_iter()
772 .map(|d| (d, d.built_in_file()))
773 .collect(),
774 };
775 for (name, text) in BUILT_IN_FILES {
776 let mut file = TokenFile::parse(name, text).expect("built-in themes parse");
777 if *name == FALLBACK_THEME {
778 let kit = crate::kit::built_in(KIT_FILES);
781 for p in kit.problems() {
782 if matches!(
783 p,
784 crate::kit::Problem::Tokens(_) | crate::kit::Problem::Repeated { .. }
785 ) {
786 panic!("the default kit: {p}");
787 }
788 }
789 for (path, token) in kit.theme.tokens {
790 let clash = file.tokens.insert(path.clone(), token);
791 assert!(clash.is_none(), "the default kit repeats {path}");
792 }
793 }
794 themes.add(file);
795 }
796 themes
797 }
798}
799
800impl Themes {
801 pub fn add(&mut self, theme: TokenFile) -> Option<TokenFile> {
803 self.themes.insert(theme.name.clone(), theme)
804 }
805
806 pub fn add_text(&mut self, name: &str, text: &str) -> Result<Vec<Warning>, Error> {
816 let (file, mut warnings) = self.check_file(TokenFile::parse(name, text)?);
817 warnings.extend(self.add_counterpart_of(&file));
818 self.add(file);
819 Ok(warnings)
820 }
821
822 fn add_counterpart_of(&mut self, file: &TokenFile) -> Vec<Warning> {
824 match file.counterpart_file() {
825 None => Vec::new(),
826 Some(Ok(other)) => {
827 let (other, warnings) = self.check_file(other);
828 self.add(other);
829 warnings
830 }
831 Some(Err(e)) => vec![Warning::Invalid {
832 path: format!("$extensions.{COUNTERPART_EXTENSION}"),
833 reason: e.to_string(),
834 }],
835 }
836 }
837
838 pub fn add_path(&mut self, name: &str, path: &Path) -> Result<Vec<Warning>, Error> {
844 self.add_path_with(name, path, &crate::cache::default())
845 }
846
847 pub fn add_path_with(
851 &mut self,
852 name: &str,
853 path: &Path,
854 cache: &Cache,
855 ) -> Result<Vec<Warning>, Error> {
856 let (file, unwritten) = TokenFile::read(name, path, cache);
857 let (file, mut warnings) = self.check_file(file?);
858 warnings.extend(self.add_counterpart_of(&file));
859 self.add(file);
860 if let Some(e) = unwritten {
861 warnings.push(Warning::NotCached {
862 file: path.display().to_string(),
863 reason: e.to_string(),
864 });
865 }
866 Ok(warnings)
867 }
868
869 pub fn check_file(&self, mut file: TokenFile) -> (TokenFile, Vec<Warning>) {
882 let mut warnings = file.upgrade();
883 warnings.extend(file.seeds().1);
884 let base = file
885 .extends
886 .clone()
887 .unwrap_or_else(|| FALLBACK_THEME.to_string());
888 if base != file.name && !self.themes.contains_key(&base) {
889 warnings.push(Warning::Unchecked { base });
890 return (file, warnings);
891 }
892 let base_raw = self.flatten(&base, &mut Vec::new());
893 let groups: BTreeSet<&str> = contract()
894 .filter_map(|r| r.path.split('.').next())
895 .collect();
896 let terms: BTreeSet<&str> = base_raw
897 .keys()
898 .filter_map(|p| p.rsplit('.').next())
899 .collect();
900 for path in file.tokens.keys() {
901 if base_raw.contains_key(path) || required(path).is_some() {
902 continue;
903 }
904 let group = path.split('.').next().unwrap_or_default();
905 let term = path.rsplit('.').next().unwrap_or_default();
906 if groups.contains(group) && !terms.contains(term) {
907 warnings.push(Warning::Unknown {
908 path: path.clone(),
909 base: base.clone(),
910 kept: true,
911 });
912 }
913 }
914 let mut trial = self.clone();
919 trial.densities.clear();
920 let base_types: BTreeMap<String, String> = trial
921 .resolve_without_fallback(&ThemeSpec::new(base.clone()))
922 .tokens
923 .into_iter()
924 .map(|(path, t)| (path, t.ty))
925 .collect();
926 loop {
927 trial.add(file.clone());
928 let r = trial.resolve_without_fallback(&ThemeSpec::new(file.name.clone()));
929 let mut bad: BTreeMap<String, String> = BTreeMap::new();
930 for p in &r.problems {
931 if matches!(p, Error::Missing { .. } | Error::UnknownOverride { .. }) {
932 continue;
933 }
934 let own: Vec<&str> = match p {
935 Error::AliasCycle { chain } => chain.iter().map(String::as_str).collect(),
936 _ => p.path().into_iter().collect(),
937 };
938 for path in own {
939 if file.tokens.contains_key(path) {
940 bad.entry(path.to_string()).or_insert_with(|| p.to_string());
941 }
942 }
943 }
944 for (path, t) in &r.tokens {
945 if let Some(ty) = base_types.get(path)
946 && *ty != t.ty
947 && file.tokens.contains_key(path)
948 {
949 bad.entry(path.clone())
950 .or_insert_with(|| format!("a {}, where `{base}` has a {ty}", t.ty));
951 }
952 }
953 if bad.is_empty() {
954 break;
955 }
956 for (path, reason) in bad {
957 file.tokens.remove(&path);
958 warnings.push(Warning::Invalid { path, reason });
959 }
960 }
961 (file, warnings)
962 }
963
964 pub fn set_density(&mut self, density: Density, overlay: TokenFile) {
966 self.densities.insert(density, overlay);
967 }
968
969 pub fn get(&self, name: &str) -> Option<&TokenFile> {
970 self.themes.get(name)
971 }
972
973 pub fn counterpart_of(&self, name: &str) -> Option<&str> {
978 let named = |file: &TokenFile| {
979 file.extensions
980 .as_ref()
981 .and_then(|e| e.get(VARIANT_OF_EXTENSION))
982 .and_then(Json::as_str)
983 .map(String::from)
984 };
985 if let Some(other) = self.themes.get(name).and_then(named)
986 && other != name
987 && let Some((key, _)) = self.themes.get_key_value(&other)
988 {
989 return Some(key);
990 }
991 self.themes
992 .iter()
993 .find(|(n, file)| n.as_str() != name && named(file).as_deref() == Some(name))
994 .map(|(n, _)| n.as_str())
995 }
996
997 pub fn counterpart(&self, spec: &ThemeSpec) -> Option<String> {
1000 match &spec.counterpart {
1001 Counterpart::Auto => self.counterpart_of(&spec.base).map(String::from),
1002 Counterpart::Theme(t) => {
1003 (*t != spec.base && self.themes.contains_key(t)).then(|| t.clone())
1004 }
1005 Counterpart::None => None,
1006 }
1007 }
1008
1009 pub fn resolve_counterpart(&self, spec: &ThemeSpec) -> Option<ResolvedTokens> {
1014 self.counterpart(spec)
1015 .map(|other| self.resolve(&spec.counterpart_variant(other)))
1016 }
1017
1018 pub fn names(&self) -> impl Iterator<Item = &str> {
1020 self.themes.keys().map(String::as_str)
1021 }
1022
1023 pub(crate) fn flatten(
1026 &self,
1027 name: &str,
1028 problems: &mut Vec<Error>,
1029 ) -> BTreeMap<String, RawToken> {
1030 let mut chain: Vec<String> = Vec::new();
1031 let mut at = Some(name.to_string());
1032 while let Some(n) = at {
1033 if chain.contains(&n) {
1034 chain.push(n);
1035 problems.push(Error::ExtendsCycle {
1036 chain: chain.clone(),
1037 });
1038 chain.pop();
1039 break;
1040 }
1041 let Some(theme) = self.themes.get(&n) else {
1042 problems.push(Error::UnknownTheme { name: n });
1043 if !chain.iter().any(|c| c == FALLBACK_THEME) {
1044 chain.push(FALLBACK_THEME.to_string());
1045 }
1046 break;
1047 };
1048 chain.push(n);
1049 at = theme.extends.clone();
1050 }
1051 let mut tokens = BTreeMap::new();
1052 for n in chain.iter().rev() {
1053 if let Some(theme) = self.themes.get(n) {
1054 let (seeds, _) = theme.seeds();
1057 if !seeds.is_empty() {
1058 let generated = seeded_scales(&tokens, &theme.tokens, &seeds);
1059 layer(&mut tokens, &generated);
1060 }
1061 layer(&mut tokens, &theme.tokens);
1062 }
1063 }
1064 tokens
1065 }
1066
1067 pub fn accents(&self, base: &str) -> Vec<String> {
1069 let raw = self.flatten(base, &mut Vec::new());
1070 let mut scales: Vec<String> = raw
1071 .keys()
1072 .filter_map(|p| p.strip_suffix(".contrast"))
1073 .filter(|s| is_accent_scale(&raw, s))
1074 .map(String::from)
1075 .collect();
1076 scales.sort_by_key(|s| {
1077 BUILT_IN_ACCENTS
1078 .iter()
1079 .position(|b| b == s)
1080 .unwrap_or(usize::MAX)
1081 });
1082 scales
1083 }
1084
1085 pub fn resolve(&self, spec: &ThemeSpec) -> ResolvedTokens {
1089 let mut resolved = self.resolve_without_fallback(spec);
1090 let missing: Vec<&str> = contract()
1091 .filter(|r| resolved.tokens.get(r.path).is_none_or(|t| t.ty != r.ty))
1092 .map(|r| r.path)
1093 .collect();
1094 if missing.is_empty() {
1095 return resolved;
1096 }
1097 let mut fallback_spec = spec.clone();
1098 fallback_spec.base = FALLBACK_THEME.to_string();
1099 fallback_spec.overrides.clear();
1100 let fallback = Themes::default().resolve_without_fallback(&fallback_spec);
1101 for path in missing {
1102 if let Some(t) = fallback.tokens.get(path) {
1103 let mut t = t.clone();
1104 t.fallback = true;
1105 resolved.tokens.insert(path.to_string(), t);
1106 }
1107 }
1108 resolved
1109 }
1110
1111 fn resolve_without_fallback(&self, spec: &ThemeSpec) -> ResolvedTokens {
1113 let mut problems = Vec::new();
1114 let mut raw = self.flatten(&spec.base, &mut problems);
1115 if let Some(density) = self.densities.get(&spec.density) {
1116 layer(&mut raw, &density.tokens);
1117 }
1118 if let Some(asked) = &spec.accent {
1119 let scale = match spec.accent_seed() {
1120 Some(seed) => {
1121 let color = |path: &str| match resolve_one(&raw, path) {
1122 Ok((_, Value::Color(c))) => Some(c),
1123 _ => None,
1124 };
1125 let scheme = color("surface.panel").map_or(Scheme::Dark, Scheme::of_background);
1126 let backdrop = Backdrop::from_tokens(color);
1127 for (path, value) in Ramp::fitted(seed, scheme, &backdrop).tokens(SEED_SCALE) {
1128 raw.insert(
1129 path,
1130 RawToken {
1131 ty: Some("color".into()),
1132 value,
1133 description: Some(format!("Generated from {}.", seed.to_hex())),
1134 extensions: None,
1135 },
1136 );
1137 }
1138 SEED_SCALE
1139 }
1140 None => asked.as_str(),
1141 };
1142 if is_accent_scale(&raw, scale) {
1143 for (role, step) in ACCENT_ROLES {
1144 let entry = raw.entry(role.to_string()).or_insert_with(|| RawToken {
1145 ty: Some("color".into()),
1146 value: Json::Null,
1147 description: None,
1148 extensions: None,
1149 });
1150 entry.value = json!(format!("{{{scale}.{step}}}"));
1151 }
1152 } else {
1153 problems.push(Error::UnknownAccent {
1154 name: asked.clone(),
1155 });
1156 }
1157 }
1158 if spec.reduced_motion {
1159 let entry = raw
1160 .entry("motion.duration".to_string())
1161 .or_insert_with(|| RawToken {
1162 ty: Some("duration".into()),
1163 value: Json::Null,
1164 description: None,
1165 extensions: None,
1166 });
1167 entry.value = json!({ "value": 0, "unit": "ms" });
1168 }
1169 inherit(&mut raw, &mut problems);
1170 for (path, value) in &spec.overrides {
1171 match raw.get_mut(path) {
1172 Some(token) => {
1175 token.value = value.clone();
1176 token.extensions = without_alpha(token.extensions.as_ref());
1177 }
1178 None => problems.push(Error::UnknownOverride { path: path.clone() }),
1179 }
1180 }
1181 user_fonts(&mut raw, spec);
1182 text_size(&mut raw, spec.text_size);
1183 user_scroll_bars(&mut raw, spec.scroll_bars);
1184
1185 let mut tokens = BTreeMap::new();
1186 for (path, token) in &raw {
1187 match resolve_one(&raw, path) {
1188 Ok((ty, value)) => {
1189 let contract = required(path);
1190 if let Some(r) = contract.filter(|r| r.ty != ty) {
1191 problems.push(Error::TypeMismatch {
1192 path: path.clone(),
1193 expected: r.ty.to_string(),
1194 found: ty,
1195 });
1196 continue;
1197 }
1198 tokens.insert(
1199 path.clone(),
1200 Token {
1201 path: path.clone(),
1202 ty,
1203 value,
1204 alias: token.alias().map(String::from),
1205 description: token.description.clone(),
1206 extensions: token.extensions.clone(),
1207 fallback: false,
1208 },
1209 );
1210 }
1211 Err(e) => {
1214 if !problems.contains(&e) {
1215 problems.push(e);
1216 }
1217 }
1218 }
1219 }
1220 for r in contract() {
1221 if !raw.contains_key(r.path) {
1222 problems.push(Error::Missing {
1223 path: r.path.to_string(),
1224 });
1225 }
1226 }
1227 ResolvedTokens {
1228 spec: spec.clone(),
1229 tokens,
1230 problems,
1231 }
1232 }
1233}
1234
1235fn user_fonts(raw: &mut BTreeMap<String, RawToken>, spec: &ThemeSpec) {
1238 for (path, family) in [
1239 ("font.family.ui", &spec.font_ui),
1240 ("font.family.mono", &spec.font_mono),
1241 ] {
1242 let Some(family) = family else { continue };
1243 let theirs = match resolve_one(raw, path) {
1244 Ok((_, Value::FontFamily(list))) => list,
1245 _ => Vec::new(),
1246 };
1247 let mut list = vec![family.clone()];
1248 list.extend(theirs.into_iter().filter(|f| f != family));
1249 let entry = raw.entry(path.to_string()).or_insert_with(|| RawToken {
1250 ty: Some("fontFamily".into()),
1251 value: Json::Null,
1252 description: None,
1253 extensions: None,
1254 });
1255 entry.value = json!(list);
1256 }
1257}
1258
1259fn user_scroll_bars(raw: &mut BTreeMap<String, RawToken>, choice: ScrollBars) {
1264 let (visibility, placement) = match choice {
1265 ScrollBars::Auto => return,
1266 ScrollBars::Always => ("always", "beside"),
1267 ScrollBars::Hover => ("hover", "over"),
1268 };
1269 for (path, value) in [
1270 ("scroll-bar.visibility", visibility),
1271 ("scroll-bar.placement", placement),
1272 ] {
1273 let entry = raw.entry(path.to_string()).or_insert_with(|| RawToken {
1274 ty: Some("string".into()),
1275 value: Json::Null,
1276 description: None,
1277 extensions: None,
1278 });
1279 entry.value = json!(value);
1280 }
1281 if choice == ScrollBars::Always
1282 && let Ok((_, Value::Color(track))) = resolve_one(raw, "scroll-bar.track-fill")
1283 && track.a == 0.0
1284 && let Some(token) = raw.get_mut("scroll-bar.track-fill")
1285 {
1286 token.value = json!("{surface.sunken}");
1287 token.extensions = without_alpha(token.extensions.as_ref());
1288 }
1289}
1290
1291fn text_size(raw: &mut BTreeMap<String, RawToken>, factor: f32) {
1294 if (factor - 1.0).abs() <= f32::EPSILON || !factor.is_finite() || factor <= 0.0 {
1295 return;
1296 }
1297 for path in SIZE_SCALE {
1298 let Ok((_, Value::Dimension(size))) = resolve_one(raw, path) else {
1299 continue;
1300 };
1301 let scaled = (size * factor * 2.0).round() / 2.0;
1302 if let Some(token) = raw.get_mut(path) {
1303 token.value = json!({ "value": scaled, "unit": "px" });
1304 }
1305 }
1306 let body = match resolve_one(raw, "font.text-style.body") {
1307 Ok((_, Value::Dimension(b))) => b,
1308 _ => return,
1309 };
1310 if let Ok((_, Value::Dimension(height))) = resolve_one(raw, "size.control.height") {
1311 let wanted = (body * 1.6).ceil();
1312 if wanted > height
1313 && let Some(token) = raw.get_mut("size.control.height")
1314 {
1315 token.value = json!({ "value": wanted, "unit": "px" });
1316 }
1317 }
1318}
1319
1320pub const BASED_ON: &str = "based-on";
1323
1324pub(crate) fn base_of<'a>(raw: &'a BTreeMap<String, RawToken>, component: &str) -> Option<&'a str> {
1327 let token = raw.get(&format!("{component}.{BASED_ON}"))?;
1328 token
1329 .value
1330 .as_str()
1331 .filter(|_| alias_target(&token.value).is_none())
1332}
1333
1334fn inherit(raw: &mut BTreeMap<String, RawToken>, problems: &mut Vec<Error>) {
1343 let suffix = format!(".{BASED_ON}");
1344 let mut bases: BTreeMap<String, String> = BTreeMap::new();
1345 for (path, token) in raw.iter() {
1346 let Some(component) = path.strip_suffix(&suffix) else {
1347 continue;
1348 };
1349 if component.contains('.') {
1350 continue;
1351 }
1352 match base_of(raw, component) {
1353 Some(base) if !base.is_empty() => {
1354 bases.insert(component.to_string(), base.to_string());
1355 }
1356 _ => problems.push(Error::InvalidValue {
1357 path: path.clone(),
1358 ty: "string".into(),
1359 reason: format!("`{}` does not name a component", token.value),
1360 }),
1361 }
1362 }
1363 if bases.is_empty() {
1364 return;
1365 }
1366 let mut cyclic: BTreeSet<String> = BTreeSet::new();
1368 for start in bases.keys() {
1369 let mut chain = vec![start.clone()];
1370 let mut at = start;
1371 while let Some(next) = bases.get(at) {
1372 if let Some(i) = chain.iter().position(|c| c == next) {
1373 let members = &chain[i..];
1374 if members.iter().all(|m| !cyclic.contains(m)) {
1375 let mut shown = members.to_vec();
1376 shown.push(next.clone());
1377 problems.push(Error::BasedOnCycle { chain: shown });
1378 cyclic.extend(members.iter().cloned());
1379 }
1380 break;
1381 }
1382 chain.push(next.clone());
1383 at = next;
1384 }
1385 }
1386 let mut done: BTreeSet<String> = BTreeSet::new();
1387 let components: Vec<String> = bases.keys().cloned().collect();
1388 for component in components {
1389 complete(raw, &bases, &cyclic, &mut done, &component, problems);
1390 }
1391}
1392
1393fn complete(
1395 raw: &mut BTreeMap<String, RawToken>,
1396 bases: &BTreeMap<String, String>,
1397 cyclic: &BTreeSet<String>,
1398 done: &mut BTreeSet<String>,
1399 component: &str,
1400 problems: &mut Vec<Error>,
1401) {
1402 if cyclic.contains(component) || !done.insert(component.to_string()) {
1403 return;
1404 }
1405 let Some(base) = bases.get(component) else {
1406 return;
1407 };
1408 complete(raw, bases, cyclic, done, base, problems);
1409 let prefix = format!("{base}.");
1410 let inherited: Vec<(String, RawToken)> = raw
1411 .range(prefix.clone()..)
1412 .take_while(|(path, _)| path.starts_with(&prefix))
1413 .filter_map(|(path, token)| {
1414 let term = &path[prefix.len()..];
1415 if term == BASED_ON {
1416 return None;
1417 }
1418 let own = format!("{component}.{term}");
1419 (!raw.contains_key(&own)).then(|| {
1420 (
1421 own,
1422 RawToken {
1423 ty: token.ty.clone(),
1424 value: json!(format!("{{{path}}}")),
1425 description: None,
1426 extensions: None,
1427 },
1428 )
1429 })
1430 })
1431 .collect();
1432 let has_base = raw
1433 .range(prefix.clone()..)
1434 .next()
1435 .is_some_and(|(path, _)| path.starts_with(&prefix));
1436 if !has_base {
1437 problems.push(Error::UnknownBase {
1438 path: format!("{component}.{BASED_ON}"),
1439 base: base.clone(),
1440 });
1441 return;
1442 }
1443 raw.extend(inherited);
1444}
1445
1446fn layer(under: &mut BTreeMap<String, RawToken>, over: &BTreeMap<String, RawToken>) {
1449 for (path, token) in over {
1450 let mut token = token.clone();
1451 if token.ty.is_none() {
1452 token.ty = under.get(path).and_then(|t| t.ty.clone());
1453 }
1454 if token.description.is_none() {
1455 token.description = under.get(path).and_then(|t| t.description.clone());
1456 }
1457 under.insert(path.clone(), token);
1458 }
1459}
1460
1461pub(crate) fn in_scales<'a>(mut scales: impl Iterator<Item = &'a String>, path: &str) -> bool {
1463 scales.any(|s| {
1464 path.strip_prefix(s.as_str())
1465 .is_some_and(|rest| rest.starts_with('.'))
1466 })
1467}
1468
1469pub(crate) fn seed_backdrop(
1473 under: &BTreeMap<String, RawToken>,
1474 own: &BTreeMap<String, RawToken>,
1475 seeds: &BTreeMap<String, Seed>,
1476) -> (Backdrop, Scheme) {
1477 let mut raw = under.clone();
1478 let others: BTreeMap<String, RawToken> = own
1479 .iter()
1480 .filter(|(p, _)| !in_scales(seeds.keys(), p))
1481 .map(|(p, t)| (p.clone(), t.clone()))
1482 .collect();
1483 layer(&mut raw, &others);
1484 let color = |path: &str| match resolve_one(&raw, path) {
1485 Ok((_, Value::Color(c))) => Some(c),
1486 _ => None,
1487 };
1488 let scheme = color("surface.panel").map_or(Scheme::Dark, Scheme::of_background);
1489 (Backdrop::from_tokens(color), scheme)
1490}
1491
1492pub(crate) fn seeded_scales(
1499 under: &BTreeMap<String, RawToken>,
1500 own: &BTreeMap<String, RawToken>,
1501 seeds: &BTreeMap<String, Seed>,
1502) -> BTreeMap<String, RawToken> {
1503 let (backdrop, scheme) = seed_backdrop(under, own, seeds);
1504 let mut out = BTreeMap::new();
1505 for (scale, seed) in seeds {
1506 let ramp = Ramp::fitted(seed.color, seed.scheme.unwrap_or(scheme), &backdrop);
1507 let known = under.contains_key(&format!("{scale}.1"));
1508 for (path, value) in ramp.tokens(scale) {
1509 if known && !under.contains_key(&path) && !own.contains_key(&path) {
1510 continue;
1511 }
1512 out.insert(
1513 path,
1514 RawToken {
1515 ty: Some("color".into()),
1516 value,
1517 description: Some(format!("Generated from {}.", seed.color.to_hex())),
1518 extensions: None,
1519 },
1520 );
1521 }
1522 }
1523 out
1524}
1525
1526fn is_accent_scale(raw: &BTreeMap<String, RawToken>, scale: &str) -> bool {
1527 ACCENT_ROLES
1528 .iter()
1529 .all(|(_, step)| raw.contains_key(&format!("{scale}.{step}")))
1530}
1531
1532fn without_alpha(extensions: Option<&Json>) -> Option<Json> {
1535 let mut e = extensions?.clone();
1536 if let Some(map) = e.as_object_mut() {
1537 map.remove(ALPHA_EXTENSION);
1538 if map.is_empty() {
1539 return None;
1540 }
1541 }
1542 Some(e)
1543}
1544
1545fn alpha_of(path: &str, token: &RawToken) -> Result<Option<f32>, Error> {
1547 let Some(a) = token
1548 .extensions
1549 .as_ref()
1550 .and_then(|e| e.get(ALPHA_EXTENSION))
1551 else {
1552 return Ok(None);
1553 };
1554 match a.as_f64() {
1555 Some(a) if (0.0..=1.0).contains(&a) => Ok(Some(a as f32)),
1556 _ => Err(Error::InvalidModifier {
1557 path: path.to_string(),
1558 reason: format!("`{ALPHA_EXTENSION}` is {a}, not a number from 0 to 1"),
1559 }),
1560 }
1561}
1562
1563fn resolve_one(raw: &BTreeMap<String, RawToken>, path: &str) -> Result<(String, Value), Error> {
1565 let mut chain = vec![path.to_string()];
1566 let mut declared = raw.get(path).and_then(|t| t.ty.clone());
1567 let mut at = raw.get(path).ok_or_else(|| Error::Missing {
1568 path: path.to_string(),
1569 })?;
1570 let mut alpha = alpha_of(path, at)?.map(|a| (a, path.to_string()));
1572 while let Some(target) = alias_target(&at.value) {
1573 if chain.iter().any(|c| c == target) {
1574 chain.push(target.to_string());
1575 return Err(Error::AliasCycle { chain });
1576 }
1577 let next = raw.get(target).ok_or_else(|| Error::UnknownAlias {
1578 path: chain.last().cloned().unwrap_or_default(),
1579 target: target.to_string(),
1580 })?;
1581 if let (Some(d), Some(t)) = (&declared, &next.ty)
1582 && d != t
1583 {
1584 return Err(Error::TypeMismatch {
1585 path: path.to_string(),
1586 expected: d.clone(),
1587 found: format!("{t} (through `{{{target}}}`)"),
1588 });
1589 }
1590 declared = declared.or_else(|| next.ty.clone());
1591 if let Some(a) = alpha_of(target, next)? {
1592 alpha = Some(match alpha {
1593 Some((b, carrier)) => (a * b, carrier),
1594 None => (a, target.to_string()),
1595 });
1596 }
1597 chain.push(target.to_string());
1598 at = next;
1599 }
1600 let ty = declared.ok_or_else(|| Error::MissingType {
1601 path: path.to_string(),
1602 })?;
1603 let mut value = Value::parse(&ty, &at.value).map_err(|reason| Error::InvalidValue {
1604 path: path.to_string(),
1605 ty: ty.clone(),
1606 reason,
1607 })?;
1608 if let Some((a, carrier)) = alpha {
1609 match &mut value {
1610 Value::Color(c) => c.a *= a,
1611 _ => {
1612 return Err(Error::InvalidModifier {
1613 path: carrier,
1614 reason: format!("`{ALPHA_EXTENSION}` is for colours, this is a {ty}"),
1615 });
1616 }
1617 }
1618 }
1619 Ok((ty, value))
1620}