Skip to main content

icedwright_semantics/
builder.rs

1//! Hand-built trees for tests.
2//!
3//! A [`TreeBuilder`] writes the same annotations an app would and runs [`crate::infer`] on
4//! them, so a hand-built tree follows every inference rule. Nodes are laid out top to bottom
5//! inside their parent unless given bounds, so each has area and none share bounds with its
6//! only child. State setters are gated by the same capability traits as the probe's
7//! `Semantic`.
8
9use std::borrow::Cow;
10use std::marker::PhantomData;
11use std::ops::RangeInclusive;
12
13use icedwright_protocol::{
14    AnnotationSource, RawAnnotation, RawCall, RawKey, RawNode, RawTree, RawValue, RawWindow,
15    RawWindowInfo, WidgetId, WindowId,
16};
17use icedwright_types::role::{
18    AnyRole, Checkable, Editable, Expandable, HasValue, Leveled, Pressable, RangeValue, RoleKind,
19    RoleType, SelectableItem,
20};
21use icedwright_types::{
22    Checked, CursorSeen, Point, Rect, ScaleFactor, Size, StateName, StateValue,
23};
24
25use crate::build::named_from_content;
26use crate::infer::infer;
27use crate::tree::SemanticTree;
28
29const ROW: f32 = 24.0;
30const INDENT: f32 = 8.0;
31const WIDTH: f32 = 800.0;
32const HEIGHT: f32 = 600.0;
33
34#[derive(Debug, Clone)]
35enum Spec {
36    Node {
37        annotation: Box<RawAnnotation>,
38        widget_id: Option<WidgetId>,
39        bounds: Option<Rect>,
40        children: Vec<Spec>,
41    },
42    Text {
43        content: String,
44        bounds: Option<Rect>,
45    },
46    Overlay {
47        depth: u16,
48        children: Vec<Spec>,
49    },
50}
51
52#[derive(Debug, Clone)]
53struct WindowSpec {
54    title: String,
55    size: Option<Size>,
56    children: Vec<Spec>,
57}
58
59/// Builds a tree of one or more windows.
60#[derive(Debug, Clone)]
61#[must_use = "a TreeBuilder does nothing until built"]
62pub struct TreeBuilder {
63    windows: Vec<WindowSpec>,
64}
65
66/// Builds one annotated node and its children.
67#[derive(Debug, Clone)]
68#[must_use = "a NodeBuilder does nothing until returned to its parent"]
69pub struct NodeBuilder<R: RoleKind = AnyRole> {
70    annotation: RawAnnotation,
71    widget_id: Option<WidgetId>,
72    bounds: Option<Rect>,
73    children: Vec<Spec>,
74    role: PhantomData<fn() -> R>,
75}
76
77fn node_spec<R: RoleKind>(builder: NodeBuilder<R>) -> Spec {
78    Spec::Node {
79        annotation: Box::new(builder.annotation),
80        widget_id: builder.widget_id,
81        bounds: builder.bounds,
82        children: builder.children,
83    }
84}
85
86fn new_node<R: RoleKind>(name: &str) -> NodeBuilder<R> {
87    let annotation = RawAnnotation {
88        role: R::ROLE,
89        name: (!name.is_empty()).then(|| name.to_owned()),
90        ..RawAnnotation::default()
91    };
92    NodeBuilder {
93        annotation,
94        widget_id: None,
95        bounds: None,
96        children: Vec::new(),
97        role: PhantomData,
98    }
99}
100
101macro_rules! children_methods {
102    () => {
103        /// Adds a child of a role, named unless `name` is empty.
104        pub fn child<R2: RoleType>(
105            mut self,
106            role: R2,
107            name: &str,
108            build: impl FnOnce(NodeBuilder<R2>) -> NodeBuilder<R2>,
109        ) -> Self {
110            let _ = role;
111            self.children_mut()
112                .push(node_spec(build(new_node::<R2>(name))));
113            self
114        }
115
116        /// Adds an annotated child with no role, which infers as a generic.
117        pub fn generic(
118            mut self,
119            build: impl FnOnce(NodeBuilder<AnyRole>) -> NodeBuilder<AnyRole>,
120        ) -> Self {
121            self.children_mut()
122                .push(node_spec(build(new_node::<AnyRole>(""))));
123            self
124        }
125
126        /// Adds an unannotated `text` call.
127        pub fn text(mut self, content: &str) -> Self {
128            self.children_mut().push(Spec::Text {
129                content: content.to_owned(),
130                bounds: None,
131            });
132            self
133        }
134
135        /// Adds an unannotated `text` call at fixed bounds.
136        pub fn text_at(mut self, content: &str, bounds: Rect) -> Self {
137            self.children_mut().push(Spec::Text {
138                content: content.to_owned(),
139                bounds: Some(bounds),
140            });
141            self
142        }
143    };
144}
145
146impl TreeBuilder {
147    /// A tree whose first window has this title.
148    pub fn window(title: &str) -> Self {
149        Self {
150            windows: vec![WindowSpec {
151                title: title.to_owned(),
152                size: None,
153                children: Vec::new(),
154            }],
155        }
156    }
157
158    /// Starts another window; later calls add to it.
159    pub fn and_window(mut self, title: &str) -> Self {
160        self.windows.push(WindowSpec {
161            title: title.to_owned(),
162            size: None,
163            children: Vec::new(),
164        });
165        self
166    }
167
168    /// The current window's size, 800 by 600 unless its content needs more height.
169    pub fn size(mut self, width: f32, height: f32) -> Self {
170        if let Some(window) = self.windows.last_mut() {
171            window.size = Some(Size::new(width, height));
172        }
173        self
174    }
175
176    /// Adds an overlay layer at `depth` to the current window, holding the builder's children.
177    pub fn overlay(
178        mut self,
179        depth: u16,
180        build: impl FnOnce(NodeBuilder<AnyRole>) -> NodeBuilder<AnyRole>,
181    ) -> Self {
182        let layer = build(new_node::<AnyRole>(""));
183        self.children_mut().push(Spec::Overlay {
184            depth,
185            children: layer.children,
186        });
187        self
188    }
189
190    fn children_mut(&mut self) -> &mut Vec<Spec> {
191        if self.windows.is_empty() {
192            self.windows.push(WindowSpec {
193                title: String::new(),
194                size: None,
195                children: Vec::new(),
196            });
197        }
198        let index = self.windows.len() - 1;
199        &mut self.windows[index].children
200    }
201
202    children_methods!();
203
204    /// The recording an app with these annotations would produce.
205    #[must_use]
206    pub fn raw(&self) -> RawTree {
207        let windows = self
208            .windows
209            .iter()
210            .enumerate()
211            .map(|(index, window)| {
212                let width = window.size.map_or(WIDTH, |s| s.width);
213                let (children, used) = layout(&window.children, 0.0, 0.0, width);
214                let height = window.size.map_or(used.max(HEIGHT), |s| s.height);
215                let id = WindowId(u64::try_from(index).unwrap_or(u64::MAX));
216                let size = Size::new(width, height);
217                RawWindow {
218                    id: Some(id),
219                    info: Some(RawWindowInfo {
220                        id,
221                        title: window.title.clone(),
222                        size,
223                        scale_factor: ScaleFactor::default(),
224                    }),
225                    root: RawNode::new(RawCall::Group, Rect::new(Point::ORIGIN, size))
226                        .with_children(children),
227                }
228            })
229            .collect();
230        RawTree { windows }
231    }
232
233    /// The tree.
234    #[must_use]
235    pub fn build(&self) -> SemanticTree {
236        infer(&self.raw())
237    }
238}
239
240fn layout(specs: &[Spec], x: f32, y: f32, width: f32) -> (Vec<RawNode>, f32) {
241    let mut nodes = Vec::with_capacity(specs.len());
242    let mut cursor = y;
243    let mut overlays = Vec::new();
244    for spec in specs {
245        match spec {
246            Spec::Text { content, bounds } => {
247                let bounds =
248                    bounds.unwrap_or(Rect::new(Point::new(x, cursor), Size::new(width, ROW)));
249                cursor += ROW;
250                nodes.push(RawNode::new(
251                    RawCall::Text {
252                        content: content.clone(),
253                    },
254                    bounds,
255                ));
256            }
257            Spec::Node {
258                annotation,
259                widget_id,
260                bounds,
261                children,
262            } => {
263                let (mut kids, used) =
264                    layout(children, x + INDENT, cursor + ROW, width - 2.0 * INDENT);
265                let label = annotation
266                    .name
267                    .clone()
268                    .filter(|_| children.is_empty())
269                    .filter(|_| annotation.role.is_some_and(named_from_content));
270                let height = if label.is_some() {
271                    2.0 * ROW
272                } else {
273                    ROW + (used - (cursor + ROW))
274                };
275                let placed =
276                    bounds.unwrap_or(Rect::new(Point::new(x, cursor), Size::new(width, height)));
277                cursor += height;
278                if let Some(label) = label {
279                    // A content-named role shows its name as text, as a real button does.
280                    let inner = Rect::new(
281                        Point::new(placed.x + 1.0, placed.y + 1.0),
282                        Size::new(
283                            (placed.width - 2.0).max(1.0),
284                            (placed.height - 2.0).max(1.0),
285                        ),
286                    );
287                    kids.push(RawNode::new(RawCall::Text { content: label }, inner));
288                }
289                let mut node = RawNode::new(RawCall::Annotation(annotation.clone()), placed)
290                    .with_children(kids);
291                node.widget_id = widget_id.clone();
292                nodes.push(node);
293            }
294            Spec::Overlay { depth, children } => overlays.push((*depth, children)),
295        }
296    }
297    for (depth, children) in overlays {
298        let (kids, _) = layout(children, 0.0, 0.0, WIDTH);
299        nodes.push(
300            RawNode::new(
301                RawCall::Overlay { depth },
302                Rect::new(Point::ORIGIN, Size::new(WIDTH, HEIGHT)),
303            )
304            .with_children(kids),
305        );
306    }
307    (nodes, cursor)
308}
309
310impl<R: RoleKind> NodeBuilder<R> {
311    fn children_mut(&mut self) -> &mut Vec<Spec> {
312        &mut self.children
313    }
314
315    children_methods!();
316
317    fn state(mut self, state: StateName, value: impl Into<StateValue>) -> Self {
318        self.annotation.states.push((state, value.into()));
319        self
320    }
321
322    /// Fixed bounds instead of the automatic layout.
323    pub fn bounds(mut self, x: f32, y: f32, width: f32, height: f32) -> Self {
324        self.bounds = Some(Rect::new(Point::new(x, y), Size::new(width, height)));
325        self
326    }
327
328    /// Reports the annotation as a component's, such as iced-cube's.
329    pub fn component(mut self, kind: &'static str) -> Self {
330        self.annotation.source = AnnotationSource::Component;
331        self.annotation.kind = Some(Cow::Borrowed(kind));
332        self
333    }
334
335    /// The kind an app annotation names.
336    pub fn kind(mut self, kind: &'static str) -> Self {
337        self.annotation.kind = Some(Cow::Borrowed(kind));
338        self
339    }
340
341    /// The accessible name.
342    pub fn name(mut self, name: &str) -> Self {
343        self.annotation.name = Some(name.to_owned());
344        self
345    }
346
347    /// The description.
348    pub fn description(mut self, text: &str) -> Self {
349        self.annotation.description = Some(text.to_owned());
350        self
351    }
352
353    /// The tooltip.
354    pub fn tooltip(mut self, text: &str) -> Self {
355        self.annotation.tooltip = Some(text.to_owned());
356        self
357    }
358
359    /// The test id.
360    pub fn test_id(mut self, id: &str) -> Self {
361        self.annotation.test_id = Some(id.to_owned());
362        self
363    }
364
365    /// A `widget::Id::new(id)`.
366    pub fn widget_id(mut self, id: &str) -> Self {
367        self.widget_id = Some(WidgetId::Custom(id.to_owned()));
368        self
369    }
370
371    /// A free-form property.
372    pub fn prop(mut self, key: &str, value: &str) -> Self {
373        self.annotation
374            .props
375            .insert(key.to_owned(), value.to_owned());
376        self
377    }
378
379    /// The text size in logical pixels.
380    pub fn text_size(mut self, size: f32) -> Self {
381        self.annotation.text_size = Some(size);
382        self
383    }
384
385    /// Caret positions by byte offset.
386    pub fn carets(mut self, carets: impl IntoIterator<Item = (usize, Point)>) -> Self {
387        self.annotation.carets = carets.into_iter().collect();
388        self
389    }
390
391    /// The cursor kind handed to the widget this frame.
392    pub fn cursor_seen(mut self, seen: CursorSeen) -> Self {
393        self.annotation.cursor_seen = Some(seen);
394        self
395    }
396
397    /// The key relations name this node by.
398    pub fn key(mut self, key: &str) -> Self {
399        self.annotation.key = Some(RawKey::Name(key.to_owned()));
400        self
401    }
402
403    /// Named by the node with this key.
404    pub fn labelled_by(mut self, key: &str) -> Self {
405        self.annotation
406            .labelled_by
407            .push(RawKey::Name(key.to_owned()));
408        self
409    }
410
411    /// Labels the node with this key.
412    pub fn label_for(mut self, key: &str) -> Self {
413        self.annotation.label_for.push(RawKey::Name(key.to_owned()));
414        self
415    }
416
417    /// Described by the node with this key.
418    pub fn described_by(mut self, key: &str) -> Self {
419        self.annotation
420            .described_by
421            .push(RawKey::Name(key.to_owned()));
422        self
423    }
424
425    /// Controls the node with this key.
426    pub fn controls(mut self, key: &str) -> Self {
427        self.annotation.controls.push(RawKey::Name(key.to_owned()));
428        self
429    }
430
431    /// Owns the node with this key.
432    pub fn owns(mut self, key: &str) -> Self {
433        self.annotation.owns.push(RawKey::Name(key.to_owned()));
434        self
435    }
436
437    /// Position in the set and set size.
438    pub fn position(mut self, index: u32, of: u32) -> Self {
439        self.annotation.position = Some((index, of));
440        self
441    }
442
443    /// Takes no input.
444    pub fn disabled(self, on: bool) -> Self {
445        self.state(StateName::Disabled, on)
446    }
447
448    /// The current item in a set.
449    pub fn current(self, on: bool) -> Self {
450        self.state(StateName::Current, on)
451    }
452
453    /// Loading or updating.
454    pub fn busy(self, on: bool) -> Self {
455        self.state(StateName::Busy, on)
456    }
457
458    /// Explicitly hidden.
459    pub fn hidden(self, on: bool) -> Self {
460        self.state(StateName::Hidden, on)
461    }
462
463    /// Everything outside it is inert.
464    pub fn modal(self, on: bool) -> Self {
465        self.state(StateName::Modal, on)
466    }
467
468    /// Must be filled in.
469    pub fn required(self, on: bool) -> Self {
470        self.state(StateName::Required, on)
471    }
472
473    /// Its value is rejected.
474    pub fn invalid(self, on: bool) -> Self {
475        self.state(StateName::Invalid, on)
476    }
477
478    /// Its value cannot be changed.
479    pub fn readonly(self, on: bool) -> Self {
480        self.state(StateName::Readonly, on)
481    }
482
483    /// Focusable, and focused or not.
484    pub fn focused(self, on: bool) -> Self {
485        self.state(StateName::Focusable, true)
486            .state(StateName::Focused, on)
487    }
488
489    /// Checked, unchecked or mixed.
490    pub fn checked(self, state: impl Into<Checked>) -> Self
491    where
492        R: Checkable,
493    {
494        self.state(StateName::Checked, state.into())
495    }
496
497    /// A toggle button is pressed.
498    pub fn pressed(self, on: bool) -> Self
499    where
500        R: Pressable,
501    {
502        self.state(StateName::Pressed, on)
503    }
504
505    /// Content or a popup is shown.
506    pub fn expanded(self, on: bool) -> Self
507    where
508        R: Expandable,
509    {
510        self.state(StateName::Expanded, on)
511    }
512
513    /// Selected in its container.
514    pub fn selected(self, on: bool) -> Self
515    where
516        R: SelectableItem,
517    {
518        self.state(StateName::Selected, on)
519    }
520
521    /// The heading or tree level, from 1.
522    pub fn level(mut self, level: u16) -> Self
523    where
524        R: Leveled,
525    {
526        self.annotation.level = Some(level);
527        self
528    }
529
530    /// A text value.
531    pub fn value(mut self, text: &str) -> Self
532    where
533        R: HasValue,
534    {
535        self.annotation.value = Some(RawValue::Text(text.to_owned()));
536        self
537    }
538
539    /// A number within a range.
540    pub fn range(mut self, now: f64, range: RangeInclusive<f64>) -> Self
541    where
542        R: RangeValue,
543    {
544        self.annotation.value = Some(RawValue::Number {
545            now,
546            min: Some(*range.start()),
547            max: Some(*range.end()),
548            step: None,
549        });
550        self
551    }
552
553    /// The placeholder.
554    pub fn placeholder(mut self, text: &str) -> Self
555    where
556        R: Editable,
557    {
558        self.annotation.placeholder = Some(text.to_owned());
559        self
560    }
561
562    /// Takes more than one line.
563    pub fn multiline(self, on: bool) -> Self
564    where
565        R: Editable,
566    {
567        self.state(StateName::Multiline, on)
568    }
569}