1use std::borrow::Cow;
24use std::fmt::Write as _;
25
26use icedwright_protocol::{WidgetId, WindowId};
27use icedwright_types::{Point, Rect, Role, Size, StateName, StateValue};
28
29use crate::build::{self, Draft, Mode, named_from_content};
30use crate::error::Error;
31use crate::path::Cursor;
32use crate::tree::{Kind, NameSource, Node, NodeId, SemanticTree, StateSource, Value};
33
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub struct YamlOptions {
37 pub include_bounds: bool,
39 pub include_ids: bool,
41 pub include_ignored: bool,
43 pub mask_props: Vec<String>,
45 pub depth: Option<usize>,
47 pub max_lines: Option<usize>,
49 pub refs: bool,
51}
52
53pub const STATE_NAMES: &[(StateName, &str)] = &[
55 (StateName::Disabled, "disabled"),
56 (StateName::Readonly, "readonly"),
57 (StateName::Checked, "checked"),
58 (StateName::Pressed, "pressed"),
59 (StateName::Expanded, "expanded"),
60 (StateName::Selected, "selected"),
61 (StateName::Focused, "focused"),
62 (StateName::Current, "current"),
63 (StateName::Busy, "busy"),
64 (StateName::Required, "required"),
65 (StateName::Invalid, "invalid"),
66 (StateName::Multiline, "multiline"),
67 (StateName::Multiselectable, "multiselectable"),
68 (StateName::Modal, "modal"),
69 (StateName::Focusable, "focusable"),
70 (StateName::Hidden, "hidden"),
71 (StateName::Offscreen, "offscreen"),
72 (StateName::Inert, "inert"),
73];
74
75const fn is_flag(state: StateName) -> bool {
76 matches!(
77 state,
78 StateName::Modal
79 | StateName::Focusable
80 | StateName::Hidden
81 | StateName::Offscreen
82 | StateName::Inert
83 )
84}
85
86struct Line {
87 depth: usize,
88 text: String,
89 bullet: bool,
92}
93
94impl Line {
95 fn entry(depth: usize, text: String) -> Self {
96 Self {
97 depth,
98 text,
99 bullet: true,
100 }
101 }
102}
103
104const IMPLICIT_KEY_LIMIT: usize = 1024;
106
107#[must_use]
109pub fn write(tree: &SemanticTree, root: NodeId, options: &YamlOptions) -> String {
110 let mut lines = Vec::new();
111 let Some(node) = tree.get(root) else {
112 return String::new();
113 };
114 if node.role == Role::Window && node.parent.is_none() {
115 for child in visible_children(tree, node, options) {
116 write_node(tree, child, 0, options, &mut lines);
117 }
118 } else {
119 write_node(tree, node, 0, options, &mut lines);
120 }
121 if let Some(max) = options.max_lines
122 && lines.len() > max
123 {
124 let cut = max.saturating_sub(1);
125 let depth = lines.get(cut).map_or(0, |l| l.depth);
126 lines.truncate(cut);
127 if lines
128 .last()
129 .is_some_and(|l| l.bullet && l.text.starts_with("? "))
130 {
131 lines.pop();
132 }
133 lines.push(Line::entry(depth, "...".to_owned()));
134 }
135 let mut out = String::new();
136 for line in lines {
137 let bullet = if line.bullet { "- " } else { " " };
138 let _ = writeln!(out, "{}{bullet}{}", " ".repeat(line.depth), line.text);
139 }
140 out
141}
142
143#[must_use]
148pub fn normalise(source: &str) -> Cow<'_, str> {
149 let needs = source.lines().any(|line| {
150 let item = line.trim_start_matches(' ');
151 item.starts_with("- '") || item.starts_with("- ? ")
152 });
153 if !needs {
154 return Cow::Borrowed(source);
155 }
156 let lines: Vec<&str> = source.lines().collect();
157 let mut out = String::with_capacity(source.len());
158 let mut index = 0;
159 while let Some(line) = lines.get(index) {
160 index += 1;
161 let indent = line.len() - line.trim_start_matches(' ').len();
162 let Some(item) = line.get(indent..).and_then(|l| l.strip_prefix("- ")) else {
163 out.push_str(line);
164 out.push('\n');
165 continue;
166 };
167 let (key, explicit) = match item.strip_prefix("? ") {
168 Some(key) => (key, true),
169 None => (item, false),
170 };
171 let mut folded = unwrap_key(key);
172 let value_line = lines.get(index).filter(|next| {
173 let next_indent = next.len() - next.trim_start_matches(' ').len();
174 explicit && next_indent == indent + 2 && next.trim_start().starts_with(':')
175 });
176 if let Some(value_line) = value_line {
177 folded.push_str(value_line.trim_start());
178 index += 1;
179 }
180 out.push_str(line.get(..indent).unwrap_or_default());
181 out.push_str("- ");
182 out.push_str(&folded);
183 out.push('\n');
184 if value_line.is_some() {
185 out.push('\n');
186 }
187 }
188 Cow::Owned(out)
189}
190
191fn quoted(text: &str) -> String {
193 let mut out = String::with_capacity(text.len() + 2);
194 out.push('"');
195 for c in text.chars() {
196 match c {
197 '"' => out.push_str("\\\""),
198 '\\' => out.push_str("\\\\"),
199 '\n' => out.push_str("\\n"),
200 '\t' => out.push_str("\\t"),
201 '\r' => out.push_str("\\r"),
202 c if needs_escape(c) => {
203 let _ = write!(out, "\\u{:04x}", u32::from(c));
204 }
205 c => out.push(c),
206 }
207 }
208 out.push('"');
209 out
210}
211
212fn needs_escape(c: char) -> bool {
214 c.is_control()
215 || matches!(
216 c,
217 '\u{feff}' | '\u{2028}' | '\u{2029}' | '\u{fffe}' | '\u{ffff}'
218 )
219}
220
221fn yaml_key(key: &str) -> String {
224 let plain = !key.contains(": ") && !key.contains(" #") && !key.ends_with(':');
225 if plain {
226 return key.to_owned();
227 }
228 format!("'{}'", key.replace('\'', "''"))
229}
230
231fn unwrap_key(item: &str) -> String {
234 let Some(rest) = item.strip_prefix('\'') else {
235 return item.to_owned();
236 };
237 let mut key = String::new();
238 let mut chars = rest.char_indices().peekable();
239 while let Some((at, c)) = chars.next() {
240 if c != '\'' {
241 key.push(c);
242 continue;
243 }
244 if chars.next_if(|(_, next)| *next == '\'').is_some() {
245 key.push('\'');
246 continue;
247 }
248 key.push_str(rest.get(at + 1..).unwrap_or_default());
249 return key;
250 }
251 item.to_owned()
252}
253
254fn visible_children<'t>(
257 tree: &'t SemanticTree,
258 node: &'t Node,
259 options: &YamlOptions,
260) -> Vec<&'t Node> {
261 let mut out = Vec::new();
262 for child in &node.children {
263 let Some(child) = tree.get(*child) else {
264 continue;
265 };
266 if child.relations.owner.is_some() {
267 continue;
268 }
269 if child.ignored && !options.include_ignored {
270 out.extend(visible_children(tree, child, options));
271 continue;
272 }
273 out.push(child);
274 }
275 for owned in &node.relations.owns {
276 if let Some(owned) = tree.get(*owned) {
277 out.push(owned);
278 }
279 }
280 out
281}
282
283fn write_node(
284 tree: &SemanticTree,
285 node: &Node,
286 depth: usize,
287 options: &YamlOptions,
288 lines: &mut Vec<Line>,
289) {
290 let children = if options.depth.is_some_and(|max| depth >= max) {
291 Vec::new()
292 } else {
293 visible_children(tree, node, options)
294 };
295 let key = yaml_key(&key(tree, node, options));
296 let colon_value = colon_value(tree, node);
297 let after = match (&colon_value, children.is_empty()) {
298 (Some(value), true) => format!(": {}", scalar(value)),
299 (None, true) => String::new(),
300 (_, false) => ":".to_owned(),
301 };
302 if after.is_empty() || key.chars().count() <= IMPLICIT_KEY_LIMIT {
303 lines.push(Line::entry(depth, key + &after));
304 } else {
305 lines.push(Line::entry(depth, format!("? {key}")));
306 lines.push(Line {
307 depth,
308 text: after,
309 bullet: false,
310 });
311 }
312 if children.is_empty() {
313 return;
314 }
315 if let Some(value) = colon_value {
316 lines.push(Line::entry(
317 depth + 1,
318 format!("/value: {}", scalar(&value)),
319 ));
320 }
321 for child in children {
322 write_node(tree, child, depth + 1, options, lines);
323 }
324}
325
326fn is_text_role(role: Role) -> bool {
327 matches!(role, Role::Text | Role::Paragraph)
328}
329
330fn text_named_by_content(tree: &SemanticTree, node: &Node) -> bool {
331 is_text_role(node.role)
332 && (node.name_source == NameSource::Text
333 || node.name.as_deref() == Some(tree.text_content(node.id)))
334}
335
336fn colon_value(tree: &SemanticTree, node: &Node) -> Option<String> {
337 if text_named_by_content(tree, node) {
338 return node.name.clone();
339 }
340 if is_text_role(node.role) {
341 let text = tree.text_content(node.id);
342 return (!text.is_empty() && node.name.as_deref() != Some(text)).then(|| text.to_owned());
343 }
344 match &node.value {
345 Some(Value::Text(text)) => Some(text.clone()),
346 _ => None,
347 }
348}
349
350fn scalar(text: &str) -> String {
353 let starts_plain = text
354 .chars()
355 .next()
356 .is_some_and(|c| !"-?:,[]{}#&*!|>'\"%@`/".contains(c));
357 let plain = starts_plain
358 && text.trim() == text
359 && !text.contains(": ")
360 && !text.contains(" #")
361 && !text.ends_with(':')
362 && !text.chars().any(|c| c == '\t' || needs_escape(c));
363 if plain {
364 return text.to_owned();
365 }
366 quoted(text)
367}
368
369fn number(value: f64) -> String {
370 format!("{value}")
371}
372
373fn key(tree: &SemanticTree, node: &Node, options: &YamlOptions) -> String {
374 let mut out = node.role.selector_name().to_owned();
375 if let Some(name) = &node.name
376 && !text_named_by_content(tree, node)
377 {
378 out.push(' ');
379 out.push_str("ed(name));
380 }
381 let mut attr = |text: String| {
382 out.push_str(" [");
383 out.push_str(&text);
384 out.push(']');
385 };
386 for (state, name) in STATE_NAMES {
387 let Some(value) = node.states.get(*state) else {
388 continue;
389 };
390 match value {
391 StateValue::Bool(true) => attr((*name).to_owned()),
392 StateValue::Bool(false) if is_flag(*state) => {}
393 other => attr(format!("{name}={other}")),
394 }
395 }
396 if let Some(level) = node.set.level {
397 attr(format!("level={level}"));
398 }
399 if let Some(position) = node.set.position {
400 attr(format!("position={position}"));
401 }
402 if let Some(size) = node.set.size {
403 attr(format!("set-size={size}"));
404 }
405 for (label, field) in [
406 ("description", &node.description),
407 ("placeholder", &node.placeholder),
408 ("tooltip", &node.tooltip),
409 ] {
410 if let Some(text) = field {
411 attr(format!("{label}={}", quoted(text)));
412 }
413 }
414 if let Some(Value::Number {
415 now,
416 min,
417 max,
418 step,
419 }) = &node.value
420 {
421 attr(format!("value={}", number(*now)));
422 for (label, bound) in [("min", min), ("max", max), ("step", step)] {
423 if let Some(bound) = bound {
424 attr(format!("{label}={}", number(*bound)));
425 }
426 }
427 }
428 for (prop, value) in &node.props {
429 let shown = if options.mask_props.iter().any(|m| m == prop) {
430 "***"
431 } else {
432 value.as_str()
433 };
434 attr(format!("prop:{prop}={}", quoted(shown)));
435 }
436 if options.include_ids {
437 if let Some(id) = &node.test_id {
438 attr(format!("test-id={}", quoted(id)));
439 }
440 match &node.widget_id {
441 Some(WidgetId::Custom(id)) => attr(format!("widget-id={}", quoted(id))),
442 Some(WidgetId::Unique(n)) => attr(format!("widget-id=#{n}")),
443 None => {}
444 }
445 }
446 if options.refs && node.role.is_interactive() {
447 attr(format!("ref={}", node.id));
448 }
449 if options.include_bounds {
450 let b = node.bounds;
451 let _ = write!(
452 out,
453 " @ {},{} {}x{}",
454 b.x.round(),
455 b.y.round(),
456 b.width.round(),
457 b.height.round()
458 );
459 }
460 out
461}
462
463pub fn read(yaml: &str) -> Result<SemanticTree, Error> {
468 let yaml = normalise(yaml);
469 let mut entries: Vec<(usize, usize, Draft, Option<String>)> = Vec::new();
470 for (index, raw_line) in yaml.lines().enumerate() {
471 let line_number = index + 1;
472 if raw_line.trim().is_empty() {
473 continue;
474 }
475 let indent = raw_line.len() - raw_line.trim_start_matches(' ').len();
476 if indent % 2 != 0 {
477 return Err(yaml_error(
478 line_number,
479 indent + 1,
480 "indentation must be a multiple of two spaces",
481 ));
482 }
483 let Some(item) = raw_line.get(indent..).and_then(|l| l.strip_prefix("- ")) else {
484 return Err(yaml_error(
485 line_number,
486 indent + 1,
487 "expected `- ` to start an entry",
488 ));
489 };
490 if item == "..." {
491 continue;
492 }
493 let column = indent + 3;
494 if let Some(value) = item.strip_prefix("/value: ") {
495 let value = read_scalar(value)
496 .map_err(|(at, m)| yaml_error(line_number, column + 8 + at, &m))?;
497 entries.push((
498 indent / 2,
499 line_number,
500 Draft::new(Node::blank(Role::Unknown, yaml_kind(), WindowId(0))),
501 Some(value),
502 ));
503 continue;
504 }
505 let draft = read_entry(item).map_err(|(at, m)| yaml_error(line_number, column + at, &m))?;
506 entries.push((indent / 2, line_number, draft, None));
507 }
508 let (_, top) = nest(&mut entries.into_iter().peekable(), 0)?;
509 let windows = if !top.is_empty() && top.iter().all(|d| d.node.role == Role::Window) {
510 top
511 } else {
512 let mut window = Draft::new(Node::blank(Role::Window, yaml_kind(), WindowId(0)));
513 window.children = top;
514 vec![window]
515 };
516 let windows = windows
517 .into_iter()
518 .enumerate()
519 .map(|(i, mut window)| {
520 let id = WindowId(u64::try_from(i).unwrap_or(u64::MAX));
521 set_window(&mut window, id);
522 window
523 })
524 .collect();
525 Ok(build::finish(windows, Mode::Keep))
526}
527
528fn set_window(draft: &mut Draft, window: WindowId) {
529 draft.node.window = window;
530 for child in &mut draft.children {
531 set_window(child, window);
532 }
533}
534
535fn yaml_kind() -> Kind {
536 Kind::Annotated(Cow::Borrowed("app"))
537}
538
539fn yaml_error(line: usize, column: usize, message: &str) -> Error {
540 Error::Yaml {
541 line,
542 column,
543 message: message.to_owned(),
544 }
545}
546
547type Entry = (usize, usize, Draft, Option<String>);
548
549fn nest(
551 entries: &mut std::iter::Peekable<impl Iterator<Item = Entry>>,
552 depth: usize,
553) -> Result<(Option<String>, Vec<Draft>), Error> {
554 let mut leading = None;
555 let mut out: Vec<Draft> = Vec::new();
556 while let Some((entry_depth, line, _, _)) = entries.peek() {
557 let (entry_depth, line) = (*entry_depth, *line);
558 if entry_depth < depth {
559 break;
560 }
561 if entry_depth > depth {
562 let Some(parent) = out.last_mut() else {
563 return Err(yaml_error(
564 line,
565 entry_depth * 2 + 1,
566 "entry is indented under nothing",
567 ));
568 };
569 let (value, children) = nest(entries, depth + 1)?;
570 if let Some(value) = value {
571 parent.node.value = Some(Value::Text(value));
572 }
573 parent.children.extend(children);
574 continue;
575 }
576 let Some((_, _, draft, value)) = entries.next() else {
577 break;
578 };
579 match value {
580 Some(value) if out.is_empty() && leading.is_none() && depth > 0 => {
581 leading = Some(value);
582 }
583 Some(_) => {
584 return Err(yaml_error(
585 line,
586 depth * 2 + 1,
587 "`/value` must be the first child of a node",
588 ));
589 }
590 None => out.push(draft),
591 }
592 }
593 Ok((leading, out))
594}
595
596fn read_scalar(text: &str) -> Result<String, (usize, String)> {
597 if !text.starts_with('"') {
598 return Ok(text.to_owned());
599 }
600 let mut cursor = Cursor::new(text);
601 let value = cursor.quoted()?;
602 if !cursor.rest().is_empty() {
603 return Err((
604 cursor.offset,
605 "unexpected text after the closing quote".to_owned(),
606 ));
607 }
608 Ok(value)
609}
610
611fn read_number(cursor: &mut Cursor<'_>) -> Result<f64, (usize, String)> {
612 let at = cursor.offset;
613 let text = cursor.take_while(|c| {
614 c.is_ascii_digit() || matches!(c, '-' | '.' | 'e' | 'E' | '+' | 'i' | 'n' | 'f' | 'N' | 'a')
615 });
616 text.parse()
617 .map_err(|_| (at, format!("`{text}` is not a number")))
618}
619
620fn read_unsigned<T: std::str::FromStr>(cursor: &mut Cursor<'_>) -> Result<T, (usize, String)> {
621 let at = cursor.offset;
622 let text = cursor.take_while(|c| c.is_ascii_digit());
623 text.parse()
624 .map_err(|_| (at, "expected a whole number".to_owned()))
625}
626
627fn read_entry(item: &str) -> Result<Draft, (usize, String)> {
628 let mut cursor = Cursor::new(item);
629 let at = cursor.offset;
630 let word = cursor.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'));
631 let role = Role::from_selector_name(word).ok_or((at, format!("unknown role `{word}`")))?;
632 let mut node = Node::blank(role, yaml_kind(), WindowId(0));
633 if cursor.rest().starts_with(" \"") {
634 cursor.offset += 1;
635 node.name = Some(cursor.quoted()?);
636 node.name_source = NameSource::Annotation;
637 }
638 while cursor.rest().starts_with(" [") {
639 cursor.offset += 2;
640 read_attribute(&mut cursor, &mut node)?;
641 if !cursor.eat("]") {
642 return Err((cursor.offset, "expected `]`".to_owned()));
643 }
644 }
645 if cursor.eat(" @ ") {
646 let x = read_number(&mut cursor)?;
647 let y = if cursor.eat(",") {
648 read_number(&mut cursor)?
649 } else {
650 return Err((cursor.offset, "expected `,`".to_owned()));
651 };
652 if !cursor.eat(" ") {
653 return Err((cursor.offset, "expected a space before the size".to_owned()));
654 }
655 let width = read_number(&mut cursor)?;
656 if !cursor.eat("x") {
657 return Err((cursor.offset, "expected `x`".to_owned()));
658 }
659 let height = read_number(&mut cursor)?;
660 node.bounds = Rect::new(
661 Point::new(x as f32, y as f32),
662 Size::new(width as f32, height as f32),
663 );
664 if node.bounds.area() > 0.0 && !node.states.offscreen {
665 node.visible_bounds = Some(node.bounds);
666 }
667 }
668 let mut value = None;
669 if cursor.eat(": ") {
670 value = Some(read_scalar(cursor.rest()).map_err(|(o, m)| (cursor.offset + o, m))?);
671 cursor.offset = cursor.input.len();
672 } else {
673 cursor.eat(":");
674 }
675 if !cursor.rest().is_empty() {
676 return Err((cursor.offset, format!("unexpected `{}`", cursor.rest())));
677 }
678 let mut draft = Draft::new(node);
679 match value {
680 Some(text) if is_text_role(role) && draft.node.name.is_none() => {
681 draft.node.name = Some(text.clone());
682 draft.node.name_source = NameSource::Text;
683 draft.own_text = Some(text);
684 }
685 Some(text) if is_text_role(role) => draft.own_text = Some(text),
686 Some(text) => draft.node.value = Some(Value::Text(text)),
687 None => {}
688 }
689 if is_text_role(role) && draft.own_text.is_none() {
690 draft.own_text = draft.node.name.clone();
691 }
692 if named_from_content(role) {
693 draft.own_text = draft.node.name.clone();
694 }
695 Ok(draft)
696}
697
698fn read_attribute(cursor: &mut Cursor<'_>, node: &mut Node) -> Result<(), (usize, String)> {
699 let at = cursor.offset;
700 let name =
701 cursor.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'));
702 let has_value = cursor.eat("=");
703 if let Some(prop) = name.strip_prefix("prop:") {
704 if !has_value {
705 return Err((cursor.offset, "expected `=` after a prop".to_owned()));
706 }
707 node.props.insert(prop.to_owned(), cursor.quoted()?);
708 return Ok(());
709 }
710 if let Some((state, _)) = STATE_NAMES.iter().find(|(_, n)| *n == name) {
711 let value = if has_value {
712 let at = cursor.offset;
713 let word = cursor.take_while(|c| c.is_ascii_alphabetic());
714 word.parse::<StateValue>()
715 .map_err(|e| (at, e.to_string()))?
716 } else {
717 StateValue::Bool(true)
718 };
719 node.states.set(*state, value, StateSource::Annotation);
720 return Ok(());
721 }
722 if !has_value {
723 return Err((at, format!("unknown attribute `{name}`")));
724 }
725 match name {
726 "level" => node.set.level = Some(read_unsigned(cursor)?),
727 "position" => node.set.position = Some(read_unsigned(cursor)?),
728 "set-size" => node.set.size = Some(read_unsigned(cursor)?),
729 "description" => node.description = Some(cursor.quoted()?),
730 "placeholder" => node.placeholder = Some(cursor.quoted()?),
731 "tooltip" => node.tooltip = Some(cursor.quoted()?),
732 "test-id" => node.test_id = Some(cursor.quoted()?),
733 "widget-id" if cursor.eat("#") => {
734 node.widget_id = Some(WidgetId::Unique(read_unsigned(cursor)?))
735 }
736 "widget-id" => node.widget_id = Some(WidgetId::Custom(cursor.quoted()?)),
737 "ref" => {
738 cursor.take_while(|c| c.is_ascii_alphanumeric());
739 }
740 "value" | "min" | "max" | "step" => {
741 let number = read_number(cursor)?;
742 let (mut now, mut min, mut max, mut step) = match node.value {
743 Some(Value::Number {
744 now,
745 min,
746 max,
747 step,
748 }) => (now, min, max, step),
749 _ => (0.0, None, None, None),
750 };
751 match name {
752 "value" => now = number,
753 "min" => min = Some(number),
754 "max" => max = Some(number),
755 _ => step = Some(number),
756 }
757 node.value = Some(Value::Number {
758 now,
759 min,
760 max,
761 step,
762 });
763 }
764 other => return Err((at, format!("unknown attribute `{other}`"))),
765 }
766 Ok(())
767}