use std::borrow::Cow;
use std::collections::BTreeMap;
use icedwright_types::{
CursorSeen, Point, Rect, Role, ScaleFactor, Size, StateName, StateValue, Vector,
};
use serde::{Deserialize, Serialize};
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct WindowId(pub u64);
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WidgetId {
Custom(String),
Unique(usize),
}
impl WidgetId {
#[must_use]
pub fn from_debug(text: &str) -> Option<WidgetId> {
let inner = text.strip_prefix("Id(")?.strip_suffix(')')?;
if let Some(number) = inner
.strip_prefix("Unique(")
.and_then(|s| s.strip_suffix(')'))
{
return number.parse().ok().map(WidgetId::Unique);
}
let quoted = inner.strip_prefix("Custom(")?.strip_suffix(')')?;
unescape_debug_str(quoted).map(WidgetId::Custom)
}
}
fn unescape_debug_str(quoted: &str) -> Option<String> {
let body = quoted.strip_prefix('"')?.strip_suffix('"')?;
let mut out = String::with_capacity(body.len());
let mut chars = body.chars();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.next()? {
'n' => out.push('\n'),
't' => out.push('\t'),
'r' => out.push('\r'),
'0' => out.push('\0'),
'\\' => out.push('\\'),
'"' => out.push('"'),
'\'' => out.push('\''),
'u' => {
let rest: String = chars.by_ref().take_while(|c| *c != '}').collect();
let hex = rest.strip_prefix('{')?;
out.push(char::from_u32(u32::from_str_radix(hex, 16).ok()?)?);
}
_ => return None,
}
}
Some(out)
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct RawTree {
pub windows: Vec<RawWindow>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RawWindow {
#[serde(default)]
pub id: Option<WindowId>,
#[serde(default)]
pub info: Option<RawWindowInfo>,
pub root: RawNode,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RawWindowInfo {
pub id: WindowId,
pub title: String,
pub size: Size,
pub scale_factor: ScaleFactor,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RawNode {
#[serde(flatten)]
pub call: RawCall,
#[serde(default)]
pub widget_id: Option<WidgetId>,
pub bounds: Rect,
#[serde(default)]
pub children: Vec<RawNode>,
}
impl RawNode {
#[must_use]
pub fn new(call: RawCall, bounds: Rect) -> Self {
Self {
call,
widget_id: None,
bounds,
children: Vec::new(),
}
}
#[must_use]
pub fn with_id(mut self, id: WidgetId) -> Self {
self.widget_id = Some(id);
self
}
#[must_use]
pub fn with_children(mut self, children: impl IntoIterator<Item = RawNode>) -> Self {
self.children = children.into_iter().collect();
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "call", rename_all = "snake_case")]
pub enum RawCall {
Container,
Scrollable {
content_bounds: Rect,
translation: Vector,
ordinal: u32,
},
Focusable {
focused: bool,
ordinal: u32,
},
TextInput {
text: String,
},
Text {
content: String,
},
Annotation(Box<RawAnnotation>),
Group,
Overlay {
depth: u16,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationSource {
#[default]
App,
Component,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RawKey {
Name(String),
Unique(u64),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RawValue {
Text(String),
Number {
now: f64,
#[serde(default)]
min: Option<f64>,
#[serde(default)]
max: Option<f64>,
#[serde(default)]
step: Option<f64>,
},
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct RawAnnotation {
pub source: AnnotationSource,
pub role: Option<Role>,
pub name: Option<String>,
pub description: Option<String>,
pub tooltip: Option<String>,
pub placeholder: Option<String>,
pub value: Option<RawValue>,
pub test_id: Option<String>,
pub rust_path: Option<String>,
pub kind: Option<Cow<'static, str>>,
pub props: BTreeMap<String, String>,
pub text_size: Option<f32>,
pub states: Vec<(StateName, StateValue)>,
pub level: Option<u16>,
pub position: Option<(u32, u32)>,
pub key: Option<RawKey>,
pub labelled_by: Vec<RawKey>,
pub label_for: Vec<RawKey>,
pub described_by: Vec<RawKey>,
pub controls: Vec<RawKey>,
pub owns: Vec<RawKey>,
pub carets: Vec<(usize, Point)>,
pub cursor_seen: Option<CursorSeen>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn widget_id_parses_both_debug_forms() {
assert_eq!(
WidgetId::from_debug(r#"Id(Custom("todo-list"))"#),
Some(WidgetId::Custom("todo-list".to_owned()))
);
assert_eq!(
WidgetId::from_debug("Id(Unique(42))"),
Some(WidgetId::Unique(42))
);
assert_eq!(
WidgetId::from_debug(r#"Id(Custom("a \"b\"\n\u{1f600}"))"#),
Some(WidgetId::Custom("a \"b\"\n\u{1f600}".to_owned()))
);
assert_eq!(WidgetId::from_debug("Id(Other(1))"), None);
assert_eq!(WidgetId::from_debug("Custom(\"x\")"), None);
assert_eq!(WidgetId::from_debug(r#"Id(Custom("x\q"))"#), None);
}
#[test]
fn widget_id_parses_what_debug_prints() {
for name in [
"plain",
"quote\"d",
"tab\there",
"back\\slash",
"é",
"\u{7f}",
] {
let printed = format!("Id(Custom({name:?}))");
assert_eq!(
WidgetId::from_debug(&printed),
Some(WidgetId::Custom(name.to_owned()))
);
}
}
}