1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
21pub enum Key {
22 Name(Cow<'static, str>),
24 Unique(u64),
26}
27
28impl Key {
29 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum ClickClock {
54 Iced,
56 Probe,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub enum CaretClock {
64 Iced,
66 Probe,
68}
69
70impl ClickClock {
71 pub const PROP: &'static str = "click-clock";
73
74 #[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 pub const PROP: &'static str = "caret-clock";
87
88 #[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 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 #[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 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#[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
247type 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 #[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 #[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 #[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 #[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 #[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
360macro_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 fn name(name: impl IntoFragment<'a>) => |f| f.name = Some(name.into_fragment());
413 fn description(text: impl IntoFragment<'a>) => |f| f.description = Some(text.into_fragment());
415 fn tooltip(text: impl IntoFragment<'a>) => |f| f.tooltip = Some(text.into_fragment());
417 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 fn kind(kind: &'static str) => |f| f.kind = Some(kind);
424 fn component(kind: &'static str) => |f| {
427 f.kind = Some(kind);
428 f.source = icedwright_protocol::AnnotationSource::Component;
429 };
430 fn prop(key: &'static str, value: impl IntoFragment<'a>) => |f| f.push_prop(key, value.into_fragment());
432 fn text_size(size: impl Into<Pixels>) => |f| f.text_size = Some(size.into().0);
434 fn click_clock(clock: ClickClock) => |f| f.push_prop(ClickClock::PROP, Cow::Borrowed(clock.as_str()));
436 fn caret_clock(clock: CaretClock) => |f| f.push_prop(CaretClock::PROP, Cow::Borrowed(clock.as_str()));
438 fn disabled(on: bool) => |f| f.set_state(StateName::Disabled, StateValue::Bool(on));
440 fn current(on: bool) => |f| f.set_state(StateName::Current, StateValue::Bool(on));
442 fn busy(on: bool) => |f| f.set_state(StateName::Busy, StateValue::Bool(on));
444 fn hidden(on: bool) => |f| f.set_state(StateName::Hidden, StateValue::Bool(on));
446 fn modal(on: bool) => |f| f.set_state(StateName::Modal, StateValue::Bool(on));
448 fn required(on: bool) => |f| f.set_state(StateName::Required, StateValue::Bool(on));
450 fn invalid(on: bool) => |f| f.set_state(StateName::Invalid, StateValue::Bool(on));
452 fn readonly(on: bool) => |f| f.set_state(StateName::Readonly, StateValue::Bool(on));
454 fn position(index: u32, of: u32) => |f| f.position = Some((index, of));
456 fn key(key: impl Into<Key>) => |f| f.key = Some(key.into());
458 fn labelled_by(key: impl Into<Key>) => |f| add_key(&mut f.labelled_by, key.into());
460 fn label_for(key: impl Into<Key>) => |f| add_key(&mut f.label_for, key.into());
462 fn described_by(key: impl Into<Key>) => |f| add_key(&mut f.described_by, key.into());
464 fn controls(key: impl Into<Key>) => |f| add_key(&mut f.controls, key.into());
466 fn owns(key: impl Into<Key>) => |f| add_key(&mut f.owns, key.into());
469 fn checked(state: impl Into<Checked>) where R: Checkable => |f| f.set_state(StateName::Checked, state.into().into());
471 fn pressed(on: bool) where R: Pressable => |f| f.set_state(StateName::Pressed, StateValue::Bool(on));
473 fn expanded(on: bool) where R: Expandable => |f| f.set_state(StateName::Expanded, StateValue::Bool(on));
475 fn selected(on: bool) where R: SelectableItem => |f| f.set_state(StateName::Selected, StateValue::Bool(on));
477 fn level(level: u16) where R: Leveled => |f| f.level = Some(level);
479 fn value(text: impl IntoFragment<'a>) where R: HasValue => |f| f.value = Some(fields::ValueField::Text(text.into_fragment()));
481 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 fn step(step: f64) where R: RangeValue => |f| f.step = Some(step);
491 fn placeholder(text: impl IntoFragment<'a>) where R: Editable => |f| f.placeholder = Some(text.into_fragment());
493 fn multiline(on: bool) where R: Editable => |f| f.set_state(StateName::Multiline, StateValue::Bool(on));
495}
496
497#[cfg(feature = "semantics")]
499#[derive(Debug, Default)]
500pub struct Ask {
501 pub wanted: bool,
503}
504
505#[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}