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