Skip to main content

icedwright_protocol/
raw.rs

1//! The raw tree a live app records: every operation callback as a node, in call order, with
2//! annotations carried as owned data. `icedwright_semantics::infer` turns it into a semantic
3//! tree.
4
5use 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/// A window, as the recorder's caller names it. Stable for the window's life.
14#[derive(
15    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
16)]
17#[serde(transparent)]
18pub struct WindowId(pub u64);
19
20/// An `iced_core::widget::Id`, read from its `Debug` form.
21#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum WidgetId {
24    /// `Id::new("name")`.
25    Custom(String),
26    /// `Id::unique()`, numbered by iced's counter.
27    Unique(usize),
28}
29
30impl WidgetId {
31    /// Parses the `Debug` form of an `iced_core::widget::Id`: `Id(Custom("name"))` or
32    /// `Id(Unique(3))`. iced 0.14 gives no other way to read an id.
33    #[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
47/// Reverses `<str as Debug>::fmt` for the escapes it produces.
48fn 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/// Every window the recorder saw.
77#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
78pub struct RawTree {
79    /// One entry per window, in the order the recorder met them.
80    pub windows: Vec<RawWindow>,
81}
82
83/// One window's recording.
84#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
85pub struct RawWindow {
86    /// The window, when the caller knew it.
87    #[serde(default)]
88    pub id: Option<WindowId>,
89    /// What the probe knows about the window.
90    #[serde(default)]
91    pub info: Option<RawWindowInfo>,
92    /// Normally a [`RawCall::Group`] holding the window's top-level reports, with each overlay
93    /// pass as a [`RawCall::Overlay`] child after the base content.
94    pub root: RawNode,
95}
96
97/// What the probe knows about a window.
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub struct RawWindowInfo {
100    /// The window.
101    pub id: WindowId,
102    /// Its title.
103    pub title: String,
104    /// Its size in logical pixels.
105    pub size: Size,
106    /// Its scale factor.
107    pub scale_factor: ScaleFactor,
108}
109
110/// One operation callback and everything reported inside its `traverse`.
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112pub struct RawNode {
113    /// What was reported. Its tag and fields sit beside the node's own on the wire.
114    #[serde(flatten)]
115    pub call: RawCall,
116    /// The widget id passed with the call.
117    #[serde(default)]
118    pub widget_id: Option<WidgetId>,
119    /// The bounds passed with the call, in logical window coordinates before scrolling.
120    pub bounds: Rect,
121    /// Calls made inside this call's `traverse`.
122    #[serde(default)]
123    pub children: Vec<RawNode>,
124}
125
126impl RawNode {
127    /// A node with no widget id and no children.
128    #[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    /// The node with a widget id.
139    #[must_use]
140    pub fn with_id(mut self, id: WidgetId) -> Self {
141        self.widget_id = Some(id);
142        self
143    }
144
145    /// The node with these children.
146    #[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/// The operation callback a raw node records.
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
155#[serde(tag = "call", rename_all = "snake_case")]
156pub enum RawCall {
157    /// `Operation::container`.
158    Container,
159    /// `Operation::scrollable`.
160    Scrollable {
161        /// The content's bounds.
162        content_bounds: Rect,
163        /// The scroll translation.
164        translation: Vector,
165        /// The count of scrollable callbacks before this one, across the whole interface.
166        ordinal: u32,
167    },
168    /// `Operation::focusable`.
169    Focusable {
170        /// Whether it is focused.
171        focused: bool,
172        /// The count of focusable callbacks before this one, across the whole interface.
173        ordinal: u32,
174    },
175    /// `Operation::text_input`, with the text it shows: the value, or the placeholder when
176    /// the value is empty.
177    TextInput {
178        /// The visible text.
179        text: String,
180    },
181    /// `Operation::text`.
182    Text {
183        /// The text.
184        content: String,
185    },
186    /// An annotation from `icedwright-probe`, reported through `Operation::custom`.
187    Annotation(Box<RawAnnotation>),
188    /// A `traverse` with nothing reported first at its level.
189    Group,
190    /// The start of an overlay pass. Its children are that overlay layer's content.
191    Overlay {
192        /// Nesting depth from `overlay::Nested`, starting at 1.
193        depth: u16,
194    },
195}
196
197/// Which kind of code wrote an annotation.
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
199#[serde(rename_all = "snake_case")]
200pub enum AnnotationSource {
201    /// The application's own `semantic(...)`.
202    #[default]
203    App,
204    /// A component library such as iced-cube.
205    Component,
206}
207
208/// A key an annotation uses to name another node in a relation.
209#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
210#[serde(rename_all = "snake_case")]
211pub enum RawKey {
212    /// A key chosen by the app.
213    Name(String),
214    /// A key from an atomic counter.
215    Unique(u64),
216}
217
218/// A value an annotation reports.
219#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
220#[serde(rename_all = "snake_case")]
221pub enum RawValue {
222    /// A text value.
223    Text(String),
224    /// A number within an optional range.
225    Number {
226        /// The current value.
227        now: f64,
228        /// The lowest value.
229        #[serde(default)]
230        min: Option<f64>,
231        /// The highest value.
232        #[serde(default)]
233        max: Option<f64>,
234        /// The step between values.
235        #[serde(default)]
236        step: Option<f64>,
237    },
238}
239
240/// Every annotation field as owned data. Unset fields are `None` or empty.
241#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
242#[serde(default)]
243pub struct RawAnnotation {
244    /// Which code wrote it.
245    pub source: AnnotationSource,
246    /// The role, when one was set.
247    pub role: Option<Role>,
248    /// The accessible name.
249    pub name: Option<String>,
250    /// The description.
251    pub description: Option<String>,
252    /// The tooltip text.
253    pub tooltip: Option<String>,
254    /// The placeholder of an editable role.
255    pub placeholder: Option<String>,
256    /// The value.
257    pub value: Option<RawValue>,
258    /// The test id string.
259    pub test_id: Option<String>,
260    /// The Rust path of a typed test id from its crate root, such as `todo::Ids::NewItem`.
261    /// `None` for a string id.
262    pub rust_path: Option<String>,
263    /// The kind, such as `"iced_cube::tree"`. `None` means `"app"`.
264    pub kind: Option<Cow<'static, str>>,
265    /// Free-form properties.
266    pub props: BTreeMap<String, String>,
267    /// The text size in logical pixels.
268    pub text_size: Option<f32>,
269    /// Reported states.
270    pub states: Vec<(StateName, StateValue)>,
271    /// The heading or tree level. ARIA levels start at 1.
272    pub level: Option<u16>,
273    /// Position in the set and set size.
274    pub position: Option<(u32, u32)>,
275    /// The key others use to name this node.
276    pub key: Option<RawKey>,
277    /// Nodes whose names label this one.
278    pub labelled_by: Vec<RawKey>,
279    /// Nodes this one labels.
280    pub label_for: Vec<RawKey>,
281    /// Nodes whose text describes this one.
282    pub described_by: Vec<RawKey>,
283    /// Nodes this one controls.
284    pub controls: Vec<RawKey>,
285    /// Nodes that are this one's logical children although they live elsewhere.
286    pub owns: Vec<RawKey>,
287    /// Byte offset to caret top, sorted by offset.
288    pub carets: Vec<(usize, Point)>,
289    /// The cursor kind handed to the widget for its last mouse event this frame.
290    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}