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;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Key {
Name(Cow<'static, str>),
Unique(u64),
}
impl Key {
#[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))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClickClock {
Iced,
Probe,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CaretClock {
Iced,
Probe,
}
impl ClickClock {
pub const PROP: &'static str = "click-clock";
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
ClickClock::Iced => "iced",
ClickClock::Probe => "probe",
}
}
}
impl CaretClock {
pub const PROP: &'static str = "caret-clock";
#[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;
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 },
}
#[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,
}
}
}
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));
}
}
}
#[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>,
}
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> {
#[inline]
pub fn new() -> Self {
Self {
#[cfg(feature = "semantics")]
fields: Fields::default(),
marker: PhantomData,
}
}
}
impl<'a, R: RoleKind> Annotation<'a, R> {
#[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,
}
}
#[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,
}
}
#[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
}
}
#[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
}
}
}
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! {
fn name(name: impl IntoFragment<'a>) => |f| f.name = Some(name.into_fragment());
fn description(text: impl IntoFragment<'a>) => |f| f.description = Some(text.into_fragment());
fn tooltip(text: impl IntoFragment<'a>) => |f| f.tooltip = Some(text.into_fragment());
fn test_id(id: impl IntoTestId<'a>) => |f| {
f.test_id_path = id.qualified_rust_path();
f.test_id = Some(id.into_test_id());
};
fn kind(kind: &'static str) => |f| f.kind = Some(kind);
fn component(kind: &'static str) => |f| {
f.kind = Some(kind);
f.source = icedwright_protocol::AnnotationSource::Component;
};
fn prop(key: &'static str, value: impl IntoFragment<'a>) => |f| f.push_prop(key, value.into_fragment());
fn text_size(size: impl Into<Pixels>) => |f| f.text_size = Some(size.into().0);
fn click_clock(clock: ClickClock) => |f| f.push_prop(ClickClock::PROP, Cow::Borrowed(clock.as_str()));
fn caret_clock(clock: CaretClock) => |f| f.push_prop(CaretClock::PROP, Cow::Borrowed(clock.as_str()));
fn disabled(on: bool) => |f| f.set_state(StateName::Disabled, StateValue::Bool(on));
fn current(on: bool) => |f| f.set_state(StateName::Current, StateValue::Bool(on));
fn busy(on: bool) => |f| f.set_state(StateName::Busy, StateValue::Bool(on));
fn hidden(on: bool) => |f| f.set_state(StateName::Hidden, StateValue::Bool(on));
fn modal(on: bool) => |f| f.set_state(StateName::Modal, StateValue::Bool(on));
fn required(on: bool) => |f| f.set_state(StateName::Required, StateValue::Bool(on));
fn invalid(on: bool) => |f| f.set_state(StateName::Invalid, StateValue::Bool(on));
fn readonly(on: bool) => |f| f.set_state(StateName::Readonly, StateValue::Bool(on));
fn position(index: u32, of: u32) => |f| f.position = Some((index, of));
fn key(key: impl Into<Key>) => |f| f.key = Some(key.into());
fn labelled_by(key: impl Into<Key>) => |f| add_key(&mut f.labelled_by, key.into());
fn label_for(key: impl Into<Key>) => |f| add_key(&mut f.label_for, key.into());
fn described_by(key: impl Into<Key>) => |f| add_key(&mut f.described_by, key.into());
fn controls(key: impl Into<Key>) => |f| add_key(&mut f.controls, key.into());
fn owns(key: impl Into<Key>) => |f| add_key(&mut f.owns, key.into());
fn checked(state: impl Into<Checked>) where R: Checkable => |f| f.set_state(StateName::Checked, state.into().into());
fn pressed(on: bool) where R: Pressable => |f| f.set_state(StateName::Pressed, StateValue::Bool(on));
fn expanded(on: bool) where R: Expandable => |f| f.set_state(StateName::Expanded, StateValue::Bool(on));
fn selected(on: bool) where R: SelectableItem => |f| f.set_state(StateName::Selected, StateValue::Bool(on));
fn level(level: u16) where R: Leveled => |f| f.level = Some(level);
fn value(text: impl IntoFragment<'a>) where R: HasValue => |f| f.value = Some(fields::ValueField::Text(text.into_fragment()));
fn range(now: f64, range: RangeInclusive<f64>) where R: RangeValue => |f| f.value = Some(fields::ValueField::Number {
now,
min: *range.start(),
max: *range.end(),
});
fn step(step: f64) where R: RangeValue => |f| f.step = Some(step);
fn placeholder(text: impl IntoFragment<'a>) where R: Editable => |f| f.placeholder = Some(text.into_fragment());
fn multiline(on: bool) where R: Editable => |f| f.set_state(StateName::Multiline, StateValue::Bool(on));
}
#[cfg(feature = "semantics")]
#[derive(Debug, Default)]
pub struct Ask {
pub wanted: bool,
}
#[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);
}
}