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) test_id: Option<TestIdRef<'a>>,
145        pub(crate) test_id_path: Option<&'static str>,
146        pub(crate) kind: Option<&'static str>,
147        pub(crate) props: Vec<(&'static str, Cow<'a, str>)>,
148        pub(crate) text_size: Option<f32>,
149        pub(crate) states: [Option<StateValue>; STATES.len()],
150        pub(crate) level: Option<u16>,
151        pub(crate) position: Option<(u32, u32)>,
152        pub(crate) key: Option<Key>,
153        pub(crate) labelled_by: Vec<Key>,
154        pub(crate) label_for: Vec<Key>,
155        pub(crate) described_by: Vec<Key>,
156        pub(crate) controls: Vec<Key>,
157        pub(crate) owns: Vec<Key>,
158        pub(crate) carets: Vec<(usize, Point)>,
159        pub(crate) cursor_seen: Option<CursorSeen>,
160    }
161
162    fn owned(text: &Option<Cow<'_, str>>) -> Option<Cow<'static, str>> {
163        text.as_ref().map(|t| Cow::Owned(t.clone().into_owned()))
164    }
165
166    impl Fields<'_> {
167        pub(crate) fn set_state(&mut self, name: StateName, value: StateValue) {
168            if let Some(slot) = STATES
169                .iter()
170                .position(|s| *s == name)
171                .and_then(|i| self.states.get_mut(i))
172            {
173                *slot = Some(value);
174            }
175        }
176
177        pub(crate) fn to_static(&self) -> Fields<'static> {
178            Fields {
179                source: self.source,
180                role: self.role,
181                name: owned(&self.name),
182                description: owned(&self.description),
183                tooltip: owned(&self.tooltip),
184                placeholder: owned(&self.placeholder),
185                value: self.value.as_ref().map(|value| match value {
186                    ValueField::Text(text) => {
187                        ValueField::Text(Cow::Owned(text.clone().into_owned()))
188                    }
189                    ValueField::Number { now, min, max } => ValueField::Number {
190                        now: *now,
191                        min: *min,
192                        max: *max,
193                    },
194                }),
195                test_id: self.test_id.clone().map(TestIdRef::into_static),
196                test_id_path: self.test_id_path,
197                kind: self.kind,
198                props: self
199                    .props
200                    .iter()
201                    .map(|(k, v)| (*k, Cow::Owned(v.clone().into_owned())))
202                    .collect(),
203                text_size: self.text_size,
204                states: self.states,
205                level: self.level,
206                position: self.position,
207                key: self.key.clone(),
208                labelled_by: self.labelled_by.clone(),
209                label_for: self.label_for.clone(),
210                described_by: self.described_by.clone(),
211                controls: self.controls.clone(),
212                owns: self.owns.clone(),
213                carets: self.carets.clone(),
214                cursor_seen: self.cursor_seen,
215            }
216        }
217    }
218
219    /// Props keep borrowed values borrowed until `to_static`.
220    impl<'a> Fields<'a> {
221        pub(crate) fn push_prop(&mut self, key: &'static str, value: Cow<'a, str>) {
222            self.props.retain(|(k, _)| *k != key);
223            self.props.push((key, value));
224        }
225    }
226}
227
228/// What an annotation says about a node: its role, name, states and relations.
229///
230/// The role is part of the type, starting at [`AnyRole`]. [`Annotation::role`] moves it to a
231/// concrete role once, and the setters for capability states compile only for roles with that
232/// capability, so `.checked(..)` on a button is a type error.
233///
234/// Apps build these through [`semantic`](crate::semantic). Widget authors who write their own
235/// `operate` build one with [`Annotation::new`] and send it with [`report`].
236///
237/// With the `semantics` feature off it holds nothing and every method does nothing.
238#[must_use = "an Annotation does nothing until it is reported"]
239pub struct Annotation<'a, R: RoleKind = AnyRole> {
240    #[cfg(feature = "semantics")]
241    pub(crate) fields: Fields<'a>,
242    marker: Marker<'a, R>,
243}
244
245/// Carries the role type and the view's lifetime without owning either.
246type Marker<'a, R> = PhantomData<(fn() -> R, &'a ())>;
247
248impl<R: RoleKind> std::fmt::Debug for Annotation<'_, R> {
249    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250        let mut out = f.debug_struct("Annotation");
251        out.field("role_type", &R::default());
252        #[cfg(feature = "semantics")]
253        out.field("fields", &self.fields);
254        out.finish()
255    }
256}
257
258impl<R: RoleKind> Clone for Annotation<'_, R> {
259    fn clone(&self) -> Self {
260        Self {
261            #[cfg(feature = "semantics")]
262            fields: self.fields.clone(),
263            marker: PhantomData,
264        }
265    }
266}
267
268impl Default for Annotation<'_, AnyRole> {
269    fn default() -> Self {
270        Self::new()
271    }
272}
273
274impl Annotation<'_, AnyRole> {
275    /// An annotation with nothing set.
276    #[inline]
277    pub fn new() -> Self {
278        Self {
279            #[cfg(feature = "semantics")]
280            fields: Fields::default(),
281            marker: PhantomData,
282        }
283    }
284}
285
286impl<'a, R: RoleKind> Annotation<'a, R> {
287    /// Gives the node a role. Only once: a second call does not compile.
288    #[inline]
289    pub fn role<R2: RoleType>(self, role: R2) -> Annotation<'a, R2>
290    where
291        R: Untyped,
292    {
293        let _ = role;
294        Annotation {
295            #[cfg(feature = "semantics")]
296            fields: Fields {
297                role: Some(R2::ROLE_VALUE),
298                ..self.fields
299            },
300            marker: PhantomData,
301        }
302    }
303
304    /// The same annotation with its strings owned and its role type erased, which is what
305    /// [`report`] sends.
306    #[inline]
307    pub fn to_static(&self) -> Annotation<'static, AnyRole> {
308        Annotation {
309            #[cfg(feature = "semantics")]
310            fields: self.fields.to_static(),
311            marker: PhantomData,
312        }
313    }
314
315    #[cfg(feature = "semantics")]
316    fn erase(self) -> Annotation<'a, AnyRole> {
317        Annotation {
318            fields: self.fields,
319            marker: PhantomData,
320        }
321    }
322
323    /// The caret position of each byte offset, for widgets that draw editable or selectable
324    /// text. Sorted by offset when recorded.
325    #[inline]
326    pub fn text_geometry(self, carets: impl IntoIterator<Item = (usize, Point)>) -> Self {
327        #[cfg(feature = "semantics")]
328        {
329            let mut this = self;
330            this.fields.carets = carets.into_iter().collect();
331            this.fields.carets.sort_by_key(|(offset, _)| *offset);
332            this
333        }
334        #[cfg(not(feature = "semantics"))]
335        {
336            let _ = carets;
337            self
338        }
339    }
340
341    /// The kind of cursor the widget was handed for its last mouse event this frame.
342    #[inline]
343    pub fn cursor_seen(self, seen: impl Into<Option<CursorSeen>>) -> Self {
344        #[cfg(feature = "semantics")]
345        {
346            let mut this = self;
347            this.fields.cursor_seen = seen.into();
348            this
349        }
350        #[cfg(not(feature = "semantics"))]
351        {
352            let _ = seen;
353            self
354        }
355    }
356}
357
358/// Generates each setter on [`Annotation`] and a forwarding copy on
359/// [`Semantic`](crate::Semantic), so the two lists cannot drift.
360macro_rules! setters {
361    ($(
362        $(#[doc = $doc:literal])+
363        fn $name:ident($($arg:ident: $ty:ty),*) $(where R: $bound:path)? => |$fields:ident| $body:expr;
364    )+) => {
365        impl<'a, R: RoleKind> Annotation<'a, R> {
366            $(
367                $(#[doc = $doc])+
368                #[inline]
369                pub fn $name(self, $($arg: $ty),*) -> Self $(where R: $bound)? {
370                    #[cfg(feature = "semantics")]
371                    {
372                        let mut this = self;
373                        let $fields = &mut this.fields;
374                        $body;
375                        this
376                    }
377                    #[cfg(not(feature = "semantics"))]
378                    {
379                        let _ = ($($arg,)*);
380                        self
381                    }
382                }
383            )+
384        }
385
386        impl<'a, Message, Theme, Renderer, R: RoleKind>
387            crate::semantic::Semantic<'a, Message, Theme, Renderer, R>
388        {
389            $(
390                $(#[doc = $doc])+
391                #[inline]
392                pub fn $name(self, $($arg: $ty),*) -> Self $(where R: $bound)? {
393                    self.map_annotation(|annotation| annotation.$name($($arg),*))
394                }
395            )+
396        }
397    };
398}
399
400#[cfg(feature = "semantics")]
401use icedwright_types::{StateName, StateValue};
402
403#[cfg(feature = "semantics")]
404fn add_key(list: &mut Vec<Key>, key: Key) {
405    list.push(key);
406}
407
408setters! {
409    /// The accessible name.
410    fn name(name: impl IntoFragment<'a>) => |f| f.name = Some(name.into_fragment());
411    /// A longer description.
412    fn description(text: impl IntoFragment<'a>) => |f| f.description = Some(text.into_fragment());
413    /// The tooltip text, which names an otherwise unnamed node.
414    fn tooltip(text: impl IntoFragment<'a>) => |f| f.tooltip = Some(text.into_fragment());
415    /// A test id, typed through [`TestId`](crate::TestId) or a string built at run time.
416    fn test_id(id: impl IntoTestId<'a>) => |f| {
417        f.test_id_path = id.qualified_rust_path();
418        f.test_id = Some(id.into_test_id());
419    };
420    /// What reported the node, for `of_type` and the inspector. `"app"` when unset.
421    fn kind(kind: &'static str) => |f| f.kind = Some(kind);
422    /// Marks the annotation as a component library's, such as `"iced_cube::tree"`. App
423    /// annotations at the same bounds take precedence over it.
424    fn component(kind: &'static str) => |f| {
425        f.kind = Some(kind);
426        f.source = icedwright_protocol::AnnotationSource::Component;
427    };
428    /// A free-form property, such as a tab's `unsaved`.
429    fn prop(key: &'static str, value: impl IntoFragment<'a>) => |f| f.push_prop(key, value.into_fragment());
430    /// The text size in logical pixels.
431    fn text_size(size: impl Into<Pixels>) => |f| f.text_size = Some(size.into().0);
432    /// Which clock counts multiple clicks.
433    fn click_clock(clock: ClickClock) => |f| f.push_prop(ClickClock::PROP, Cow::Borrowed(clock.as_str()));
434    /// Which clock blinks the caret.
435    fn caret_clock(clock: CaretClock) => |f| f.push_prop(CaretClock::PROP, Cow::Borrowed(clock.as_str()));
436    /// The node takes no input.
437    fn disabled(on: bool) => |f| f.set_state(StateName::Disabled, StateValue::Bool(on));
438    /// The current item in a set, such as the open page in a sidebar.
439    fn current(on: bool) => |f| f.set_state(StateName::Current, StateValue::Bool(on));
440    /// The node is loading or updating.
441    fn busy(on: bool) => |f| f.set_state(StateName::Busy, StateValue::Bool(on));
442    /// The node is not shown, such as a hover-only control while the pointer is elsewhere.
443    fn hidden(on: bool) => |f| f.set_state(StateName::Hidden, StateValue::Bool(on));
444    /// Everything outside the node is inert while it is shown.
445    fn modal(on: bool) => |f| f.set_state(StateName::Modal, StateValue::Bool(on));
446    /// A form control must be filled in.
447    fn required(on: bool) => |f| f.set_state(StateName::Required, StateValue::Bool(on));
448    /// A form control's value is rejected.
449    fn invalid(on: bool) => |f| f.set_state(StateName::Invalid, StateValue::Bool(on));
450    /// The node shows a value that cannot be changed.
451    fn readonly(on: bool) => |f| f.set_state(StateName::Readonly, StateValue::Bool(on));
452    /// The position in its set, counted from 1, and the size of the set.
453    fn position(index: u32, of: u32) => |f| f.position = Some((index, of));
454    /// The key other annotations use to name this one.
455    fn key(key: impl Into<Key>) => |f| f.key = Some(key.into());
456    /// The node whose name labels this one.
457    fn labelled_by(key: impl Into<Key>) => |f| add_key(&mut f.labelled_by, key.into());
458    /// The node this one labels.
459    fn label_for(key: impl Into<Key>) => |f| add_key(&mut f.label_for, key.into());
460    /// The node whose text describes this one.
461    fn described_by(key: impl Into<Key>) => |f| add_key(&mut f.described_by, key.into());
462    /// The node this one controls, such as the panel a disclosure button opens.
463    fn controls(key: impl Into<Key>) => |f| add_key(&mut f.controls, key.into());
464    /// A node that is this one's logical child although it lives elsewhere, such as an
465    /// overlay panel.
466    fn owns(key: impl Into<Key>) => |f| add_key(&mut f.owns, key.into());
467    /// Checked, unchecked or mixed.
468    fn checked(state: impl Into<Checked>) where R: Checkable => |f| f.set_state(StateName::Checked, state.into().into());
469    /// Whether a toggle button is pressed.
470    fn pressed(on: bool) where R: Pressable => |f| f.set_state(StateName::Pressed, StateValue::Bool(on));
471    /// Whether the node's content or popup is shown.
472    fn expanded(on: bool) where R: Expandable => |f| f.set_state(StateName::Expanded, StateValue::Bool(on));
473    /// Whether the item is selected in its container.
474    fn selected(on: bool) where R: SelectableItem => |f| f.set_state(StateName::Selected, StateValue::Bool(on));
475    /// The nesting level, from 1. A 0 is reported as a tree warning.
476    fn level(level: u16) where R: Leveled => |f| f.level = Some(level);
477    /// The value as text.
478    fn value(text: impl IntoFragment<'a>) where R: HasValue => |f| f.value = Some(fields::ValueField::Text(text.into_fragment()));
479    /// A numeric value within a range.
480    fn range(now: f64, range: RangeInclusive<f64>) where R: RangeValue => |f| f.value = Some(fields::ValueField::Number {
481        now,
482        min: *range.start(),
483        max: *range.end(),
484    });
485    /// The placeholder shown while the value is empty.
486    fn placeholder(text: impl IntoFragment<'a>) where R: Editable => |f| f.placeholder = Some(text.into_fragment());
487    /// Whether the text box takes more than one line.
488    fn multiline(on: bool) where R: Editable => |f| f.set_state(StateName::Multiline, StateValue::Bool(on));
489}
490
491/// The question [`report`] asks before it builds an annotation. A recorder sets `wanted`.
492#[cfg(feature = "semantics")]
493#[derive(Debug, Default)]
494pub struct Ask {
495    /// Whether the operation wants the annotation.
496    pub wanted: bool,
497}
498
499/// Reports an annotation for a widget at `bounds` to whatever operation is running.
500///
501/// It asks first through `Operation::custom` and builds the annotation only when a recorder
502/// says yes, so every other operation costs one ignored call. Call it from `operate` before
503/// traversing the widget's children. With the `semantics` feature off it does nothing and
504/// `build` is never called.
505#[inline]
506pub fn report<T, R: RoleKind>(
507    operation: &mut dyn Operation<T>,
508    bounds: Rectangle,
509    build: impl FnOnce() -> Annotation<'static, R>,
510) {
511    #[cfg(feature = "semantics")]
512    {
513        let mut ask = Ask { wanted: false };
514        operation.custom(None, bounds, &mut ask);
515        if !ask.wanted {
516            return;
517        }
518        let mut annotation = build().erase();
519        operation.custom(None, bounds, &mut annotation);
520    }
521    #[cfg(not(feature = "semantics"))]
522    {
523        let _ = (operation, bounds, build);
524    }
525}