icedwright-probe 0.1.4

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
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
//! What an annotation says about a node, and how it reaches the recorder.

use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::RangeInclusive;
use std::sync::atomic::{AtomicU64, Ordering};

use iced_core::text::IntoFragment;
use iced_core::widget::Operation;
use iced_core::{Pixels, Rectangle};
use icedwright_types::role::{
    AnyRole, Checkable, Editable, Expandable, HasValue, Leveled, Pressable, RangeValue, RoleKind,
    RoleType, SelectableItem, Untyped,
};
use icedwright_types::{Checked, CursorSeen, Point};

use crate::test_id::IntoTestId;

/// A key one annotation uses to name another in a relation such as `labelled_by` or `owns`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Key {
    /// A key the app chose.
    Name(Cow<'static, str>),
    /// A key from [`Key::unique`].
    Unique(u64),
}

impl Key {
    /// A key no other call returns, like `iced_core::widget::Id::unique`. Keep it in widget
    /// state so it survives frames.
    #[must_use]
    pub fn unique() -> Self {
        static NEXT: AtomicU64 = AtomicU64::new(0);
        Key::Unique(NEXT.fetch_add(1, Ordering::Relaxed))
    }
}

impl From<&'static str> for Key {
    fn from(name: &'static str) -> Self {
        Key::Name(Cow::Borrowed(name))
    }
}

impl From<String> for Key {
    fn from(name: String) -> Self {
        Key::Name(Cow::Owned(name))
    }
}

/// Whether a widget counts multiple clicks on the virtual clock or through iced's
/// `mouse::Click`, which reads the real one. Written as the `click-clock` prop.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClickClock {
    /// Counted by `iced_core::mouse::Click`, so double clicks cannot be timed in a test.
    Iced,
    /// Counted on `icedwright_probe::time::now`, so a harness can time them.
    Probe,
}

/// Whether a widget's caret blinks on the virtual clock or the real one. Written as the
/// `caret-clock` prop.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CaretClock {
    /// Blinks on the real clock, as iced's text inputs do.
    Iced,
    /// Blinks on `icedwright_probe::time::now`.
    Probe,
}

impl ClickClock {
    /// The prop it is written as.
    pub const PROP: &'static str = "click-clock";

    /// The prop's value.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            ClickClock::Iced => "iced",
            ClickClock::Probe => "probe",
        }
    }
}

impl CaretClock {
    /// The prop it is written as.
    pub const PROP: &'static str = "caret-clock";

    /// The prop's value.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            CaretClock::Iced => "iced",
            CaretClock::Probe => "probe",
        }
    }
}

#[cfg(feature = "semantics")]
pub(crate) use fields::Fields;

#[cfg(feature = "semantics")]
pub(crate) mod fields {
    use std::borrow::Cow;

    use icedwright_protocol::AnnotationSource;
    use icedwright_types::{CursorSeen, Point, Role, StateName, StateValue};

    use super::Key;
    use crate::test_id::TestIdRef;

    /// The states an annotation can set, in the order the recorder writes them.
    pub(crate) const STATES: [StateName; 13] = [
        StateName::Disabled,
        StateName::Readonly,
        StateName::Checked,
        StateName::Pressed,
        StateName::Expanded,
        StateName::Selected,
        StateName::Current,
        StateName::Busy,
        StateName::Required,
        StateName::Invalid,
        StateName::Multiline,
        StateName::Modal,
        StateName::Hidden,
    ];

    #[derive(Debug, Clone, PartialEq)]
    pub(crate) enum ValueField<'a> {
        Text(Cow<'a, str>),
        Number { now: f64, min: f64, max: f64 },
    }

    /// Every field, borrowing strings from the view so building one allocates nothing.
    #[derive(Debug, Clone, PartialEq, Default)]
    pub(crate) struct Fields<'a> {
        pub(crate) source: AnnotationSource,
        pub(crate) role: Option<Role>,
        pub(crate) name: Option<Cow<'a, str>>,
        pub(crate) description: Option<Cow<'a, str>>,
        pub(crate) tooltip: Option<Cow<'a, str>>,
        pub(crate) placeholder: Option<Cow<'a, str>>,
        pub(crate) value: Option<ValueField<'a>>,
        pub(crate) step: Option<f64>,
        pub(crate) test_id: Option<TestIdRef<'a>>,
        pub(crate) test_id_path: Option<&'static str>,
        pub(crate) kind: Option<&'static str>,
        pub(crate) props: Vec<(&'static str, Cow<'a, str>)>,
        pub(crate) text_size: Option<f32>,
        pub(crate) states: [Option<StateValue>; STATES.len()],
        pub(crate) level: Option<u16>,
        pub(crate) position: Option<(u32, u32)>,
        pub(crate) key: Option<Key>,
        pub(crate) labelled_by: Vec<Key>,
        pub(crate) label_for: Vec<Key>,
        pub(crate) described_by: Vec<Key>,
        pub(crate) controls: Vec<Key>,
        pub(crate) owns: Vec<Key>,
        pub(crate) carets: Vec<(usize, Point)>,
        pub(crate) cursor_seen: Option<CursorSeen>,
    }

    fn owned(text: &Option<Cow<'_, str>>) -> Option<Cow<'static, str>> {
        text.as_ref().map(|t| Cow::Owned(t.clone().into_owned()))
    }

    impl Fields<'_> {
        pub(crate) fn set_state(&mut self, name: StateName, value: StateValue) {
            if let Some(slot) = STATES
                .iter()
                .position(|s| *s == name)
                .and_then(|i| self.states.get_mut(i))
            {
                *slot = Some(value);
            }
        }

        pub(crate) fn to_static(&self) -> Fields<'static> {
            Fields {
                source: self.source,
                role: self.role,
                name: owned(&self.name),
                description: owned(&self.description),
                tooltip: owned(&self.tooltip),
                placeholder: owned(&self.placeholder),
                value: self.value.as_ref().map(|value| match value {
                    ValueField::Text(text) => {
                        ValueField::Text(Cow::Owned(text.clone().into_owned()))
                    }
                    ValueField::Number { now, min, max } => ValueField::Number {
                        now: *now,
                        min: *min,
                        max: *max,
                    },
                }),
                step: self.step,
                test_id: self.test_id.clone().map(TestIdRef::into_static),
                test_id_path: self.test_id_path,
                kind: self.kind,
                props: self
                    .props
                    .iter()
                    .map(|(k, v)| (*k, Cow::Owned(v.clone().into_owned())))
                    .collect(),
                text_size: self.text_size,
                states: self.states,
                level: self.level,
                position: self.position,
                key: self.key.clone(),
                labelled_by: self.labelled_by.clone(),
                label_for: self.label_for.clone(),
                described_by: self.described_by.clone(),
                controls: self.controls.clone(),
                owns: self.owns.clone(),
                carets: self.carets.clone(),
                cursor_seen: self.cursor_seen,
            }
        }
    }

    /// Props keep borrowed values borrowed until `to_static`.
    impl<'a> Fields<'a> {
        pub(crate) fn push_prop(&mut self, key: &'static str, value: Cow<'a, str>) {
            self.props.retain(|(k, _)| *k != key);
            self.props.push((key, value));
        }
    }
}

/// What an annotation says about a node: its role, name, states and relations.
///
/// The role is part of the type, starting at [`AnyRole`]. [`Annotation::role`] moves it to a
/// concrete role once, and the setters for capability states compile only for roles with that
/// capability, so `.checked(..)` on a button is a type error.
///
/// Apps build these through [`semantic`](crate::semantic). Widget authors who write their own
/// `operate` build one with [`Annotation::new`] and send it with [`report`].
///
/// With the `semantics` feature off it holds nothing and every method does nothing.
#[must_use = "an Annotation does nothing until it is reported"]
pub struct Annotation<'a, R: RoleKind = AnyRole> {
    #[cfg(feature = "semantics")]
    pub(crate) fields: Fields<'a>,
    marker: Marker<'a, R>,
}

/// Carries the role type and the view's lifetime without owning either.
type Marker<'a, R> = PhantomData<(fn() -> R, &'a ())>;

impl<R: RoleKind> std::fmt::Debug for Annotation<'_, R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut out = f.debug_struct("Annotation");
        out.field("role_type", &R::default());
        #[cfg(feature = "semantics")]
        out.field("fields", &self.fields);
        out.finish()
    }
}

impl<R: RoleKind> Clone for Annotation<'_, R> {
    fn clone(&self) -> Self {
        Self {
            #[cfg(feature = "semantics")]
            fields: self.fields.clone(),
            marker: PhantomData,
        }
    }
}

impl Default for Annotation<'_, AnyRole> {
    fn default() -> Self {
        Self::new()
    }
}

impl Annotation<'_, AnyRole> {
    /// An annotation with nothing set.
    #[inline]
    pub fn new() -> Self {
        Self {
            #[cfg(feature = "semantics")]
            fields: Fields::default(),
            marker: PhantomData,
        }
    }
}

impl<'a, R: RoleKind> Annotation<'a, R> {
    /// Gives the node a role. Only once: a second call does not compile.
    #[inline]
    pub fn role<R2: RoleType>(self, role: R2) -> Annotation<'a, R2>
    where
        R: Untyped,
    {
        let _ = role;
        Annotation {
            #[cfg(feature = "semantics")]
            fields: Fields {
                role: Some(R2::ROLE_VALUE),
                ..self.fields
            },
            marker: PhantomData,
        }
    }

    /// The same annotation with its strings owned and its role type erased, which is what
    /// [`report`] sends.
    #[inline]
    pub fn to_static(&self) -> Annotation<'static, AnyRole> {
        Annotation {
            #[cfg(feature = "semantics")]
            fields: self.fields.to_static(),
            marker: PhantomData,
        }
    }

    #[cfg(feature = "semantics")]
    fn erase(self) -> Annotation<'a, AnyRole> {
        Annotation {
            fields: self.fields,
            marker: PhantomData,
        }
    }

    /// The caret position of each byte offset, for widgets that draw editable or selectable
    /// text. Sorted by offset when recorded.
    #[inline]
    pub fn text_geometry(self, carets: impl IntoIterator<Item = (usize, Point)>) -> Self {
        #[cfg(feature = "semantics")]
        {
            let mut this = self;
            this.fields.carets = carets.into_iter().collect();
            this.fields.carets.sort_by_key(|(offset, _)| *offset);
            this
        }
        #[cfg(not(feature = "semantics"))]
        {
            let _ = carets;
            self
        }
    }

    /// The kind of cursor the widget was handed for its last mouse event this frame.
    #[inline]
    pub fn cursor_seen(self, seen: impl Into<Option<CursorSeen>>) -> Self {
        #[cfg(feature = "semantics")]
        {
            let mut this = self;
            this.fields.cursor_seen = seen.into();
            this
        }
        #[cfg(not(feature = "semantics"))]
        {
            let _ = seen;
            self
        }
    }
}

/// Generates each setter on [`Annotation`] and a forwarding copy on
/// [`Semantic`](crate::Semantic), so the two lists cannot drift.
macro_rules! setters {
    ($(
        $(#[doc = $doc:literal])+
        fn $name:ident($($arg:ident: $ty:ty),*) $(where R: $bound:path)? => |$fields:ident| $body:expr;
    )+) => {
        impl<'a, R: RoleKind> Annotation<'a, R> {
            $(
                $(#[doc = $doc])+
                #[inline]
                pub fn $name(self, $($arg: $ty),*) -> Self $(where R: $bound)? {
                    #[cfg(feature = "semantics")]
                    {
                        let mut this = self;
                        let $fields = &mut this.fields;
                        $body;
                        this
                    }
                    #[cfg(not(feature = "semantics"))]
                    {
                        let _ = ($($arg,)*);
                        self
                    }
                }
            )+
        }

        impl<'a, Message, Theme, Renderer, R: RoleKind>
            crate::semantic::Semantic<'a, Message, Theme, Renderer, R>
        {
            $(
                $(#[doc = $doc])+
                #[inline]
                pub fn $name(self, $($arg: $ty),*) -> Self $(where R: $bound)? {
                    self.map_annotation(|annotation| annotation.$name($($arg),*))
                }
            )+
        }
    };
}

#[cfg(feature = "semantics")]
use icedwright_types::{StateName, StateValue};

#[cfg(feature = "semantics")]
fn add_key(list: &mut Vec<Key>, key: Key) {
    list.push(key);
}

setters! {
    /// The accessible name.
    fn name(name: impl IntoFragment<'a>) => |f| f.name = Some(name.into_fragment());
    /// A longer description.
    fn description(text: impl IntoFragment<'a>) => |f| f.description = Some(text.into_fragment());
    /// The tooltip text, which names an otherwise unnamed node.
    fn tooltip(text: impl IntoFragment<'a>) => |f| f.tooltip = Some(text.into_fragment());
    /// A test id, typed through [`TestId`](crate::TestId) or a string built at run time.
    fn test_id(id: impl IntoTestId<'a>) => |f| {
        f.test_id_path = id.qualified_rust_path();
        f.test_id = Some(id.into_test_id());
    };
    /// What reported the node, for `of_type` and the inspector. `"app"` when unset.
    fn kind(kind: &'static str) => |f| f.kind = Some(kind);
    /// Marks the annotation as a component library's, such as `"iced_cube::tree"`. App
    /// annotations at the same bounds take precedence over it.
    fn component(kind: &'static str) => |f| {
        f.kind = Some(kind);
        f.source = icedwright_protocol::AnnotationSource::Component;
    };
    /// A free-form property, such as a tab's `unsaved`.
    fn prop(key: &'static str, value: impl IntoFragment<'a>) => |f| f.push_prop(key, value.into_fragment());
    /// The text size in logical pixels.
    fn text_size(size: impl Into<Pixels>) => |f| f.text_size = Some(size.into().0);
    /// Which clock counts multiple clicks.
    fn click_clock(clock: ClickClock) => |f| f.push_prop(ClickClock::PROP, Cow::Borrowed(clock.as_str()));
    /// Which clock blinks the caret.
    fn caret_clock(clock: CaretClock) => |f| f.push_prop(CaretClock::PROP, Cow::Borrowed(clock.as_str()));
    /// The node takes no input.
    fn disabled(on: bool) => |f| f.set_state(StateName::Disabled, StateValue::Bool(on));
    /// The current item in a set, such as the open page in a sidebar.
    fn current(on: bool) => |f| f.set_state(StateName::Current, StateValue::Bool(on));
    /// The node is loading or updating.
    fn busy(on: bool) => |f| f.set_state(StateName::Busy, StateValue::Bool(on));
    /// The node is not shown, such as a hover-only control while the pointer is elsewhere.
    fn hidden(on: bool) => |f| f.set_state(StateName::Hidden, StateValue::Bool(on));
    /// Everything outside the node is inert while it is shown.
    fn modal(on: bool) => |f| f.set_state(StateName::Modal, StateValue::Bool(on));
    /// A form control must be filled in.
    fn required(on: bool) => |f| f.set_state(StateName::Required, StateValue::Bool(on));
    /// A form control's value is rejected.
    fn invalid(on: bool) => |f| f.set_state(StateName::Invalid, StateValue::Bool(on));
    /// The node shows a value that cannot be changed.
    fn readonly(on: bool) => |f| f.set_state(StateName::Readonly, StateValue::Bool(on));
    /// The position in its set, counted from 1, and the size of the set.
    fn position(index: u32, of: u32) => |f| f.position = Some((index, of));
    /// The key other annotations use to name this one.
    fn key(key: impl Into<Key>) => |f| f.key = Some(key.into());
    /// The node whose name labels this one.
    fn labelled_by(key: impl Into<Key>) => |f| add_key(&mut f.labelled_by, key.into());
    /// The node this one labels.
    fn label_for(key: impl Into<Key>) => |f| add_key(&mut f.label_for, key.into());
    /// The node whose text describes this one.
    fn described_by(key: impl Into<Key>) => |f| add_key(&mut f.described_by, key.into());
    /// The node this one controls, such as the panel a disclosure button opens.
    fn controls(key: impl Into<Key>) => |f| add_key(&mut f.controls, key.into());
    /// A node that is this one's logical child although it lives elsewhere, such as an
    /// overlay panel.
    fn owns(key: impl Into<Key>) => |f| add_key(&mut f.owns, key.into());
    /// Checked, unchecked or mixed.
    fn checked(state: impl Into<Checked>) where R: Checkable => |f| f.set_state(StateName::Checked, state.into().into());
    /// Whether a toggle button is pressed.
    fn pressed(on: bool) where R: Pressable => |f| f.set_state(StateName::Pressed, StateValue::Bool(on));
    /// Whether the node's content or popup is shown.
    fn expanded(on: bool) where R: Expandable => |f| f.set_state(StateName::Expanded, StateValue::Bool(on));
    /// Whether the item is selected in its container.
    fn selected(on: bool) where R: SelectableItem => |f| f.set_state(StateName::Selected, StateValue::Bool(on));
    /// The nesting level, from 1. A 0 is reported as a tree warning.
    fn level(level: u16) where R: Leveled => |f| f.level = Some(level);
    /// The value as text.
    fn value(text: impl IntoFragment<'a>) where R: HasValue => |f| f.value = Some(fields::ValueField::Text(text.into_fragment()));
    /// A numeric value within a range.
    fn range(now: f64, range: RangeInclusive<f64>) where R: RangeValue => |f| f.value = Some(fields::ValueField::Number {
        now,
        min: *range.start(),
        max: *range.end(),
    });
    /// The distance between neighbouring values of the range, such as 1 for a slider over
    /// whole steps. With it, `set_value` moves a focusable slider with the keyboard and lands
    /// exactly on the value however its steps are placed along the track.
    fn step(step: f64) where R: RangeValue => |f| f.step = Some(step);
    /// The placeholder shown while the value is empty.
    fn placeholder(text: impl IntoFragment<'a>) where R: Editable => |f| f.placeholder = Some(text.into_fragment());
    /// Whether the text box takes more than one line.
    fn multiline(on: bool) where R: Editable => |f| f.set_state(StateName::Multiline, StateValue::Bool(on));
}

/// The question [`report`] asks before it builds an annotation. A recorder sets `wanted`.
#[cfg(feature = "semantics")]
#[derive(Debug, Default)]
pub struct Ask {
    /// Whether the operation wants the annotation.
    pub wanted: bool,
}

/// Reports an annotation for a widget at `bounds` to whatever operation is running.
///
/// It asks first through `Operation::custom` and builds the annotation only when a recorder
/// says yes, so every other operation costs one ignored call. Call it from `operate` before
/// traversing the widget's children. With the `semantics` feature off it does nothing and
/// `build` is never called.
#[inline]
pub fn report<T, R: RoleKind>(
    operation: &mut dyn Operation<T>,
    bounds: Rectangle,
    build: impl FnOnce() -> Annotation<'static, R>,
) {
    #[cfg(feature = "semantics")]
    {
        let mut ask = Ask { wanted: false };
        operation.custom(None, bounds, &mut ask);
        if !ask.wanted {
            return;
        }
        let mut annotation = build().erase();
        operation.custom(None, bounds, &mut annotation);
    }
    #[cfg(not(feature = "semantics"))]
    {
        let _ = (operation, bounds, build);
    }
}