use std::borrow::Cow;
use std::slice;
use icedwright_protocol::{
AnnotationSource, RawAnnotation, RawCall, RawNode, RawTree, RawValue, RawWindow, WidgetId,
WindowId,
};
use icedwright_types::{Point, Rect, Role, StateName, StateValue, Vector};
use crate::build::{self, Draft, DraftWarning, Mode};
use crate::tree::{
Kind, Layer, NameSource, Node, OperationKind, Scroll, ScrollAncestor, SemanticTree,
StateSource, TextGeometry, Value,
};
#[must_use]
pub fn infer(raw: &RawTree) -> SemanticTree {
let windows = raw
.windows
.iter()
.enumerate()
.map(|(index, window)| window_draft(index, window))
.collect();
build::finish(windows, Mode::Derive)
}
#[derive(Debug, Clone)]
struct Context {
window: WindowId,
window_bounds: Option<Rect>,
layer: Layer,
viewport: Option<Rect>,
translation: Vector,
scrolls: Vec<crate::tree::ScrollAncestor>,
}
impl Context {
fn place(&self, bounds: Rect) -> (Rect, Option<Rect>) {
let placed = bounds + self.translation;
let visible = match self.viewport {
Some(viewport) => viewport.intersection(placed),
None => (placed.area() > 0.0).then_some(placed),
};
(placed, visible)
}
fn overlay(&self, depth: u16) -> Context {
Context {
window: self.window,
window_bounds: self.window_bounds,
layer: Layer::Overlay(depth),
viewport: self.window_bounds,
translation: Vector::ZERO,
scrolls: Vec::new(),
}
}
fn scrolled(&self, raw: &RawNode, ordinal: u32, content: Rect, translation: Vector) -> Context {
let (bounds, visible) = self.place(raw.bounds);
let mut scrolls = self.scrolls.clone();
scrolls.push(ScrollAncestor {
ordinal,
bounds,
content_bounds: content + self.translation,
translation,
});
Context {
window: self.window,
window_bounds: self.window_bounds,
layer: self.layer,
viewport: Some(visible.unwrap_or(Rect::ZERO)),
translation: self.translation - translation,
scrolls,
}
}
}
fn window_draft(index: usize, window: &RawWindow) -> Draft {
let id = window
.id
.or(window.info.as_ref().map(|info| info.id))
.unwrap_or(WindowId(u64::try_from(index).unwrap_or(u64::MAX)));
let bounds = window.info.as_ref().map_or(window.root.bounds, |info| {
Rect::new(Point::ORIGIN, info.size)
});
let mut node = Node::blank(Role::Window, Kind::Inferred(OperationKind::Window), id);
if let Some(info) = &window.info {
node.name = Some(info.title.clone());
node.name_source = NameSource::Annotation;
}
node.bounds = bounds;
node.visible_bounds = (bounds.area() > 0.0).then_some(bounds);
node.sources.inferred = true;
let window_index = u32::try_from(index).unwrap_or(u32::MAX);
node.raw = vec![window_index];
let context = Context {
window: id,
window_bounds: window.info.as_ref().map(|_| bounds),
layer: Layer::Base,
viewport: window.info.as_ref().map(|_| bounds),
translation: Vector::ZERO,
scrolls: Vec::new(),
};
let mut draft = Draft::new(node);
draft.children = match window.root.call {
RawCall::Group => level(&window.root.children, &[window_index], &context),
_ => level(slice::from_ref(&window.root), &[window_index], &context)
.into_iter()
.map(|mut child| {
child.node.raw = vec![window_index];
child
})
.collect(),
};
draft
}
struct Unit<'a> {
raw: &'a RawNode,
path: Vec<u32>,
focusable: Option<&'a RawNode>,
}
fn is_leaf_focusable(raw: &RawNode) -> bool {
raw.children.is_empty() && matches!(raw.call, RawCall::Focusable { .. })
}
fn units<'a>(raws: &'a [RawNode], prefix: &[u32]) -> Vec<Unit<'a>> {
let mut out: Vec<Unit<'a>> = Vec::with_capacity(raws.len());
for (i, raw) in raws.iter().enumerate() {
if is_leaf_focusable(raw)
&& let Some(previous) = out.last_mut()
&& previous.focusable.is_none()
&& previous.raw.children.is_empty()
&& !matches!(
previous.raw.call,
RawCall::Focusable { .. } | RawCall::Overlay { .. }
)
&& previous.raw.bounds == raw.bounds
&& previous.raw.widget_id == raw.widget_id
{
previous.focusable = Some(raw);
continue;
}
let mut path = prefix.to_vec();
path.push(u32::try_from(i).unwrap_or(u32::MAX));
out.push(Unit {
raw,
path,
focusable: None,
});
}
out
}
fn level(raws: &[RawNode], prefix: &[u32], context: &Context) -> Vec<Draft> {
let mut out = Vec::new();
for unit in units(raws, prefix) {
if let RawCall::Overlay { depth } = unit.raw.call {
out.extend(level(
&unit.raw.children,
&unit.path,
&context.overlay(depth),
));
continue;
}
out.push(convert(&unit, context));
}
out
}
fn convert(unit: &Unit<'_>, context: &Context) -> Draft {
if let RawCall::Annotation(annotation) = &unit.raw.call {
return annotated(unit, annotation, context);
}
let (mut draft, inner) = inferred(unit.raw, context);
draft.node.raw = unit.path.clone();
if let Some(focusable) = unit.focusable {
donate_focus(&mut draft.node, focusable);
}
draft.children = level(&unit.raw.children, &unit.path, &inner);
draft
}
fn placed_node(role: Role, kind: Kind, raw: &RawNode, context: &Context) -> Node {
let (bounds, visible) = context.place(raw.bounds);
let mut node = Node::blank(role, kind, context.window);
node.bounds = bounds;
node.visible_bounds = visible;
node.layer = context.layer;
node.scroll_ancestors = context.scrolls.clone();
node.widget_id = raw.widget_id.clone();
node
}
fn inferred(raw: &RawNode, context: &Context) -> (Draft, Context) {
let (role, kind) = inferred_role(&raw.call);
let mut node = placed_node(role, Kind::Inferred(kind), raw, context);
node.sources.inferred = true;
let mut own_text = None;
let mut inner = context.clone();
match &raw.call {
RawCall::Text { content } => own_text = Some(content.clone()),
RawCall::TextInput { text } => {
node.value = Some(Value::Text(text.clone()));
node.sources.visible_text = true;
}
RawCall::Focusable { focused, ordinal } => {
node.states.set(
StateName::Multiline,
StateValue::Bool(true),
StateSource::Inferred,
);
set_focus(&mut node, *focused, *ordinal);
}
RawCall::Scrollable {
content_bounds,
translation,
ordinal,
} => {
node.scroll = Some(Scroll {
content_bounds: *content_bounds + context.translation,
translation: *translation,
});
inner = context.scrolled(raw, *ordinal, *content_bounds, *translation);
}
RawCall::Container | RawCall::Group | RawCall::Annotation(_) | RawCall::Overlay { .. } => {}
}
let mut draft = Draft::new(node);
draft.own_text = own_text;
(draft, inner)
}
const fn inferred_role(call: &RawCall) -> (Role, OperationKind) {
match call {
RawCall::Text { .. } => (Role::Text, OperationKind::Text),
RawCall::TextInput { .. } => (Role::TextBox, OperationKind::TextInput),
RawCall::Focusable { .. } => (Role::TextBox, OperationKind::Focusable),
RawCall::Scrollable { .. } => (Role::ScrollView, OperationKind::Scrollable),
RawCall::Container | RawCall::Group | RawCall::Overlay { .. } => {
(Role::Generic, OperationKind::Container)
}
RawCall::Annotation(_) => (Role::Generic, OperationKind::Custom),
}
}
fn set_focus(node: &mut Node, focused: bool, ordinal: u32) {
if node.states.focused.is_none() {
node.states.set(
StateName::Focused,
StateValue::Bool(focused),
StateSource::Inferred,
);
}
if !node.states.focusable {
node.states.set(
StateName::Focusable,
StateValue::Bool(true),
StateSource::Inferred,
);
}
node.focusable_ordinal = node.focusable_ordinal.or(Some(ordinal));
}
fn donate_focus(node: &mut Node, focusable: &RawNode) {
if let RawCall::Focusable { focused, ordinal } = focusable.call {
set_focus(node, focused, ordinal);
}
}
struct Chain<'a> {
annotations: Vec<&'a RawAnnotation>,
absorbed: Vec<&'a RawNode>,
innermost: &'a RawNode,
innermost_path: Vec<u32>,
context: Context,
}
fn absorb_chain<'a>(unit: &Unit<'a>, first: &'a RawAnnotation, context: &Context) -> Chain<'a> {
let mut chain = Chain {
annotations: vec![first],
absorbed: unit.focusable.into_iter().collect(),
innermost: unit.raw,
innermost_path: unit.path.clone(),
context: context.clone(),
};
loop {
let children = units(&chain.innermost.children, &chain.innermost_path);
let [only] = children.as_slice() else {
return chain;
};
if only.raw.bounds != unit.raw.bounds || matches!(only.raw.call, RawCall::Overlay { .. }) {
return chain;
}
match &only.raw.call {
RawCall::Annotation(annotation) if conflicts(&chain.annotations, annotation) => {
return chain;
}
RawCall::Annotation(annotation) => chain.annotations.push(annotation),
RawCall::Scrollable {
content_bounds,
translation,
ordinal,
} => {
chain.absorbed.push(only.raw);
chain.context =
chain
.context
.scrolled(only.raw, *ordinal, *content_bounds, *translation);
}
_ => chain.absorbed.push(only.raw),
}
chain.absorbed.extend(only.focusable);
chain.innermost = only.raw;
chain.innermost_path = only.path.clone();
}
}
fn conflicts(chain: &[&RawAnnotation], inner: &RawAnnotation) -> bool {
let Some(inner_role) = inner.role else {
return false;
};
chain
.iter()
.find_map(|a| a.role)
.is_some_and(|role| role != inner_role)
}
fn state_source(source: AnnotationSource) -> StateSource {
match source {
AnnotationSource::App => StateSource::Annotation,
AnnotationSource::Component => StateSource::Component,
}
}
fn first<'a, T>(
annotations: &[&'a RawAnnotation],
field: impl Fn(&'a RawAnnotation) -> Option<T>,
) -> Option<T> {
annotations.iter().find_map(|a| field(a))
}
fn valid_test_id(id: &str) -> bool {
id.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))
}
fn annotated(unit: &Unit<'_>, outermost: &RawAnnotation, context: &Context) -> Draft {
let mut chain = absorb_chain(unit, outermost, context);
chain
.annotations
.sort_by_key(|a| a.source == AnnotationSource::Component);
let annotations = chain.annotations.as_slice();
let top = annotations.first().copied().unwrap_or(outermost);
let mut warnings = Vec::new();
let roles: Vec<Role> = annotations.iter().filter_map(|a| a.role).collect();
let absorbed_role = chain
.absorbed
.iter()
.map(|raw| inferred_role(&raw.call).0)
.find(|role| *role != Role::Generic);
let role = roles
.first()
.copied()
.or(absorbed_role)
.unwrap_or(Role::Generic);
if role == Role::Unknown && !roles.is_empty() {
warnings.push(DraftWarning::UnknownRole);
}
let kind = match (top.source, &top.kind) {
(AnnotationSource::Component, kind) => {
Kind::Component(kind.clone().unwrap_or(Cow::Borrowed("component")))
}
(AnnotationSource::App, kind) => {
Kind::Annotated(kind.clone().unwrap_or(Cow::Borrowed("app")))
}
};
let mut node = placed_node(role, kind, unit.raw, context);
node.raw = unit.path.clone();
node.widget_id = unit
.raw
.widget_id
.clone()
.or_else(|| first_widget_id(&chain.absorbed));
for annotation in annotations {
match annotation.source {
AnnotationSource::App => node.sources.annotation = true,
AnnotationSource::Component => node.sources.component = true,
}
}
node.sources.inferred = !chain.absorbed.is_empty();
if let Some(name) = first(annotations, |a| a.name.clone()) {
node.name = Some(name);
node.name_source = NameSource::Annotation;
}
node.description = first(annotations, |a| a.description.clone());
node.tooltip = first(annotations, |a| a.tooltip.clone());
node.placeholder = first(annotations, |a| a.placeholder.clone());
node.value = first(annotations, |a| a.value.clone()).map(|value| match value {
RawValue::Text(text) => Value::Text(text),
RawValue::Number {
now,
min,
max,
step,
} => Value::Number {
now,
min,
max,
step,
},
});
node.test_id = first(annotations, |a| a.test_id.clone());
if let Some(id) = node.test_id.as_deref().filter(|id| !valid_test_id(id)) {
warnings.push(DraftWarning::InvalidTestId(id.to_owned()));
}
node.text_size = first(annotations, |a| a.text_size);
node.cursor_seen = first(annotations, |a| a.cursor_seen);
node.text_geometry = first(annotations, |a| {
(!a.carets.is_empty()).then(|| {
let mut carets = a.carets.clone();
carets.sort_by_key(|(offset, _)| *offset);
TextGeometry { carets }
})
});
for annotation in annotations.iter().rev() {
for (key, value) in &annotation.props {
node.props.insert(key.clone(), value.clone());
}
for (state, value) in &annotation.states {
node.states
.set(*state, *value, state_source(annotation.source));
}
}
match first(annotations, |a| a.level) {
Some(0) => warnings.push(DraftWarning::InvalidLevel),
level => node.set.level = level,
}
if let Some((position, size)) = first(annotations, |a| a.position) {
node.set.position = Some(position);
node.set.size = Some(size);
}
let mut own_text = None;
for raw in &chain.absorbed {
match &raw.call {
RawCall::Focusable { focused, ordinal } => set_focus(&mut node, *focused, *ordinal),
RawCall::Scrollable {
content_bounds,
translation,
..
} if node.scroll.is_none() => {
node.scroll = Some(Scroll {
content_bounds: *content_bounds + context.translation,
translation: *translation,
});
}
RawCall::TextInput { text } if node.value.is_none() => {
node.value = Some(Value::Text(text.clone()));
node.sources.visible_text = true;
}
RawCall::Text { content } if own_text.is_none() => own_text = Some(content.clone()),
_ => {}
}
}
let mut draft = Draft::new(node);
draft.own_text = own_text;
draft.warnings = warnings;
draft.keys.key = first(annotations, |a| a.key.clone());
for annotation in annotations {
draft
.keys
.labelled_by
.extend(annotation.labelled_by.iter().cloned());
draft
.keys
.label_for
.extend(annotation.label_for.iter().cloned());
draft
.keys
.described_by
.extend(annotation.described_by.iter().cloned());
draft
.keys
.controls
.extend(annotation.controls.iter().cloned());
draft.keys.owns.extend(annotation.owns.iter().cloned());
}
draft.children = level(
&chain.innermost.children,
&chain.innermost_path,
&chain.context,
);
draft
}
fn first_widget_id(absorbed: &[&RawNode]) -> Option<WidgetId> {
absorbed.iter().find_map(|raw| raw.widget_id.clone())
}