Skip to main content

qframe/animation/
write.rs

1//! Writing an animation back as the `[animations.<name>]` table the loaders read.
2
3use std::fmt::Write as _;
4
5use super::CellAnimation;
6use crate::icons::GlyphMode;
7
8impl CellAnimation {
9    /// The `[animations.<name>]` table for this animation, ready to paste into an icon set, theme
10    /// or animation file. Reading it back gives the same animation. Glyphs a frame leaves to its
11    /// fallback are left out, and Nerd Font glyphs from the private use areas are written as
12    /// `\u` escapes so they survive fonts and clipboards that cannot show them.
13    #[must_use]
14    pub fn to_toml(&self, name: &str) -> String {
15        let mut out = format!("[animations.{name}]\n");
16        let _ = writeln!(out, "frame = {}", quoted(&self.frame_time.to_string()));
17        let _ = writeln!(out, "playback = {}", quoted(self.playback.name()));
18        let _ = writeln!(out, "colors = {}", quoted(self.colors.name()));
19        if let Some(rest) = self.rest {
20            let _ = writeln!(out, "rest = {}", rest + 1);
21        }
22        out.push_str("frames = [\n");
23        for frame in &self.frames {
24            let mut fields = Vec::new();
25            for (key, mode) in [("nerd", GlyphMode::Nerd), ("unicode", GlyphMode::Unicode), ("ascii", GlyphMode::Ascii)]
26            {
27                if let Some(glyph) = frame.own_glyph(mode) {
28                    fields.push(format!("{key} = {}", quoted(glyph)));
29                }
30            }
31            if let Some(color) = &frame.color {
32                fields.push(format!("color = {}", quoted(color.as_str())));
33            }
34            if let Some(duration) = frame.duration {
35                fields.push(format!("duration = {}", quoted(&duration.to_string())));
36            }
37            let _ = writeln!(out, "  {{ {} }},", fields.join(", "));
38        }
39        out.push_str("]\n");
40        out
41    }
42}
43
44/// `text` as a TOML basic string.
45fn quoted(text: &str) -> String {
46    let mut out = String::from("\"");
47    for c in text.chars() {
48        match c {
49            '"' => out.push_str("\\\""),
50            '\\' => out.push_str("\\\\"),
51            c if c.is_control() || is_private_use(c) => {
52                let code = u32::from(c);
53                if code > 0xFFFF {
54                    let _ = write!(out, "\\U{code:08X}");
55                } else {
56                    let _ = write!(out, "\\u{code:04X}");
57                }
58            }
59            c => out.push(c),
60        }
61    }
62    out.push('"');
63    out
64}
65
66/// Whether `c` is in a private use area, where Nerd Font glyphs live.
67fn is_private_use(c: char) -> bool {
68    matches!(u32::from(c), 0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x10_0000..=0x10_FFFD)
69}