Skip to main content

icedwright_probe/
annotation.rs

1//! What an annotation says about a node, and how it reaches the recorder.
2
3use std::borrow::Cow;
4use std::marker::PhantomData;
5use std::ops::RangeInclusive;
6use std::sync::atomic::{AtomicU64, Ordering};
7
8use iced_core::text::IntoFragment;
9use iced_core::widget::Operation;
10use iced_core::{Pixels, Rectangle};
11use icedwright_types::role::{
12    AnyRole, Checkable, Editable, Expandable, HasValue, Leveled, Pressable, RangeValue, RoleKind,
13    RoleType, SelectableItem, Untyped,
14};
15use icedwright_types::{Checked, CursorSeen, Point};
16
17use crate::test_id::IntoTestId;
18
19/// A key one annotation uses to name another in a relation such as `labelled_by` or `owns`.
20#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
21pub enum Key {
22    /// A key the app chose.
23    Name(Cow<'static, str>),
24    /// A key from [`Key::unique`].
25    Unique(u64),
26}
27
28impl Key {
29    /// A key no other call returns, like `iced_core::widget::Id::unique`. Keep it in widget
30    /// state so it survives frames.
31    #[must_use]
32    pub fn unique() -> Self {
33        static NEXT: AtomicU64 = AtomicU64::new(0);
34        Key::Unique(NEXT.fetch_add(1, Ordering::Relaxed))
35    }
36}
37
38impl From<&'static str> for Key {
39    fn from(name: &'static str) -> Self {
40        Key::Name(Cow::Borrowed(name))
41    }
42}
43
44impl From<String> for Key {
45    fn from(name: String) -> Self {
46        Key::Name(Cow::Owned(name))
47    }
48}
49
50/// Whether a widget counts multiple clicks on the virtual clock or through iced's
51/// `mouse::Click`, which reads the real one. Written as the `click-clock` prop.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum ClickClock {
54    /// Counted by `iced_core::mouse::Click`, so double clicks cannot be timed in a test.
55    Iced,
56    /// Counted on `icedwright_probe::time::now`, so a harness can time them.
57    Probe,
58}
59
60/// Whether a widget's caret blinks on the virtual clock or the real one. Written as the
61/// `caret-clock` prop.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub enum CaretClock {
64    /// Blinks on the real clock, as iced's text inputs do.
65    Iced,
66    /// Blinks on `icedwright_probe::time::now`.
67    Probe,
68}
69
70impl ClickClock {
71    /// The prop it is written as.
72    pub const PROP: &'static str = "click-clock";
73
74    /// The prop's value.
75    #[must_use]
76    pub const fn as_str(self) -> &'static str {
77        match self {
78            ClickClock::Iced => "iced",
79            ClickClock::Probe => "probe",
80        }
81    }
82}
83
84impl CaretClock {
85    /// The prop it is written as.
86    pub const PROP: &'static str = "caret-clock";
87
88    /// The prop's value.
89    #[must_use]
90    pub const fn as_str(self) -> &'static str {
91        match self {
92            CaretClock::Iced => "iced",
93            CaretClock::Probe => "probe",
94        }
95    }
96}
97
98#[cfg(feature = "semantics")]
99pub(crate) use fields::Fields;
100
101#[cfg(feature = "semantics")]
102pub(crate) mod fields {
103    use std::borrow::Cow;
104
105    use icedwright_protocol::AnnotationSource;
106    use icedwright_types::{CursorSeen, Point, Role, StateName, StateValue};
107
108    use super::Key;
109    use crate::test_id::TestIdRef;
110
111    /// The states an annotation can set, in the order the recorder writes them.
112    pub(crate) const STATES: [StateName; 13] = [
113        StateName::Disabled,
114        StateName::Readonly,
115        StateName::Checked,
116        StateName::Pressed,
117        StateName::Expanded,
118        StateName::Selected,
119        StateName::Current,
120        StateName::Busy,
121        StateName::Required,
122        StateName::Invalid,
123        StateName::Multiline,
124        StateName::Modal,
125        StateName::Hidden,
126    ];
127
128    #[derive(Debug, Clone, PartialEq)]
129    pub(crate) enum ValueField<'a> {
130        Text(Cow<'a, str>),
131        Number { now: f64, min: f64, max: f64 },
132    }
133
134    /// Every field, borrowing strings from the view so building one allocates nothing.
135    #[derive(Debug, Clone, PartialEq, Default)]
136    pub(crate) struct Fields<'a> {
137        pub(crate) source: AnnotationSource,
138        pub(crate) role: Option<Role>,
139        pub(crate) name: Option<Cow<'a, str>>,
140        pub(crate) description: Option<Cow<'a, str>>,
141        pub(crate) tooltip: Option<Cow<'a, str>>,
142        pub(crate) placeholder: Option<Cow<'a, str>>,
143        pub(crate) value: Option<ValueField<'a>>,
144        pub(crate) step: Option<f64>,
145        pub(crate) test_id: Option<TestIdRef<'a>>,
146        pub(crate) test_id_path: Option<&'static str>,
147        pub(crate) kind: Option<&'static str>,
148        pub(crate) props: Vec<(&'static str, Cow<'a, str>)>,
149        pub(crate) text_size: Option<f32>,
150        pub(crate) states: [Option<StateValue>; STATES.len()],
151        pub(crate) level: Option<u16>,
152        pub(crate) position: Option<(u32, u32)>,
153        pub(crate) key: Option<Key>,
154        pub(crate) labelled_by: Vec<Key>,
155        pub(crate) label_for: Vec<Key>,
156        pub(crate) described_by: Vec<Key>,
157        pub(crate) controls: Vec<Key>,
158        pub(crate) owns: Vec<Key>,
159        pub(crate) carets: Vec<(usize, Point)>,
160        pub(crate) cursor_seen: Option<CursorSeen>,
161    }
162
163    fn owned(text: &Option<Cow<'_, str>>) -> Option<Cow<'static, str>> {
164        text.as_ref().map(|t| Cow::Owned(t.clone().into_owned()))
165    }
166
167    impl Fields<'_> {
168        pub(crate) fn set_state(&mut self, name: StateName, value: StateValue) {
169            if let Some(slot) = STATES
170                .iter()
171                .position(|s| *s == name)
172                .and_then(|i| self.states.get_mut(i))
173            {
174                *slot = Some(value);
175            }
176        }
177
178        pub(crate) fn to_static(&self) -> Fields<'static> {
179            Fields {
180                source: self.source,
181                role: self.role,
182                name: owned(&self.name),
183                description: owned(&self.description),
184                tooltip: owned(&self.tooltip),
185                placeholder: owned(&self.placeholder),
186                value: self.value.as_ref().map(|value| match value {
187                    ValueField::Text(text) => {
188                        ValueField::Text(Cow::Owned(text.clone().into_owned()))
189                    }
190                    ValueField::Number { now, min, max } => ValueField::Number {
191                        now: *now,
192                        min: *min,
193                        max: *max,
194                    },
195                }),
196                step: self.step,
197                test_id: self.test_id.clone().map(TestIdRef::into_static),
198                test_id_path: self.test_id_path,
199                kind: self.kind,
200                props: self
201                    .props
202                    .iter()
203                    .map(|(k, v)| (*k, Cow::Owned(v.clone().into_owned())))
204                    .collect(),
205                text_size: self.text_size,
206                states: self.states,
207                level: self.level,
208                position: self.position,
209                key: self.key.clone(),
210                labelled_by: self.labelled_by.clone(),
211                label_for: self.label_for.clone(),
212                described_by: self.described_by.clone(),
213                controls: self.controls.clone(),
214                owns: self.owns.clone(),
215                carets: self.carets.clone(),
216                cursor_seen: self.cursor_seen,
217            }
218        }
219    }
220
221    /// Props keep borrowed values borrowed until `to_static`.
222    impl<'a> Fields<'a> {
223        pub(crate) fn push_prop(&mut self, key: &'static str, value: Cow<'a, str>) {
224            self.props.retain(|(k, _)| *k != key);
225            self.props.push((key, value));
226        }
227    }
228}
229
230/// What an annotation says about a node: its role, name, states and relations.
231///
232/// The role is part of the type, starting at [`AnyRole`]. [`Annotation::role`] moves it to a
233/// concrete role once, and the setters for capability states compile only for roles with that
234/// capability, so `.checked(..)` on a button is a type error.
235///
236/// Apps build these through [`semantic`](crate::semantic). Widget authors who write their own
237/// `operate` build one with [`Annotation::new`] and send it with [`report`].
238///
239/// With the `semantics` feature off it holds nothing and every method does nothing.
240#[must_use = "an Annotation does nothing until it is reported"]
241pub struct Annotation<'a, R: RoleKind = AnyRole> {
242    #[cfg(feature = "semantics")]
243    pub(crate) fields: Fields<'a>,
244    marker: Marker<'a, R>,
245}
246
247/// Carries the role type and the view's lifetime without owning either.
248type Marker<'a, R> = PhantomData<(fn() -> R, &'a ())>;
249
250impl<R: RoleKind> std::fmt::Debug for Annotation<'_, R> {
251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252        let mut out = f.debug_struct("Annotation");
253        out.field("role_type", &R::default());
254        #[cfg(feature = "semantics")]
255        out.field("fields", &self.fields);
256        out.finish()
257    }
258}
259
260impl<R: RoleKind> Clone for Annotation<'_, R> {
261    fn clone(&self) -> Self {
262        Self {
263            #[cfg(feature = "semantics")]
264            fields: self.fields.clone(),
265            marker: PhantomData,
266        }
267    }
268}
269
270impl Default for Annotation<'_, AnyRole> {
271    fn default() -> Self {
272        Self::new()
273    }
274}
275
276impl Annotation<'_, AnyRole> {
277    /// An annotation with nothing set.
278    #[inline]
279    pub fn new() -> Self {
280        Self {
281            #[cfg(feature = "semantics")]
282            fields: Fields::default(),
283            marker: PhantomData,
284        }
285    }
286}
287
288impl<'a, R: RoleKind> Annotation<'a, R> {
289    /// Gives the node a role. Only once: a second call does not compile.
290    #[inline]
291    pub fn role<R2: RoleType>(self, role: R2) -> Annotation<'a, R2>
292    where
293        R: Untyped,
294    {
295        let _ = role;
296        Annotation {
297            #[cfg(feature = "semantics")]
298            fields: Fields {
299                role: Some(R2::ROLE_VALUE),
300                ..self.fields
301            },
302            marker: PhantomData,
303        }
304    }
305
306    /// The same annotation with its strings owned and its role type erased, which is what
307    /// [`report`] sends.
308    #[inline]
309    pub fn to_static(&self) -> Annotation<'static, AnyRole> {
310        Annotation {
311            #[cfg(feature = "semantics")]
312            fields: self.fields.to_static(),
313            marker: PhantomData,
314        }
315    }
316
317    #[cfg(feature = "semantics")]
318    fn erase(self) -> Annotation<'a, AnyRole> {
319        Annotation {
320            fields: self.fields,
321            marker: PhantomData,
322        }
323    }
324
325    /// The caret position of each byte offset, for widgets that draw editable or selectable
326    /// text. Sorted by offset when recorded.
327    #[inline]
328    pub fn text_geometry(self, carets: impl IntoIterator<Item = (usize, Point)>) -> Self {
329        #[cfg(feature = "semantics")]
330        {
331            let mut this = self;
332            this.fields.carets = carets.into_iter().collect();
333            this.fields.carets.sort_by_key(|(offset, _)| *offset);
334            this
335        }
336        #[cfg(not(feature = "semantics"))]
337        {
338            let _ = carets;
339            self
340        }
341    }
342
343    /// The kind of cursor the widget was handed for its last mouse event this frame.
344    #[inline]
345    pub fn cursor_seen(self, seen: impl Into<Option<CursorSeen>>) -> Self {
346        #[cfg(feature = "semantics")]
347        {
348            let mut this = self;
349            this.fields.cursor_seen = seen.into();
350            this
351        }
352        #[cfg(not(feature = "semantics"))]
353        {
354            let _ = seen;
355            self
356        }
357    }
358}
359
360/// Generates each setter on [`Annotation`] and a forwarding copy on
361/// [`Semantic`](crate::Semantic), so the two lists cannot drift.
362macro_rules! setters {
363    ($(
364        $(#[doc = $doc:literal])+
365        fn $name:ident($($arg:ident: $ty:ty),*) $(where R: $bound:path)? => |$fields:ident| $body:expr;
366    )+) => {
367        impl<'a, R: RoleKind> Annotation<'a, R> {
368            $(
369                $(#[doc = $doc])+
370                #[inline]
371                pub fn $name(self, $($arg: $ty),*) -> Self $(where R: $bound)? {
372                    #[cfg(feature = "semantics")]
373                    {
374                        let mut this = self;
375                        let $fields = &mut this.fields;
376                        $body;
377                        this
378                    }
379                    #[cfg(not(feature = "semantics"))]
380                    {
381                        let _ = ($($arg,)*);
382                        self
383                    }
384                }
385            )+
386        }
387
388        impl<'a, Message, Theme, Renderer, R: RoleKind>
389            crate::semantic::Semantic<'a, Message, Theme, Renderer, R>
390        {
391            $(
392                $(#[doc = $doc])+
393                #[inline]
394                pub fn $name(self, $($arg: $ty),*) -> Self $(where R: $bound)? {
395                    self.map_annotation(|annotation| annotation.$name($($arg),*))
396                }
397            )+
398        }
399    };
400}
401
402#[cfg(feature = "semantics")]
403use icedwright_types::{StateName, StateValue};
404
405#[cfg(feature = "semantics")]
406fn add_key(list: &mut Vec<Key>, key: Key) {
407    list.push(key);
408}
409
410setters! {
411    /// The accessible name.
412    fn name(name: impl IntoFragment<'a>) => |f| f.name = Some(name.into_fragment());
413    /// A longer description.
414    fn description(text: impl IntoFragment<'a>) => |f| f.description = Some(text.into_fragment());
415    /// The tooltip text, which names an otherwise unnamed node.
416    fn tooltip(text: impl IntoFragment<'a>) => |f| f.tooltip = Some(text.into_fragment());
417    /// A test id, typed through [`TestId`](crate::TestId) or a string built at run time.
418    fn test_id(id: impl IntoTestId<'a>) => |f| {
419        f.test_id_path = id.qualified_rust_path();
420        f.test_id = Some(id.into_test_id());
421    };
422    /// What reported the node, for `of_type` and the inspector. `"app"` when unset.
423    fn kind(kind: &'static str) => |f| f.kind = Some(kind);
424    /// Marks the annotation as a component library's, such as `"iced_cube::tree"`. App
425    /// annotations at the same bounds take precedence over it.
426    fn component(kind: &'static str) => |f| {
427        f.kind = Some(kind);
428        f.source = icedwright_protocol::AnnotationSource::Component;
429    };
430    /// A free-form property, such as a tab's `unsaved`.
431    fn prop(key: &'static str, value: impl IntoFragment<'a>) => |f| f.push_prop(key, value.into_fragment());
432    /// The text size in logical pixels.
433    fn text_size(size: impl Into<Pixels>) => |f| f.text_size = Some(size.into().0);
434    /// Which clock counts multiple clicks.
435    fn click_clock(clock: ClickClock) => |f| f.push_prop(ClickClock::PROP, Cow::Borrowed(clock.as_str()));
436    /// Which clock blinks the caret.
437    fn caret_clock(clock: CaretClock) => |f| f.push_prop(CaretClock::PROP, Cow::Borrowed(clock.as_str()));
438    /// The node takes no input.
439    fn disabled(on: bool) => |f| f.set_state(StateName::Disabled, StateValue::Bool(on));
440    /// The current item in a set, such as the open page in a sidebar.
441    fn current(on: bool) => |f| f.set_state(StateName::Current, StateValue::Bool(on));
442    /// The node is loading or updating.
443    fn busy(on: bool) => |f| f.set_state(StateName::Busy, StateValue::Bool(on));
444    /// The node is not shown, such as a hover-only control while the pointer is elsewhere.
445    fn hidden(on: bool) => |f| f.set_state(StateName::Hidden, StateValue::Bool(on));
446    /// Everything outside the node is inert while it is shown.
447    fn modal(on: bool) => |f| f.set_state(StateName::Modal, StateValue::Bool(on));
448    /// A form control must be filled in.
449    fn required(on: bool) => |f| f.set_state(StateName::Required, StateValue::Bool(on));
450    /// A form control's value is rejected.
451    fn invalid(on: bool) => |f| f.set_state(StateName::Invalid, StateValue::Bool(on));
452    /// The node shows a value that cannot be changed.
453    fn readonly(on: bool) => |f| f.set_state(StateName::Readonly, StateValue::Bool(on));
454    /// The position in its set, counted from 1, and the size of the set.
455    fn position(index: u32, of: u32) => |f| f.position = Some((index, of));
456    /// The key other annotations use to name this one.
457    fn key(key: impl Into<Key>) => |f| f.key = Some(key.into());
458    /// The node whose name labels this one.
459    fn labelled_by(key: impl Into<Key>) => |f| add_key(&mut f.labelled_by, key.into());
460    /// The node this one labels.
461    fn label_for(key: impl Into<Key>) => |f| add_key(&mut f.label_for, key.into());
462    /// The node whose text describes this one.
463    fn described_by(key: impl Into<Key>) => |f| add_key(&mut f.described_by, key.into());
464    /// The node this one controls, such as the panel a disclosure button opens.
465    fn controls(key: impl Into<Key>) => |f| add_key(&mut f.controls, key.into());
466    /// A node that is this one's logical child although it lives elsewhere, such as an
467    /// overlay panel.
468    fn owns(key: impl Into<Key>) => |f| add_key(&mut f.owns, key.into());
469    /// Checked, unchecked or mixed.
470    fn checked(state: impl Into<Checked>) where R: Checkable => |f| f.set_state(StateName::Checked, state.into().into());
471    /// Whether a toggle button is pressed.
472    fn pressed(on: bool) where R: Pressable => |f| f.set_state(StateName::Pressed, StateValue::Bool(on));
473    /// Whether the node's content or popup is shown.
474    fn expanded(on: bool) where R: Expandable => |f| f.set_state(StateName::Expanded, StateValue::Bool(on));
475    /// Whether the item is selected in its container.
476    fn selected(on: bool) where R: SelectableItem => |f| f.set_state(StateName::Selected, StateValue::Bool(on));
477    /// The nesting level, from 1. A 0 is reported as a tree warning.
478    fn level(level: u16) where R: Leveled => |f| f.level = Some(level);
479    /// The value as text.
480    fn value(text: impl IntoFragment<'a>) where R: HasValue => |f| f.value = Some(fields::ValueField::Text(text.into_fragment()));
481    /// A numeric value within a range.
482    fn range(now: f64, range: RangeInclusive<f64>) where R: RangeValue => |f| f.value = Some(fields::ValueField::Number {
483        now,
484        min: *range.start(),
485        max: *range.end(),
486    });
487    /// The distance between neighbouring values of the range, such as 1 for a slider over
488    /// whole steps. With it, `set_value` moves a focusable slider with the keyboard and lands
489    /// exactly on the value however its steps are placed along the track.
490    fn step(step: f64) where R: RangeValue => |f| f.step = Some(step);
491    /// The placeholder shown while the value is empty.
492    fn placeholder(text: impl IntoFragment<'a>) where R: Editable => |f| f.placeholder = Some(text.into_fragment());
493    /// Whether the text box takes more than one line.
494    fn multiline(on: bool) where R: Editable => |f| f.set_state(StateName::Multiline, StateValue::Bool(on));
495}
496
497/// The question [`report`] asks before it builds an annotation. A recorder sets `wanted`.
498#[cfg(feature = "semantics")]
499#[derive(Debug, Default)]
500pub struct Ask {
501    /// Whether the operation wants the annotation.
502    pub wanted: bool,
503}
504
505/// Reports an annotation for a widget at `bounds` to whatever operation is running.
506///
507/// It asks first through `Operation::custom` and builds the annotation only when a recorder
508/// says yes, so every other operation costs one ignored call. Call it from `operate` before
509/// traversing the widget's children. With the `semantics` feature off it does nothing and
510/// `build` is never called.
511#[inline]
512pub fn report<T, R: RoleKind>(
513    operation: &mut dyn Operation<T>,
514    bounds: Rectangle,
515    build: impl FnOnce() -> Annotation<'static, R>,
516) {
517    #[cfg(feature = "semantics")]
518    {
519        let mut ask = Ask { wanted: false };
520        operation.custom(None, bounds, &mut ask);
521        if !ask.wanted {
522            return;
523        }
524        let mut annotation = build().erase();
525        operation.custom(None, bounds, &mut annotation);
526    }
527    #[cfg(not(feature = "semantics"))]
528    {
529        let _ = (operation, bounds, build);
530    }
531}