icedwright-probe 0.1.4

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
Documentation
//! `RawRecorder`, the operation that records every widget report into a raw tree.

use std::any::Any;
use std::collections::BTreeMap;

use iced_core::widget::operation::{Focusable, Outcome, Scrollable, TextInput};
use iced_core::widget::{Id, Operation};
use iced_core::{Rectangle, Vector, window};
use icedwright_protocol::{
    RawAnnotation, RawCall, RawKey, RawNode, RawTree, RawValue, RawWindow, RawWindowInfo, WidgetId,
    WindowId,
};
use icedwright_types::Rect;
use icedwright_types::role::AnyRole;

use crate::annotation::fields::{Fields, STATES, ValueField};
use crate::annotation::{Annotation, Ask, Key};

/// Reported through `Operation::custom` by a root wrapper before each window's content, when
/// one operation visits several windows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WindowMarker(pub window::Id);

/// Reported through `Operation::custom` by an overlay wrapper before it traverses the
/// overlay's content. Everything reported inside that traverse is the overlay's layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OverlayMarker {
    /// Nesting depth, from 1 for the root's overlay.
    pub depth: u16,
}

/// One level of the call stack: the nodes reported at it, and whether the last one has
/// already been traversed into.
#[derive(Debug, Default)]
struct Level {
    nodes: Vec<RawNode>,
    last_open: bool,
}

#[derive(Debug)]
struct Window {
    id: Option<WindowId>,
    info: Option<RawWindowInfo>,
    levels: Vec<Level>,
}

impl Window {
    fn new(id: Option<WindowId>, info: Option<RawWindowInfo>) -> Self {
        Self {
            id,
            info,
            levels: vec![Level::default()],
        }
    }

    fn is_empty(&self) -> bool {
        self.id.is_none()
            && self.info.is_none()
            && self.levels.iter().all(|level| level.nodes.is_empty())
    }

    fn push(&mut self, node: RawNode) {
        let Some(level) = self.levels.last_mut() else {
            return;
        };
        level.nodes.push(node);
        level.last_open = true;
    }

    /// Closes the innermost open traverse, giving its nodes to the node that opened it.
    fn close(&mut self) {
        if self.levels.len() < 2 {
            return;
        }
        let Some(children) = self.levels.pop() else {
            return;
        };
        let Some(parent) = self
            .levels
            .last_mut()
            .and_then(|level| level.nodes.last_mut())
        else {
            return;
        };
        parent.children = children.nodes;
    }

    fn finish(mut self) -> RawWindow {
        while self.levels.len() > 1 {
            self.close();
        }
        let nodes = self
            .levels
            .pop()
            .map(|level| level.nodes)
            .unwrap_or_default();
        let bounds = nodes
            .iter()
            .map(|node| node.bounds)
            .reduce(union)
            .unwrap_or_default();
        RawWindow {
            id: self.id,
            info: self.info,
            root: RawNode::new(RawCall::Group, bounds).with_children(nodes),
        }
    }
}

fn union(a: Rect, b: Rect) -> Rect {
    let x = a.x.min(b.x);
    let y = a.y.min(b.y);
    Rect {
        x,
        y,
        width: (a.x + a.width).max(b.x + b.width) - x,
        height: (a.y + a.height).max(b.y + b.height) - y,
    }
}

/// Records every operation callback into an [`icedwright_protocol::RawTree`], keeping the
/// call structure: each `traverse` makes the most recent report at its level the parent of
/// everything reported inside it, or a `Group` when nothing was reported first.
///
/// Run it through `UserInterface::operate` and take the tree with [`RawRecorder::into_tree`].
/// It answers [`Ask`] so annotations are built, counts scrollable and focusable callbacks
/// for their ordinals, starts a window at each [`WindowMarker`] and an overlay layer at each
/// [`OverlayMarker`].
#[derive(Debug)]
pub struct RawRecorder {
    done: Vec<RawWindow>,
    window: Window,
    window_ids: BTreeMap<window::Id, WindowId>,
    scrollables: u32,
    focusables: u32,
}

impl Default for RawRecorder {
    fn default() -> Self {
        Self::new()
    }
}

impl RawRecorder {
    /// A recorder whose first window is unnamed until a [`WindowMarker`] arrives.
    #[must_use]
    pub fn new() -> Self {
        Self {
            done: Vec::new(),
            window: Window::new(None, None),
            window_ids: BTreeMap::new(),
            scrollables: 0,
            focusables: 0,
        }
    }

    /// A recorder for one window the caller already knows, as the harness runs it.
    #[must_use]
    pub fn for_window(info: RawWindowInfo) -> Self {
        Self {
            window: Window::new(Some(info.id), Some(info)),
            ..Self::new()
        }
    }

    /// The window ids met in [`WindowMarker`]s, numbered in order of first appearance.
    #[must_use]
    pub fn window_ids(&self) -> &BTreeMap<window::Id, WindowId> {
        &self.window_ids
    }

    /// Everything recorded, one entry per window.
    #[must_use]
    pub fn into_tree(mut self) -> RawTree {
        let last = std::mem::replace(&mut self.window, Window::new(None, None));
        if !last.is_empty() || self.done.is_empty() {
            self.done.push(last.finish());
        }
        RawTree { windows: self.done }
    }

    fn report(&mut self, call: RawCall, id: Option<&Id>, bounds: Rectangle) {
        let mut node = RawNode::new(call, Rect::from(bounds));
        node.widget_id = id.and_then(|id| WidgetId::from_debug(&format!("{id:?}")));
        self.window.push(node);
    }

    fn start_window(&mut self, id: window::Id) {
        let next = WindowId(self.window_ids.len() as u64);
        let id = *self.window_ids.entry(id).or_insert(next);
        let previous = std::mem::replace(&mut self.window, Window::new(Some(id), None));
        if !previous.is_empty() {
            self.done.push(previous.finish());
        }
    }
}

impl Operation for RawRecorder {
    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
        let needs_group = self
            .window
            .levels
            .last()
            .is_none_or(|level| !level.last_open);
        if needs_group {
            self.window
                .push(RawNode::new(RawCall::Group, Rect::default()));
        }
        if let Some(level) = self.window.levels.last_mut() {
            level.last_open = false;
        }
        let depth = self.window.levels.len();
        self.window.levels.push(Level::default());
        operate(self);
        // A window marker inside the traverse may have replaced the window; only close our own.
        if self.window.levels.len() > depth {
            while self.window.levels.len() > depth + 1 {
                self.window.close();
            }
            self.window.close();
        }
    }

    fn container(&mut self, id: Option<&Id>, bounds: Rectangle) {
        self.report(RawCall::Container, id, bounds);
    }

    fn scrollable(
        &mut self,
        id: Option<&Id>,
        bounds: Rectangle,
        content_bounds: Rectangle,
        translation: Vector,
        _state: &mut dyn Scrollable,
    ) {
        let ordinal = self.scrollables;
        self.scrollables += 1;
        let call = RawCall::Scrollable {
            content_bounds: Rect::from(content_bounds),
            translation: translation.into(),
            ordinal,
        };
        self.report(call, id, bounds);
    }

    fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) {
        let ordinal = self.focusables;
        self.focusables += 1;
        let call = RawCall::Focusable {
            focused: state.is_focused(),
            ordinal,
        };
        self.report(call, id, bounds);
    }

    fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) {
        let call = RawCall::TextInput {
            text: state.text().to_owned(),
        };
        self.report(call, id, bounds);
    }

    fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) {
        let call = RawCall::Text {
            content: text.to_owned(),
        };
        self.report(call, id, bounds);
    }

    fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) {
        if let Some(ask) = state.downcast_mut::<Ask>() {
            ask.wanted = true;
            return;
        }
        if let Some(annotation) = state.downcast_mut::<Annotation<'static, AnyRole>>() {
            let fields = std::mem::take(&mut annotation.fields);
            let call = RawCall::Annotation(Box::new(raw_annotation(fields)));
            self.report(call, id, bounds);
            return;
        }
        if let Some(marker) = state.downcast_ref::<WindowMarker>() {
            self.start_window(marker.0);
            return;
        }
        if let Some(marker) = state.downcast_ref::<OverlayMarker>() {
            self.report(
                RawCall::Overlay {
                    depth: marker.depth,
                },
                id,
                bounds,
            );
        }
    }

    fn finish(&self) -> Outcome<()> {
        Outcome::None
    }
}

fn raw_key(key: Key) -> RawKey {
    match key {
        Key::Name(name) => RawKey::Name(name.into_owned()),
        Key::Unique(n) => RawKey::Unique(n),
    }
}

fn raw_keys(keys: Vec<Key>) -> Vec<RawKey> {
    keys.into_iter().map(raw_key).collect()
}

/// The only place probe annotations become protocol data.
fn raw_annotation(fields: Fields<'static>) -> RawAnnotation {
    RawAnnotation {
        source: fields.source,
        role: fields.role,
        name: fields.name.map(|t| t.into_owned()),
        description: fields.description.map(|t| t.into_owned()),
        tooltip: fields.tooltip.map(|t| t.into_owned()),
        placeholder: fields.placeholder.map(|t| t.into_owned()),
        value: fields.value.map(|value| match value {
            ValueField::Text(text) => RawValue::Text(text.into_owned()),
            ValueField::Number { now, min, max } => RawValue::Number {
                now,
                min: Some(min),
                max: Some(max),
                step: fields.step,
            },
        }),
        test_id: fields.test_id.map(|id| id.id.into_owned()),
        rust_path: fields.test_id_path.map(str::to_owned),
        kind: fields.kind.map(Into::into),
        props: fields
            .props
            .into_iter()
            .map(|(key, value)| (key.to_owned(), value.into_owned()))
            .collect(),
        text_size: fields.text_size,
        states: STATES
            .iter()
            .zip(fields.states)
            .filter_map(|(name, value)| value.map(|value| (*name, value)))
            .collect(),
        level: fields.level,
        position: fields.position,
        key: fields.key.map(raw_key),
        labelled_by: raw_keys(fields.labelled_by),
        label_for: raw_keys(fields.label_for),
        described_by: raw_keys(fields.described_by),
        controls: raw_keys(fields.controls),
        owns: raw_keys(fields.owns),
        carets: fields.carets,
        cursor_seen: fields.cursor_seen,
    }
}