1use std::collections::HashSet;
24use std::fmt::Write as _;
25use std::path::{Path, PathBuf};
26
27use yog_gfx::image::ImageSource;
28
29#[derive(Debug, Clone)]
33pub struct Element {
34 pub name: String,
35 pub attrs: Vec<(String, String)>,
36 pub children: Vec<Element>,
37 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 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 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 `&`".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
245pub 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
258pub(crate) const UI_USE: &str =
262 "use ::yog_api::ui::{widget, Align, Dock, FlexDir, FocusStyle, Units};";
263
264pub(crate) fn is_builtin(kind: &str) -> bool {
266 CONTAINERS.contains(&kind) || LEAVES.contains(&kind)
267}
268
269pub(crate) fn is_custom_component(kind: &str) -> bool {
271 !is_builtin(kind) && is_component_name(kind)
272}
273
274pub(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
279pub(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
357pub 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
373pub(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
392fn is_resource_text(reference: &str) -> bool {
394 RESOURCE_REFS.with(|r| r.borrow().texts.contains_key(reference.trim()))
395}
396
397fn 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
417fn 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
435pub(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
451fn 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
475pub(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
519pub 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
532fn 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
538fn 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 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
567pub 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 static RESOURCE_REFS: std::cell::RefCell<crate::yres::Refs> = Default::default();
590}
591
592pub fn set_resource_refs(refs: &crate::yres::Refs) {
595 RESOURCE_REFS.with(|r| *r.borrow_mut() = refs.clone());
596}
597
598pub 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#[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
648pub(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 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 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 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 source = image_source(el, "source", source, self.mod_id.as_deref())?;
719 let mut expr = format!("widget::image({source:?})");
720 if let Some(v) = el.attr("stretch") {
721 let s = match v.trim().to_ascii_lowercase().replace('_', "").as_str() {
722 "none" => "None",
723 "fill" => "Fill",
724 "uniform" => "Uniform",
725 "uniformtofill" => "UniformToFill",
726 _ => {
727 return Err(format!(
728 "line {line}: <Image> stretch=\"{v}\": expected None, Fill, Uniform or UniformToFill"
729 ));
730 }
731 };
732 let _ = write!(expr, ".stretch(::yog_api::ui::Stretch::{s})");
733 }
734 if let Some(v) = el.attr("uv") {
735 let nums: Vec<f32> = v
736 .split([',', ' '])
737 .filter(|p| !p.trim().is_empty())
738 .map(|p| number(el, "uv", p))
739 .collect::<Result<_, _>>()?;
740 let [u, vv, w, h] = nums[..] else {
741 return Err(format!(
742 "line {line}: <Image> uv=\"{v}\": expected \"u v width height\""
743 ));
744 };
745 let _ = write!(expr, ".region([{}, {}, {}, {}])", f(u), f(vv), f(w), f(h));
746 }
747 if let Some(v) = el.attr("tint") {
748 let _ = write!(expr, ".tint(0x{:08X})", color_attr(el, "tint", v)?);
749 }
750 Ok(expr)
751 }
752
753 fn widget(&mut self, el: &Element, in_canvas: bool, depth: usize) -> Result<String, String> {
756 let kind = el.name.as_str();
757 let is_container = CONTAINERS.contains(&kind);
758 let is_component = !is_container && !LEAVES.contains(&kind) && is_component_name(kind);
761 if !is_container && !LEAVES.contains(&kind) && !is_component {
762 return Err(format!(
763 "line {}: unknown element <{kind}> (expected one of {}, {}, or a custom component's PascalCase name)",
764 el.line,
765 CONTAINERS[1..].join(", "),
766 LEAVES.join(", ")
767 ));
768 }
769 if kind == "Screen" && depth > 0 {
770 return Err(format!(
771 "line {}: <Screen> must be the root element",
772 el.line
773 ));
774 }
775 if !is_container && !el.children.is_empty() {
776 return Err(format!("line {}: <{kind}> can't have children", el.line));
777 }
778 for (key, _) in &el.attrs {
779 if !is_component
780 && !key.starts_with(RAW_CALL)
781 && !COMMON_ATTRS.contains(&key.as_str())
782 && !kind_attrs(kind).contains(&key.as_str())
783 {
784 let hint = wpf_hint(key)
785 .map(|h| format!(" — .yui writes it `{h}`"))
786 .unwrap_or_default();
787 return Err(format!(
788 "line {}: <{kind}> has no attribute `{key}`{hint}",
789 el.line
790 ));
791 }
792 }
793 let text = || text_expr(el.attr("text").unwrap_or_default());
794 let mut expr = match kind {
795 "Screen" | "Canvas" | "Column" => "widget::panel(FlexDir::Column)".to_string(),
796 "Row" => "widget::panel(FlexDir::Row)".to_string(),
797 "ScrollView" => "widget::scroll_view()".to_string(),
798 "Grid" => "widget::grid()".to_string(),
799 "Label" => format!("widget::label({})", text()),
800 "Button" => format!("widget::button({})", text()),
801 "TextBox" => format!("widget::text_box({})", text()),
802 "ItemSlot" => format!(
803 "widget::item_slot({:?})",
804 el.attr("item").unwrap_or_default()
805 ),
806 "InvSlot" => {
807 let count = match el.attr("count") {
808 Some(c) => c.trim().parse::<u32>().map_err(|_| {
809 format!(
810 "line {}: <InvSlot> count=\"{c}\": expected a whole number",
811 el.line
812 )
813 })?,
814 None => 1,
815 };
816 format!(
817 "widget::inv_slot({:?}, {count})",
818 el.attr("item").unwrap_or_default()
819 )
820 }
821 "Slot" => {
822 let index = el.attr("index").unwrap_or_default();
823 let index = index.trim().parse::<usize>().map_err(|_| {
824 format!(
825 "line {}: <Slot> index=\"{index}\": expected the container slot's number (0, 1, ...)",
826 el.line
827 )
828 })?;
829 format!("widget::slot({index})")
830 }
831 "PlayerInventory" => "widget::player_inventory()".to_string(),
832 "Image" => self.image(el)?,
833 "Surface" => self.surface(el)?,
834 _ if is_component => component_expr(el),
835 _ => "widget::spacer()".to_string(),
836 };
837 let indent = " ".repeat(depth + 2);
838 let mut call = |s: String| {
839 let _ = write!(expr, "\n{indent}.{s}");
840 };
841 if kind == "Screen" {
842 if let Some(v) = el.attr("width") {
843 call(format!("w(Units::Px({}))", f(number(el, "width", v)?)));
844 }
845 if let Some(v) = el.attr("height") {
846 call(format!("h(Units::Px({}))", f(number(el, "height", v)?)));
847 }
848 }
849 let x = el.attr("x").map(|v| number(el, "x", v)).transpose()?;
850 let y = el.attr("y").map(|v| number(el, "y", v)).transpose()?;
851 if in_canvas || x.is_some() || y.is_some() {
852 call(format!(
853 "at({}, {})",
854 f(x.unwrap_or(0.0)),
855 f(y.unwrap_or(0.0))
856 ));
857 }
858 for (key, value) in &el.attrs {
859 let v = value.as_str();
860 if key.starts_with(RAW_CALL) {
861 call(value.clone());
863 continue;
864 }
865 if is_component && !COMMON_ATTRS.contains(&key.as_str()) {
866 if key.starts_with("on_") && !v.trim().is_empty() {
869 self.events.push(value);
870 }
871 continue;
872 }
873 match key.as_str() {
874 "id" => {
875 self.ids.push(value);
876 call(format!("id({v:?})"));
877 }
878 "on_click" | "on_change" | "on_submit" => {
879 self.events.push(value);
880 call(format!("{key}({v:?})"));
881 }
882 "placeholder" => call(format!("placeholder({})", text_expr(v))),
883 "font" => call(format!("font({:?})", v.trim())),
884 "max_length" => {
885 let n = v.trim().parse::<usize>().map_err(|_| {
886 format!(
887 "line {}: <{kind}> max_length=\"{v}\": expected a whole number",
888 el.line
889 )
890 })?;
891 call(format!("max_length({n})"));
892 }
893 "w" | "h" => {
894 if let Some(s) = size(el, key, v)? {
895 call(format!("{key}({s})"));
896 }
897 }
898 "min_w" | "min_h" | "flex" | "gap" | "font_scale" => {
899 call(format!("{key}({})", f(number(el, key, v)?)));
900 }
901 "dock" => {
902 let d = pick(
903 el,
904 key,
905 v,
906 &["none", "fill", "left", "right", "top", "bottom"],
907 )?;
908 call(format!("dock(Dock::{})", pascal(d)));
909 }
910 "align" => {
911 let a = pick(el, key, v, &["start", "center", "end"])?;
912 call(format!("align(Align::{})", pascal(a)));
913 }
914 "focus_style" => {
915 let s = pick(el, key, v, &["outline", "fill", "none"])?;
916 call(format!("focus_style(FocusStyle::{})", pascal(s)));
917 }
918 "padding" | "margin" => {
919 let [t, r, b, l] = padding(el, key, v)?;
920 call(format!("{key}({}, {}, {}, {})", f(t), f(r), f(b), f(l)));
921 }
922 "halign" => {
923 let a = pick(el, key, v, &["left", "center", "right", "stretch"])?;
924 call(format!("halign(::yog_api::ui::HAlign::{})", pascal(a)));
925 }
926 "valign" => {
927 let a = pick(el, key, v, &["top", "center", "bottom", "stretch"])?;
928 call(format!("valign(::yog_api::ui::VAlign::{})", pascal(a)));
929 }
930 "bg" if is_image_value(v) => {
931 let src = image_source(el, key, v.trim(), self.mod_id.as_deref())?;
932 call(format!("bg_image({src:?})"));
933 }
934 "bg" | "color" | "focus_color" => {
935 call(format!("{key}(0x{:08X})", color_attr(el, key, v)?));
936 }
937 "shadow" | "enabled" => call(format!("{key}({})", boolean(el, key, v)?)),
938 "no_wrap" if boolean(el, key, v)? => call("no_wrap()".to_string()),
939 "ellipsis" if boolean(el, key, v)? => call("ellipsis()".to_string()),
940 _ => {} }
942 }
943 if !el.children.is_empty() {
944 let canvas = matches!(kind, "Screen" | "Canvas");
945 for child in &el.children {
946 let c = self.widget(child, canvas, depth + 1)?;
947 let _ = write!(expr, "\n{indent}.child({c})");
948 }
949 }
950 Ok(expr)
951 }
952}
953
954pub(crate) fn is_image_value(v: &str) -> bool {
957 let v = v.trim();
958 match v.strip_prefix('@') {
959 Some(name) => RESOURCE_REFS.with(|r| r.borrow().images.contains_key(name)),
960 None => !v.starts_with('#') && v.contains(':'),
961 }
962}
963
964pub(crate) fn image_source(el: &Element, attr: &str, source: &str, mod_id: Option<&str>) -> Result<String, String> {
967 let line = el.line;
968 let kind = el.name.as_str();
969 let mod_id = mod_id.map(str::to_owned);
970 let resolved;
971 let source = match source.strip_prefix('@') {
972 Some(name) => {
973 resolved = RESOURCE_REFS
974 .with(|r| r.borrow().images.get(name).cloned())
975 .ok_or_else(|| format!("line {line}: <{kind}> {attr}=\"{source}\": no image `{name}` in resources/*.yres"))?;
976 resolved.as_str()
977 }
978 None => source,
979 };
980 let parsed = ImageSource::parse(source).ok_or_else(|| {
981 format!(
982 "line {line}: <{kind}> {attr}=\"{source}\": expected item:<id>, block:<id>, \
983 sprite:<name>, mod:<path> or <namespace>:<path>"
984 )
985 })?;
986 let source = match parsed {
987 ImageSource::ModPath(path) => match &mod_id {
988 Some(id) => yog_gfx::image::texture_id(id, &path),
989 None => {
990 return Err(format!(
991 "line {line}: <{kind}> {attr}=\"{source}\": mod: needs the mod id (no yog.toml found)"
992 ));
993 }
994 },
995 ImageSource::Sprite(name)
996 if !name.contains(':') && yog_gfx::image::sprite(&name).is_none() =>
997 {
998 let names: Vec<&str> = yog_gfx::image::SPRITES.iter().map(|s| s.name).collect();
999 return Err(format!(
1000 "line {line}: <{kind}> {attr}=\"{source}\": unknown sprite (known: {})",
1001 names.join(", ")
1002 ));
1003 }
1004 ImageSource::Texture(_) => {
1005 if let Some(alias) = yog_gfx::image::suggest_alias(source) {
1006 return Err(format!(
1007 "line {line}: <{kind}> {attr}=\"{source}\" is a raw resource path, which \
1008 changes between Minecraft versions — write {attr}=\"{alias}\""
1009 ));
1010 }
1011 source.to_string()
1012 }
1013 _ => source.to_string(),
1014 };
1015 Ok(source)
1016}
1017
1018pub(crate) const RAW_VALUE: &str = "\u{1}rs:";
1022
1023pub(crate) const RAW_CALL: &str = "__rs";
1026
1027pub(crate) fn static_widget(
1030 el: &Element,
1031 in_canvas: bool,
1032 depth: usize,
1033 mod_id: Option<&str>,
1034) -> Result<(String, Vec<String>), String> {
1035 let mut codegen = Gen::new(mod_id);
1036 let expr = codegen.widget(el, in_canvas, depth)?;
1037 Ok((expr, codegen.ids.into_vec()))
1038}
1039
1040#[cfg_attr(not(test), allow(dead_code))] pub fn generate(src: &str, name: &str) -> Result<String, String> {
1045 generate_for(src, name, None).map(|(code, _)| code)
1046}
1047
1048pub fn generate_for(
1051 src: &str,
1052 name: &str,
1053 mod_id: Option<&str>,
1054) -> Result<(String, Vec<String>), String> {
1055 let mut root = parse_xml(src)?;
1056 crate::yui_grid::normalize(&mut root)?;
1057 if root.name == "Component" {
1058 return crate::yui_component::generate(&root, name, mod_id);
1059 }
1060 if root.attr("x:ViewModel").is_some() {
1061 return crate::yui_vm::generate(&root, name, mod_id);
1062 }
1063 if root.name != "Screen" {
1064 return Err(format!(
1065 "line {}: the root element must be <Screen>, not <{}>",
1066 root.line, root.name
1067 ));
1068 }
1069 let id = root
1070 .attr("id")
1071 .filter(|s| !s.trim().is_empty())
1072 .ok_or_else(|| {
1073 format!(
1074 "line {}: <Screen> needs an id (the UI id, e.g. \"mymod:main\")",
1075 root.line
1076 )
1077 })?
1078 .to_string();
1079 let (width, height, anchor) = screen_frame(&root)?;
1080 let modal = root
1081 .attr("modal")
1082 .map(|v| boolean(&root, "modal", v))
1083 .transpose()?
1084 .unwrap_or(true);
1085 let pause = root
1086 .attr("pause")
1087 .map(|v| boolean(&root, "pause", v))
1088 .transpose()?
1089 .unwrap_or(false);
1090
1091 let mut codegen = Gen::new(mod_id);
1092 let mut content_root = root.clone();
1094 content_root.attrs.retain(|(k, _)| k != "id");
1095 let body = codegen.widget(&content_root, false, 0)?;
1096
1097 let (ax, ay) = match anchor {
1098 "top_left" => ("0.0", "0.0"),
1099 "top" => ("((screen_w - WIDTH) / 2.0).floor()", "0.0"),
1100 "top_right" => ("screen_w - WIDTH", "0.0"),
1101 "left" => ("0.0", "((screen_h - HEIGHT) / 2.0).floor()"),
1102 "right" => ("screen_w - WIDTH", "((screen_h - HEIGHT) / 2.0).floor()"),
1103 "bottom_left" => ("0.0", "screen_h - HEIGHT"),
1104 "bottom" => ("((screen_w - WIDTH) / 2.0).floor()", "screen_h - HEIGHT"),
1105 "bottom_right" => ("screen_w - WIDTH", "screen_h - HEIGHT"),
1106 _ => (
1107 "((screen_w - WIDTH) / 2.0).floor()",
1108 "((screen_h - HEIGHT) / 2.0).floor()",
1109 ),
1110 };
1111 let place = if anchor == "fill" {
1112 "content.w(Units::Percent(100.0)).h(Units::Percent(100.0)).at(0.0, 0.0)".to_string()
1113 } else {
1114 format!("content.at(({ax}).max(0.0), ({ay}).max(0.0))")
1115 };
1116
1117 let mut out = String::new();
1118 let _ = write!(
1119 out,
1120 r#"// <auto-generated>
1121// Generated by yog from src/{name}.yui — do not edit: changes are lost
1122// on the next `yog build` / `yog check` / `yog ui gen`. Edit the .yui
1123// file (Yog-IDLE's screen designer) instead.
1124// </auto-generated>
1125//
1126// Pulled into the screen's code-behind module with:
1127//
1128// yog_api::ui_include!("{name}");
1129
1130/// The UI id this screen registers under (`register_ui`, `on_ui_render`, `open_ui`).
1131#[allow(dead_code)]
1132pub const ID: &str = {id:?};
1133/// Design-time size in GUI pixels.
1134#[allow(dead_code)]
1135pub const WIDTH: f32 = {width};
1136#[allow(dead_code)]
1137pub const HEIGHT: f32 = {height};
1138
1139/// `on_click`/`on_change`/`on_submit` events raised by this screen's widgets.
1140#[allow(dead_code)]
1141pub mod events {{
1142{events}}}
1143
1144/// Ids of this screen's named widgets (for `Widget::find_mut`, `UiRoot::find_rect`).
1145#[allow(dead_code)]
1146pub mod ids {{
1147{ids}}}
1148
1149/// The screen's widget tree, positioned at (0, 0).
1150#[allow(dead_code)]
1151pub fn build() -> ::yog_api::ui::Widget {{
1152 #[allow(unused_imports)]
1153 {UI_USE}
1154 {body}
1155}}
1156
1157/// The screen laid out for a `screen_w` × `screen_h` GUI, anchored {anchor}
1158/// — `customize` may change the tree first (dynamic text, enabled state, ...).
1159#[allow(dead_code)]
1160pub fn root_with(
1161 screen_w: f32,
1162 screen_h: f32,
1163 customize: impl FnOnce(&mut ::yog_api::ui::Widget),
1164) -> ::yog_api::ui::UiRoot {{
1165 use ::yog_api::ui::{{widget, FlexDir, Units}};
1166 let mut content = build();
1167 customize(&mut content);
1168 let screen = widget::panel(FlexDir::Column)
1169 .w(Units::Px(screen_w))
1170 .h(Units::Px(screen_h))
1171 .child({place});
1172 let mut ui = ::yog_api::ui::UiRoot::new(ID, screen);
1173 ui.layout(screen_w, screen_h);
1174 ui
1175}}
1176
1177/// [`root_with`] without changes.
1178#[allow(dead_code)]
1179pub fn root(screen_w: f32, screen_h: f32) -> ::yog_api::ui::UiRoot {{
1180 root_with(screen_w, screen_h, |_| {{}})
1181}}
1182
1183static __YUI_LAST: ::std::sync::Mutex<Option<::yog_api::ui::UiRoot>> = ::std::sync::Mutex::new(None);
1184
1185/// Draws the screen — call from `on_ui_render(ID, ...)`. Remembers the
1186/// layout for [`click`].
1187#[allow(dead_code)]
1188pub fn render(gfx: &::yog_api::GfxContext) {{
1189 render_with(gfx, |_| {{}})
1190}}
1191
1192/// [`render`], changing the tree first (see [`root_with`]).
1193#[allow(dead_code)]
1194pub fn render_with(gfx: &::yog_api::GfxContext, customize: impl FnOnce(&mut ::yog_api::ui::Widget)) {{
1195 let (w, h) = gfx.screen_size();
1196 let ui = root_with(w as f32, h as f32, customize);
1197 ui.render(gfx);
1198 if let Ok(mut last) = __YUI_LAST.lock() {{
1199 *last = Some(ui);
1200 }}
1201}}
1202
1203/// The `on_click` event of the widget under a `"click:X:Y"` UI event (what
1204/// `register_ui`'s handler receives) — `None` for other events or a miss.
1205#[allow(dead_code)]
1206pub fn click(event: &str) -> Option<String> {{
1207 let mut parts = event.strip_prefix("click:")?.split(':');
1208 let x: f32 = parts.next()?.parse().ok()?;
1209 let y: f32 = parts.next()?.parse().ok()?;
1210 let last = __YUI_LAST.lock().ok()?;
1211 last.as_ref()?.hit_test(x, y)?.on_click.clone()
1212}}
1213
1214/// Runs `f` on the layout drawn by the last [`render`] — for reading
1215/// rects and scroll state (`UiRoot::find_node`) when handling UI events.
1216/// `None` before the first render.
1217#[allow(dead_code)]
1218pub fn with_last<R>(f: impl FnOnce(&::yog_api::ui::UiRoot) -> R) -> Option<R> {{
1219 let last = __YUI_LAST.lock().ok()?;
1220 last.as_ref().map(f)
1221}}
1222
1223/// Feeds a UI event to the text box `id` (one of [`ids`]) as laid out by the
1224/// last [`render`] — call from `register_ui`'s handler; pass the same state
1225/// to `TextBoxState::apply` in [`render_with`]'s customize. `Ignored` before
1226/// the first render or for an unknown id.
1227#[allow(dead_code)]
1228pub fn text_box(
1229 id: &str,
1230 state: &mut ::yog_api::ui::TextBoxState,
1231 event: &str,
1232) -> ::yog_api::ui::TextBoxEvent {{
1233 with_last(|ui| ui.find_node(id).map(|node| state.handle(event, node)))
1234 .flatten()
1235 .unwrap_or(::yog_api::ui::TextBoxEvent::Ignored)
1236}}
1237
1238/// Opens the screen (modal: {modal}, pauses the game: {pause}).
1239#[allow(dead_code)]
1240pub fn open() {{
1241 ::yog_api::open_ui(ID, {modal}, {pause});
1242}}
1243
1244/// Closes the screen if it's open (what Esc does) — for a Done/Cancel
1245/// button. Takes effect after the current event handler returns.
1246#[allow(dead_code)]
1247pub fn close() {{
1248 ::yog_api::close_ui(ID);
1249}}
1250"#,
1251 width = f(width),
1252 height = f(height),
1253 events = str_consts(codegen.events.as_slice()),
1254 ids = str_consts(codegen.ids.as_slice()),
1255 );
1256 Ok((out, Vec::new()))
1258}
1259
1260pub const GENERATED_DIR: &str = ".yog-build/generated";
1262
1263fn absolute(path: &Path) -> PathBuf {
1264 if path.is_absolute() {
1265 path.to_path_buf()
1266 } else {
1267 std::env::current_dir().unwrap_or_default().join(path)
1268 }
1269}
1270
1271pub fn project_root(yui: &Path) -> Option<PathBuf> {
1273 absolute(yui)
1274 .ancestors()
1275 .skip(1)
1276 .find(|d| d.join(crate::manifest::MANIFEST).is_file())
1277 .map(Path::to_path_buf)
1278}
1279
1280pub fn include_name(root: &Path, yui: &Path) -> String {
1283 let abs = absolute(yui);
1284 let rel = abs
1285 .strip_prefix(root.join("src"))
1286 .or_else(|_| abs.strip_prefix(root))
1287 .unwrap_or(&abs)
1288 .with_extension("");
1289 rel.components()
1290 .map(|c| c.as_os_str().to_string_lossy().into_owned())
1291 .collect::<Vec<_>>()
1292 .join("/")
1293}
1294
1295pub fn generated_path(root: &Path, name: &str) -> PathBuf {
1298 root.join(GENERATED_DIR).join(format!("{name}.g.rs"))
1299}
1300
1301pub fn generate_file(root: &Path, yui: &Path) -> Result<PathBuf, String> {
1305 let src = std::fs::read_to_string(yui).map_err(|e| format!("{}: {e}", yui.display()))?;
1306 let name = include_name(root, yui);
1307 let mod_id = std::fs::read_to_string(root.join(crate::manifest::MANIFEST))
1308 .ok()
1309 .and_then(|t| crate::manifest::parse_yog_toml(&t).ok())
1310 .map(|t| t.id);
1311 let (code, warnings) = generate_for(&src, &name, mod_id.as_deref())
1312 .map_err(|e| format!("{}: {e}", yui.display()))?;
1313 for w in warnings {
1314 eprintln!(" warning: {}: {w}", yui.display());
1315 }
1316 let out = generated_path(root, &name);
1317 crate::write_if_changed(&out, &code)?;
1318 Ok(out)
1319}
1320
1321fn find_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
1323 let mut found = Vec::new();
1324 let Ok(entries) = std::fs::read_dir(dir) else {
1325 return found;
1326 };
1327 for entry in entries.flatten() {
1328 let path = entry.path();
1329 if path.is_dir() {
1330 found.extend(find_files(&path, ext));
1331 } else if path.extension().is_some_and(|e| e == ext) {
1332 found.push(path);
1333 }
1334 }
1335 found.sort();
1336 found
1337}
1338
1339pub fn find_yui_files(dir: &Path) -> Vec<PathBuf> {
1341 find_files(dir, "yui")
1342}
1343
1344pub fn generate_all(root: &Path) -> Result<usize, String> {
1347 let files = find_yui_files(&root.join("src"));
1348 let mut wanted = Vec::new();
1349 for file in &files {
1350 wanted.push(generate_file(root, file)?);
1351 }
1352 wanted.push(crate::yui_component::write_index(root)?);
1354 let res_index = root.join(crate::yres::GENERATED_FILE);
1356 let res_dir = root.join(crate::yres::GENERATED_DIR);
1357 let content_file = root.join(crate::content::GENERATED_FILE);
1359 for stale in find_files(&root.join(GENERATED_DIR), "rs") {
1360 if stale.to_string_lossy().ends_with(".g.rs")
1361 && !wanted.contains(&stale)
1362 && stale != res_index
1363 && stale != content_file
1364 && !stale.starts_with(&res_dir)
1365 {
1366 let _ = std::fs::remove_file(&stale);
1367 }
1368 }
1369 Ok(files.len())
1370}
1371
1372#[cfg(test)]
1373mod tests {
1374 use super::*;
1375
1376 fn screen(body: &str) -> String {
1377 format!(r#"<Screen id="mymod:s">{body}</Screen>"#)
1378 }
1379
1380 #[test]
1381 fn custom_components() {
1382 let (code, _) = generate_for(
1383 &screen(r##"<StatBar x="4" w="80" label="@@hp" value="0.5" on_select="pick" bg="#FF000000"/>"##),
1384 "s",
1385 None,
1386 )
1387 .unwrap();
1388 assert!(
1389 code.contains(r#"::yog_api::ui::component::build("StatBar", &[("label", &*"@hp"), ("value", "0.5"), ("on_select", "pick")])"#),
1390 "{code}"
1391 );
1392 assert!(
1393 code.contains(".bg(0xFF000000)") && code.contains(".w(Units::Px(80.0))"),
1394 "{code}"
1395 );
1396 assert!(!code.contains(".value("), "{code}");
1397 assert!(generate_for(&screen(r#"<statBar/>"#), "s", None).is_err());
1398 assert!(generate_for(&screen(r#"<StatBar><Label/></StatBar>"#), "s", None).is_err());
1399 }
1400
1401 #[test]
1402 fn surfaces() {
1403 let (code, _) = generate_for(
1404 &screen(r#"<Surface w="100" h="50" source="mod:grid"/>"#),
1405 "s",
1406 Some("example"),
1407 )
1408 .unwrap();
1409 assert!(
1410 code.contains(r#"widget::surface("example:grid")"#),
1411 "{code}"
1412 );
1413 let (code, _) =
1414 generate_for(&screen(r#"<Surface source="other:pad"/>"#), "s", None).unwrap();
1415 assert!(code.contains(r#"widget::surface("other:pad")"#), "{code}");
1416 assert!(generate_for(&screen(r#"<Surface/>"#), "s", None).is_err());
1417 assert!(generate_for(&screen(r#"<Surface source="pad"/>"#), "s", None).is_err());
1418 assert!(generate_for(&screen(r#"<Surface source="mod:pad"/>"#), "s", None).is_err());
1419 assert!(generate_for(&screen(r#"<Surface source="a:b" text="x"/>"#), "s", None).is_err());
1420 }
1421
1422 #[test]
1423 fn image_sources() {
1424 let (code, warnings) = generate_for(
1425 &screen(r##"<Image w="156" h="29" source="item:apple" stretch="UniformToFill" tint="#80FFFFFF"/>"##),
1426 "s",
1427 None,
1428 )
1429 .unwrap();
1430 assert!(code.contains(r#"widget::image("item:apple").stretch(::yog_api::ui::Stretch::UniformToFill).tint(0x80FFFFFF)"#), "{code}");
1431 assert!(
1432 code.contains(".w(Units::Px(156.0))") || code.contains("w(156"),
1433 "{code}"
1434 );
1435 assert!(warnings.is_empty(), "{warnings:?}");
1436
1437 let (code, _) = generate_for(
1438 &screen(r#"<Image source="mod:gui/logo" uv="0 0 32 16"/>"#),
1439 "s",
1440 Some("mymod"),
1441 )
1442 .unwrap();
1443 assert!(
1444 code.contains(
1445 r#"widget::image("mymod:textures/gui/logo.png").region([0.0, 0.0, 32.0, 16.0])"#
1446 ),
1447 "{code}"
1448 );
1449 assert!(generate_for(&screen(r#"<Image source="mod:gui/logo"/>"#), "s", None).is_err());
1450 assert!(generate_for(&screen(r#"<Image source="sprite:nope"/>"#), "s", None).is_err());
1451 assert!(generate_for(&screen(r#"<Image/>"#), "s", None).is_err());
1452 assert!(
1453 generate_for(
1454 &screen(r#"<Image source="item:apple" stretch="big"/>"#),
1455 "s",
1456 None
1457 )
1458 .is_err()
1459 );
1460 }
1461
1462 #[test]
1463 fn raw_texture_paths_are_errors_naming_the_alias() {
1464 let err = generate_for(
1465 &screen(r#"<Image source="minecraft:textures/item/apple.png"/>"#),
1466 "s",
1467 None,
1468 )
1469 .unwrap_err();
1470 assert!(err.contains(r#"source="item:apple""#), "{err}");
1471 assert!(
1472 generate_for(&screen(r#"<Image texture="item:apple"/>"#), "s", None)
1473 .unwrap_err()
1474 .contains("no attribute `texture`")
1475 );
1476 }
1477
1478 #[test]
1479 fn image_backgrounds() {
1480 let code = generate_for(&screen(r##"<Column bg="sprite:panel"><Label bg="#FF000000"/></Column>"##), "s", None)
1481 .unwrap()
1482 .0;
1483 assert!(code.contains(r#"bg_image("sprite:panel")"#), "{code}");
1484 assert!(code.contains("bg(0xFF000000)"), "{code}");
1485 let err = generate_for(&screen(r#"<Column bg="sprite:nope"/>"#), "s", None).unwrap_err();
1486 assert!(err.contains("<Column> bg=\"sprite:nope\": unknown sprite"), "{err}");
1487 }
1488
1489 #[test]
1490 fn inventory_slots() {
1491 let code = generate_for(
1492 &screen(r#"<Column><Slot index="2"/><PlayerInventory/></Column>"#),
1493 "s",
1494 None,
1495 )
1496 .unwrap()
1497 .0;
1498 assert!(code.contains("widget::slot(2)"), "{code}");
1499 assert!(code.contains("widget::player_inventory()"), "{code}");
1500 let err = generate_for(&screen(r#"<Slot index="first"/>"#), "s", None).unwrap_err();
1501 assert!(err.contains("expected the container slot's number"), "{err}");
1502 }
1503
1504 const SAMPLE: &str = r##"<?xml version="1.0" encoding="utf-8"?>
1505<!-- a comment -->
1506<Screen id="mymod:main" width="176" height="166" bg="#C0101010" padding="8">
1507 <Label id="title" x="8" y="6" text="Main & Menu" color="#FFFFFF" no_wrap="true"/>
1508 <Button x="38" y="40" w="100" h="20" text="Play" bg="#FF555555" on_click="mymod:play"/>
1509 <Row x="8" y="70" w="50%" gap="2" align="center">
1510 <InvSlot item="minecraft:diamond" count="3"/>
1511 <Spacer flex="1"/>
1512 </Row>
1513 <ScrollView id="list" x="0" y="100" w="80" h="40">
1514 <Label text="A long line" ellipsis="true"/>
1515 </ScrollView>
1516</Screen>
1517"##;
1518
1519 #[test]
1520 fn parses_the_subset() {
1521 let root = parse_xml(SAMPLE).unwrap();
1522 assert_eq!(root.name, "Screen");
1523 assert_eq!(root.children.len(), 4);
1524 assert_eq!(root.children[0].attr("text"), Some("Main & Menu"));
1525 assert_eq!(root.children[2].children[0].attr("count"), Some("3"));
1526 assert_eq!(root.children[1].line, 5);
1527 }
1528
1529 #[test]
1530 fn generates_builder_code() {
1531 let code = generate(SAMPLE, "main").unwrap();
1532 assert!(code.contains(r#"pub const ID: &str = "mymod:main";"#));
1533 assert!(code.contains(r#"widget::label("Main & Menu")"#));
1534 assert!(code.contains(".at(8.0, 6.0)"));
1535 assert!(code.contains(".color(0xFFFFFFFF)"));
1536 assert!(code.contains(".bg(0xC0101010)"));
1537 assert!(code.contains(".no_wrap()"));
1538 assert!(code.contains(".w(Units::Percent(50.0))"));
1539 assert!(code.contains("widget::inv_slot(\"minecraft:diamond\", 3)"));
1540 assert!(code.contains(r#"pub const MYMOD_PLAY: &str = "mymod:play";"#));
1541 assert!(code.contains(r#"pub const TITLE: &str = "title";"#));
1542 assert!(code.contains(".padding(8.0, 8.0, 8.0, 8.0)"));
1543 assert!(code.contains("widget::scroll_view()"));
1544 assert!(code.contains(".ellipsis()"));
1545 assert!(code.contains("pub fn with_last<R>"));
1546 assert!(code.starts_with("// <auto-generated>"));
1547 assert!(code.contains(r#"yog_api::ui_include!("main");"#));
1548 assert!(code.contains("pub fn close()"));
1549 assert!(!code.contains("widget::spacer()\n .at("));
1551 }
1552
1553 #[test]
1554 fn reports_errors_with_lines() {
1555 let bad = "<Screen id=\"a:b\">\n <Label txt=\"x\"/>\n</Screen>";
1556 let err = generate(bad, "x.yui").unwrap_err();
1557 assert!(err.contains("line 2") && err.contains("txt"), "{err}");
1558 assert!(generate("<Screen id=\"a:b\"><Label/></Scren>", "x.yui").is_err());
1559 assert!(generate("<Column/>", "x.yui").is_err());
1560 assert!(generate("<Screen/>", "x.yui").unwrap_err().contains("id"));
1561 let bad_color = "<Screen id=\"a:b\" bg=\"red\"/>";
1562 assert!(
1563 generate(bad_color, "x.yui")
1564 .unwrap_err()
1565 .contains("#RRGGBB")
1566 );
1567 }
1568
1569 #[test]
1572 fn parses_formatted_markup() {
1573 let src = r##"<?xml version="1.0" encoding="utf-8"?>
1574<Screen id="mymod:main"
1575 width="176"
1576 height="166"
1577 bg="#C0101010">
1578 <!-- the title -->
1579 <Label id="title"
1580 x="8"
1581 y="6"
1582 text="Main"
1583 no_wrap="true" />
1584
1585 <Row x="8" y="70" w="160">
1586 <!--
1587 a multi-line comment
1588 -->
1589 <Spacer flex="1" />
1590 </Row>
1591</Screen>
1592"##;
1593 let root = parse_xml(src).unwrap();
1594 assert_eq!(root.attr("height"), Some("166"));
1595 assert_eq!(root.children.len(), 2);
1596 assert_eq!(root.children[0].attr("no_wrap"), Some("true"));
1597 assert_eq!(root.children[0].line, 7);
1598 assert_eq!(root.children[1].children.len(), 1);
1599 let code = generate(src, "main.yui").unwrap();
1600 assert!(code.contains(".at(8.0, 6.0)"));
1601 }
1602
1603 #[test]
1604 fn text_box_and_font() {
1605 let src = r#"<Screen id="a:b">
1606 <TextBox id="search" w="100%" placeholder="Search..." max_length="64" on_change="search" on_submit="go" font="minecraft:uniform" shadow="false"/>
1607</Screen>"#;
1608 let code = generate(src, "x").unwrap();
1609 assert!(code.contains(r#"widget::text_box("")"#), "{code}");
1610 assert!(code.contains(r#".placeholder("Search...")"#));
1611 assert!(code.contains(".max_length(64)"));
1612 assert!(code.contains(r#".on_change("search")"#));
1613 assert!(code.contains(r#".on_submit("go")"#));
1614 assert!(code.contains(r#".font("minecraft:uniform")"#));
1615 assert!(code.contains(".shadow(false)"));
1616 assert!(code.contains(r#"pub const GO: &str = "go";"#));
1617 assert!(code.contains("pub fn text_box("));
1618 let bad = r#"<Screen id="a:b"><TextBox max_length="x"/></Screen>"#;
1619 assert!(generate(bad, "x").unwrap_err().contains("whole number"));
1620 }
1621
1622 #[test]
1623 fn generated_paths() {
1624 let dir = std::env::temp_dir().join(format!("yog-yui-test-{}", std::process::id()));
1625 let _ = std::fs::remove_dir_all(&dir);
1626 std::fs::create_dir_all(dir.join("src/screens")).unwrap();
1627 std::fs::write(dir.join("yog.toml"), "").unwrap();
1628 let yui = dir.join("src/screens/opts.yui");
1629 std::fs::write(&yui, r#"<Screen id="a:b"/>"#).unwrap();
1630 assert_eq!(project_root(&yui).as_deref(), Some(dir.as_path()));
1631 assert_eq!(include_name(&dir, &yui), "screens/opts");
1632 assert_eq!(generate_all(&dir).unwrap(), 1);
1633 let generated = dir.join(".yog-build/generated/screens/opts.g.rs");
1634 assert!(generated.is_file());
1635 std::fs::remove_file(&yui).unwrap();
1636 generate_all(&dir).unwrap();
1637 assert!(!generated.exists());
1638 let _ = std::fs::remove_dir_all(&dir);
1639 }
1640
1641 #[test]
1642 fn const_names() {
1643 assert_eq!(const_name("mymod:btn-play"), "MYMOD_BTN_PLAY");
1644 assert_eq!(const_name("openMenu"), "OPEN_MENU");
1645 assert_eq!(const_name("1st"), "_1ST");
1646 }
1647
1648 #[test]
1649 fn text_starting_with_at_is_a_translation_key() {
1650 assert_eq!(text_expr("@mymod.title"), "::yog_api::tr(\"mymod.title\")");
1651 assert_eq!(text_expr("@@home"), "\"@home\"");
1652 assert_eq!(text_expr("plain"), "\"plain\"");
1653 assert_eq!(text_expr("@"), "\"@\"");
1654 let mut refs = crate::yres::Refs::default();
1655 refs.texts.insert(
1656 "Strings.title".into(),
1657 ("mymod.title".into(), "Title".into()),
1658 );
1659 set_resource_refs(&refs);
1660 assert_eq!(
1661 text_expr("@Strings.title"),
1662 "::yog_api::tr(\"mymod.title\")"
1663 );
1664 set_resource_refs(&crate::yres::Refs::default());
1665 let code = generate(
1666 r#"<Screen id="m:s" width="10" height="10"><Label text="@m.title"/><Button text="@@x"/></Screen>"#,
1667 "s.yui",
1668 )
1669 .unwrap();
1670 assert!(
1671 code.contains("widget::label(::yog_api::tr(\"m.title\"))"),
1672 "{code}"
1673 );
1674 assert!(code.contains("widget::button(\"@x\")"), "{code}");
1675 }
1676
1677 #[test]
1678 fn color_attributes_resolve_yres_colors() {
1679 let mut refs = crate::yres::Refs::default();
1680 refs.colors.insert("Colors.text".into(), 0xFF12_3456);
1681 set_resource_refs(&refs);
1682 let code = generate(
1683 r#"<Screen id="m:s" width="10" height="10"><Label text="x" color="@Colors.text"/></Screen>"#,
1684 "s.yui",
1685 );
1686 let missing = generate(
1687 r#"<Screen id="m:s" width="10" height="10"><Label text="x" color="@Colors.nope"/></Screen>"#,
1688 "s.yui",
1689 );
1690 set_resource_refs(&crate::yres::Refs::default());
1691 let code = code.unwrap();
1692 assert!(code.contains("0xFF123456"), "{code}");
1693 assert!(missing.unwrap_err().contains("no color `Colors.nope`"));
1694 }
1695}