Skip to main content

yog_cli/
yui.rs

1//! `.yui` screen files — the declarative form of a `yog-ui` widget tree that
2//! Yog-IDLE's screen designer edits — and their code generation.
3//!
4//! A `.yui` file is a small XAML-like XML document: one element per widget,
5//! attributes named after the `yog-ui` builder methods they become:
6//!
7//! ```xml
8//! <Screen id="mymod:main_menu" width="176" height="166" anchor="center" bg="#C0101010" padding="8">
9//!   <Label id="title" x="8" y="6" text="Main Menu" color="#FFFFFF" no_wrap="true"/>
10//!   <Button x="38" y="40" w="100" h="20" text="Play" bg="#FF555555" on_click="play"/>
11//!   <Column x="8" y="70" w="160" gap="2">
12//!     <Label text="Flowing child"/>
13//!   </Column>
14//! </Screen>
15//! ```
16//!
17//! `yog build` (and `yog check`, `yog ui gen`) turns `src/**/foo.yui` into
18//! `.yog-build/generated/**/foo.g.rs` — WPF's `MainWindow.g.cs`: generated
19//! into the build directory on every build, never committed, pulled into the
20//! screen's hand-written code-behind module with `yog_api::ui_include!("foo")`.
21//! See `docs/yui.md` in Yog-IDLE for the full format.
22
23use std::collections::HashSet;
24use std::fmt::Write as _;
25use std::path::{Path, PathBuf};
26
27use yog_gfx::image::ImageSource;
28
29// ── XML subset ────────────────────────────────────────────────────────────────
30
31/// One XML element: name, attributes in source order, child elements.
32#[derive(Debug, Clone)]
33pub struct Element {
34    pub name: String,
35    pub attrs: Vec<(String, String)>,
36    pub children: Vec<Element>,
37    /// 1-based line of the start tag, for error messages.
38    pub line: usize,
39}
40
41impl Element {
42    pub(crate) fn attr(&self, key: &str) -> Option<&str> {
43        self.attrs
44            .iter()
45            .find(|(k, _)| k == key)
46            .map(|(_, v)| v.as_str())
47    }
48}
49
50struct Parser<'a> {
51    src: &'a str,
52    pos: usize,
53    /// The last [`Parser::line`] answer: (position, line there) — the
54    /// parser only moves forward, so lines are counted from there on.
55    line_at: std::cell::Cell<(usize, usize)>,
56}
57
58impl<'a> Parser<'a> {
59    fn new(src: &'a str) -> Self {
60        Parser {
61            src,
62            pos: 0,
63            line_at: std::cell::Cell::new((0, 1)),
64        }
65    }
66
67    fn line(&self) -> usize {
68        let (at, line) = self.line_at.get();
69        let (from, line) = if self.pos >= at { (at, line) } else { (0, 1) };
70        let line = line
71            + self.src.as_bytes()[from..self.pos]
72                .iter()
73                .filter(|&&b| b == b'\n')
74                .count();
75        self.line_at.set((self.pos, line));
76        line
77    }
78
79    fn err<T>(&self, msg: impl std::fmt::Display) -> Result<T, String> {
80        Err(format!("line {}: {msg}", self.line()))
81    }
82
83    fn rest(&self) -> &'a str {
84        &self.src[self.pos..]
85    }
86
87    fn skip_ws(&mut self) {
88        let trimmed = self.rest().trim_start();
89        self.pos = self.src.len() - trimmed.len();
90    }
91
92    /// Skips whitespace, comments, `<?...?>` and `<!DOCTYPE ...>`.
93    fn skip_misc(&mut self) -> Result<(), String> {
94        loop {
95            self.skip_ws();
96            let rest = self.rest();
97            let end = if rest.starts_with("<!--") {
98                rest.find("-->").map(|i| i + 3)
99            } else if rest.starts_with("<?") {
100                rest.find("?>").map(|i| i + 2)
101            } else if rest.starts_with("<!") {
102                rest.find('>').map(|i| i + 1)
103            } else {
104                return Ok(());
105            };
106            match end {
107                Some(n) => self.pos += n,
108                None => return self.err("unterminated comment or declaration"),
109            }
110        }
111    }
112
113    fn name(&mut self) -> Result<String, String> {
114        let rest = self.rest();
115        let len = rest
116            .find(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '-' | ':' | '.')))
117            .unwrap_or(rest.len());
118        if len == 0 {
119            return self.err("expected a name");
120        }
121        self.pos += len;
122        Ok(rest[..len].to_string())
123    }
124
125    fn element(&mut self) -> Result<Element, String> {
126        let line = self.line();
127        if !self.rest().starts_with('<') {
128            return self.err("expected an element");
129        }
130        self.pos += 1;
131        let name = self.name()?;
132        let mut attrs: Vec<(String, String)> = Vec::new();
133        loop {
134            self.skip_ws();
135            let rest = self.rest();
136            if rest.starts_with("/>") {
137                self.pos += 2;
138                return Ok(Element {
139                    name,
140                    attrs,
141                    children: Vec::new(),
142                    line,
143                });
144            }
145            if rest.starts_with('>') {
146                self.pos += 1;
147                break;
148            }
149            if rest.is_empty() {
150                return self.err(format!("unterminated <{name}>"));
151            }
152            let key = self.name()?;
153            self.skip_ws();
154            if !self.rest().starts_with('=') {
155                return self.err(format!("expected `=` after attribute `{key}`"));
156            }
157            self.pos += 1;
158            self.skip_ws();
159            let quote = match self.rest().chars().next() {
160                Some(q @ ('"' | '\'')) => q,
161                _ => return self.err(format!("attribute `{key}`: expected a quoted value")),
162            };
163            self.pos += 1;
164            let Some(end) = self.rest().find(quote) else {
165                return self.err(format!("attribute `{key}`: unterminated value"));
166            };
167            let raw = &self.rest()[..end];
168            let value = unescape(raw).map_err(|e| format!("line {}: {e}", self.line()))?;
169            self.pos += end + 1;
170            if attrs.iter().any(|(k, _)| *k == key) {
171                return self.err(format!("<{name}>: duplicate attribute `{key}`"));
172            }
173            attrs.push((key, value));
174        }
175        let mut children = Vec::new();
176        loop {
177            self.skip_misc()?;
178            let rest = self.rest();
179            if rest.starts_with("</") {
180                self.pos += 2;
181                let close = self.name()?;
182                if close != name {
183                    return self.err(format!("</{close}> closes <{name}>"));
184                }
185                self.skip_ws();
186                if !self.rest().starts_with('>') {
187                    return self.err("expected `>`");
188                }
189                self.pos += 1;
190                return Ok(Element {
191                    name,
192                    attrs,
193                    children,
194                    line,
195                });
196            }
197            if rest.is_empty() {
198                return self.err(format!("<{name}> is never closed"));
199            }
200            if !rest.starts_with('<') {
201                return self.err(format!(
202                    "<{name}>: text content isn't allowed — use a `text` attribute"
203                ));
204            }
205            children.push(self.element()?);
206        }
207    }
208}
209
210fn unescape(raw: &str) -> Result<String, String> {
211    let mut out = String::with_capacity(raw.len());
212    let mut rest = raw;
213    while let Some(i) = rest.find('&') {
214        out.push_str(&rest[..i]);
215        let Some(semi) = rest[i..].find(';') else {
216            return Err("`&` without `;` — write `&amp;`".into());
217        };
218        let entity = &rest[i + 1..i + semi];
219        match entity {
220            "amp" => out.push('&'),
221            "lt" => out.push('<'),
222            "gt" => out.push('>'),
223            "quot" => out.push('"'),
224            "apos" => out.push('\''),
225            _ => {
226                let code = if let Some(hex) = entity.strip_prefix("#x") {
227                    u32::from_str_radix(hex, 16).ok()
228                } else if let Some(dec) = entity.strip_prefix('#') {
229                    dec.parse().ok()
230                } else {
231                    None
232                };
233                match code.and_then(char::from_u32) {
234                    Some(c) => out.push(c),
235                    None => return Err(format!("unknown entity `&{entity};`")),
236                }
237            }
238        }
239        rest = &rest[i + semi + 1..];
240    }
241    out.push_str(rest);
242    Ok(out)
243}
244
245/// Parses an XML document (the subset `.yui` uses) into its root element.
246pub fn parse_xml(src: &str) -> Result<Element, String> {
247    let src = src.strip_prefix('\u{feff}').unwrap_or(src);
248    let mut p = Parser::new(src);
249    p.skip_misc()?;
250    let root = p.element()?;
251    p.skip_misc()?;
252    if !p.rest().is_empty() {
253        return p.err("content after the root element");
254    }
255    Ok(root)
256}
257
258// ── Screen model ──────────────────────────────────────────────────────────────
259
260/// The import generated widget-building code starts with.
261pub(crate) const UI_USE: &str =
262    "use ::yog_api::ui::{widget, Align, Dock, FlexDir, FocusStyle, Units};";
263
264/// Whether `<kind>` is a built-in element.
265pub(crate) fn is_builtin(kind: &str) -> bool {
266    CONTAINERS.contains(&kind) || LEAVES.contains(&kind)
267}
268
269/// Whether `<kind>` is a mod's own component (not a built-in element).
270pub(crate) fn is_custom_component(kind: &str) -> bool {
271    !is_builtin(kind) && is_component_name(kind)
272}
273
274/// `line N: <Kind> msg`.
275pub(crate) fn err<T>(el: &Element, msg: impl std::fmt::Display) -> Result<T, String> {
276    Err(format!("line {}: <{}> {msg}", el.line, el.name))
277}
278
279/// Whether `key` is an attribute every element takes (not a component's
280/// own property).
281pub(crate) fn is_common_attr(key: &str) -> bool {
282    COMMON_ATTRS.contains(&key) || key == "visible"
283}
284
285const CONTAINERS: &[&str] = &["Screen", "Canvas", "Column", "Row", "ScrollView", "Grid"];
286const LEAVES: &[&str] = &[
287    "Label", "Button", "TextBox", "ItemSlot", "InvSlot", "Slot", "PlayerInventory", "Image",
288    "Spacer", "Surface",
289];
290const COMMON_ATTRS: &[&str] = &[
291    "id",
292    "x",
293    "y",
294    "w",
295    "h",
296    "min_w",
297    "min_h",
298    "flex",
299    "dock",
300    "gap",
301    "padding",
302    "bg",
303    "color",
304    "align",
305    "halign",
306    "valign",
307    "margin",
308    "font_scale",
309    "font",
310    "shadow",
311    "no_wrap",
312    "ellipsis",
313    "focus_style",
314    "focus_color",
315    "enabled",
316    "on_click",
317];
318
319fn kind_attrs(kind: &str) -> &'static [&'static str] {
320    match kind {
321        "Screen" => &["width", "height", "anchor", "modal", "pause"],
322        "Label" | "Button" => &["text"],
323        "TextBox" => &[
324            "text",
325            "placeholder",
326            "max_length",
327            "on_change",
328            "on_submit",
329        ],
330        "ItemSlot" => &["item"],
331        "InvSlot" => &["item", "count"],
332        "Slot" => &["index"],
333        "Image" => &["source", "stretch", "uv", "tint"],
334        "Surface" => &["source"],
335        _ => &[],
336    }
337}
338
339pub(crate) fn number(el: &Element, key: &str, value: &str) -> Result<f32, String> {
340    value
341        .trim()
342        .parse::<f32>()
343        .or_else(|_| err(el, format_args!("{key}=\"{value}\": expected a number")))
344}
345
346pub(crate) fn boolean(el: &Element, key: &str, value: &str) -> Result<bool, String> {
347    match value.trim() {
348        "true" => Ok(true),
349        "false" => Ok(false),
350        _ => err(
351            el,
352            format_args!("{key}=\"{value}\": expected true or false"),
353        ),
354    }
355}
356
357/// `#RRGGBB`, `#AARRGGBB` or `0xAARRGGBB` → `0xAARRGGBB`.
358pub fn color(value: &str) -> Option<u32> {
359    let v = value.trim();
360    let hex = v
361        .strip_prefix('#')
362        .or_else(|| v.strip_prefix("0x"))
363        .or_else(|| v.strip_prefix("0X"))?
364        .replace('_', "");
365    let n = u32::from_str_radix(&hex, 16).ok()?;
366    match hex.len() {
367        6 => Some(0xFF00_0000 | n),
368        8 => Some(n),
369        _ => None,
370    }
371}
372
373/// A color attribute: a literal (see [`color`]) or `@<Set>.<name>`, a color
374/// of `resources/<Set>.yres` (see [`set_resource_refs`]).
375pub(crate) fn color_attr(el: &Element, key: &str, value: &str) -> Result<u32, String> {
376    if let Some(reference) = value.trim().strip_prefix('@') {
377        return resource_color(reference).ok_or_else(|| {
378            format!(
379                "line {}: <{}> {key}=\"{value}\": no color `{reference}` in resources/*.yres",
380                el.line, el.name
381            )
382        });
383    }
384    color(value).ok_or_else(|| {
385        format!(
386            "line {}: <{}> {key}=\"{value}\": expected #RRGGBB, #AARRGGBB or @<Set>.<name>",
387            el.line, el.name
388        )
389    })
390}
391
392/// Whether `@<Set>.<name>` names a text of the mod's `.yres` resources.
393fn is_resource_text(reference: &str) -> bool {
394    RESOURCE_REFS.with(|r| r.borrow().texts.contains_key(reference.trim()))
395}
396
397/// The color `@<Set>.<name>` names in the mod's `.yres` resources.
398fn resource_color(reference: &str) -> Option<u32> {
399    RESOURCE_REFS.with(|r| r.borrow().colors.get(reference.trim()).copied())
400}
401
402fn f(v: f32) -> String {
403    format!("{v:?}")
404}
405
406fn size(el: &Element, key: &str, value: &str) -> Result<Option<String>, String> {
407    let v = value.trim();
408    if v.is_empty() || v == "auto" {
409        return Ok(None);
410    }
411    if let Some(p) = v.strip_suffix('%') {
412        return Ok(Some(format!("Units::Percent({})", f(number(el, key, p)?))));
413    }
414    Ok(Some(format!("Units::Px({})", f(number(el, key, v)?))))
415}
416
417/// CSS-style shorthand: 1 value = all sides, 2 = vertical horizontal, 4 = top right bottom left.
418fn padding(el: &Element, key: &str, value: &str) -> Result<[f32; 4], String> {
419    let parts: Vec<f32> = value
420        .split([' ', ','])
421        .filter(|s| !s.is_empty())
422        .map(|s| number(el, key, s))
423        .collect::<Result<_, _>>()?;
424    match parts.as_slice() {
425        [a] => Ok([*a; 4]),
426        [v, h] => Ok([*v, *h, *v, *h]),
427        [t, r, b, l] => Ok([*t, *r, *b, *l]),
428        _ => Err(format!(
429            "line {}: <{}> {key}=\"{value}\": expected 1, 2 or 4 numbers",
430            el.line, el.name
431        )),
432    }
433}
434
435/// `MinHeight` → `min_height`.
436pub(crate) fn snake(name: &str) -> String {
437    let mut out = String::new();
438    for (i, c) in name.chars().enumerate() {
439        if c.is_ascii_uppercase() {
440            if i > 0 {
441                out.push('_');
442            }
443            out.push(c.to_ascii_lowercase());
444        } else {
445            out.push(c);
446        }
447    }
448    out
449}
450
451/// The `.yui` spelling of a WPF/WinUI attribute name, for error hints.
452fn wpf_hint(key: &str) -> Option<&'static str> {
453    Some(match key {
454        "HorizontalAlignment" => "halign",
455        "VerticalAlignment" => "valign",
456        "Margin" => "margin",
457        "Padding" => "padding",
458        "Width" => "w",
459        "Height" => "h",
460        "MinWidth" => "min_w",
461        "MinHeight" => "min_h",
462        "Background" => "bg",
463        "Foreground" => "color",
464        "Text" | "Content" => "text",
465        "RowDefinitions" => "rows",
466        "ColumnDefinitions" => "columns",
467        "RowSpacing" => "row_spacing",
468        "ColumnSpacing" => "column_spacing",
469        "Visibility" => "visible",
470        "IsEnabled" => "enabled",
471        _ => return None,
472    })
473}
474
475/// A `<Screen>`'s `width`, `height` (default 176 × 166, the vanilla
476/// container size) and `anchor` (default `center`).
477pub(crate) fn screen_frame(root: &Element) -> Result<(f32, f32, &'static str), String> {
478    let size = |key: &str, default: f32| {
479        root.attr(key)
480            .map(|v| number(root, key, v))
481            .transpose()
482            .map(|v| v.unwrap_or(default))
483    };
484    let anchor = pick(
485        root,
486        "anchor",
487        root.attr("anchor").unwrap_or("center"),
488        &[
489            "center",
490            "top_left",
491            "top",
492            "top_right",
493            "left",
494            "right",
495            "bottom_left",
496            "bottom",
497            "bottom_right",
498            "fill",
499        ],
500    )?;
501    Ok((size("width", 176.0)?, size("height", 166.0)?, anchor))
502}
503
504fn pick<'v>(el: &Element, key: &str, value: &str, options: &[&'v str]) -> Result<&'v str, String> {
505    options
506        .iter()
507        .find(|o| **o == value.trim())
508        .copied()
509        .ok_or_else(|| {
510            format!(
511                "line {}: <{}> {key}=\"{value}\": expected one of {}",
512                el.line,
513                el.name,
514                options.join(", ")
515            )
516        })
517}
518
519/// `stat_bar` / `my-mod` → `StatBar` / `MyMod`.
520pub fn pascal(value: &str) -> String {
521    value
522        .split(['_', '-'])
523        .map(|w| {
524            let mut c = w.chars();
525            c.next()
526                .map(|f| f.to_uppercase().collect::<String>() + c.as_str())
527                .unwrap_or_default()
528        })
529        .collect()
530}
531
532/// `<StatBar …/>`: a custom component's name (not a built-in element).
533fn is_component_name(kind: &str) -> bool {
534    kind.chars().next().is_some_and(|c| c.is_ascii_uppercase())
535        && kind.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
536}
537
538/// A custom component built by name from its own (non-common) attributes;
539/// `@key` values are translated like `text`.
540fn component_expr(el: &Element) -> String {
541    let props: Vec<String> = el
542        .attrs
543        .iter()
544        .filter(|(k, _)| !COMMON_ATTRS.contains(&k.as_str()))
545        .map(|(k, v)| {
546            if let Some(rust) = v.strip_prefix(RAW_VALUE) {
547                return format!("({k:?}, &*{rust})");
548            }
549            match v.strip_prefix('@') {
550                // A `.yres` color (for a color property): its value.
551                Some(rest) if !is_resource_text(rest) && resource_color(rest).is_some() => {
552                    let c = resource_color(rest).unwrap_or_default();
553                    format!("({k:?}, \"#{c:08X}\")")
554                }
555                Some(rest) if !rest.trim().is_empty() => format!("({k:?}, &*{})", text_expr(v)),
556                _ => format!("({k:?}, {v:?})"),
557            }
558        })
559        .collect();
560    format!(
561        "::yog_api::ui::component::build({:?}, &[{}])",
562        el.name,
563        props.join(", ")
564    )
565}
566
567/// The Rust expression for a text attribute: `"@mymod.key"` is translation
568/// key `mymod.key`, looked up when the tree is built (`::yog_api::tr`, so it
569/// follows the game's language); `"@@..."` is a literal text starting
570/// with `@`; anything else is the literal text.
571///
572/// `"@<Set>.<name>"` naming a text of `resources/<Set>.yres` (see
573/// [`set_resource_refs`]) is that text's translation key.
574pub fn text_expr(value: &str) -> String {
575    match value.strip_prefix('@') {
576        Some(rest) if rest.starts_with('@') => format!("{rest:?}"),
577        Some(key) if !key.trim().is_empty() => {
578            let key = key.trim();
579            let resolved =
580                RESOURCE_REFS.with(|r| r.borrow().texts.get(key).map(|(k, _)| k.clone()));
581            format!("::yog_api::tr({:?})", resolved.as_deref().unwrap_or(key))
582        }
583        _ => format!("{value:?}"),
584    }
585}
586
587thread_local! {
588    /// The mod's `.yres` resources, for `@<Set>.<name>` in attributes.
589    static RESOURCE_REFS: std::cell::RefCell<crate::yres::Refs> = Default::default();
590}
591
592/// Makes the mod's compiled `.yres` resources visible to the generator:
593/// `text="@Strings.title"` and `source="@Icons.logo"` resolve through them.
594pub fn set_resource_refs(refs: &crate::yres::Refs) {
595    RESOURCE_REFS.with(|r| *r.borrow_mut() = refs.clone());
596}
597
598/// A Rust constant name for an event/widget id: `mymod:btn-play` → `MYMOD_BTN_PLAY`.
599pub fn const_name(value: &str) -> String {
600    let mut out = String::new();
601    let mut prev_lower = false;
602    for c in value.chars() {
603        if c.is_ascii_alphanumeric() {
604            if c.is_ascii_uppercase() && prev_lower {
605                out.push('_');
606            }
607            prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
608            out.push(c.to_ascii_uppercase());
609        } else {
610            if !out.ends_with('_') {
611                out.push('_');
612            }
613            prev_lower = false;
614        }
615    }
616    let out = out.trim_matches('_').to_string();
617    if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
618        format!("_{out}")
619    } else {
620        out
621    }
622}
623
624/// Names in first-seen order, each once.
625#[derive(Debug, Default)]
626pub(crate) struct Names {
627    list: Vec<String>,
628    seen: HashSet<String>,
629}
630
631impl Names {
632    pub(crate) fn push(&mut self, name: &str) {
633        if !self.seen.contains(name) {
634            self.seen.insert(name.to_string());
635            self.list.push(name.to_string());
636        }
637    }
638
639    pub(crate) fn as_slice(&self) -> &[String] {
640        &self.list
641    }
642
643    pub(crate) fn into_vec(self) -> Vec<String> {
644        self.list
645    }
646}
647
648/// `pub const NAME: &str = "value";` lines for `values`, the names from
649/// [`const_name`] (a `_` appended to repeats).
650pub(crate) fn str_consts(values: &[String]) -> String {
651    let mut out = String::new();
652    let mut used: HashSet<String> = HashSet::new();
653    for v in values {
654        let mut name = const_name(v);
655        while used.contains(&name) {
656            name.push('_');
657        }
658        let _ = writeln!(out, "    pub const {name}: &str = {v:?};");
659        used.insert(name);
660    }
661    out
662}
663
664struct Gen {
665    events: Names,
666    ids: Names,
667    /// The mod's id (from `yog.toml`), for `mod:` image sources.
668    mod_id: Option<String>,
669}
670
671impl Gen {
672    fn new(mod_id: Option<&str>) -> Self {
673        Gen {
674            events: Names::default(),
675            ids: Names::default(),
676            mod_id: mod_id.map(str::to_string),
677        }
678    }
679
680    /// `widget::surface(...)` for a `<Surface>`: the id its drawing is
681    /// registered under (`ns:path`; `mod:path` = the mod's namespace).
682    fn surface(&mut self, el: &Element) -> Result<String, String> {
683        let line = el.line;
684        let source = el
685            .attr("source")
686            .ok_or_else(|| format!("line {line}: <Surface> needs a source (the id its code registers, e.g. source=\"mod:grid\")"))?
687            .trim();
688        let id = match source.strip_prefix("mod:") {
689            Some(path) => match &self.mod_id {
690                Some(m) => format!("{m}:{path}"),
691                None => {
692                    return Err(format!(
693                        "line {line}: <Surface> source=\"{source}\": mod: needs the mod id (no yog.toml found)"
694                    ));
695                }
696            },
697            None => source.to_string(),
698        };
699        if !id.contains(':') || !crate::content::valid_id(&id) {
700            return Err(format!(
701                "line {line}: <Surface> source=\"{source}\": expected <namespace>:<name> or mod:<name> \
702                 (lower case a-z, 0-9, `_`, `-`, `.`, `/`)"
703            ));
704        }
705        Ok(format!("widget::surface({id:?})"))
706    }
707
708    /// `widget::image(...)` for an `<Image>`: its `source` checked and
709    /// `mod:` resolved, plus `stretch`/`uv`/`tint`.
710    fn image(&mut self, el: &Element) -> Result<String, String> {
711        let line = el.line;
712        let source = el
713            .attr("source")
714            .ok_or_else(|| {
715                format!("line {line}: <Image> needs a source (e.g. source=\"item:apple\")")
716            })?
717            .trim();
718        let resolved;
719        let source = match source.strip_prefix('@') {
720            Some(name) => {
721                resolved = RESOURCE_REFS
722                    .with(|r| r.borrow().images.get(name).cloned())
723                    .ok_or_else(|| format!("line {line}: <Image> source=\"{source}\": no image `{name}` in resources/*.yres"))?;
724                resolved.as_str()
725            }
726            None => source,
727        };
728        let parsed = ImageSource::parse(source).ok_or_else(|| {
729            format!(
730                "line {line}: <Image> source=\"{source}\": expected item:<id>, block:<id>, \
731                 sprite:<name>, mod:<path> or <namespace>:<path>"
732            )
733        })?;
734        let source = match parsed {
735            ImageSource::ModPath(path) => match &self.mod_id {
736                Some(id) => yog_gfx::image::texture_id(id, &path),
737                None => {
738                    return Err(format!(
739                        "line {line}: <Image> source=\"{source}\": mod: needs the mod id (no yog.toml found)"
740                    ));
741                }
742            },
743            ImageSource::Sprite(name)
744                if !name.contains(':') && yog_gfx::image::sprite(&name).is_none() =>
745            {
746                let names: Vec<&str> = yog_gfx::image::SPRITES.iter().map(|s| s.name).collect();
747                return Err(format!(
748                    "line {line}: <Image> source=\"{source}\": unknown sprite (known: {})",
749                    names.join(", ")
750                ));
751            }
752            ImageSource::Texture(_) => {
753                if let Some(alias) = yog_gfx::image::suggest_alias(source) {
754                    return Err(format!(
755                        "line {line}: <Image> source=\"{source}\" is a raw resource path, which \
756                         changes between Minecraft versions — write source=\"{alias}\""
757                    ));
758                }
759                source.to_string()
760            }
761            _ => source.to_string(),
762        };
763        let mut expr = format!("widget::image({source:?})");
764        if let Some(v) = el.attr("stretch") {
765            let s = match v.trim().to_ascii_lowercase().replace('_', "").as_str() {
766                "none" => "None",
767                "fill" => "Fill",
768                "uniform" => "Uniform",
769                "uniformtofill" => "UniformToFill",
770                _ => {
771                    return Err(format!(
772                        "line {line}: <Image> stretch=\"{v}\": expected None, Fill, Uniform or UniformToFill"
773                    ));
774                }
775            };
776            let _ = write!(expr, ".stretch(::yog_api::ui::Stretch::{s})");
777        }
778        if let Some(v) = el.attr("uv") {
779            let nums: Vec<f32> = v
780                .split([',', ' '])
781                .filter(|p| !p.trim().is_empty())
782                .map(|p| number(el, "uv", p))
783                .collect::<Result<_, _>>()?;
784            let [u, vv, w, h] = nums[..] else {
785                return Err(format!(
786                    "line {line}: <Image> uv=\"{v}\": expected \"u v width height\""
787                ));
788            };
789            let _ = write!(expr, ".region([{}, {}, {}, {}])", f(u), f(vv), f(w), f(h));
790        }
791        if let Some(v) = el.attr("tint") {
792            let _ = write!(expr, ".tint(0x{:08X})", color_attr(el, "tint", v)?);
793        }
794        Ok(expr)
795    }
796
797    /// The builder expression for `el`. `in_canvas`: the parent positions
798    /// every child absolutely (`Screen`/`Canvas`) — a missing x/y means 0.
799    fn widget(&mut self, el: &Element, in_canvas: bool, depth: usize) -> Result<String, String> {
800        let kind = el.name.as_str();
801        let is_container = CONTAINERS.contains(&kind);
802        // Any other PascalCase element is one of the mod's own components
803        // (`yog_api::ui_component!`), looked up by name when the tree is built.
804        let is_component = !is_container && !LEAVES.contains(&kind) && is_component_name(kind);
805        if !is_container && !LEAVES.contains(&kind) && !is_component {
806            return Err(format!(
807                "line {}: unknown element <{kind}> (expected one of {}, {}, or a custom component's PascalCase name)",
808                el.line,
809                CONTAINERS[1..].join(", "),
810                LEAVES.join(", ")
811            ));
812        }
813        if kind == "Screen" && depth > 0 {
814            return Err(format!(
815                "line {}: <Screen> must be the root element",
816                el.line
817            ));
818        }
819        if !is_container && !el.children.is_empty() {
820            return Err(format!("line {}: <{kind}> can't have children", el.line));
821        }
822        for (key, _) in &el.attrs {
823            if !is_component
824                && !key.starts_with(RAW_CALL)
825                && !COMMON_ATTRS.contains(&key.as_str())
826                && !kind_attrs(kind).contains(&key.as_str())
827            {
828                let hint = wpf_hint(key)
829                    .map(|h| format!(" — .yui writes it `{h}`"))
830                    .unwrap_or_default();
831                return Err(format!(
832                    "line {}: <{kind}> has no attribute `{key}`{hint}",
833                    el.line
834                ));
835            }
836        }
837        let text = || text_expr(el.attr("text").unwrap_or_default());
838        let mut expr = match kind {
839            "Screen" | "Canvas" | "Column" => "widget::panel(FlexDir::Column)".to_string(),
840            "Row" => "widget::panel(FlexDir::Row)".to_string(),
841            "ScrollView" => "widget::scroll_view()".to_string(),
842            "Grid" => "widget::grid()".to_string(),
843            "Label" => format!("widget::label({})", text()),
844            "Button" => format!("widget::button({})", text()),
845            "TextBox" => format!("widget::text_box({})", text()),
846            "ItemSlot" => format!(
847                "widget::item_slot({:?})",
848                el.attr("item").unwrap_or_default()
849            ),
850            "InvSlot" => {
851                let count = match el.attr("count") {
852                    Some(c) => c.trim().parse::<u32>().map_err(|_| {
853                        format!(
854                            "line {}: <InvSlot> count=\"{c}\": expected a whole number",
855                            el.line
856                        )
857                    })?,
858                    None => 1,
859                };
860                format!(
861                    "widget::inv_slot({:?}, {count})",
862                    el.attr("item").unwrap_or_default()
863                )
864            }
865            "Slot" => {
866                let index = el.attr("index").unwrap_or_default();
867                let index = index.trim().parse::<usize>().map_err(|_| {
868                    format!(
869                        "line {}: <Slot> index=\"{index}\": expected the container slot's number (0, 1, ...)",
870                        el.line
871                    )
872                })?;
873                format!("widget::slot({index})")
874            }
875            "PlayerInventory" => "widget::player_inventory()".to_string(),
876            "Image" => self.image(el)?,
877            "Surface" => self.surface(el)?,
878            _ if is_component => component_expr(el),
879            _ => "widget::spacer()".to_string(),
880        };
881        let indent = "    ".repeat(depth + 2);
882        let mut call = |s: String| {
883            let _ = write!(expr, "\n{indent}.{s}");
884        };
885        if kind == "Screen" {
886            if let Some(v) = el.attr("width") {
887                call(format!("w(Units::Px({}))", f(number(el, "width", v)?)));
888            }
889            if let Some(v) = el.attr("height") {
890                call(format!("h(Units::Px({}))", f(number(el, "height", v)?)));
891            }
892        }
893        let x = el.attr("x").map(|v| number(el, "x", v)).transpose()?;
894        let y = el.attr("y").map(|v| number(el, "y", v)).transpose()?;
895        if in_canvas || x.is_some() || y.is_some() {
896            call(format!(
897                "at({}, {})",
898                f(x.unwrap_or(0.0)),
899                f(y.unwrap_or(0.0))
900            ));
901        }
902        for (key, value) in &el.attrs {
903            let v = value.as_str();
904            if key.starts_with(RAW_CALL) {
905                // Builder calls added by the view-model generator.
906                call(value.clone());
907                continue;
908            }
909            if is_component && !COMMON_ATTRS.contains(&key.as_str()) {
910                // A component's own property (passed to `build` above); an
911                // `on_*` one names an event like `on_click` does.
912                if key.starts_with("on_") && !v.trim().is_empty() {
913                    self.events.push(value);
914                }
915                continue;
916            }
917            match key.as_str() {
918                "id" => {
919                    self.ids.push(value);
920                    call(format!("id({v:?})"));
921                }
922                "on_click" | "on_change" | "on_submit" => {
923                    self.events.push(value);
924                    call(format!("{key}({v:?})"));
925                }
926                "placeholder" => call(format!("placeholder({})", text_expr(v))),
927                "font" => call(format!("font({:?})", v.trim())),
928                "max_length" => {
929                    let n = v.trim().parse::<usize>().map_err(|_| {
930                        format!(
931                            "line {}: <{kind}> max_length=\"{v}\": expected a whole number",
932                            el.line
933                        )
934                    })?;
935                    call(format!("max_length({n})"));
936                }
937                "w" | "h" => {
938                    if let Some(s) = size(el, key, v)? {
939                        call(format!("{key}({s})"));
940                    }
941                }
942                "min_w" | "min_h" | "flex" | "gap" | "font_scale" => {
943                    call(format!("{key}({})", f(number(el, key, v)?)));
944                }
945                "dock" => {
946                    let d = pick(
947                        el,
948                        key,
949                        v,
950                        &["none", "fill", "left", "right", "top", "bottom"],
951                    )?;
952                    call(format!("dock(Dock::{})", pascal(d)));
953                }
954                "align" => {
955                    let a = pick(el, key, v, &["start", "center", "end"])?;
956                    call(format!("align(Align::{})", pascal(a)));
957                }
958                "focus_style" => {
959                    let s = pick(el, key, v, &["outline", "fill", "none"])?;
960                    call(format!("focus_style(FocusStyle::{})", pascal(s)));
961                }
962                "padding" | "margin" => {
963                    let [t, r, b, l] = padding(el, key, v)?;
964                    call(format!("{key}({}, {}, {}, {})", f(t), f(r), f(b), f(l)));
965                }
966                "halign" => {
967                    let a = pick(el, key, v, &["left", "center", "right", "stretch"])?;
968                    call(format!("halign(::yog_api::ui::HAlign::{})", pascal(a)));
969                }
970                "valign" => {
971                    let a = pick(el, key, v, &["top", "center", "bottom", "stretch"])?;
972                    call(format!("valign(::yog_api::ui::VAlign::{})", pascal(a)));
973                }
974                "bg" | "color" | "focus_color" => {
975                    call(format!("{key}(0x{:08X})", color_attr(el, key, v)?));
976                }
977                "shadow" | "enabled" => call(format!("{key}({})", boolean(el, key, v)?)),
978                "no_wrap" if boolean(el, key, v)? => call("no_wrap()".to_string()),
979                "ellipsis" if boolean(el, key, v)? => call("ellipsis()".to_string()),
980                _ => {} // kind-specific, handled above (or Screen metadata)
981            }
982        }
983        if !el.children.is_empty() {
984            let canvas = matches!(kind, "Screen" | "Canvas");
985            for child in &el.children {
986                let c = self.widget(child, canvas, depth + 1)?;
987                let _ = write!(expr, "\n{indent}.child({c})");
988            }
989        }
990        Ok(expr)
991    }
992}
993
994/// Prefix of a custom component property's value that is a Rust
995/// expression (a `String`) rather than text — set by the component
996/// generator for bound properties; never in a `.yui`.
997pub(crate) const RAW_VALUE: &str = "\u{1}rs:";
998
999/// Attribute-name prefix of a raw builder call (`__rs0="action(...)"`)
1000/// that the view-model generator attaches to elements; never in a `.yui`.
1001pub(crate) const RAW_CALL: &str = "__rs";
1002
1003/// The builder expression of `el` and its subtree, and the ids found —
1004/// the static half of a view-model screen.
1005pub(crate) fn static_widget(
1006    el: &Element,
1007    in_canvas: bool,
1008    depth: usize,
1009    mod_id: Option<&str>,
1010) -> Result<(String, Vec<String>), String> {
1011    let mut codegen = Gen::new(mod_id);
1012    let expr = codegen.widget(el, in_canvas, depth)?;
1013    Ok((expr, codegen.ids.into_vec()))
1014}
1015
1016/// Generates the `.g.rs` source for a `.yui` document. `name` is the screen's
1017/// path under `src/` without the extension (`mod_list`, `screens/options`):
1018/// what the code-behind passes to `ui_include!`.
1019#[cfg_attr(not(test), allow(dead_code))] // the tests' entry point
1020pub fn generate(src: &str, name: &str) -> Result<String, String> {
1021    generate_for(src, name, None).map(|(code, _)| code)
1022}
1023
1024/// [`generate`] for the mod `mod_id` (resolves `mod:` image sources), also
1025/// returning `line N: ...` warnings.
1026pub fn generate_for(
1027    src: &str,
1028    name: &str,
1029    mod_id: Option<&str>,
1030) -> Result<(String, Vec<String>), String> {
1031    let mut root = parse_xml(src)?;
1032    crate::yui_grid::normalize(&mut root)?;
1033    if root.name == "Component" {
1034        return crate::yui_component::generate(&root, name, mod_id);
1035    }
1036    if root.attr("x:ViewModel").is_some() {
1037        return crate::yui_vm::generate(&root, name, mod_id);
1038    }
1039    if root.name != "Screen" {
1040        return Err(format!(
1041            "line {}: the root element must be <Screen>, not <{}>",
1042            root.line, root.name
1043        ));
1044    }
1045    let id = root
1046        .attr("id")
1047        .filter(|s| !s.trim().is_empty())
1048        .ok_or_else(|| {
1049            format!(
1050                "line {}: <Screen> needs an id (the UI id, e.g. \"mymod:main\")",
1051                root.line
1052            )
1053        })?
1054        .to_string();
1055    let (width, height, anchor) = screen_frame(&root)?;
1056    let modal = root
1057        .attr("modal")
1058        .map(|v| boolean(&root, "modal", v))
1059        .transpose()?
1060        .unwrap_or(true);
1061    let pause = root
1062        .attr("pause")
1063        .map(|v| boolean(&root, "pause", v))
1064        .transpose()?
1065        .unwrap_or(false);
1066
1067    let mut codegen = Gen::new(mod_id);
1068    // The screen's own id is the UI id, not a widget id.
1069    let mut content_root = root.clone();
1070    content_root.attrs.retain(|(k, _)| k != "id");
1071    let body = codegen.widget(&content_root, false, 0)?;
1072
1073    let (ax, ay) = match anchor {
1074        "top_left" => ("0.0", "0.0"),
1075        "top" => ("((screen_w - WIDTH) / 2.0).floor()", "0.0"),
1076        "top_right" => ("screen_w - WIDTH", "0.0"),
1077        "left" => ("0.0", "((screen_h - HEIGHT) / 2.0).floor()"),
1078        "right" => ("screen_w - WIDTH", "((screen_h - HEIGHT) / 2.0).floor()"),
1079        "bottom_left" => ("0.0", "screen_h - HEIGHT"),
1080        "bottom" => ("((screen_w - WIDTH) / 2.0).floor()", "screen_h - HEIGHT"),
1081        "bottom_right" => ("screen_w - WIDTH", "screen_h - HEIGHT"),
1082        _ => (
1083            "((screen_w - WIDTH) / 2.0).floor()",
1084            "((screen_h - HEIGHT) / 2.0).floor()",
1085        ),
1086    };
1087    let place = if anchor == "fill" {
1088        "content.w(Units::Percent(100.0)).h(Units::Percent(100.0)).at(0.0, 0.0)".to_string()
1089    } else {
1090        format!("content.at(({ax}).max(0.0), ({ay}).max(0.0))")
1091    };
1092
1093    let mut out = String::new();
1094    let _ = write!(
1095        out,
1096        r#"// <auto-generated>
1097//     Generated by yog from src/{name}.yui — do not edit: changes are lost
1098//     on the next `yog build` / `yog check` / `yog ui gen`. Edit the .yui
1099//     file (Yog-IDLE's screen designer) instead.
1100// </auto-generated>
1101//
1102// Pulled into the screen's code-behind module with:
1103//
1104//     yog_api::ui_include!("{name}");
1105
1106/// The UI id this screen registers under (`register_ui`, `on_ui_render`, `open_ui`).
1107#[allow(dead_code)]
1108pub const ID: &str = {id:?};
1109/// Design-time size in GUI pixels.
1110#[allow(dead_code)]
1111pub const WIDTH: f32 = {width};
1112#[allow(dead_code)]
1113pub const HEIGHT: f32 = {height};
1114
1115/// `on_click`/`on_change`/`on_submit` events raised by this screen's widgets.
1116#[allow(dead_code)]
1117pub mod events {{
1118{events}}}
1119
1120/// Ids of this screen's named widgets (for `Widget::find_mut`, `UiRoot::find_rect`).
1121#[allow(dead_code)]
1122pub mod ids {{
1123{ids}}}
1124
1125/// The screen's widget tree, positioned at (0, 0).
1126#[allow(dead_code)]
1127pub fn build() -> ::yog_api::ui::Widget {{
1128    #[allow(unused_imports)]
1129    {UI_USE}
1130    {body}
1131}}
1132
1133/// The screen laid out for a `screen_w` × `screen_h` GUI, anchored {anchor}
1134/// — `customize` may change the tree first (dynamic text, enabled state, ...).
1135#[allow(dead_code)]
1136pub fn root_with(
1137    screen_w: f32,
1138    screen_h: f32,
1139    customize: impl FnOnce(&mut ::yog_api::ui::Widget),
1140) -> ::yog_api::ui::UiRoot {{
1141    use ::yog_api::ui::{{widget, FlexDir, Units}};
1142    let mut content = build();
1143    customize(&mut content);
1144    let screen = widget::panel(FlexDir::Column)
1145        .w(Units::Px(screen_w))
1146        .h(Units::Px(screen_h))
1147        .child({place});
1148    let mut ui = ::yog_api::ui::UiRoot::new(ID, screen);
1149    ui.layout(screen_w, screen_h);
1150    ui
1151}}
1152
1153/// [`root_with`] without changes.
1154#[allow(dead_code)]
1155pub fn root(screen_w: f32, screen_h: f32) -> ::yog_api::ui::UiRoot {{
1156    root_with(screen_w, screen_h, |_| {{}})
1157}}
1158
1159static __YUI_LAST: ::std::sync::Mutex<Option<::yog_api::ui::UiRoot>> = ::std::sync::Mutex::new(None);
1160
1161/// Draws the screen — call from `on_ui_render(ID, ...)`. Remembers the
1162/// layout for [`click`].
1163#[allow(dead_code)]
1164pub fn render(gfx: &::yog_api::GfxContext) {{
1165    render_with(gfx, |_| {{}})
1166}}
1167
1168/// [`render`], changing the tree first (see [`root_with`]).
1169#[allow(dead_code)]
1170pub fn render_with(gfx: &::yog_api::GfxContext, customize: impl FnOnce(&mut ::yog_api::ui::Widget)) {{
1171    let (w, h) = gfx.screen_size();
1172    let ui = root_with(w as f32, h as f32, customize);
1173    ui.render(gfx);
1174    if let Ok(mut last) = __YUI_LAST.lock() {{
1175        *last = Some(ui);
1176    }}
1177}}
1178
1179/// The `on_click` event of the widget under a `"click:X:Y"` UI event (what
1180/// `register_ui`'s handler receives) — `None` for other events or a miss.
1181#[allow(dead_code)]
1182pub fn click(event: &str) -> Option<String> {{
1183    let mut parts = event.strip_prefix("click:")?.split(':');
1184    let x: f32 = parts.next()?.parse().ok()?;
1185    let y: f32 = parts.next()?.parse().ok()?;
1186    let last = __YUI_LAST.lock().ok()?;
1187    last.as_ref()?.hit_test(x, y)?.on_click.clone()
1188}}
1189
1190/// Runs `f` on the layout drawn by the last [`render`] — for reading
1191/// rects and scroll state (`UiRoot::find_node`) when handling UI events.
1192/// `None` before the first render.
1193#[allow(dead_code)]
1194pub fn with_last<R>(f: impl FnOnce(&::yog_api::ui::UiRoot) -> R) -> Option<R> {{
1195    let last = __YUI_LAST.lock().ok()?;
1196    last.as_ref().map(f)
1197}}
1198
1199/// Feeds a UI event to the text box `id` (one of [`ids`]) as laid out by the
1200/// last [`render`] — call from `register_ui`'s handler; pass the same state
1201/// to `TextBoxState::apply` in [`render_with`]'s customize. `Ignored` before
1202/// the first render or for an unknown id.
1203#[allow(dead_code)]
1204pub fn text_box(
1205    id: &str,
1206    state: &mut ::yog_api::ui::TextBoxState,
1207    event: &str,
1208) -> ::yog_api::ui::TextBoxEvent {{
1209    with_last(|ui| ui.find_node(id).map(|node| state.handle(event, node)))
1210        .flatten()
1211        .unwrap_or(::yog_api::ui::TextBoxEvent::Ignored)
1212}}
1213
1214/// Opens the screen (modal: {modal}, pauses the game: {pause}).
1215#[allow(dead_code)]
1216pub fn open() {{
1217    ::yog_api::open_ui(ID, {modal}, {pause});
1218}}
1219
1220/// Closes the screen if it's open (what Esc does) — for a Done/Cancel
1221/// button. Takes effect after the current event handler returns.
1222#[allow(dead_code)]
1223pub fn close() {{
1224    ::yog_api::close_ui(ID);
1225}}
1226"#,
1227        width = f(width),
1228        height = f(height),
1229        events = str_consts(codegen.events.as_slice()),
1230        ids = str_consts(codegen.ids.as_slice()),
1231    );
1232    // Plain screens have nothing to warn about (yet); view-model screens do.
1233    Ok((out, Vec::new()))
1234}
1235
1236/// Where generated screen code goes, under the project root.
1237pub const GENERATED_DIR: &str = ".yog-build/generated";
1238
1239fn absolute(path: &Path) -> PathBuf {
1240    if path.is_absolute() {
1241        path.to_path_buf()
1242    } else {
1243        std::env::current_dir().unwrap_or_default().join(path)
1244    }
1245}
1246
1247/// The project root (the folder with `yog.toml`) a `.yui` file belongs to.
1248pub fn project_root(yui: &Path) -> Option<PathBuf> {
1249    absolute(yui)
1250        .ancestors()
1251        .skip(1)
1252        .find(|d| d.join(crate::manifest::MANIFEST).is_file())
1253        .map(Path::to_path_buf)
1254}
1255
1256/// `foo.yui`'s name for `ui_include!`: its path under `src/` without the
1257/// extension, `/`-separated (`mod_list`, `screens/options`).
1258pub fn include_name(root: &Path, yui: &Path) -> String {
1259    let abs = absolute(yui);
1260    let rel = abs
1261        .strip_prefix(root.join("src"))
1262        .or_else(|_| abs.strip_prefix(root))
1263        .unwrap_or(&abs)
1264        .with_extension("");
1265    rel.components()
1266        .map(|c| c.as_os_str().to_string_lossy().into_owned())
1267        .collect::<Vec<_>>()
1268        .join("/")
1269}
1270
1271/// Where `src/<name>.yui`'s generated code goes:
1272/// `.yog-build/generated/<name>.g.rs`.
1273pub fn generated_path(root: &Path, name: &str) -> PathBuf {
1274    root.join(GENERATED_DIR).join(format!("{name}.g.rs"))
1275}
1276
1277/// Generates `.yog-build/generated/<name>.g.rs` for one `.yui` file of the
1278/// project at `root` — only rewritten when the output changed, so cargo
1279/// doesn't rebuild for nothing.
1280pub fn generate_file(root: &Path, yui: &Path) -> Result<PathBuf, String> {
1281    let src = std::fs::read_to_string(yui).map_err(|e| format!("{}: {e}", yui.display()))?;
1282    let name = include_name(root, yui);
1283    let mod_id = std::fs::read_to_string(root.join(crate::manifest::MANIFEST))
1284        .ok()
1285        .and_then(|t| crate::manifest::parse_yog_toml(&t).ok())
1286        .map(|t| t.id);
1287    let (code, warnings) = generate_for(&src, &name, mod_id.as_deref())
1288        .map_err(|e| format!("{}: {e}", yui.display()))?;
1289    for w in warnings {
1290        eprintln!("    warning: {}: {w}", yui.display());
1291    }
1292    let out = generated_path(root, &name);
1293    crate::write_if_changed(&out, &code)?;
1294    Ok(out)
1295}
1296
1297/// Every `*.<ext>` file under `dir`, recursively.
1298fn find_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
1299    let mut found = Vec::new();
1300    let Ok(entries) = std::fs::read_dir(dir) else {
1301        return found;
1302    };
1303    for entry in entries.flatten() {
1304        let path = entry.path();
1305        if path.is_dir() {
1306            found.extend(find_files(&path, ext));
1307        } else if path.extension().is_some_and(|e| e == ext) {
1308            found.push(path);
1309        }
1310    }
1311    found.sort();
1312    found
1313}
1314
1315/// Every `.yui` file under `dir`, recursively.
1316pub fn find_yui_files(dir: &Path) -> Vec<PathBuf> {
1317    find_files(dir, "yui")
1318}
1319
1320/// `yog build`'s step: regenerates every `src/**/*.yui`'s `.g.rs` and drops
1321/// generated files whose `.yui` is gone.
1322pub fn generate_all(root: &Path) -> Result<usize, String> {
1323    let files = find_yui_files(&root.join("src"));
1324    let mut wanted = Vec::new();
1325    for file in &files {
1326        wanted.push(generate_file(root, file)?);
1327    }
1328    // Components without a code-behind, for `ui_components!()`.
1329    wanted.push(crate::yui_component::write_index(root)?);
1330    // `.yres` accessors live there too (`crate::yres` cleans those up).
1331    let res_index = root.join(crate::yres::GENERATED_FILE);
1332    let res_dir = root.join(crate::yres::GENERATED_DIR);
1333    // So do `content/` blocks and items (`crate::content`).
1334    let content_file = root.join(crate::content::GENERATED_FILE);
1335    for stale in find_files(&root.join(GENERATED_DIR), "rs") {
1336        if stale.to_string_lossy().ends_with(".g.rs")
1337            && !wanted.contains(&stale)
1338            && stale != res_index
1339            && stale != content_file
1340            && !stale.starts_with(&res_dir)
1341        {
1342            let _ = std::fs::remove_file(&stale);
1343        }
1344    }
1345    Ok(files.len())
1346}
1347
1348#[cfg(test)]
1349mod tests {
1350    use super::*;
1351
1352    fn screen(body: &str) -> String {
1353        format!(r#"<Screen id="mymod:s">{body}</Screen>"#)
1354    }
1355
1356    #[test]
1357    fn custom_components() {
1358        let (code, _) = generate_for(
1359            &screen(r##"<StatBar x="4" w="80" label="@@hp" value="0.5" on_select="pick" bg="#FF000000"/>"##),
1360            "s",
1361            None,
1362        )
1363        .unwrap();
1364        assert!(
1365            code.contains(r#"::yog_api::ui::component::build("StatBar", &[("label", &*"@hp"), ("value", "0.5"), ("on_select", "pick")])"#),
1366            "{code}"
1367        );
1368        assert!(
1369            code.contains(".bg(0xFF000000)") && code.contains(".w(Units::Px(80.0))"),
1370            "{code}"
1371        );
1372        assert!(!code.contains(".value("), "{code}");
1373        assert!(generate_for(&screen(r#"<statBar/>"#), "s", None).is_err());
1374        assert!(generate_for(&screen(r#"<StatBar><Label/></StatBar>"#), "s", None).is_err());
1375    }
1376
1377    #[test]
1378    fn surfaces() {
1379        let (code, _) = generate_for(
1380            &screen(r#"<Surface w="100" h="50" source="mod:grid"/>"#),
1381            "s",
1382            Some("example"),
1383        )
1384        .unwrap();
1385        assert!(
1386            code.contains(r#"widget::surface("example:grid")"#),
1387            "{code}"
1388        );
1389        let (code, _) =
1390            generate_for(&screen(r#"<Surface source="other:pad"/>"#), "s", None).unwrap();
1391        assert!(code.contains(r#"widget::surface("other:pad")"#), "{code}");
1392        assert!(generate_for(&screen(r#"<Surface/>"#), "s", None).is_err());
1393        assert!(generate_for(&screen(r#"<Surface source="pad"/>"#), "s", None).is_err());
1394        assert!(generate_for(&screen(r#"<Surface source="mod:pad"/>"#), "s", None).is_err());
1395        assert!(generate_for(&screen(r#"<Surface source="a:b" text="x"/>"#), "s", None).is_err());
1396    }
1397
1398    #[test]
1399    fn image_sources() {
1400        let (code, warnings) = generate_for(
1401            &screen(r##"<Image w="156" h="29" source="item:apple" stretch="UniformToFill" tint="#80FFFFFF"/>"##),
1402            "s",
1403            None,
1404        )
1405        .unwrap();
1406        assert!(code.contains(r#"widget::image("item:apple").stretch(::yog_api::ui::Stretch::UniformToFill).tint(0x80FFFFFF)"#), "{code}");
1407        assert!(
1408            code.contains(".w(Units::Px(156.0))") || code.contains("w(156"),
1409            "{code}"
1410        );
1411        assert!(warnings.is_empty(), "{warnings:?}");
1412
1413        let (code, _) = generate_for(
1414            &screen(r#"<Image source="mod:gui/logo" uv="0 0 32 16"/>"#),
1415            "s",
1416            Some("mymod"),
1417        )
1418        .unwrap();
1419        assert!(
1420            code.contains(
1421                r#"widget::image("mymod:textures/gui/logo.png").region([0.0, 0.0, 32.0, 16.0])"#
1422            ),
1423            "{code}"
1424        );
1425        assert!(generate_for(&screen(r#"<Image source="mod:gui/logo"/>"#), "s", None).is_err());
1426        assert!(generate_for(&screen(r#"<Image source="sprite:nope"/>"#), "s", None).is_err());
1427        assert!(generate_for(&screen(r#"<Image/>"#), "s", None).is_err());
1428        assert!(
1429            generate_for(
1430                &screen(r#"<Image source="item:apple" stretch="big"/>"#),
1431                "s",
1432                None
1433            )
1434            .is_err()
1435        );
1436    }
1437
1438    #[test]
1439    fn raw_texture_paths_are_errors_naming_the_alias() {
1440        let err = generate_for(
1441            &screen(r#"<Image source="minecraft:textures/item/apple.png"/>"#),
1442            "s",
1443            None,
1444        )
1445        .unwrap_err();
1446        assert!(err.contains(r#"source="item:apple""#), "{err}");
1447        assert!(
1448            generate_for(&screen(r#"<Image texture="item:apple"/>"#), "s", None)
1449                .unwrap_err()
1450                .contains("no attribute `texture`")
1451        );
1452    }
1453
1454    #[test]
1455    fn inventory_slots() {
1456        let code = generate_for(
1457            &screen(r#"<Column><Slot index="2"/><PlayerInventory/></Column>"#),
1458            "s",
1459            None,
1460        )
1461        .unwrap()
1462        .0;
1463        assert!(code.contains("widget::slot(2)"), "{code}");
1464        assert!(code.contains("widget::player_inventory()"), "{code}");
1465        let err = generate_for(&screen(r#"<Slot index="first"/>"#), "s", None).unwrap_err();
1466        assert!(err.contains("expected the container slot's number"), "{err}");
1467    }
1468
1469    const SAMPLE: &str = r##"<?xml version="1.0" encoding="utf-8"?>
1470<!-- a comment -->
1471<Screen id="mymod:main" width="176" height="166" bg="#C0101010" padding="8">
1472  <Label id="title" x="8" y="6" text="Main &amp; Menu" color="#FFFFFF" no_wrap="true"/>
1473  <Button x="38" y="40" w="100" h="20" text="Play" bg="#FF555555" on_click="mymod:play"/>
1474  <Row x="8" y="70" w="50%" gap="2" align="center">
1475    <InvSlot item="minecraft:diamond" count="3"/>
1476    <Spacer flex="1"/>
1477  </Row>
1478  <ScrollView id="list" x="0" y="100" w="80" h="40">
1479    <Label text="A long line" ellipsis="true"/>
1480  </ScrollView>
1481</Screen>
1482"##;
1483
1484    #[test]
1485    fn parses_the_subset() {
1486        let root = parse_xml(SAMPLE).unwrap();
1487        assert_eq!(root.name, "Screen");
1488        assert_eq!(root.children.len(), 4);
1489        assert_eq!(root.children[0].attr("text"), Some("Main & Menu"));
1490        assert_eq!(root.children[2].children[0].attr("count"), Some("3"));
1491        assert_eq!(root.children[1].line, 5);
1492    }
1493
1494    #[test]
1495    fn generates_builder_code() {
1496        let code = generate(SAMPLE, "main").unwrap();
1497        assert!(code.contains(r#"pub const ID: &str = "mymod:main";"#));
1498        assert!(code.contains(r#"widget::label("Main & Menu")"#));
1499        assert!(code.contains(".at(8.0, 6.0)"));
1500        assert!(code.contains(".color(0xFFFFFFFF)"));
1501        assert!(code.contains(".bg(0xC0101010)"));
1502        assert!(code.contains(".no_wrap()"));
1503        assert!(code.contains(".w(Units::Percent(50.0))"));
1504        assert!(code.contains("widget::inv_slot(\"minecraft:diamond\", 3)"));
1505        assert!(code.contains(r#"pub const MYMOD_PLAY: &str = "mymod:play";"#));
1506        assert!(code.contains(r#"pub const TITLE: &str = "title";"#));
1507        assert!(code.contains(".padding(8.0, 8.0, 8.0, 8.0)"));
1508        assert!(code.contains("widget::scroll_view()"));
1509        assert!(code.contains(".ellipsis()"));
1510        assert!(code.contains("pub fn with_last<R>"));
1511        assert!(code.starts_with("// <auto-generated>"));
1512        assert!(code.contains(r#"yog_api::ui_include!("main");"#));
1513        assert!(code.contains("pub fn close()"));
1514        // Children of a Row aren't positioned unless they say so.
1515        assert!(!code.contains("widget::spacer()\n                .at("));
1516    }
1517
1518    #[test]
1519    fn reports_errors_with_lines() {
1520        let bad = "<Screen id=\"a:b\">\n  <Label txt=\"x\"/>\n</Screen>";
1521        let err = generate(bad, "x.yui").unwrap_err();
1522        assert!(err.contains("line 2") && err.contains("txt"), "{err}");
1523        assert!(generate("<Screen id=\"a:b\"><Label/></Scren>", "x.yui").is_err());
1524        assert!(generate("<Column/>", "x.yui").is_err());
1525        assert!(generate("<Screen/>", "x.yui").unwrap_err().contains("id"));
1526        let bad_color = "<Screen id=\"a:b\" bg=\"red\"/>";
1527        assert!(
1528            generate(bad_color, "x.yui")
1529                .unwrap_err()
1530                .contains("#RRGGBB")
1531        );
1532    }
1533
1534    /// What the IDE's Format Document writes (Visual Studio's XAML layout):
1535    /// one attribute per line, comments among the children, ` />`.
1536    #[test]
1537    fn parses_formatted_markup() {
1538        let src = r##"<?xml version="1.0" encoding="utf-8"?>
1539<Screen id="mymod:main"
1540        width="176"
1541        height="166"
1542        bg="#C0101010">
1543    <!-- the title -->
1544    <Label id="title"
1545           x="8"
1546           y="6"
1547           text="Main"
1548           no_wrap="true" />
1549
1550    <Row x="8" y="70" w="160">
1551        <!--
1552          a multi-line comment
1553        -->
1554        <Spacer flex="1" />
1555    </Row>
1556</Screen>
1557"##;
1558        let root = parse_xml(src).unwrap();
1559        assert_eq!(root.attr("height"), Some("166"));
1560        assert_eq!(root.children.len(), 2);
1561        assert_eq!(root.children[0].attr("no_wrap"), Some("true"));
1562        assert_eq!(root.children[0].line, 7);
1563        assert_eq!(root.children[1].children.len(), 1);
1564        let code = generate(src, "main.yui").unwrap();
1565        assert!(code.contains(".at(8.0, 6.0)"));
1566    }
1567
1568    #[test]
1569    fn text_box_and_font() {
1570        let src = r#"<Screen id="a:b">
1571  <TextBox id="search" w="100%" placeholder="Search..." max_length="64" on_change="search" on_submit="go" font="minecraft:uniform" shadow="false"/>
1572</Screen>"#;
1573        let code = generate(src, "x").unwrap();
1574        assert!(code.contains(r#"widget::text_box("")"#), "{code}");
1575        assert!(code.contains(r#".placeholder("Search...")"#));
1576        assert!(code.contains(".max_length(64)"));
1577        assert!(code.contains(r#".on_change("search")"#));
1578        assert!(code.contains(r#".on_submit("go")"#));
1579        assert!(code.contains(r#".font("minecraft:uniform")"#));
1580        assert!(code.contains(".shadow(false)"));
1581        assert!(code.contains(r#"pub const GO: &str = "go";"#));
1582        assert!(code.contains("pub fn text_box("));
1583        let bad = r#"<Screen id="a:b"><TextBox max_length="x"/></Screen>"#;
1584        assert!(generate(bad, "x").unwrap_err().contains("whole number"));
1585    }
1586
1587    #[test]
1588    fn generated_paths() {
1589        let dir = std::env::temp_dir().join(format!("yog-yui-test-{}", std::process::id()));
1590        let _ = std::fs::remove_dir_all(&dir);
1591        std::fs::create_dir_all(dir.join("src/screens")).unwrap();
1592        std::fs::write(dir.join("yog.toml"), "").unwrap();
1593        let yui = dir.join("src/screens/opts.yui");
1594        std::fs::write(&yui, r#"<Screen id="a:b"/>"#).unwrap();
1595        assert_eq!(project_root(&yui).as_deref(), Some(dir.as_path()));
1596        assert_eq!(include_name(&dir, &yui), "screens/opts");
1597        assert_eq!(generate_all(&dir).unwrap(), 1);
1598        let generated = dir.join(".yog-build/generated/screens/opts.g.rs");
1599        assert!(generated.is_file());
1600        std::fs::remove_file(&yui).unwrap();
1601        generate_all(&dir).unwrap();
1602        assert!(!generated.exists());
1603        let _ = std::fs::remove_dir_all(&dir);
1604    }
1605
1606    #[test]
1607    fn const_names() {
1608        assert_eq!(const_name("mymod:btn-play"), "MYMOD_BTN_PLAY");
1609        assert_eq!(const_name("openMenu"), "OPEN_MENU");
1610        assert_eq!(const_name("1st"), "_1ST");
1611    }
1612
1613    #[test]
1614    fn text_starting_with_at_is_a_translation_key() {
1615        assert_eq!(text_expr("@mymod.title"), "::yog_api::tr(\"mymod.title\")");
1616        assert_eq!(text_expr("@@home"), "\"@home\"");
1617        assert_eq!(text_expr("plain"), "\"plain\"");
1618        assert_eq!(text_expr("@"), "\"@\"");
1619        let mut refs = crate::yres::Refs::default();
1620        refs.texts.insert(
1621            "Strings.title".into(),
1622            ("mymod.title".into(), "Title".into()),
1623        );
1624        set_resource_refs(&refs);
1625        assert_eq!(
1626            text_expr("@Strings.title"),
1627            "::yog_api::tr(\"mymod.title\")"
1628        );
1629        set_resource_refs(&crate::yres::Refs::default());
1630        let code = generate(
1631            r#"<Screen id="m:s" width="10" height="10"><Label text="@m.title"/><Button text="@@x"/></Screen>"#,
1632            "s.yui",
1633        )
1634        .unwrap();
1635        assert!(
1636            code.contains("widget::label(::yog_api::tr(\"m.title\"))"),
1637            "{code}"
1638        );
1639        assert!(code.contains("widget::button(\"@x\")"), "{code}");
1640    }
1641
1642    #[test]
1643    fn color_attributes_resolve_yres_colors() {
1644        let mut refs = crate::yres::Refs::default();
1645        refs.colors.insert("Colors.text".into(), 0xFF12_3456);
1646        set_resource_refs(&refs);
1647        let code = generate(
1648            r#"<Screen id="m:s" width="10" height="10"><Label text="x" color="@Colors.text"/></Screen>"#,
1649            "s.yui",
1650        );
1651        let missing = generate(
1652            r#"<Screen id="m:s" width="10" height="10"><Label text="x" color="@Colors.nope"/></Screen>"#,
1653            "s.yui",
1654        );
1655        set_resource_refs(&crate::yres::Refs::default());
1656        let code = code.unwrap();
1657        assert!(code.contains("0xFF123456"), "{code}");
1658        assert!(missing.unwrap_err().contains("no color `Colors.nope`"));
1659    }
1660}