Skip to main content

egui_pop_tokens/
format.rs

1//! What a token file says about itself: its format stamp, the renames
2//! a file written for an older contract goes through, and the warnings
3//! a file loads with.
4//!
5//! The stamp sits in the root's `$extensions`:
6//!
7//! ```json
8//! { "$extensions": { "org.egui-pop.format": { "version": 1, "contract": 1 } } }
9//! ```
10//!
11//! A file without it is read as current, so a file written by hand needs
12//! none. A file stamped newer than this egui-pop knows loads all the same,
13//! best-effort, with a warning.
14//!
15//! ```
16//! use egui_pop_tokens::{FormatStamp, TokenFile};
17//!
18//! let mut file = TokenFile::new("mine");
19//! assert_eq!(FormatStamp::read(&file), (FormatStamp::CURRENT, vec![]));
20//! file.stamp();
21//! assert_eq!(FormatStamp::read(&file).0, FormatStamp::CURRENT);
22//! ```
23
24use std::fmt;
25
26use serde_json::{Map, Value as Json, json};
27
28use crate::TokenFile;
29use crate::contract::{CONTRACT_VERSION, RENAMED, Renamed};
30use crate::file::alias_target;
31
32/// The root `$extensions` key of a token file's format stamp.
33pub const FORMAT_EXTENSION: &str = "org.egui-pop.format";
34
35/// The version of the file format egui-pop writes: how a token file is
36/// laid out (DTCG, `$extends`, egui-pop's `$extensions`), apart from
37/// which tokens it gives ([`CONTRACT_VERSION`]).
38pub const FORMAT_VERSION: u64 = 1;
39
40/// A token file's format stamp: the format and contract versions it was
41/// written for.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct FormatStamp {
44    /// The format's version ([`FORMAT_VERSION`]).
45    pub version: u64,
46    /// The contract's version ([`CONTRACT_VERSION`]).
47    pub contract: u64,
48}
49
50impl FormatStamp {
51    /// What this egui-pop writes, and what a file without a stamp is
52    /// read as.
53    pub const CURRENT: FormatStamp = FormatStamp {
54        version: FORMAT_VERSION,
55        contract: CONTRACT_VERSION,
56    };
57
58    /// The stamp as written under [`FORMAT_EXTENSION`].
59    pub fn to_json(self) -> Json {
60        json!({ "version": self.version, "contract": self.contract })
61    }
62
63    /// The stamp a file carries, [`FormatStamp::CURRENT`] when it has
64    /// none, and what is wrong with it: a part that cannot be read
65    /// counts as current, and a version newer than this egui-pop's is
66    /// read best-effort; each says so in a warning.
67    pub fn read(file: &TokenFile) -> (FormatStamp, Vec<Warning>) {
68        let mut warnings = Vec::new();
69        let mut stamp = FormatStamp::CURRENT;
70        let Some(raw) = file
71            .extensions
72            .as_ref()
73            .and_then(|x| x.get(FORMAT_EXTENSION))
74        else {
75            return (stamp, warnings);
76        };
77        let Some(obj) = raw.as_object() else {
78            warnings.push(Warning::BadStamp {
79                path: format!("$extensions.{FORMAT_EXTENSION}"),
80                reason: format!("`{raw}` is not a map; read as current"),
81            });
82            return (stamp, warnings);
83        };
84        for (key, known, slot) in [
85            ("version", FORMAT_VERSION, &mut stamp.version),
86            ("contract", CONTRACT_VERSION, &mut stamp.contract),
87        ] {
88            let path = format!("$extensions.{FORMAT_EXTENSION}.{key}");
89            match obj.get(key) {
90                None => {}
91                Some(v) => match v.as_u64().filter(|n| *n > 0) {
92                    Some(n) => {
93                        *slot = n;
94                        if n > known {
95                            warnings.push(Warning::Newer {
96                                path,
97                                found: n,
98                                known,
99                            });
100                        }
101                    }
102                    None => warnings.push(Warning::BadStamp {
103                        path,
104                        reason: format!(
105                            "`{v}` is not a version (a whole number from 1); read as current"
106                        ),
107                    }),
108                },
109            }
110        }
111        (stamp, warnings)
112    }
113}
114
115impl TokenFile {
116    /// Stamps the file with [`FormatStamp::CURRENT`] under
117    /// [`FORMAT_EXTENSION`], keeping the rest of its root `$extensions`.
118    pub fn stamp(&mut self) {
119        let mut map = match self.extensions.take() {
120            Some(Json::Object(m)) => m,
121            _ => Map::new(),
122        };
123        map.insert(FORMAT_EXTENSION.to_string(), FormatStamp::CURRENT.to_json());
124        self.extensions = Some(Json::Object(map));
125    }
126}
127
128/// Something a token file loaded with, short of failing: the file still
129/// loads, and the warning says what was read otherwise than written.
130#[derive(Clone, Debug, PartialEq)]
131#[non_exhaustive]
132pub enum Warning {
133    /// The file is stamped with a newer format or contract than this
134    /// egui-pop knows: it is read best-effort.
135    Newer {
136        /// The stamp's part (`$extensions.org.egui-pop.format.contract`).
137        path: String,
138        found: u64,
139        known: u64,
140    },
141    /// The stamp cannot be read: the file is read as current.
142    BadStamp { path: String, reason: String },
143    /// A token renamed since the contract the file was written for: read
144    /// under its new name.
145    Renamed {
146        from: String,
147        to: String,
148        /// The contract version that dropped the former name.
149        contract: u64,
150    },
151    /// A token the base theme does not have: `kept` as the file's own,
152    /// or left out (the theme editor changes its base's tokens only).
153    Unknown {
154        path: String,
155        base: String,
156        kept: bool,
157    },
158    /// A token whose value does not load over the base theme: left out,
159    /// the base theme's value kept.
160    Invalid { path: String, reason: String },
161    /// The base theme (`$extends`) is not known yet: the tokens were not
162    /// checked; resolving the theme reports what is wrong.
163    Unchecked { base: String },
164    /// The file's compiled form could not be kept in the cache
165    /// ([`crate::cache`]): it was read uncached, and is compiled again
166    /// next time.
167    NotCached { file: String, reason: String },
168    /// A file of a theme package ([`crate::package`]) not read: a face
169    /// missing, not a font or outside the package (the families naming
170    /// it fall back), or a second token file.
171    Font { file: String, reason: String },
172    /// A font family a token names (`font.family.ui`) not found where
173    /// the theme is loaded (a system face not installed on this
174    /// machine): the theme still loads, and `fallback`, the next name
175    /// of the list found, draws instead.
176    FontMissing {
177        path: String,
178        family: String,
179        fallback: String,
180    },
181}
182
183impl Warning {
184    /// The token, or the part of the stamp, the warning is about.
185    pub fn path(&self) -> Option<&str> {
186        match self {
187            Warning::Newer { path, .. }
188            | Warning::BadStamp { path, .. }
189            | Warning::Unknown { path, .. }
190            | Warning::Invalid { path, .. }
191            | Warning::FontMissing { path, .. } => Some(path),
192            Warning::Renamed { from, .. } => Some(from),
193            Warning::Unchecked { .. } | Warning::NotCached { .. } | Warning::Font { .. } => None,
194        }
195    }
196
197    /// Whether the token the warning is about was left out of the file.
198    pub fn left_out(&self) -> bool {
199        matches!(
200            self,
201            Warning::Invalid { .. } | Warning::Unknown { kept: false, .. }
202        )
203    }
204}
205
206impl fmt::Display for Warning {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        match self {
209            Warning::Newer { path, found, known } => write!(
210                f,
211                "`{path}`: {found} is newer than this egui-pop's ({known}); read best-effort"
212            ),
213            Warning::BadStamp { path, reason } => write!(f, "`{path}`: {reason}"),
214            Warning::Renamed { from, to, contract } => write!(
215                f,
216                "`{from}` was renamed `{to}` in contract {contract}; read as `{to}`, update your file"
217            ),
218            Warning::Unknown { path, base, kept } => {
219                if *kept {
220                    write!(
221                        f,
222                        "`{path}` is not a token of `{base}`; kept as the file's own (a typo, or a token renamed or removed?)"
223                    )
224                } else {
225                    write!(f, "`{path}` is not a token of `{base}`; left out")
226                }
227            }
228            Warning::Invalid { path, reason } => {
229                write!(
230                    f,
231                    "`{path}` left out, the base theme's value kept: {reason}"
232                )
233            }
234            Warning::Unchecked { base } => write!(
235                f,
236                "no theme `{base}` yet: the tokens were not checked against it"
237            ),
238            Warning::NotCached { file, reason } => {
239                write!(f, "`{file}`: read uncached: {reason}")
240            }
241            Warning::Font { file, reason } => write!(f, "`{file}`: {reason}"),
242            Warning::FontMissing {
243                path,
244                family,
245                fallback,
246            } => write!(
247                f,
248                "`{path}`: no font named `{family}` here; {fallback} draws instead"
249            ),
250        }
251    }
252}
253
254impl TokenFile {
255    /// Brings a file to the current contract: reads its stamp
256    /// ([`FormatStamp::read`]) and moves the tokens renamed since the
257    /// contract it was written for to their new names ([`RENAMED`]), the
258    /// aliases naming them too. What was read otherwise than written
259    /// comes back as warnings. The stamp itself is left as it was.
260    pub fn upgrade(&mut self) -> Vec<Warning> {
261        prepare_with(self, RENAMED)
262    }
263}
264
265fn prepare_with(file: &mut TokenFile, renames: &[Renamed]) -> Vec<Warning> {
266    let (stamp, mut warnings) = FormatStamp::read(file);
267    // A file that does not say its contract is current: nothing to move.
268    let stated = file
269        .extensions
270        .as_ref()
271        .and_then(|x| x.get(FORMAT_EXTENSION))
272        .and_then(|x| x.get("contract"))
273        .and_then(Json::as_u64)
274        .is_some_and(|n| n > 0);
275    if stated {
276        migrate(file, stamp.contract, renames, &mut warnings);
277    }
278    warnings
279}
280
281/// Renames the tokens of a file written for `contract`, and the aliases
282/// naming them, in the order of the table (so that a chain of renames is
283/// followed). A new name the file gives itself wins over the former one.
284fn migrate(file: &mut TokenFile, contract: u64, renames: &[Renamed], warnings: &mut Vec<Warning>) {
285    let mut order: Vec<&Renamed> = renames.iter().filter(|r| r.contract > contract).collect();
286    order.sort_by_key(|r| r.contract);
287    for r in order {
288        let mut met = false;
289        if let Some(token) = file.tokens.remove(r.from) {
290            met = true;
291            file.tokens.entry(r.to.to_string()).or_insert(token);
292        }
293        for token in file.tokens.values_mut() {
294            if alias_target(&token.value) == Some(r.from) {
295                token.value = json!(format!("{{{}}}", r.to));
296                met = true;
297            }
298        }
299        if met {
300            warnings.push(Warning::Renamed {
301                from: r.from.to_string(),
302                to: r.to.to_string(),
303                contract: r.contract,
304            });
305        }
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    fn file(text: &str) -> TokenFile {
314        TokenFile::parse("t", text).unwrap()
315    }
316
317    #[test]
318    fn a_missing_stamp_is_current_and_a_stamp_reads_back() {
319        let mut f = file(r##"{ "$extensions": { "org.example": 1 } }"##);
320        assert_eq!(FormatStamp::read(&f), (FormatStamp::CURRENT, vec![]));
321        f.stamp();
322        let back = file(&f.to_json_pretty());
323        assert_eq!(FormatStamp::read(&back), (FormatStamp::CURRENT, vec![]));
324        // Other extensions stay.
325        assert_eq!(back.extensions.unwrap()["org.example"], json!(1));
326    }
327
328    #[test]
329    fn a_newer_or_unreadable_stamp_is_a_warning() {
330        let f = file(
331            r#"{ "$extensions": { "org.egui-pop.format": { "version": 9, "contract": 7 } } }"#,
332        );
333        let (stamp, warnings) = FormatStamp::read(&f);
334        assert_eq!(
335            stamp,
336            FormatStamp {
337                version: 9,
338                contract: 7
339            }
340        );
341        assert_eq!(warnings.len(), 2, "{warnings:?}");
342        assert!(matches!(warnings[1], Warning::Newer { found: 7, .. }));
343        assert!(warnings[1].to_string().contains("read best-effort"));
344        let f = file(r#"{ "$extensions": { "org.egui-pop.format": { "contract": "0.1" } } }"#);
345        let (stamp, warnings) = FormatStamp::read(&f);
346        assert_eq!(stamp, FormatStamp::CURRENT);
347        assert!(matches!(&warnings[..], [Warning::BadStamp { .. }]));
348        let f = file(r#"{ "$extensions": { "org.egui-pop.format": 1 } }"#);
349        assert!(matches!(
350            &FormatStamp::read(&f).1[..],
351            [Warning::BadStamp { .. }]
352        ));
353    }
354
355    #[test]
356    fn tokens_renamed_since_the_files_contract_are_read_under_their_new_names() {
357        // A fake table: the contract has no rename yet.
358        let renames = [
359            Renamed {
360                from: "panel.fill",
361                to: "surface.panel",
362                contract: 2,
363                since: "0.2",
364            },
365            Renamed {
366                from: "old.b",
367                to: "mid.b",
368                contract: 2,
369                since: "0.2",
370            },
371            Renamed {
372                from: "mid.b",
373                to: "new.b",
374                contract: 3,
375                since: "0.4",
376            },
377        ];
378        let text = r##"{
379          "$extensions": { "org.egui-pop.format": { "version": 1, "contract": 1 } },
380          "panel": { "fill": { "$type": "color", "$value": "#101010" } },
381          "old": { "b": { "$type": "color", "$value": "#202020" } },
382          "x": { "$type": "color", "$value": "{panel.fill}" }
383        }"##;
384        let mut f = file(text);
385        let warnings = prepare_with(&mut f, &renames);
386        assert!(!f.tokens.contains_key("panel.fill"));
387        assert_eq!(f.tokens["surface.panel"].value, json!("#101010"));
388        assert_eq!(f.tokens["x"].value, json!("{surface.panel}"));
389        // A chain of renames is followed.
390        assert_eq!(f.tokens["new.b"].value, json!("#202020"));
391        assert_eq!(warnings.len(), 3, "{warnings:?}");
392        assert!(
393            warnings[0].to_string().contains(
394                "renamed `surface.panel` in contract 2; read as `surface.panel`, update your file"
395            ),
396            "{}",
397            warnings[0]
398        );
399        // A file written for the contract that renamed them is left alone
400        // (a contract newer than the real one, said so).
401        let mut f = file(&text.replace("\"contract\": 1", "\"contract\": 2"));
402        let warnings = prepare_with(&mut f, &renames);
403        assert!(
404            warnings.iter().all(|w| matches!(w, Warning::Newer { .. })),
405            "{warnings:?}"
406        );
407        assert!(f.tokens.contains_key("panel.fill"));
408        assert!(f.tokens.contains_key("old.b"));
409        // So is a file without a stamp: it is current.
410        let mut f = file(r##"{ "panel": { "fill": { "$type": "color", "$value": "#101010" } } }"##);
411        assert!(prepare_with(&mut f, &renames).is_empty());
412        assert!(f.tokens.contains_key("panel.fill"));
413    }
414
415    #[test]
416    fn renames_name_a_contract_that_dropped_a_name() {
417        for r in RENAMED {
418            // The first contract dropped nothing.
419            assert!(r.contract >= 2, "{} → {}", r.from, r.to);
420            assert!(r.contract <= CONTRACT_VERSION, "{} → {}", r.from, r.to);
421            assert!(crate::contract::required(r.from).is_none(), "{}", r.from);
422        }
423    }
424
425    #[test]
426    fn a_rename_entry_stays_two_minor_releases() {
427        let r = Renamed {
428            from: "a",
429            to: "b",
430            contract: 2,
431            since: "0.3",
432        };
433        for (version, expired) in [
434            ("0.3.0", false),
435            ("0.4.1", false),
436            ("0.5.0-rc.1", false),
437            ("0.6.0", true),
438            // A major counts as one more minor release.
439            ("1.0.0", false),
440            ("1.1.0", false),
441            ("1.2.0", true),
442        ] {
443            assert_eq!(r.expired_at(version), Some(expired), "{version}");
444        }
445        assert_eq!(r.expired_at("0.2.0"), None, "older than the entry");
446        assert_eq!(r.expired_at("one"), None);
447    }
448
449    /// Fails once an entry has outlived its window: the release raising
450    /// this crate's version past it drops the entry (docs/tokens.md, "A
451    /// file's version").
452    #[test]
453    fn no_rename_entry_outlives_its_window() {
454        let now = env!("CARGO_PKG_VERSION");
455        for r in RENAMED {
456            match r.expired_at(now) {
457                Some(false) => {}
458                Some(true) => panic!(
459                    "`{}` → `{}` was renamed in {} and is past its window in {now}: drop it from RENAMED",
460                    r.from, r.to, r.since
461                ),
462                None => panic!(
463                    "`{}` → `{}`: `since` ({}) is not a release at or before {now}",
464                    r.from, r.to, r.since
465                ),
466            }
467        }
468    }
469}