Skip to main content

yog_cli/ui/yui/
values.rs

1//! The values of `.yui` attributes: numbers, flags, colors, texts, image
2//! sources, names — read and turned into Rust.
3
4use std::collections::HashSet;
5use std::fmt::Write as _;
6
7use yog_gfx::image::ImageSource;
8
9use super::{Element, err};
10use yog_data::Diagnostic;
11
12/// A number attribute.
13pub(crate) fn number(el: &Element, key: &str, value: &str) -> Result<f32, Diagnostic> {
14    value
15        .trim()
16        .parse::<f32>()
17        .or_else(|_| err(el, format_args!("{key}=\"{value}\": expected a number")))
18}
19
20/// A yes/no attribute: `true` or `false`.
21pub(crate) fn boolean(el: &Element, key: &str, value: &str) -> Result<bool, Diagnostic> {
22    match value.trim() {
23        yog_ids::yui_value::TRUE => Ok(true),
24        yog_ids::yui_value::FALSE => Ok(false),
25        _ => err(
26            el,
27            format_args!("{key}=\"{value}\": expected true or false"),
28        ),
29    }
30}
31
32/// `#RRGGBB`, `#AARRGGBB` or `0xAARRGGBB` → `0xAARRGGBB` (`Color::parse`;
33/// a file's color is written with its `#` or `0x`, not as a decimal).
34pub fn color(value: &str) -> Option<u32> {
35    yog_ui::attr::written_color(value).map(|c| c.0)
36}
37
38/// What a color written in hex starts with: `#RRGGBB`.
39pub const HEX_MARK: &str = yog_ui::attr::HEX_MARKS[0];
40
41/// A color attribute: a literal (see [`color`]) or `@<Set>.<name>`, a color
42/// of `resources/<Set>.yres` (see [`set_resource_refs`]).
43pub(crate) fn color_attr(el: &Element, key: &str, value: &str) -> Result<u32, Diagnostic> {
44    if let Some(reference) = value.trim().strip_prefix('@') {
45        return resource_color(reference).ok_or_else(|| {
46            Diagnostic::from(format!(
47                "<{}> {key}=\"{value}\": no color `{reference}` in resources/*.yres",
48                el.name
49            ))
50            .at_line(el.line)
51        });
52    }
53    color(value).ok_or_else(|| {
54        Diagnostic::from(format!(
55            "<{}> {key}=\"{value}\": expected #RRGGBB, #AARRGGBB or @<Set>.<name>",
56            el.name
57        ))
58        .at_line(el.line)
59    })
60}
61
62/// Whether `@<Set>.<name>` names a text of the mod's `.yres` resources.
63pub(super) fn is_resource_text(reference: &str) -> bool {
64    RESOURCE_REFS.with(|r| r.borrow().texts.contains_key(reference.trim()))
65}
66
67/// The color `@<Set>.<name>` names in the mod's `.yres` resources.
68pub(super) fn resource_color(reference: &str) -> Option<u32> {
69    RESOURCE_REFS.with(|r| r.borrow().colors.get(reference.trim()).copied())
70}
71
72/// `value`, one of `options`.
73pub(super) fn pick<'v>(
74    el: &Element,
75    key: &str,
76    value: &str,
77    options: &[&'v str],
78) -> Result<&'v str, Diagnostic> {
79    options
80        .iter()
81        .find(|o| **o == value.trim())
82        .copied()
83        .ok_or_else(|| {
84            Diagnostic::from(format!(
85                "<{}> {key}=\"{value}\": expected one of {}",
86                el.name,
87                options.join(", ")
88            ))
89            .at_line(el.line)
90        })
91}
92
93/// The Rust expression for a text attribute, its `@` forms as everywhere
94/// in Yog Data (`yog_data::typed`): `"@Strings.title"` is a text of
95/// `resources/Strings.yres` (see [`set_resource_refs`]), `"@lang:gui.done"`
96/// any translation key, `"@item:minecraft:stick"` (`@block:`, `@entity:`)
97/// that content's name — each looked up when the tree is built
98/// (`::yog_api::tr`, so it follows the game's language); `"@@..."` is a
99/// literal text starting with `@`; anything else is the literal text.
100pub fn text_expr(value: &str) -> Result<String, Diagnostic> {
101    if value.trim() == "@" || !value.starts_with('@') {
102        return Ok(format!("{value:?}"));
103    }
104    let tr = |key: &str| format!("::yog_api::tr({key:?})");
105    match yog_data::typed::classify(value.trim()) {
106        Ok(yog_data::Value::Str(s)) => Ok(format!("{s:?}")),
107        Ok(yog_data::Value::Lang(key)) => Ok(tr(&key)),
108        Ok(yog_data::Value::Res(r)) => {
109            RESOURCE_REFS.with(|refs| Ok(refs.borrow().text(&r).map(|(k, _)| tr(k))?))
110        }
111        Ok(yog_data::Value::Ref(r))
112            if matches!(
113                r.kind.as_str(),
114                yog_ids::kind::ITEM | yog_ids::kind::BLOCK | yog_ids::kind::ENTITY
115            ) =>
116        {
117            // A block's state (`[facing=north]`) isn't part of its name.
118            let id = r.id.split(STATE_OPEN).next().unwrap_or(&r.id);
119            Ok(tr(&yog_ids::lang_key(&r.kind, id)))
120        }
121        Ok(other) => Err(format!("{} isn't a text", other.kind_name()).into()),
122        Err(_) if !value.contains(':') => Err(format!(
123            "write a translation key as `@lang:{}`, a .yres text as `@Set.name`, a literal `@` as `@@`",
124            value[1..].trim()
125        ).into()),
126        Err(e) => Err(e.into()),
127    }
128}
129
130/// Where a block id's state begins: `minecraft:furnace[facing=north]`.
131const STATE_OPEN: char = '[';
132
133/// [`text_expr`] for attribute `key` of `el`, a problem saying where.
134pub(crate) fn text_attr(el: &Element, key: &str, value: &str) -> Result<String, Diagnostic> {
135    text_expr(value).map_err(|e| {
136        Diagnostic::from(format!("<{}> {key}=\"{value}\": {e}", el.name)).at_line(el.line)
137    })
138}
139
140thread_local! {
141    /// The mod's `.yres` resources, for `@<Set>.<name>` in attributes.
142    static RESOURCE_REFS: std::cell::RefCell<crate::yres::Refs> = Default::default();
143}
144
145/// Makes the mod's compiled `.yres` resources visible to the generator:
146/// `text="@Strings.title"` and `source="@Icons.logo"` resolve through them.
147pub fn set_resource_refs(refs: &crate::yres::Refs) {
148    RESOURCE_REFS.with(|r| *r.borrow_mut() = refs.clone());
149}
150
151/// A Rust constant name for an event/widget id: `mymod:btn-play` → `MYMOD_BTN_PLAY`.
152pub fn const_name(value: &str) -> String {
153    let mut out = String::new();
154    let mut prev_lower = false;
155    for c in value.chars() {
156        if c.is_ascii_alphanumeric() {
157            if c.is_ascii_uppercase() && prev_lower {
158                out.push('_');
159            }
160            prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
161            out.push(c.to_ascii_uppercase());
162        } else {
163            if !out.ends_with('_') {
164                out.push('_');
165            }
166            prev_lower = false;
167        }
168    }
169    let out = out.trim_matches('_').to_string();
170    if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
171        format!("_{out}")
172    } else {
173        out
174    }
175}
176
177/// Names in first-seen order, each once.
178#[derive(Debug, Default)]
179pub(crate) struct Names {
180    list: Vec<String>,
181    seen: HashSet<String>,
182}
183
184impl Names {
185    pub(crate) fn push(&mut self, name: &str) {
186        if !self.seen.contains(name) {
187            self.seen.insert(name.to_string());
188            self.list.push(name.to_string());
189        }
190    }
191
192    pub(crate) fn as_slice(&self) -> &[String] {
193        &self.list
194    }
195
196    pub(crate) fn into_vec(self) -> Vec<String> {
197        self.list
198    }
199}
200
201/// `pub const NAME: &str = "value";` lines for `values`, the names from
202/// [`const_name`] (a `_` appended to repeats).
203pub(crate) fn str_consts(values: &[String]) -> String {
204    let mut out = String::new();
205    let mut used: HashSet<String> = HashSet::new();
206    for v in values {
207        let mut name = const_name(v);
208        while used.contains(&name) {
209            name.push('_');
210        }
211        let _ = writeln!(out, "    pub const {name}: &str = {v:?};");
212        used.insert(name);
213    }
214    out
215}
216
217/// Whether a `bg` value is an image (`sprite:panel`, `mymod:gui/frame`,
218/// an `@Set.name` image) rather than a color (`#RRGGBB`, `@Colors.name`).
219pub(crate) fn is_image_value(v: &str) -> bool {
220    let v = v.trim();
221    match v.strip_prefix('@') {
222        Some(name) => RESOURCE_REFS.with(|r| r.borrow().images.contains_key(name)),
223        None => !v.starts_with('#') && v.contains(':'),
224    }
225}
226
227/// An image source attribute (`<Image source>`, `bg="sprite:..."`): checks
228/// it and resolves `@Set.name` and `mod:` → the source the host draws.
229pub(crate) fn image_source(
230    el: &Element,
231    attr: &str,
232    source: &str,
233    mod_id: Option<&str>,
234) -> Result<String, Diagnostic> {
235    let line = el.line;
236    let kind = el.name.as_str();
237    let mod_id = mod_id.map(str::to_owned);
238    let resolved;
239    let source = match source.strip_prefix('@') {
240        Some(name) => {
241            resolved = RESOURCE_REFS
242                .with(|r| r.borrow().images.get(name).cloned())
243                .ok_or_else(|| {
244                    Diagnostic::from(format!(
245                        "<{kind}> {attr}=\"{source}\": no image `{name}` in resources/*.yres"
246                    ))
247                    .at_line(line)
248                })?;
249            resolved.as_str()
250        }
251        None => source,
252    };
253    let parsed = ImageSource::parse(source).ok_or_else(|| {
254        Diagnostic::from(format!(
255            "<{kind}> {attr}=\"{source}\": expected item:<id>, block:<id>, \
256             sprite:<name>, mod:<path> or <namespace>:<path>"
257        ))
258        .at_line(line)
259    })?;
260    let source = match parsed {
261        ImageSource::ModPath(path) => match &mod_id {
262            Some(id) => yog_gfx::image::texture_id(id, &path),
263            None => {
264                return Err(Diagnostic::from(format!(
265                    "<{kind}> {attr}=\"{source}\": mod: needs the mod id (no yog.toml found)"
266                ))
267                .at_line(line));
268            }
269        },
270        ImageSource::Sprite(name)
271            if !name.contains(':') && yog_gfx::image::sprite(&name).is_none() =>
272        {
273            let names: Vec<&str> = yog_gfx::image::SPRITES
274                .iter()
275                .map(|s| s.name.as_str())
276                .collect();
277            return Err(Diagnostic::from(format!(
278                "<{kind}> {attr}=\"{source}\": unknown sprite (known: {})",
279                names.join(", ")
280            ))
281            .at_line(line));
282        }
283        ImageSource::Texture(_) => {
284            if let Some(alias) = yog_gfx::image::suggest_alias(source) {
285                return Err(Diagnostic::from(format!(
286                    "<{kind}> {attr}=\"{source}\" is a raw resource path, which \
287                     changes between Minecraft versions — write {attr}=\"{alias}\""
288                ))
289                .at_line(line));
290            }
291            source.to_string()
292        }
293        _ => source.to_string(),
294    };
295    Ok(source)
296}
297
298/// A `font` attribute: a Yog font, or a game font by Yog's alias — never
299/// the game's own id.
300pub(super) fn font_attr<'a>(el: &Element, v: &'a str) -> Result<&'a str, Diagnostic> {
301    let font = v.trim();
302    match yog_ids::split(font) {
303        (yog_ids::ns::MINECRAFT, name) if !font.is_empty() => err(
304            el,
305            format!(
306                "font=\"{font}\": the game's fonts are named by Yog's alias, {}",
307                yog_ids::font_alias(name)
308            ),
309        ),
310        _ => Ok(font),
311    }
312}