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