Skip to main content

icedwright_semantics/
infer.rs

1//! Inference: fusing raw operation calls and annotations into semantic nodes.
2//!
3//! The rules, each with its own tests:
4//!
5//! - `merge-leaf`: a `focusable` leaf merges into the leaf before it when both have the same
6//!   bounds and widget id, as `text_input` and iced-cube controls report them.
7//! - `absorb`: an annotation absorbs the chain of single raw children directly beneath it that
8//!   have its bounds, taking the fields it left unset from them.
9//! - `stack-annotations`: annotations in that chain merge too, app annotations above component
10//!   ones and outer above inner. The chain stops at an annotation naming a role other than the
11//!   one it already has, so a one-item list keeps its item.
12//! - `role-text`, `role-textbox`, `role-editor`, `role-scrollview`, `role-generic`: the role an
13//!   unannotated call gets.
14//! - `viewport`: scroll translation and clipping as `iced_selector` computes them, reset to
15//!   the window for each overlay layer.
16//! - `ignore-generic`, `derive-hidden`, `derive-offscreen`, `derive-inert`, `resolve-keys`,
17//!   `name` and `path` run in the finishing pass every tree goes through.
18
19use std::borrow::Cow;
20use std::slice;
21
22use icedwright_protocol::{
23    AnnotationSource, RawAnnotation, RawCall, RawNode, RawTree, RawValue, RawWindow, WidgetId,
24    WindowId,
25};
26use icedwright_types::{Point, Rect, Role, StateName, StateValue, Vector};
27
28use crate::build::{self, Draft, DraftWarning, Mode};
29use crate::tree::{
30    Kind, Layer, NameSource, Node, OperationKind, Scroll, ScrollAncestor, SemanticTree,
31    StateSource, TextGeometry, Value,
32};
33
34/// Builds the semantic tree from a recording. Linear in the number of raw nodes.
35#[must_use]
36pub fn infer(raw: &RawTree) -> SemanticTree {
37    let windows = raw
38        .windows
39        .iter()
40        .enumerate()
41        .map(|(index, window)| window_draft(index, window))
42        .collect();
43    build::finish(windows, Mode::Derive)
44}
45
46#[derive(Debug, Clone)]
47struct Context {
48    window: WindowId,
49    window_bounds: Option<Rect>,
50    layer: Layer,
51    viewport: Option<Rect>,
52    translation: Vector,
53    scrolls: Vec<crate::tree::ScrollAncestor>,
54}
55
56impl Context {
57    fn place(&self, bounds: Rect) -> (Rect, Option<Rect>) {
58        let placed = bounds + self.translation;
59        let visible = match self.viewport {
60            Some(viewport) => viewport.intersection(placed),
61            None => (placed.area() > 0.0).then_some(placed),
62        };
63        (placed, visible)
64    }
65
66    fn overlay(&self, depth: u16) -> Context {
67        Context {
68            window: self.window,
69            window_bounds: self.window_bounds,
70            layer: Layer::Overlay(depth),
71            viewport: self.window_bounds,
72            translation: Vector::ZERO,
73            scrolls: Vec::new(),
74        }
75    }
76
77    /// The context inside a scrollable, after its own call.
78    fn scrolled(&self, raw: &RawNode, ordinal: u32, content: Rect, translation: Vector) -> Context {
79        let (bounds, visible) = self.place(raw.bounds);
80        let mut scrolls = self.scrolls.clone();
81        scrolls.push(ScrollAncestor {
82            ordinal,
83            bounds,
84            content_bounds: content + self.translation,
85            translation,
86        });
87        Context {
88            window: self.window,
89            window_bounds: self.window_bounds,
90            layer: self.layer,
91            viewport: Some(visible.unwrap_or(Rect::ZERO)),
92            translation: self.translation - translation,
93            scrolls,
94        }
95    }
96}
97
98fn window_draft(index: usize, window: &RawWindow) -> Draft {
99    let id = window
100        .id
101        .or(window.info.as_ref().map(|info| info.id))
102        .unwrap_or(WindowId(u64::try_from(index).unwrap_or(u64::MAX)));
103    let bounds = window.info.as_ref().map_or(window.root.bounds, |info| {
104        Rect::new(Point::ORIGIN, info.size)
105    });
106    let mut node = Node::blank(Role::Window, Kind::Inferred(OperationKind::Window), id);
107    if let Some(info) = &window.info {
108        node.name = Some(info.title.clone());
109        node.name_source = NameSource::Annotation;
110    }
111    node.bounds = bounds;
112    node.visible_bounds = (bounds.area() > 0.0).then_some(bounds);
113    node.sources.inferred = true;
114    let window_index = u32::try_from(index).unwrap_or(u32::MAX);
115    node.raw = vec![window_index];
116    let context = Context {
117        window: id,
118        window_bounds: window.info.as_ref().map(|_| bounds),
119        layer: Layer::Base,
120        viewport: window.info.as_ref().map(|_| bounds),
121        translation: Vector::ZERO,
122        scrolls: Vec::new(),
123    };
124    let mut draft = Draft::new(node);
125    draft.children = match window.root.call {
126        RawCall::Group => level(&window.root.children, &[window_index], &context),
127        _ => level(slice::from_ref(&window.root), &[window_index], &context)
128            .into_iter()
129            .map(|mut child| {
130                child.node.raw = vec![window_index];
131                child
132            })
133            .collect(),
134    };
135    draft
136}
137
138/// A raw node, and the `focusable` leaf that `merge-leaf` folded into it.
139struct Unit<'a> {
140    raw: &'a RawNode,
141    path: Vec<u32>,
142    focusable: Option<&'a RawNode>,
143}
144
145fn is_leaf_focusable(raw: &RawNode) -> bool {
146    raw.children.is_empty() && matches!(raw.call, RawCall::Focusable { .. })
147}
148
149fn units<'a>(raws: &'a [RawNode], prefix: &[u32]) -> Vec<Unit<'a>> {
150    let mut out: Vec<Unit<'a>> = Vec::with_capacity(raws.len());
151    for (i, raw) in raws.iter().enumerate() {
152        if is_leaf_focusable(raw)
153            && let Some(previous) = out.last_mut()
154            && previous.focusable.is_none()
155            && previous.raw.children.is_empty()
156            && !matches!(
157                previous.raw.call,
158                RawCall::Focusable { .. } | RawCall::Overlay { .. }
159            )
160            && previous.raw.bounds == raw.bounds
161            && previous.raw.widget_id == raw.widget_id
162        {
163            previous.focusable = Some(raw);
164            continue;
165        }
166        let mut path = prefix.to_vec();
167        path.push(u32::try_from(i).unwrap_or(u32::MAX));
168        out.push(Unit {
169            raw,
170            path,
171            focusable: None,
172        });
173    }
174    out
175}
176
177fn level(raws: &[RawNode], prefix: &[u32], context: &Context) -> Vec<Draft> {
178    let mut out = Vec::new();
179    for unit in units(raws, prefix) {
180        if let RawCall::Overlay { depth } = unit.raw.call {
181            out.extend(level(
182                &unit.raw.children,
183                &unit.path,
184                &context.overlay(depth),
185            ));
186            continue;
187        }
188        out.push(convert(&unit, context));
189    }
190    out
191}
192
193fn convert(unit: &Unit<'_>, context: &Context) -> Draft {
194    if let RawCall::Annotation(annotation) = &unit.raw.call {
195        return annotated(unit, annotation, context);
196    }
197    let (mut draft, inner) = inferred(unit.raw, context);
198    draft.node.raw = unit.path.clone();
199    if let Some(focusable) = unit.focusable {
200        donate_focus(&mut draft.node, focusable);
201    }
202    draft.children = level(&unit.raw.children, &unit.path, &inner);
203    draft
204}
205
206fn placed_node(role: Role, kind: Kind, raw: &RawNode, context: &Context) -> Node {
207    let (bounds, visible) = context.place(raw.bounds);
208    let mut node = Node::blank(role, kind, context.window);
209    node.bounds = bounds;
210    node.visible_bounds = visible;
211    node.layer = context.layer;
212    node.scroll_ancestors = context.scrolls.clone();
213    node.widget_id = raw.widget_id.clone();
214    node
215}
216
217/// The node an unannotated call becomes, and the context for its children.
218fn inferred(raw: &RawNode, context: &Context) -> (Draft, Context) {
219    let (role, kind) = inferred_role(&raw.call);
220    let mut node = placed_node(role, Kind::Inferred(kind), raw, context);
221    node.sources.inferred = true;
222    let mut own_text = None;
223    let mut inner = context.clone();
224    match &raw.call {
225        RawCall::Text { content } => own_text = Some(content.clone()),
226        RawCall::TextInput { text } => {
227            node.value = Some(Value::Text(text.clone()));
228            node.sources.visible_text = true;
229        }
230        RawCall::Focusable { focused, ordinal } => {
231            node.states.set(
232                StateName::Multiline,
233                StateValue::Bool(true),
234                StateSource::Inferred,
235            );
236            set_focus(&mut node, *focused, *ordinal);
237        }
238        RawCall::Scrollable {
239            content_bounds,
240            translation,
241            ordinal,
242        } => {
243            node.scroll = Some(Scroll {
244                content_bounds: *content_bounds + context.translation,
245                translation: *translation,
246            });
247            inner = context.scrolled(raw, *ordinal, *content_bounds, *translation);
248        }
249        RawCall::Container | RawCall::Group | RawCall::Annotation(_) | RawCall::Overlay { .. } => {}
250    }
251    let mut draft = Draft::new(node);
252    draft.own_text = own_text;
253    (draft, inner)
254}
255
256const fn inferred_role(call: &RawCall) -> (Role, OperationKind) {
257    match call {
258        RawCall::Text { .. } => (Role::Text, OperationKind::Text),
259        RawCall::TextInput { .. } => (Role::TextBox, OperationKind::TextInput),
260        RawCall::Focusable { .. } => (Role::TextBox, OperationKind::Focusable),
261        RawCall::Scrollable { .. } => (Role::ScrollView, OperationKind::Scrollable),
262        RawCall::Container | RawCall::Group | RawCall::Overlay { .. } => {
263            (Role::Generic, OperationKind::Container)
264        }
265        RawCall::Annotation(_) => (Role::Generic, OperationKind::Custom),
266    }
267}
268
269fn set_focus(node: &mut Node, focused: bool, ordinal: u32) {
270    if node.states.focused.is_none() {
271        node.states.set(
272            StateName::Focused,
273            StateValue::Bool(focused),
274            StateSource::Inferred,
275        );
276    }
277    if !node.states.focusable {
278        node.states.set(
279            StateName::Focusable,
280            StateValue::Bool(true),
281            StateSource::Inferred,
282        );
283    }
284    node.focusable_ordinal = node.focusable_ordinal.or(Some(ordinal));
285}
286
287fn donate_focus(node: &mut Node, focusable: &RawNode) {
288    if let RawCall::Focusable { focused, ordinal } = focusable.call {
289        set_focus(node, focused, ordinal);
290    }
291}
292
293/// What the chain beneath an annotation holds.
294struct Chain<'a> {
295    annotations: Vec<&'a RawAnnotation>,
296    absorbed: Vec<&'a RawNode>,
297    innermost: &'a RawNode,
298    innermost_path: Vec<u32>,
299    context: Context,
300}
301
302fn absorb_chain<'a>(unit: &Unit<'a>, first: &'a RawAnnotation, context: &Context) -> Chain<'a> {
303    let mut chain = Chain {
304        annotations: vec![first],
305        absorbed: unit.focusable.into_iter().collect(),
306        innermost: unit.raw,
307        innermost_path: unit.path.clone(),
308        context: context.clone(),
309    };
310    loop {
311        let children = units(&chain.innermost.children, &chain.innermost_path);
312        let [only] = children.as_slice() else {
313            return chain;
314        };
315        if only.raw.bounds != unit.raw.bounds || matches!(only.raw.call, RawCall::Overlay { .. }) {
316            return chain;
317        }
318        match &only.raw.call {
319            RawCall::Annotation(annotation) if conflicts(&chain.annotations, annotation) => {
320                return chain;
321            }
322            RawCall::Annotation(annotation) => chain.annotations.push(annotation),
323            RawCall::Scrollable {
324                content_bounds,
325                translation,
326                ordinal,
327            } => {
328                chain.absorbed.push(only.raw);
329                chain.context =
330                    chain
331                        .context
332                        .scrolled(only.raw, *ordinal, *content_bounds, *translation);
333            }
334            _ => chain.absorbed.push(only.raw),
335        }
336        chain.absorbed.extend(only.focusable);
337        chain.innermost = only.raw;
338        chain.innermost_path = only.path.clone();
339    }
340}
341
342/// Whether `inner` names a role other than the one the chain already has.
343fn conflicts(chain: &[&RawAnnotation], inner: &RawAnnotation) -> bool {
344    let Some(inner_role) = inner.role else {
345        return false;
346    };
347    chain
348        .iter()
349        .find_map(|a| a.role)
350        .is_some_and(|role| role != inner_role)
351}
352
353fn state_source(source: AnnotationSource) -> StateSource {
354    match source {
355        AnnotationSource::App => StateSource::Annotation,
356        AnnotationSource::Component => StateSource::Component,
357    }
358}
359
360fn first<'a, T>(
361    annotations: &[&'a RawAnnotation],
362    field: impl Fn(&'a RawAnnotation) -> Option<T>,
363) -> Option<T> {
364    annotations.iter().find_map(|a| field(a))
365}
366
367fn valid_test_id(id: &str) -> bool {
368    id.chars()
369        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))
370}
371
372fn annotated(unit: &Unit<'_>, outermost: &RawAnnotation, context: &Context) -> Draft {
373    let mut chain = absorb_chain(unit, outermost, context);
374    // App annotations take precedence over component ones; a stable sort keeps outer first.
375    chain
376        .annotations
377        .sort_by_key(|a| a.source == AnnotationSource::Component);
378    let annotations = chain.annotations.as_slice();
379    let top = annotations.first().copied().unwrap_or(outermost);
380
381    let mut warnings = Vec::new();
382    let roles: Vec<Role> = annotations.iter().filter_map(|a| a.role).collect();
383    let absorbed_role = chain
384        .absorbed
385        .iter()
386        .map(|raw| inferred_role(&raw.call).0)
387        .find(|role| *role != Role::Generic);
388    let role = roles
389        .first()
390        .copied()
391        .or(absorbed_role)
392        .unwrap_or(Role::Generic);
393    if role == Role::Unknown && !roles.is_empty() {
394        warnings.push(DraftWarning::UnknownRole);
395    }
396
397    let kind = match (top.source, &top.kind) {
398        (AnnotationSource::Component, kind) => {
399            Kind::Component(kind.clone().unwrap_or(Cow::Borrowed("component")))
400        }
401        (AnnotationSource::App, kind) => {
402            Kind::Annotated(kind.clone().unwrap_or(Cow::Borrowed("app")))
403        }
404    };
405    let mut node = placed_node(role, kind, unit.raw, context);
406    node.raw = unit.path.clone();
407    node.widget_id = unit
408        .raw
409        .widget_id
410        .clone()
411        .or_else(|| first_widget_id(&chain.absorbed));
412    for annotation in annotations {
413        match annotation.source {
414            AnnotationSource::App => node.sources.annotation = true,
415            AnnotationSource::Component => node.sources.component = true,
416        }
417    }
418    node.sources.inferred = !chain.absorbed.is_empty();
419    if let Some(name) = first(annotations, |a| a.name.clone()) {
420        node.name = Some(name);
421        node.name_source = NameSource::Annotation;
422    }
423    node.description = first(annotations, |a| a.description.clone());
424    node.tooltip = first(annotations, |a| a.tooltip.clone());
425    node.placeholder = first(annotations, |a| a.placeholder.clone());
426    node.value = first(annotations, |a| a.value.clone()).map(|value| match value {
427        RawValue::Text(text) => Value::Text(text),
428        RawValue::Number {
429            now,
430            min,
431            max,
432            step,
433        } => Value::Number {
434            now,
435            min,
436            max,
437            step,
438        },
439    });
440    node.test_id = first(annotations, |a| a.test_id.clone());
441    if let Some(id) = node.test_id.as_deref().filter(|id| !valid_test_id(id)) {
442        warnings.push(DraftWarning::InvalidTestId(id.to_owned()));
443    }
444    node.text_size = first(annotations, |a| a.text_size);
445    node.cursor_seen = first(annotations, |a| a.cursor_seen);
446    node.text_geometry = first(annotations, |a| {
447        (!a.carets.is_empty()).then(|| {
448            let mut carets = a.carets.clone();
449            carets.sort_by_key(|(offset, _)| *offset);
450            TextGeometry { carets }
451        })
452    });
453    for annotation in annotations.iter().rev() {
454        for (key, value) in &annotation.props {
455            node.props.insert(key.clone(), value.clone());
456        }
457        for (state, value) in &annotation.states {
458            node.states
459                .set(*state, *value, state_source(annotation.source));
460        }
461    }
462    match first(annotations, |a| a.level) {
463        Some(0) => warnings.push(DraftWarning::InvalidLevel),
464        level => node.set.level = level,
465    }
466    if let Some((position, size)) = first(annotations, |a| a.position) {
467        node.set.position = Some(position);
468        node.set.size = Some(size);
469    }
470
471    let mut own_text = None;
472    for raw in &chain.absorbed {
473        match &raw.call {
474            RawCall::Focusable { focused, ordinal } => set_focus(&mut node, *focused, *ordinal),
475            RawCall::Scrollable {
476                content_bounds,
477                translation,
478                ..
479            } if node.scroll.is_none() => {
480                node.scroll = Some(Scroll {
481                    content_bounds: *content_bounds + context.translation,
482                    translation: *translation,
483                });
484            }
485            RawCall::TextInput { text } if node.value.is_none() => {
486                node.value = Some(Value::Text(text.clone()));
487                node.sources.visible_text = true;
488            }
489            RawCall::Text { content } if own_text.is_none() => own_text = Some(content.clone()),
490            _ => {}
491        }
492    }
493
494    let mut draft = Draft::new(node);
495    draft.own_text = own_text;
496    draft.warnings = warnings;
497    draft.keys.key = first(annotations, |a| a.key.clone());
498    for annotation in annotations {
499        draft
500            .keys
501            .labelled_by
502            .extend(annotation.labelled_by.iter().cloned());
503        draft
504            .keys
505            .label_for
506            .extend(annotation.label_for.iter().cloned());
507        draft
508            .keys
509            .described_by
510            .extend(annotation.described_by.iter().cloned());
511        draft
512            .keys
513            .controls
514            .extend(annotation.controls.iter().cloned());
515        draft.keys.owns.extend(annotation.owns.iter().cloned());
516    }
517    draft.children = level(
518        &chain.innermost.children,
519        &chain.innermost_path,
520        &chain.context,
521    );
522    draft
523}
524
525fn first_widget_id(absorbed: &[&RawNode]) -> Option<WidgetId> {
526    absorbed.iter().find_map(|raw| raw.widget_id.clone())
527}