icedwright-protocol 0.1.0

Wire types for icedwright: the raw semantic tree a live app records and the typed remote protocol
Documentation
//! The raw tree a live app records: every operation callback as a node, in call order, with
//! annotations carried as owned data. `icedwright_semantics::infer` turns it into a semantic
//! tree.

use std::borrow::Cow;
use std::collections::BTreeMap;

use icedwright_types::{
    CursorSeen, Point, Rect, Role, ScaleFactor, Size, StateName, StateValue, Vector,
};
use serde::{Deserialize, Serialize};

/// A window, as the recorder's caller names it. Stable for the window's life.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct WindowId(pub u64);

/// An `iced_core::widget::Id`, read from its `Debug` form.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WidgetId {
    /// `Id::new("name")`.
    Custom(String),
    /// `Id::unique()`, numbered by iced's counter.
    Unique(usize),
}

impl WidgetId {
    /// Parses the `Debug` form of an `iced_core::widget::Id`: `Id(Custom("name"))` or
    /// `Id(Unique(3))`. iced 0.14 gives no other way to read an id.
    #[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)
    }
}

/// Reverses `<str as Debug>::fmt` for the escapes it produces.
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)
}

/// Every window the recorder saw.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct RawTree {
    /// One entry per window, in the order the recorder met them.
    pub windows: Vec<RawWindow>,
}

/// One window's recording.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RawWindow {
    /// The window, when the caller knew it.
    #[serde(default)]
    pub id: Option<WindowId>,
    /// What the probe knows about the window.
    #[serde(default)]
    pub info: Option<RawWindowInfo>,
    /// Normally a [`RawCall::Group`] holding the window's top-level reports, with each overlay
    /// pass as a [`RawCall::Overlay`] child after the base content.
    pub root: RawNode,
}

/// What the probe knows about a window.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RawWindowInfo {
    /// The window.
    pub id: WindowId,
    /// Its title.
    pub title: String,
    /// Its size in logical pixels.
    pub size: Size,
    /// Its scale factor.
    pub scale_factor: ScaleFactor,
}

/// One operation callback and everything reported inside its `traverse`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RawNode {
    /// What was reported. Its tag and fields sit beside the node's own on the wire.
    #[serde(flatten)]
    pub call: RawCall,
    /// The widget id passed with the call.
    #[serde(default)]
    pub widget_id: Option<WidgetId>,
    /// The bounds passed with the call, in logical window coordinates before scrolling.
    pub bounds: Rect,
    /// Calls made inside this call's `traverse`.
    #[serde(default)]
    pub children: Vec<RawNode>,
}

impl RawNode {
    /// A node with no widget id and no children.
    #[must_use]
    pub fn new(call: RawCall, bounds: Rect) -> Self {
        Self {
            call,
            widget_id: None,
            bounds,
            children: Vec::new(),
        }
    }

    /// The node with a widget id.
    #[must_use]
    pub fn with_id(mut self, id: WidgetId) -> Self {
        self.widget_id = Some(id);
        self
    }

    /// The node with these children.
    #[must_use]
    pub fn with_children(mut self, children: impl IntoIterator<Item = RawNode>) -> Self {
        self.children = children.into_iter().collect();
        self
    }
}

/// The operation callback a raw node records.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "call", rename_all = "snake_case")]
pub enum RawCall {
    /// `Operation::container`.
    Container,
    /// `Operation::scrollable`.
    Scrollable {
        /// The content's bounds.
        content_bounds: Rect,
        /// The scroll translation.
        translation: Vector,
        /// The count of scrollable callbacks before this one, across the whole interface.
        ordinal: u32,
    },
    /// `Operation::focusable`.
    Focusable {
        /// Whether it is focused.
        focused: bool,
        /// The count of focusable callbacks before this one, across the whole interface.
        ordinal: u32,
    },
    /// `Operation::text_input`, with the text it shows: the value, or the placeholder when
    /// the value is empty.
    TextInput {
        /// The visible text.
        text: String,
    },
    /// `Operation::text`.
    Text {
        /// The text.
        content: String,
    },
    /// An annotation from `icedwright-probe`, reported through `Operation::custom`.
    Annotation(Box<RawAnnotation>),
    /// A `traverse` with nothing reported first at its level.
    Group,
    /// The start of an overlay pass. Its children are that overlay layer's content.
    Overlay {
        /// Nesting depth from `overlay::Nested`, starting at 1.
        depth: u16,
    },
}

/// Which kind of code wrote an annotation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationSource {
    /// The application's own `semantic(...)`.
    #[default]
    App,
    /// A component library such as iced-cube.
    Component,
}

/// A key an annotation uses to name another node in a relation.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RawKey {
    /// A key chosen by the app.
    Name(String),
    /// A key from an atomic counter.
    Unique(u64),
}

/// A value an annotation reports.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RawValue {
    /// A text value.
    Text(String),
    /// A number within an optional range.
    Number {
        /// The current value.
        now: f64,
        /// The lowest value.
        #[serde(default)]
        min: Option<f64>,
        /// The highest value.
        #[serde(default)]
        max: Option<f64>,
        /// The step between values.
        #[serde(default)]
        step: Option<f64>,
    },
}

/// Every annotation field as owned data. Unset fields are `None` or empty.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct RawAnnotation {
    /// Which code wrote it.
    pub source: AnnotationSource,
    /// The role, when one was set.
    pub role: Option<Role>,
    /// The accessible name.
    pub name: Option<String>,
    /// The description.
    pub description: Option<String>,
    /// The tooltip text.
    pub tooltip: Option<String>,
    /// The placeholder of an editable role.
    pub placeholder: Option<String>,
    /// The value.
    pub value: Option<RawValue>,
    /// The test id string.
    pub test_id: Option<String>,
    /// The Rust path of a typed test id from its crate root, such as `todo::Ids::NewItem`.
    /// `None` for a string id.
    pub rust_path: Option<String>,
    /// The kind, such as `"iced_cube::tree"`. `None` means `"app"`.
    pub kind: Option<Cow<'static, str>>,
    /// Free-form properties.
    pub props: BTreeMap<String, String>,
    /// The text size in logical pixels.
    pub text_size: Option<f32>,
    /// Reported states.
    pub states: Vec<(StateName, StateValue)>,
    /// The heading or tree level. ARIA levels start at 1.
    pub level: Option<u16>,
    /// Position in the set and set size.
    pub position: Option<(u32, u32)>,
    /// The key others use to name this node.
    pub key: Option<RawKey>,
    /// Nodes whose names label this one.
    pub labelled_by: Vec<RawKey>,
    /// Nodes this one labels.
    pub label_for: Vec<RawKey>,
    /// Nodes whose text describes this one.
    pub described_by: Vec<RawKey>,
    /// Nodes this one controls.
    pub controls: Vec<RawKey>,
    /// Nodes that are this one's logical children although they live elsewhere.
    pub owns: Vec<RawKey>,
    /// Byte offset to caret top, sorted by offset.
    pub carets: Vec<(usize, Point)>,
    /// The cursor kind handed to the widget for its last mouse event this frame.
    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()))
            );
        }
    }
}