icedwright-semantics 0.0.1

The icedwright semantic tree: inference from recorded widget operations, stable node paths, hit testing, diffs and YAML
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Hand-built trees for tests.
//!
//! A [`TreeBuilder`] writes the same annotations an app would and runs [`crate::infer`] on
//! them, so a hand-built tree follows every inference rule. Nodes are laid out top to bottom
//! inside their parent unless given bounds, so each has area and none share bounds with its
//! only child. State setters are gated by the same capability traits as the probe's
//! `Semantic`.

use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::RangeInclusive;

use icedwright_protocol::{
    AnnotationSource, RawAnnotation, RawCall, RawKey, RawNode, RawTree, RawValue, RawWindow,
    RawWindowInfo, WidgetId, WindowId,
};
use icedwright_types::role::{
    AnyRole, Checkable, Editable, Expandable, HasValue, Leveled, Pressable, RangeValue, RoleKind,
    RoleType, SelectableItem,
};
use icedwright_types::{
    Checked, CursorSeen, Point, Rect, ScaleFactor, Size, StateName, StateValue,
};

use crate::build::named_from_content;
use crate::infer::infer;
use crate::tree::SemanticTree;

const ROW: f32 = 24.0;
const INDENT: f32 = 8.0;
const WIDTH: f32 = 800.0;
const HEIGHT: f32 = 600.0;

#[derive(Debug, Clone)]
enum Spec {
    Node {
        annotation: Box<RawAnnotation>,
        widget_id: Option<WidgetId>,
        bounds: Option<Rect>,
        children: Vec<Spec>,
    },
    Text {
        content: String,
        bounds: Option<Rect>,
    },
    Overlay {
        depth: u16,
        children: Vec<Spec>,
    },
}

#[derive(Debug, Clone)]
struct WindowSpec {
    title: String,
    size: Option<Size>,
    children: Vec<Spec>,
}

/// Builds a tree of one or more windows.
#[derive(Debug, Clone)]
#[must_use = "a TreeBuilder does nothing until built"]
pub struct TreeBuilder {
    windows: Vec<WindowSpec>,
}

/// Builds one annotated node and its children.
#[derive(Debug, Clone)]
#[must_use = "a NodeBuilder does nothing until returned to its parent"]
pub struct NodeBuilder<R: RoleKind = AnyRole> {
    annotation: RawAnnotation,
    widget_id: Option<WidgetId>,
    bounds: Option<Rect>,
    children: Vec<Spec>,
    role: PhantomData<fn() -> R>,
}

fn node_spec<R: RoleKind>(builder: NodeBuilder<R>) -> Spec {
    Spec::Node {
        annotation: Box::new(builder.annotation),
        widget_id: builder.widget_id,
        bounds: builder.bounds,
        children: builder.children,
    }
}

fn new_node<R: RoleKind>(name: &str) -> NodeBuilder<R> {
    let annotation = RawAnnotation {
        role: R::ROLE,
        name: (!name.is_empty()).then(|| name.to_owned()),
        ..RawAnnotation::default()
    };
    NodeBuilder {
        annotation,
        widget_id: None,
        bounds: None,
        children: Vec::new(),
        role: PhantomData,
    }
}

macro_rules! children_methods {
    () => {
        /// Adds a child of a role, named unless `name` is empty.
        pub fn child<R2: RoleType>(
            mut self,
            role: R2,
            name: &str,
            build: impl FnOnce(NodeBuilder<R2>) -> NodeBuilder<R2>,
        ) -> Self {
            let _ = role;
            self.children_mut()
                .push(node_spec(build(new_node::<R2>(name))));
            self
        }

        /// Adds an annotated child with no role, which infers as a generic.
        pub fn generic(
            mut self,
            build: impl FnOnce(NodeBuilder<AnyRole>) -> NodeBuilder<AnyRole>,
        ) -> Self {
            self.children_mut()
                .push(node_spec(build(new_node::<AnyRole>(""))));
            self
        }

        /// Adds an unannotated `text` call.
        pub fn text(mut self, content: &str) -> Self {
            self.children_mut().push(Spec::Text {
                content: content.to_owned(),
                bounds: None,
            });
            self
        }

        /// Adds an unannotated `text` call at fixed bounds.
        pub fn text_at(mut self, content: &str, bounds: Rect) -> Self {
            self.children_mut().push(Spec::Text {
                content: content.to_owned(),
                bounds: Some(bounds),
            });
            self
        }
    };
}

impl TreeBuilder {
    /// A tree whose first window has this title.
    pub fn window(title: &str) -> Self {
        Self {
            windows: vec![WindowSpec {
                title: title.to_owned(),
                size: None,
                children: Vec::new(),
            }],
        }
    }

    /// Starts another window; later calls add to it.
    pub fn and_window(mut self, title: &str) -> Self {
        self.windows.push(WindowSpec {
            title: title.to_owned(),
            size: None,
            children: Vec::new(),
        });
        self
    }

    /// The current window's size, 800 by 600 unless its content needs more height.
    pub fn size(mut self, width: f32, height: f32) -> Self {
        if let Some(window) = self.windows.last_mut() {
            window.size = Some(Size::new(width, height));
        }
        self
    }

    /// Adds an overlay layer at `depth` to the current window, holding the builder's children.
    pub fn overlay(
        mut self,
        depth: u16,
        build: impl FnOnce(NodeBuilder<AnyRole>) -> NodeBuilder<AnyRole>,
    ) -> Self {
        let layer = build(new_node::<AnyRole>(""));
        self.children_mut().push(Spec::Overlay {
            depth,
            children: layer.children,
        });
        self
    }

    fn children_mut(&mut self) -> &mut Vec<Spec> {
        if self.windows.is_empty() {
            self.windows.push(WindowSpec {
                title: String::new(),
                size: None,
                children: Vec::new(),
            });
        }
        let index = self.windows.len() - 1;
        &mut self.windows[index].children
    }

    children_methods!();

    /// The recording an app with these annotations would produce.
    #[must_use]
    pub fn raw(&self) -> RawTree {
        let windows = self
            .windows
            .iter()
            .enumerate()
            .map(|(index, window)| {
                let width = window.size.map_or(WIDTH, |s| s.width);
                let (children, used) = layout(&window.children, 0.0, 0.0, width);
                let height = window.size.map_or(used.max(HEIGHT), |s| s.height);
                let id = WindowId(u64::try_from(index).unwrap_or(u64::MAX));
                let size = Size::new(width, height);
                RawWindow {
                    id: Some(id),
                    info: Some(RawWindowInfo {
                        id,
                        title: window.title.clone(),
                        size,
                        scale_factor: ScaleFactor::default(),
                    }),
                    root: RawNode::new(RawCall::Group, Rect::new(Point::ORIGIN, size))
                        .with_children(children),
                }
            })
            .collect();
        RawTree { windows }
    }

    /// The tree.
    #[must_use]
    pub fn build(&self) -> SemanticTree {
        infer(&self.raw())
    }
}

fn layout(specs: &[Spec], x: f32, y: f32, width: f32) -> (Vec<RawNode>, f32) {
    let mut nodes = Vec::with_capacity(specs.len());
    let mut cursor = y;
    let mut overlays = Vec::new();
    for spec in specs {
        match spec {
            Spec::Text { content, bounds } => {
                let bounds =
                    bounds.unwrap_or(Rect::new(Point::new(x, cursor), Size::new(width, ROW)));
                cursor += ROW;
                nodes.push(RawNode::new(
                    RawCall::Text {
                        content: content.clone(),
                    },
                    bounds,
                ));
            }
            Spec::Node {
                annotation,
                widget_id,
                bounds,
                children,
            } => {
                let (mut kids, used) =
                    layout(children, x + INDENT, cursor + ROW, width - 2.0 * INDENT);
                let label = annotation
                    .name
                    .clone()
                    .filter(|_| children.is_empty())
                    .filter(|_| annotation.role.is_some_and(named_from_content));
                let height = if label.is_some() {
                    2.0 * ROW
                } else {
                    ROW + (used - (cursor + ROW))
                };
                let placed =
                    bounds.unwrap_or(Rect::new(Point::new(x, cursor), Size::new(width, height)));
                cursor += height;
                if let Some(label) = label {
                    // A content-named role shows its name as text, as a real button does.
                    let inner = Rect::new(
                        Point::new(placed.x + 1.0, placed.y + 1.0),
                        Size::new(
                            (placed.width - 2.0).max(1.0),
                            (placed.height - 2.0).max(1.0),
                        ),
                    );
                    kids.push(RawNode::new(RawCall::Text { content: label }, inner));
                }
                let mut node = RawNode::new(RawCall::Annotation(annotation.clone()), placed)
                    .with_children(kids);
                node.widget_id = widget_id.clone();
                nodes.push(node);
            }
            Spec::Overlay { depth, children } => overlays.push((*depth, children)),
        }
    }
    for (depth, children) in overlays {
        let (kids, _) = layout(children, 0.0, 0.0, WIDTH);
        nodes.push(
            RawNode::new(
                RawCall::Overlay { depth },
                Rect::new(Point::ORIGIN, Size::new(WIDTH, HEIGHT)),
            )
            .with_children(kids),
        );
    }
    (nodes, cursor)
}

impl<R: RoleKind> NodeBuilder<R> {
    fn children_mut(&mut self) -> &mut Vec<Spec> {
        &mut self.children
    }

    children_methods!();

    fn state(mut self, state: StateName, value: impl Into<StateValue>) -> Self {
        self.annotation.states.push((state, value.into()));
        self
    }

    /// Fixed bounds instead of the automatic layout.
    pub fn bounds(mut self, x: f32, y: f32, width: f32, height: f32) -> Self {
        self.bounds = Some(Rect::new(Point::new(x, y), Size::new(width, height)));
        self
    }

    /// Reports the annotation as a component's, such as iced-cube's.
    pub fn component(mut self, kind: &'static str) -> Self {
        self.annotation.source = AnnotationSource::Component;
        self.annotation.kind = Some(Cow::Borrowed(kind));
        self
    }

    /// The kind an app annotation names.
    pub fn kind(mut self, kind: &'static str) -> Self {
        self.annotation.kind = Some(Cow::Borrowed(kind));
        self
    }

    /// The accessible name.
    pub fn name(mut self, name: &str) -> Self {
        self.annotation.name = Some(name.to_owned());
        self
    }

    /// The description.
    pub fn description(mut self, text: &str) -> Self {
        self.annotation.description = Some(text.to_owned());
        self
    }

    /// The tooltip.
    pub fn tooltip(mut self, text: &str) -> Self {
        self.annotation.tooltip = Some(text.to_owned());
        self
    }

    /// The test id.
    pub fn test_id(mut self, id: &str) -> Self {
        self.annotation.test_id = Some(id.to_owned());
        self
    }

    /// A `widget::Id::new(id)`.
    pub fn widget_id(mut self, id: &str) -> Self {
        self.widget_id = Some(WidgetId::Custom(id.to_owned()));
        self
    }

    /// A free-form property.
    pub fn prop(mut self, key: &str, value: &str) -> Self {
        self.annotation
            .props
            .insert(key.to_owned(), value.to_owned());
        self
    }

    /// The text size in logical pixels.
    pub fn text_size(mut self, size: f32) -> Self {
        self.annotation.text_size = Some(size);
        self
    }

    /// Caret positions by byte offset.
    pub fn carets(mut self, carets: impl IntoIterator<Item = (usize, Point)>) -> Self {
        self.annotation.carets = carets.into_iter().collect();
        self
    }

    /// The cursor kind handed to the widget this frame.
    pub fn cursor_seen(mut self, seen: CursorSeen) -> Self {
        self.annotation.cursor_seen = Some(seen);
        self
    }

    /// The key relations name this node by.
    pub fn key(mut self, key: &str) -> Self {
        self.annotation.key = Some(RawKey::Name(key.to_owned()));
        self
    }

    /// Named by the node with this key.
    pub fn labelled_by(mut self, key: &str) -> Self {
        self.annotation
            .labelled_by
            .push(RawKey::Name(key.to_owned()));
        self
    }

    /// Labels the node with this key.
    pub fn label_for(mut self, key: &str) -> Self {
        self.annotation.label_for.push(RawKey::Name(key.to_owned()));
        self
    }

    /// Described by the node with this key.
    pub fn described_by(mut self, key: &str) -> Self {
        self.annotation
            .described_by
            .push(RawKey::Name(key.to_owned()));
        self
    }

    /// Controls the node with this key.
    pub fn controls(mut self, key: &str) -> Self {
        self.annotation.controls.push(RawKey::Name(key.to_owned()));
        self
    }

    /// Owns the node with this key.
    pub fn owns(mut self, key: &str) -> Self {
        self.annotation.owns.push(RawKey::Name(key.to_owned()));
        self
    }

    /// Position in the set and set size.
    pub fn position(mut self, index: u32, of: u32) -> Self {
        self.annotation.position = Some((index, of));
        self
    }

    /// Takes no input.
    pub fn disabled(self, on: bool) -> Self {
        self.state(StateName::Disabled, on)
    }

    /// The current item in a set.
    pub fn current(self, on: bool) -> Self {
        self.state(StateName::Current, on)
    }

    /// Loading or updating.
    pub fn busy(self, on: bool) -> Self {
        self.state(StateName::Busy, on)
    }

    /// Explicitly hidden.
    pub fn hidden(self, on: bool) -> Self {
        self.state(StateName::Hidden, on)
    }

    /// Everything outside it is inert.
    pub fn modal(self, on: bool) -> Self {
        self.state(StateName::Modal, on)
    }

    /// Must be filled in.
    pub fn required(self, on: bool) -> Self {
        self.state(StateName::Required, on)
    }

    /// Its value is rejected.
    pub fn invalid(self, on: bool) -> Self {
        self.state(StateName::Invalid, on)
    }

    /// Its value cannot be changed.
    pub fn readonly(self, on: bool) -> Self {
        self.state(StateName::Readonly, on)
    }

    /// Focusable, and focused or not.
    pub fn focused(self, on: bool) -> Self {
        self.state(StateName::Focusable, true)
            .state(StateName::Focused, on)
    }

    /// Checked, unchecked or mixed.
    pub fn checked(self, state: impl Into<Checked>) -> Self
    where
        R: Checkable,
    {
        self.state(StateName::Checked, state.into())
    }

    /// A toggle button is pressed.
    pub fn pressed(self, on: bool) -> Self
    where
        R: Pressable,
    {
        self.state(StateName::Pressed, on)
    }

    /// Content or a popup is shown.
    pub fn expanded(self, on: bool) -> Self
    where
        R: Expandable,
    {
        self.state(StateName::Expanded, on)
    }

    /// Selected in its container.
    pub fn selected(self, on: bool) -> Self
    where
        R: SelectableItem,
    {
        self.state(StateName::Selected, on)
    }

    /// The heading or tree level, from 1.
    pub fn level(mut self, level: u16) -> Self
    where
        R: Leveled,
    {
        self.annotation.level = Some(level);
        self
    }

    /// A text value.
    pub fn value(mut self, text: &str) -> Self
    where
        R: HasValue,
    {
        self.annotation.value = Some(RawValue::Text(text.to_owned()));
        self
    }

    /// A number within a range.
    pub fn range(mut self, now: f64, range: RangeInclusive<f64>) -> Self
    where
        R: RangeValue,
    {
        self.annotation.value = Some(RawValue::Number {
            now,
            min: Some(*range.start()),
            max: Some(*range.end()),
            step: None,
        });
        self
    }

    /// The placeholder.
    pub fn placeholder(mut self, text: &str) -> Self
    where
        R: Editable,
    {
        self.annotation.placeholder = Some(text.to_owned());
        self
    }

    /// Takes more than one line.
    pub fn multiline(self, on: bool) -> Self
    where
        R: Editable,
    {
        self.state(StateName::Multiline, on)
    }
}