1use std::borrow::Cow;
6use std::collections::BTreeMap;
7
8use icedwright_types::{
9 CursorSeen, Point, Rect, Role, ScaleFactor, Size, StateName, StateValue, Vector,
10};
11use serde::{Deserialize, Serialize};
12
13#[derive(
15 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
16)]
17#[serde(transparent)]
18pub struct WindowId(pub u64);
19
20#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum WidgetId {
24 Custom(String),
26 Unique(usize),
28}
29
30impl WidgetId {
31 #[must_use]
34 pub fn from_debug(text: &str) -> Option<WidgetId> {
35 let inner = text.strip_prefix("Id(")?.strip_suffix(')')?;
36 if let Some(number) = inner
37 .strip_prefix("Unique(")
38 .and_then(|s| s.strip_suffix(')'))
39 {
40 return number.parse().ok().map(WidgetId::Unique);
41 }
42 let quoted = inner.strip_prefix("Custom(")?.strip_suffix(')')?;
43 unescape_debug_str(quoted).map(WidgetId::Custom)
44 }
45}
46
47fn unescape_debug_str(quoted: &str) -> Option<String> {
49 let body = quoted.strip_prefix('"')?.strip_suffix('"')?;
50 let mut out = String::with_capacity(body.len());
51 let mut chars = body.chars();
52 while let Some(c) = chars.next() {
53 if c != '\\' {
54 out.push(c);
55 continue;
56 }
57 match chars.next()? {
58 'n' => out.push('\n'),
59 't' => out.push('\t'),
60 'r' => out.push('\r'),
61 '0' => out.push('\0'),
62 '\\' => out.push('\\'),
63 '"' => out.push('"'),
64 '\'' => out.push('\''),
65 'u' => {
66 let rest: String = chars.by_ref().take_while(|c| *c != '}').collect();
67 let hex = rest.strip_prefix('{')?;
68 out.push(char::from_u32(u32::from_str_radix(hex, 16).ok()?)?);
69 }
70 _ => return None,
71 }
72 }
73 Some(out)
74}
75
76#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
78pub struct RawTree {
79 pub windows: Vec<RawWindow>,
81}
82
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
85pub struct RawWindow {
86 #[serde(default)]
88 pub id: Option<WindowId>,
89 #[serde(default)]
91 pub info: Option<RawWindowInfo>,
92 pub root: RawNode,
95}
96
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub struct RawWindowInfo {
100 pub id: WindowId,
102 pub title: String,
104 pub size: Size,
106 pub scale_factor: ScaleFactor,
108}
109
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112pub struct RawNode {
113 #[serde(flatten)]
115 pub call: RawCall,
116 #[serde(default)]
118 pub widget_id: Option<WidgetId>,
119 pub bounds: Rect,
121 #[serde(default)]
123 pub children: Vec<RawNode>,
124}
125
126impl RawNode {
127 #[must_use]
129 pub fn new(call: RawCall, bounds: Rect) -> Self {
130 Self {
131 call,
132 widget_id: None,
133 bounds,
134 children: Vec::new(),
135 }
136 }
137
138 #[must_use]
140 pub fn with_id(mut self, id: WidgetId) -> Self {
141 self.widget_id = Some(id);
142 self
143 }
144
145 #[must_use]
147 pub fn with_children(mut self, children: impl IntoIterator<Item = RawNode>) -> Self {
148 self.children = children.into_iter().collect();
149 self
150 }
151}
152
153#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
155#[serde(tag = "call", rename_all = "snake_case")]
156pub enum RawCall {
157 Container,
159 Scrollable {
161 content_bounds: Rect,
163 translation: Vector,
165 ordinal: u32,
167 },
168 Focusable {
170 focused: bool,
172 ordinal: u32,
174 },
175 TextInput {
178 text: String,
180 },
181 Text {
183 content: String,
185 },
186 Annotation(Box<RawAnnotation>),
188 Group,
190 Overlay {
192 depth: u16,
194 },
195}
196
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
199#[serde(rename_all = "snake_case")]
200pub enum AnnotationSource {
201 #[default]
203 App,
204 Component,
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
210#[serde(rename_all = "snake_case")]
211pub enum RawKey {
212 Name(String),
214 Unique(u64),
216}
217
218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
220#[serde(rename_all = "snake_case")]
221pub enum RawValue {
222 Text(String),
224 Number {
226 now: f64,
228 #[serde(default)]
230 min: Option<f64>,
231 #[serde(default)]
233 max: Option<f64>,
234 #[serde(default)]
236 step: Option<f64>,
237 },
238}
239
240#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
242#[serde(default)]
243pub struct RawAnnotation {
244 pub source: AnnotationSource,
246 pub role: Option<Role>,
248 pub name: Option<String>,
250 pub description: Option<String>,
252 pub tooltip: Option<String>,
254 pub placeholder: Option<String>,
256 pub value: Option<RawValue>,
258 pub test_id: Option<String>,
260 pub rust_path: Option<String>,
263 pub kind: Option<Cow<'static, str>>,
265 pub props: BTreeMap<String, String>,
267 pub text_size: Option<f32>,
269 pub states: Vec<(StateName, StateValue)>,
271 pub level: Option<u16>,
273 pub position: Option<(u32, u32)>,
275 pub key: Option<RawKey>,
277 pub labelled_by: Vec<RawKey>,
279 pub label_for: Vec<RawKey>,
281 pub described_by: Vec<RawKey>,
283 pub controls: Vec<RawKey>,
285 pub owns: Vec<RawKey>,
287 pub carets: Vec<(usize, Point)>,
289 pub cursor_seen: Option<CursorSeen>,
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn widget_id_parses_both_debug_forms() {
299 assert_eq!(
300 WidgetId::from_debug(r#"Id(Custom("todo-list"))"#),
301 Some(WidgetId::Custom("todo-list".to_owned()))
302 );
303 assert_eq!(
304 WidgetId::from_debug("Id(Unique(42))"),
305 Some(WidgetId::Unique(42))
306 );
307 assert_eq!(
308 WidgetId::from_debug(r#"Id(Custom("a \"b\"\n\u{1f600}"))"#),
309 Some(WidgetId::Custom("a \"b\"\n\u{1f600}".to_owned()))
310 );
311 assert_eq!(WidgetId::from_debug("Id(Other(1))"), None);
312 assert_eq!(WidgetId::from_debug("Custom(\"x\")"), None);
313 assert_eq!(WidgetId::from_debug(r#"Id(Custom("x\q"))"#), None);
314 }
315
316 #[test]
317 fn widget_id_parses_what_debug_prints() {
318 for name in [
319 "plain",
320 "quote\"d",
321 "tab\there",
322 "back\\slash",
323 "é",
324 "\u{7f}",
325 ] {
326 let printed = format!("Id(Custom({name:?}))");
327 assert_eq!(
328 WidgetId::from_debug(&printed),
329 Some(WidgetId::Custom(name.to_owned()))
330 );
331 }
332 }
333}