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) 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 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#[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
245type 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 #[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 #[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 #[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 #[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 #[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
358macro_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 fn name(name: impl IntoFragment<'a>) => |f| f.name = Some(name.into_fragment());
411 fn description(text: impl IntoFragment<'a>) => |f| f.description = Some(text.into_fragment());
413 fn tooltip(text: impl IntoFragment<'a>) => |f| f.tooltip = Some(text.into_fragment());
415 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 fn kind(kind: &'static str) => |f| f.kind = Some(kind);
422 fn component(kind: &'static str) => |f| {
425 f.kind = Some(kind);
426 f.source = icedwright_protocol::AnnotationSource::Component;
427 };
428 fn prop(key: &'static str, value: impl IntoFragment<'a>) => |f| f.push_prop(key, value.into_fragment());
430 fn text_size(size: impl Into<Pixels>) => |f| f.text_size = Some(size.into().0);
432 fn click_clock(clock: ClickClock) => |f| f.push_prop(ClickClock::PROP, Cow::Borrowed(clock.as_str()));
434 fn caret_clock(clock: CaretClock) => |f| f.push_prop(CaretClock::PROP, Cow::Borrowed(clock.as_str()));
436 fn disabled(on: bool) => |f| f.set_state(StateName::Disabled, StateValue::Bool(on));
438 fn current(on: bool) => |f| f.set_state(StateName::Current, StateValue::Bool(on));
440 fn busy(on: bool) => |f| f.set_state(StateName::Busy, StateValue::Bool(on));
442 fn hidden(on: bool) => |f| f.set_state(StateName::Hidden, StateValue::Bool(on));
444 fn modal(on: bool) => |f| f.set_state(StateName::Modal, StateValue::Bool(on));
446 fn required(on: bool) => |f| f.set_state(StateName::Required, StateValue::Bool(on));
448 fn invalid(on: bool) => |f| f.set_state(StateName::Invalid, StateValue::Bool(on));
450 fn readonly(on: bool) => |f| f.set_state(StateName::Readonly, StateValue::Bool(on));
452 fn position(index: u32, of: u32) => |f| f.position = Some((index, of));
454 fn key(key: impl Into<Key>) => |f| f.key = Some(key.into());
456 fn labelled_by(key: impl Into<Key>) => |f| add_key(&mut f.labelled_by, key.into());
458 fn label_for(key: impl Into<Key>) => |f| add_key(&mut f.label_for, key.into());
460 fn described_by(key: impl Into<Key>) => |f| add_key(&mut f.described_by, key.into());
462 fn controls(key: impl Into<Key>) => |f| add_key(&mut f.controls, key.into());
464 fn owns(key: impl Into<Key>) => |f| add_key(&mut f.owns, key.into());
467 fn checked(state: impl Into<Checked>) where R: Checkable => |f| f.set_state(StateName::Checked, state.into().into());
469 fn pressed(on: bool) where R: Pressable => |f| f.set_state(StateName::Pressed, StateValue::Bool(on));
471 fn expanded(on: bool) where R: Expandable => |f| f.set_state(StateName::Expanded, StateValue::Bool(on));
473 fn selected(on: bool) where R: SelectableItem => |f| f.set_state(StateName::Selected, StateValue::Bool(on));
475 fn level(level: u16) where R: Leveled => |f| f.level = Some(level);
477 fn value(text: impl IntoFragment<'a>) where R: HasValue => |f| f.value = Some(fields::ValueField::Text(text.into_fragment()));
479 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 fn placeholder(text: impl IntoFragment<'a>) where R: Editable => |f| f.placeholder = Some(text.into_fragment());
487 fn multiline(on: bool) where R: Editable => |f| f.set_state(StateName::Multiline, StateValue::Bool(on));
489}
490
491#[cfg(feature = "semantics")]
493#[derive(Debug, Default)]
494pub struct Ask {
495 pub wanted: bool,
497}
498
499#[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}