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