use std::borrow::Cow;
use std::fmt::Write as _;
use icedwright_protocol::{WidgetId, WindowId};
use icedwright_types::{Point, Rect, Role, Size, StateName, StateValue};
use crate::build::{self, Draft, Mode, named_from_content};
use crate::error::Error;
use crate::path::Cursor;
use crate::tree::{Kind, NameSource, Node, NodeId, SemanticTree, StateSource, Value};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct YamlOptions {
pub include_bounds: bool,
pub include_ids: bool,
pub include_ignored: bool,
pub mask_props: Vec<String>,
pub depth: Option<usize>,
pub max_lines: Option<usize>,
pub refs: bool,
}
pub const STATE_NAMES: &[(StateName, &str)] = &[
(StateName::Disabled, "disabled"),
(StateName::Readonly, "readonly"),
(StateName::Checked, "checked"),
(StateName::Pressed, "pressed"),
(StateName::Expanded, "expanded"),
(StateName::Selected, "selected"),
(StateName::Focused, "focused"),
(StateName::Current, "current"),
(StateName::Busy, "busy"),
(StateName::Required, "required"),
(StateName::Invalid, "invalid"),
(StateName::Multiline, "multiline"),
(StateName::Multiselectable, "multiselectable"),
(StateName::Modal, "modal"),
(StateName::Focusable, "focusable"),
(StateName::Hidden, "hidden"),
(StateName::Offscreen, "offscreen"),
(StateName::Inert, "inert"),
];
const fn is_flag(state: StateName) -> bool {
matches!(
state,
StateName::Modal
| StateName::Focusable
| StateName::Hidden
| StateName::Offscreen
| StateName::Inert
)
}
struct Line {
depth: usize,
text: String,
bullet: bool,
}
impl Line {
fn entry(depth: usize, text: String) -> Self {
Self {
depth,
text,
bullet: true,
}
}
}
const IMPLICIT_KEY_LIMIT: usize = 1024;
#[must_use]
pub fn write(tree: &SemanticTree, root: NodeId, options: &YamlOptions) -> String {
let mut lines = Vec::new();
let Some(node) = tree.get(root) else {
return String::new();
};
if node.role == Role::Window && node.parent.is_none() {
for child in visible_children(tree, node, options) {
write_node(tree, child, 0, options, &mut lines);
}
} else {
write_node(tree, node, 0, options, &mut lines);
}
if let Some(max) = options.max_lines
&& lines.len() > max
{
let cut = max.saturating_sub(1);
let depth = lines.get(cut).map_or(0, |l| l.depth);
lines.truncate(cut);
if lines
.last()
.is_some_and(|l| l.bullet && l.text.starts_with("? "))
{
lines.pop();
}
lines.push(Line::entry(depth, "...".to_owned()));
}
let mut out = String::new();
for line in lines {
let bullet = if line.bullet { "- " } else { " " };
let _ = writeln!(out, "{}{bullet}{}", " ".repeat(line.depth), line.text);
}
out
}
#[must_use]
pub fn normalise(source: &str) -> Cow<'_, str> {
let needs = source.lines().any(|line| {
let item = line.trim_start_matches(' ');
item.starts_with("- '") || item.starts_with("- ? ")
});
if !needs {
return Cow::Borrowed(source);
}
let lines: Vec<&str> = source.lines().collect();
let mut out = String::with_capacity(source.len());
let mut index = 0;
while let Some(line) = lines.get(index) {
index += 1;
let indent = line.len() - line.trim_start_matches(' ').len();
let Some(item) = line.get(indent..).and_then(|l| l.strip_prefix("- ")) else {
out.push_str(line);
out.push('\n');
continue;
};
let (key, explicit) = match item.strip_prefix("? ") {
Some(key) => (key, true),
None => (item, false),
};
let mut folded = unwrap_key(key);
let value_line = lines.get(index).filter(|next| {
let next_indent = next.len() - next.trim_start_matches(' ').len();
explicit && next_indent == indent + 2 && next.trim_start().starts_with(':')
});
if let Some(value_line) = value_line {
folded.push_str(value_line.trim_start());
index += 1;
}
out.push_str(line.get(..indent).unwrap_or_default());
out.push_str("- ");
out.push_str(&folded);
out.push('\n');
if value_line.is_some() {
out.push('\n');
}
}
Cow::Owned(out)
}
fn quoted(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
c if needs_escape(c) => {
let _ = write!(out, "\\u{:04x}", u32::from(c));
}
c => out.push(c),
}
}
out.push('"');
out
}
fn needs_escape(c: char) -> bool {
c.is_control()
|| matches!(
c,
'\u{feff}' | '\u{2028}' | '\u{2029}' | '\u{fffe}' | '\u{ffff}'
)
}
fn yaml_key(key: &str) -> String {
let plain = !key.contains(": ") && !key.contains(" #") && !key.ends_with(':');
if plain {
return key.to_owned();
}
format!("'{}'", key.replace('\'', "''"))
}
fn unwrap_key(item: &str) -> String {
let Some(rest) = item.strip_prefix('\'') else {
return item.to_owned();
};
let mut key = String::new();
let mut chars = rest.char_indices().peekable();
while let Some((at, c)) = chars.next() {
if c != '\'' {
key.push(c);
continue;
}
if chars.next_if(|(_, next)| *next == '\'').is_some() {
key.push('\'');
continue;
}
key.push_str(rest.get(at + 1..).unwrap_or_default());
return key;
}
item.to_owned()
}
fn visible_children<'t>(
tree: &'t SemanticTree,
node: &'t Node,
options: &YamlOptions,
) -> Vec<&'t Node> {
let mut out = Vec::new();
for child in &node.children {
let Some(child) = tree.get(*child) else {
continue;
};
if child.relations.owner.is_some() {
continue;
}
if child.ignored && !options.include_ignored {
out.extend(visible_children(tree, child, options));
continue;
}
out.push(child);
}
for owned in &node.relations.owns {
if let Some(owned) = tree.get(*owned) {
out.push(owned);
}
}
out
}
fn write_node(
tree: &SemanticTree,
node: &Node,
depth: usize,
options: &YamlOptions,
lines: &mut Vec<Line>,
) {
let children = if options.depth.is_some_and(|max| depth >= max) {
Vec::new()
} else {
visible_children(tree, node, options)
};
let key = yaml_key(&key(tree, node, options));
let colon_value = colon_value(tree, node);
let after = match (&colon_value, children.is_empty()) {
(Some(value), true) => format!(": {}", scalar(value)),
(None, true) => String::new(),
(_, false) => ":".to_owned(),
};
if after.is_empty() || key.chars().count() <= IMPLICIT_KEY_LIMIT {
lines.push(Line::entry(depth, key + &after));
} else {
lines.push(Line::entry(depth, format!("? {key}")));
lines.push(Line {
depth,
text: after,
bullet: false,
});
}
if children.is_empty() {
return;
}
if let Some(value) = colon_value {
lines.push(Line::entry(
depth + 1,
format!("/value: {}", scalar(&value)),
));
}
for child in children {
write_node(tree, child, depth + 1, options, lines);
}
}
fn is_text_role(role: Role) -> bool {
matches!(role, Role::Text | Role::Paragraph)
}
fn text_named_by_content(tree: &SemanticTree, node: &Node) -> bool {
is_text_role(node.role)
&& (node.name_source == NameSource::Text
|| node.name.as_deref() == Some(tree.text_content(node.id)))
}
fn colon_value(tree: &SemanticTree, node: &Node) -> Option<String> {
if text_named_by_content(tree, node) {
return node.name.clone();
}
if is_text_role(node.role) {
let text = tree.text_content(node.id);
return (!text.is_empty() && node.name.as_deref() != Some(text)).then(|| text.to_owned());
}
match &node.value {
Some(Value::Text(text)) => Some(text.clone()),
_ => None,
}
}
fn scalar(text: &str) -> String {
let starts_plain = text
.chars()
.next()
.is_some_and(|c| !"-?:,[]{}#&*!|>'\"%@`/".contains(c));
let plain = starts_plain
&& text.trim() == text
&& !text.contains(": ")
&& !text.contains(" #")
&& !text.ends_with(':')
&& !text.chars().any(|c| c == '\t' || needs_escape(c));
if plain {
return text.to_owned();
}
quoted(text)
}
fn number(value: f64) -> String {
format!("{value}")
}
fn key(tree: &SemanticTree, node: &Node, options: &YamlOptions) -> String {
let mut out = node.role.selector_name().to_owned();
if let Some(name) = &node.name
&& !text_named_by_content(tree, node)
{
out.push(' ');
out.push_str("ed(name));
}
let mut attr = |text: String| {
out.push_str(" [");
out.push_str(&text);
out.push(']');
};
for (state, name) in STATE_NAMES {
let Some(value) = node.states.get(*state) else {
continue;
};
match value {
StateValue::Bool(true) => attr((*name).to_owned()),
StateValue::Bool(false) if is_flag(*state) => {}
other => attr(format!("{name}={other}")),
}
}
if let Some(level) = node.set.level {
attr(format!("level={level}"));
}
if let Some(position) = node.set.position {
attr(format!("position={position}"));
}
if let Some(size) = node.set.size {
attr(format!("set-size={size}"));
}
for (label, field) in [
("description", &node.description),
("placeholder", &node.placeholder),
("tooltip", &node.tooltip),
] {
if let Some(text) = field {
attr(format!("{label}={}", quoted(text)));
}
}
if let Some(Value::Number {
now,
min,
max,
step,
}) = &node.value
{
attr(format!("value={}", number(*now)));
for (label, bound) in [("min", min), ("max", max), ("step", step)] {
if let Some(bound) = bound {
attr(format!("{label}={}", number(*bound)));
}
}
}
for (prop, value) in &node.props {
let shown = if options.mask_props.iter().any(|m| m == prop) {
"***"
} else {
value.as_str()
};
attr(format!("prop:{prop}={}", quoted(shown)));
}
if options.include_ids {
if let Some(id) = &node.test_id {
attr(format!("test-id={}", quoted(id)));
}
match &node.widget_id {
Some(WidgetId::Custom(id)) => attr(format!("widget-id={}", quoted(id))),
Some(WidgetId::Unique(n)) => attr(format!("widget-id=#{n}")),
None => {}
}
}
if options.refs && node.role.is_interactive() {
attr(format!("ref={}", node.id));
}
if options.include_bounds {
let b = node.bounds;
let _ = write!(
out,
" @ {},{} {}x{}",
b.x.round(),
b.y.round(),
b.width.round(),
b.height.round()
);
}
out
}
pub fn read(yaml: &str) -> Result<SemanticTree, Error> {
let yaml = normalise(yaml);
let mut entries: Vec<(usize, usize, Draft, Option<String>)> = Vec::new();
for (index, raw_line) in yaml.lines().enumerate() {
let line_number = index + 1;
if raw_line.trim().is_empty() {
continue;
}
let indent = raw_line.len() - raw_line.trim_start_matches(' ').len();
if indent % 2 != 0 {
return Err(yaml_error(
line_number,
indent + 1,
"indentation must be a multiple of two spaces",
));
}
let Some(item) = raw_line.get(indent..).and_then(|l| l.strip_prefix("- ")) else {
return Err(yaml_error(
line_number,
indent + 1,
"expected `- ` to start an entry",
));
};
if item == "..." {
continue;
}
let column = indent + 3;
if let Some(value) = item.strip_prefix("/value: ") {
let value = read_scalar(value)
.map_err(|(at, m)| yaml_error(line_number, column + 8 + at, &m))?;
entries.push((
indent / 2,
line_number,
Draft::new(Node::blank(Role::Unknown, yaml_kind(), WindowId(0))),
Some(value),
));
continue;
}
let draft = read_entry(item).map_err(|(at, m)| yaml_error(line_number, column + at, &m))?;
entries.push((indent / 2, line_number, draft, None));
}
let (_, top) = nest(&mut entries.into_iter().peekable(), 0)?;
let windows = if !top.is_empty() && top.iter().all(|d| d.node.role == Role::Window) {
top
} else {
let mut window = Draft::new(Node::blank(Role::Window, yaml_kind(), WindowId(0)));
window.children = top;
vec![window]
};
let windows = windows
.into_iter()
.enumerate()
.map(|(i, mut window)| {
let id = WindowId(u64::try_from(i).unwrap_or(u64::MAX));
set_window(&mut window, id);
window
})
.collect();
Ok(build::finish(windows, Mode::Keep))
}
fn set_window(draft: &mut Draft, window: WindowId) {
draft.node.window = window;
for child in &mut draft.children {
set_window(child, window);
}
}
fn yaml_kind() -> Kind {
Kind::Annotated(Cow::Borrowed("app"))
}
fn yaml_error(line: usize, column: usize, message: &str) -> Error {
Error::Yaml {
line,
column,
message: message.to_owned(),
}
}
type Entry = (usize, usize, Draft, Option<String>);
fn nest(
entries: &mut std::iter::Peekable<impl Iterator<Item = Entry>>,
depth: usize,
) -> Result<(Option<String>, Vec<Draft>), Error> {
let mut leading = None;
let mut out: Vec<Draft> = Vec::new();
while let Some((entry_depth, line, _, _)) = entries.peek() {
let (entry_depth, line) = (*entry_depth, *line);
if entry_depth < depth {
break;
}
if entry_depth > depth {
let Some(parent) = out.last_mut() else {
return Err(yaml_error(
line,
entry_depth * 2 + 1,
"entry is indented under nothing",
));
};
let (value, children) = nest(entries, depth + 1)?;
if let Some(value) = value {
parent.node.value = Some(Value::Text(value));
}
parent.children.extend(children);
continue;
}
let Some((_, _, draft, value)) = entries.next() else {
break;
};
match value {
Some(value) if out.is_empty() && leading.is_none() && depth > 0 => {
leading = Some(value);
}
Some(_) => {
return Err(yaml_error(
line,
depth * 2 + 1,
"`/value` must be the first child of a node",
));
}
None => out.push(draft),
}
}
Ok((leading, out))
}
fn read_scalar(text: &str) -> Result<String, (usize, String)> {
if !text.starts_with('"') {
return Ok(text.to_owned());
}
let mut cursor = Cursor::new(text);
let value = cursor.quoted()?;
if !cursor.rest().is_empty() {
return Err((
cursor.offset,
"unexpected text after the closing quote".to_owned(),
));
}
Ok(value)
}
fn read_number(cursor: &mut Cursor<'_>) -> Result<f64, (usize, String)> {
let at = cursor.offset;
let text = cursor.take_while(|c| {
c.is_ascii_digit() || matches!(c, '-' | '.' | 'e' | 'E' | '+' | 'i' | 'n' | 'f' | 'N' | 'a')
});
text.parse()
.map_err(|_| (at, format!("`{text}` is not a number")))
}
fn read_unsigned<T: std::str::FromStr>(cursor: &mut Cursor<'_>) -> Result<T, (usize, String)> {
let at = cursor.offset;
let text = cursor.take_while(|c| c.is_ascii_digit());
text.parse()
.map_err(|_| (at, "expected a whole number".to_owned()))
}
fn read_entry(item: &str) -> Result<Draft, (usize, String)> {
let mut cursor = Cursor::new(item);
let at = cursor.offset;
let word = cursor.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'));
let role = Role::from_selector_name(word).ok_or((at, format!("unknown role `{word}`")))?;
let mut node = Node::blank(role, yaml_kind(), WindowId(0));
if cursor.rest().starts_with(" \"") {
cursor.offset += 1;
node.name = Some(cursor.quoted()?);
node.name_source = NameSource::Annotation;
}
while cursor.rest().starts_with(" [") {
cursor.offset += 2;
read_attribute(&mut cursor, &mut node)?;
if !cursor.eat("]") {
return Err((cursor.offset, "expected `]`".to_owned()));
}
}
if cursor.eat(" @ ") {
let x = read_number(&mut cursor)?;
let y = if cursor.eat(",") {
read_number(&mut cursor)?
} else {
return Err((cursor.offset, "expected `,`".to_owned()));
};
if !cursor.eat(" ") {
return Err((cursor.offset, "expected a space before the size".to_owned()));
}
let width = read_number(&mut cursor)?;
if !cursor.eat("x") {
return Err((cursor.offset, "expected `x`".to_owned()));
}
let height = read_number(&mut cursor)?;
node.bounds = Rect::new(
Point::new(x as f32, y as f32),
Size::new(width as f32, height as f32),
);
if node.bounds.area() > 0.0 && !node.states.offscreen {
node.visible_bounds = Some(node.bounds);
}
}
let mut value = None;
if cursor.eat(": ") {
value = Some(read_scalar(cursor.rest()).map_err(|(o, m)| (cursor.offset + o, m))?);
cursor.offset = cursor.input.len();
} else {
cursor.eat(":");
}
if !cursor.rest().is_empty() {
return Err((cursor.offset, format!("unexpected `{}`", cursor.rest())));
}
let mut draft = Draft::new(node);
match value {
Some(text) if is_text_role(role) && draft.node.name.is_none() => {
draft.node.name = Some(text.clone());
draft.node.name_source = NameSource::Text;
draft.own_text = Some(text);
}
Some(text) if is_text_role(role) => draft.own_text = Some(text),
Some(text) => draft.node.value = Some(Value::Text(text)),
None => {}
}
if is_text_role(role) && draft.own_text.is_none() {
draft.own_text = draft.node.name.clone();
}
if named_from_content(role) {
draft.own_text = draft.node.name.clone();
}
Ok(draft)
}
fn read_attribute(cursor: &mut Cursor<'_>, node: &mut Node) -> Result<(), (usize, String)> {
let at = cursor.offset;
let name =
cursor.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'));
let has_value = cursor.eat("=");
if let Some(prop) = name.strip_prefix("prop:") {
if !has_value {
return Err((cursor.offset, "expected `=` after a prop".to_owned()));
}
node.props.insert(prop.to_owned(), cursor.quoted()?);
return Ok(());
}
if let Some((state, _)) = STATE_NAMES.iter().find(|(_, n)| *n == name) {
let value = if has_value {
let at = cursor.offset;
let word = cursor.take_while(|c| c.is_ascii_alphabetic());
word.parse::<StateValue>()
.map_err(|e| (at, e.to_string()))?
} else {
StateValue::Bool(true)
};
node.states.set(*state, value, StateSource::Annotation);
return Ok(());
}
if !has_value {
return Err((at, format!("unknown attribute `{name}`")));
}
match name {
"level" => node.set.level = Some(read_unsigned(cursor)?),
"position" => node.set.position = Some(read_unsigned(cursor)?),
"set-size" => node.set.size = Some(read_unsigned(cursor)?),
"description" => node.description = Some(cursor.quoted()?),
"placeholder" => node.placeholder = Some(cursor.quoted()?),
"tooltip" => node.tooltip = Some(cursor.quoted()?),
"test-id" => node.test_id = Some(cursor.quoted()?),
"widget-id" if cursor.eat("#") => {
node.widget_id = Some(WidgetId::Unique(read_unsigned(cursor)?))
}
"widget-id" => node.widget_id = Some(WidgetId::Custom(cursor.quoted()?)),
"ref" => {
cursor.take_while(|c| c.is_ascii_alphanumeric());
}
"value" | "min" | "max" | "step" => {
let number = read_number(cursor)?;
let (mut now, mut min, mut max, mut step) = match node.value {
Some(Value::Number {
now,
min,
max,
step,
}) => (now, min, max, step),
_ => (0.0, None, None, None),
};
match name {
"value" => now = number,
"min" => min = Some(number),
"max" => max = Some(number),
_ => step = Some(number),
}
node.value = Some(Value::Number {
now,
min,
max,
step,
});
}
other => return Err((at, format!("unknown attribute `{other}`"))),
}
Ok(())
}