mod common;
use std::any::Any;
use std::cell::Cell;
use iced_core::widget::{Id, Operation};
use iced_core::{Point, Rectangle, Size};
use icedwright_probe::{
Annotation, CaretClock, ClickClock, Key, SemanticExt, TestId, report, role, semantic, test_id,
};
use common::{El, Leaf};
#[derive(Debug, Clone, Copy, PartialEq, Eq, TestId)]
enum Ids {
NewItem,
#[test_id("delete-{0}")]
Delete(u32),
}
#[derive(Debug, PartialEq)]
enum Call {
Ask,
Annotation,
Other,
}
struct Recording {
answer: bool,
calls: Vec<Call>,
}
impl Operation for Recording {
fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
operate(self);
}
fn custom(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Any) {
#[cfg(feature = "semantics")]
if let Some(ask) = state.downcast_mut::<icedwright_probe::Ask>() {
ask.wanted = self.answer;
self.calls.push(Call::Ask);
return;
}
if state.is::<Annotation<'static>>() {
self.calls.push(Call::Annotation);
return;
}
self.calls.push(Call::Other);
}
}
fn bounds() -> Rectangle {
Rectangle::new(Point::ORIGIN, Size::new(10.0, 10.0))
}
#[test]
fn report_builds_and_sends_only_when_asked() {
let built = Cell::new(0);
let mut yes = Recording {
answer: true,
calls: Vec::new(),
};
report(&mut yes, bounds(), || {
built.set(built.get() + 1);
Annotation::new().role(role::Button).name("Save")
});
let mut no = Recording {
answer: false,
calls: Vec::new(),
};
report(&mut no, bounds(), || {
built.set(built.get() + 1);
Annotation::new()
});
assert!(yes.answer && !no.answer);
if cfg!(feature = "semantics") {
assert_eq!(yes.calls, [Call::Ask, Call::Annotation]);
assert_eq!(no.calls, [Call::Ask]);
assert_eq!(built.get(), 1);
} else {
assert!(yes.calls.is_empty());
assert!(no.calls.is_empty());
assert_eq!(built.get(), 0);
}
}
#[test]
fn every_setter_chains_for_its_role() {
let text = String::from("draft");
let annotation = Annotation::new()
.role(role::TextBox)
.name("New item")
.description("What needs doing")
.tooltip("Type here")
.placeholder("What needs doing?")
.value(&text)
.multiline(false)
.test_id(Ids::NewItem)
.kind("app")
.prop("unsaved", "true")
.text_size(14.0)
.click_clock(ClickClock::Iced)
.caret_clock(CaretClock::Probe)
.disabled(false)
.current(true)
.busy(false)
.hidden(false)
.modal(false)
.required(true)
.invalid(false)
.readonly(false)
.position(1, 3)
.key("field")
.labelled_by("label")
.label_for(Key::unique())
.described_by(String::from("help"))
.controls("list")
.owns("panel")
.text_geometry([(4, icedwright_types::Point::new(0.0, 0.0))])
.cursor_seen(None);
let _ = annotation.to_static();
let _ = Annotation::new().role(role::CheckBox).checked(true);
let _ = Annotation::new()
.role(role::TreeItem)
.checked(icedwright_probe::Checked::Mixed)
.expanded(true)
.selected(false)
.level(2);
let _ = Annotation::new().role(role::ToggleButton).pressed(true);
let _ = Annotation::new()
.role(role::Slider)
.range(3.0, 0.0..=10.0)
.step(1.0);
}
#[test]
fn keys_and_clock_props_have_fixed_spellings() {
assert_ne!(Key::unique(), Key::unique());
assert_eq!(Key::from("a"), Key::Name("a".into()));
assert_eq!(ClickClock::PROP, "click-clock");
assert_eq!(ClickClock::Iced.as_str(), "iced");
assert_eq!(CaretClock::PROP, "caret-clock");
assert_eq!(CaretClock::Probe.as_str(), "probe");
}
#[test]
fn test_ids_and_strings_give_the_same_reference() {
use icedwright_probe::IntoTestId;
let typed = Ids::NewItem.into_test_id();
let plain = "new-item".into_test_id();
assert_eq!(typed.id, plain.id);
assert_eq!(typed.rust_path, Some("Ids::NewItem"));
assert_eq!(plain.rust_path, None);
assert_eq!(
Ids::NewItem.qualified_rust_path(),
Some("annotation::Ids::NewItem")
);
assert_eq!("new-item".qualified_rust_path(), None);
assert_eq!(Ids::Delete(3).into_test_id().id, "delete-3");
assert_eq!(String::from("row-2").into_test_id().to_string(), "row-2");
}
#[cfg(not(feature = "semantics"))]
#[test]
fn without_semantics_the_wrapper_is_the_element_itself() {
let leaf: El<'static> = El::new(Leaf::new("Save"));
let before = std::ptr::from_ref(leaf.as_widget()).cast::<()>();
let wrapped: El<'static> = semantic(leaf)
.role(role::Button)
.name("Save")
.test_id(Ids::NewItem)
.into();
let after = std::ptr::from_ref(wrapped.as_widget()).cast::<()>();
assert_eq!(before, after);
assert_eq!(std::mem::size_of::<Annotation<'static, role::Button>>(), 0);
}
#[test]
fn test_id_and_the_extension_method_wrap_like_semantic() {
let mut by_id: El<'static> = test_id("row", Leaf::new("x")).into();
let mut chained: El<'static> = Leaf::new("x").semantic().name("x").into();
let mut count = Counting(0);
common::operate(&mut by_id, &mut count);
common::operate(&mut chained, &mut count);
assert_eq!(count.0, if cfg!(feature = "semantics") { 4 } else { 0 });
}
struct Counting(usize);
impl Operation for Counting {
fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
operate(self);
}
fn custom(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Any) {
#[cfg(feature = "semantics")]
if let Some(ask) = state.downcast_mut::<icedwright_probe::Ask>() {
ask.wanted = true;
}
let _ = state;
self.0 += 1;
}
}
#[cfg(all(test, feature = "semantics"))]
mod with_semantics {
use super::*;
use iced_core::widget::Tree;
use iced_core::{Event, mouse};
use icedwright_probe::RawRecorder;
use icedwright_protocol::{RawAnnotation, RawCall, RawKey, RawValue};
use icedwright_types::{CursorSeen, Role, StateName, StateValue};
fn recorded(mut element: El<'_>) -> Option<RawAnnotation> {
let mut recorder = RawRecorder::new();
common::operate(&mut element, &mut recorder);
let tree = recorder.into_tree();
match &tree.windows.first()?.root.children.first()?.call {
RawCall::Annotation(annotation) => Some((**annotation).clone()),
_ => None,
}
}
macro_rules! annotation_of {
($element:expr $(,)?) => {
recorded($element).expect("the element reports an annotation first")
};
}
#[test]
fn the_wrapper_reports_then_traverses_its_content() {
let mut element: El<'_> = semantic(Leaf::new("Delete"))
.role(role::Button)
.name("Delete")
.test_id(Ids::Delete(3))
.into();
let mut recorder = RawRecorder::new();
common::operate(&mut element, &mut recorder);
let tree = recorder.into_tree();
let root = &tree.windows[0].root;
assert_eq!(root.children.len(), 1);
let button = &root.children[0];
let RawCall::Annotation(annotation) = &button.call else {
panic!("{button:?}");
};
assert_eq!(annotation.role, Some(Role::Button));
assert_eq!(annotation.name.as_deref(), Some("Delete"));
assert_eq!(annotation.test_id.as_deref(), Some("delete-3"));
assert_eq!(button.children.len(), 1);
assert_eq!(button.children[0].call, RawCall::Container);
assert_eq!(
button.children[0].children[0].call,
RawCall::Text {
content: "Delete".to_owned()
}
);
}
#[test]
fn every_field_reaches_the_raw_annotation() {
let annotation = annotation_of!(
semantic(Leaf::new("x"))
.role(role::TextBox)
.name("New item")
.description("desc")
.tooltip("tip")
.placeholder("What needs doing?")
.value("milk")
.multiline(true)
.test_id("new-item")
.component("iced_cube::input")
.prop("unsaved", "true")
.text_size(14.0)
.click_clock(ClickClock::Probe)
.disabled(true)
.required(true)
.position(2, 5)
.key("field")
.labelled_by("label")
.described_by("help")
.controls("list")
.owns("panel")
.into(),
);
assert_eq!(annotation.role, Some(Role::TextBox));
assert_eq!(annotation.description.as_deref(), Some("desc"));
assert_eq!(annotation.tooltip.as_deref(), Some("tip"));
assert_eq!(annotation.placeholder.as_deref(), Some("What needs doing?"));
assert_eq!(annotation.value, Some(RawValue::Text("milk".to_owned())));
assert_eq!(annotation.kind.as_deref(), Some("iced_cube::input"));
assert_eq!(
annotation.source,
icedwright_protocol::AnnotationSource::Component
);
assert_eq!(
annotation.props.get("unsaved").map(String::as_str),
Some("true")
);
assert_eq!(
annotation.props.get("click-clock").map(String::as_str),
Some("probe")
);
assert_eq!(annotation.text_size, Some(14.0));
assert_eq!(
annotation.states,
[
(StateName::Disabled, StateValue::Bool(true)),
(StateName::Required, StateValue::Bool(true)),
(StateName::Multiline, StateValue::Bool(true)),
]
);
assert_eq!(annotation.position, Some((2, 5)));
assert_eq!(annotation.key, Some(RawKey::Name("field".to_owned())));
assert_eq!(annotation.labelled_by, [RawKey::Name("label".to_owned())]);
assert_eq!(annotation.described_by, [RawKey::Name("help".to_owned())]);
assert_eq!(annotation.controls, [RawKey::Name("list".to_owned())]);
assert_eq!(annotation.owns, [RawKey::Name("panel".to_owned())]);
assert_eq!(annotation.cursor_seen, None);
}
#[test]
fn capability_states_and_ranges_are_recorded() {
let tree_item = annotation_of!(
semantic(Leaf::new("x"))
.role(role::TreeItem)
.checked(icedwright_probe::Checked::Mixed)
.expanded(false)
.selected(true)
.level(0)
.into(),
);
assert_eq!(
tree_item.states,
[
(StateName::Checked, StateValue::Mixed),
(StateName::Expanded, StateValue::Bool(false)),
(StateName::Selected, StateValue::Bool(true)),
]
);
assert_eq!(tree_item.level, Some(0));
let slider = annotation_of!(
semantic(Leaf::new("x"))
.role(role::Slider)
.range(3.0, 0.0..=10.0)
.into(),
);
assert_eq!(
slider.value,
Some(RawValue::Number {
now: 3.0,
min: Some(0.0),
max: Some(10.0),
step: None
})
);
let stepped = annotation_of!(
semantic(Leaf::new("x"))
.role(role::Slider)
.step(0.5)
.range(3.0, 0.0..=10.0)
.into(),
);
assert_eq!(
stepped.value,
Some(RawValue::Number {
now: 3.0,
min: Some(0.0),
max: Some(10.0),
step: Some(0.5)
})
);
let step_without_range =
annotation_of!(semantic(Leaf::new("x")).role(role::Slider).step(1.0).into(),);
assert_eq!(step_without_range.value, None);
let toggle = annotation_of!(
semantic(Leaf::new("x"))
.role(role::ToggleButton)
.pressed(true)
.into(),
);
assert_eq!(
toggle.states,
[(StateName::Pressed, StateValue::Bool(true))]
);
}
#[test]
fn a_later_setter_replaces_an_earlier_one() {
let annotation = annotation_of!(
semantic(Leaf::new("x"))
.name("first")
.name("second")
.disabled(true)
.disabled(false)
.prop("p", "1")
.prop("p", "2")
.into(),
);
assert_eq!(annotation.name.as_deref(), Some("second"));
assert_eq!(
annotation.states,
[(StateName::Disabled, StateValue::Bool(false))]
);
assert_eq!(annotation.props.len(), 1);
assert_eq!(annotation.props.get("p").map(String::as_str), Some("2"));
}
#[test]
fn text_geometry_is_sorted_by_offset() {
let mut recorder = RawRecorder::new();
report(&mut recorder, bounds(), || {
Annotation::new()
.text_geometry([
(5, icedwright_types::Point::new(10.0, 0.0)),
(0, icedwright_types::Point::new(0.0, 0.0)),
])
.cursor_seen(CursorSeen::Levitating)
});
let tree = recorder.into_tree();
let RawCall::Annotation(annotation) = &tree.windows[0].root.children[0].call else {
panic!("{tree:?}");
};
assert_eq!(
annotation
.carets
.iter()
.map(|(o, _)| *o)
.collect::<Vec<_>>(),
[0, 5]
);
assert_eq!(annotation.cursor_seen, Some(CursorSeen::Levitating));
}
#[test]
fn the_wrapper_forwards_tag_state_children_and_diff() {
let plain: El<'_> = El::new(Leaf::new("x"));
let wrapped: El<'_> = semantic(Leaf::new("x")).name("x").into();
let a = Tree::new(plain.as_widget());
let b = Tree::new(wrapped.as_widget());
assert_eq!(a.tag, b.tag);
assert_eq!(a.children.len(), b.children.len());
assert_eq!(b.state.downcast_ref::<u32>(), &7);
let mut tree = Tree::new(wrapped.as_widget());
tree.diff(wrapped.as_widget());
assert_eq!(tree.children.len(), 1);
}
fn cursor_after(
element: &mut El<'_>,
tree: &mut Tree,
cursor: mouse::Cursor,
) -> Option<CursorSeen> {
let event = Event::Mouse(mouse::Event::CursorMoved {
position: Point::new(1.0, 1.0),
});
common::update(element, tree, &event, cursor);
let mut recorder = RawRecorder::new();
common::operate(element, &mut recorder);
let tree = recorder.into_tree();
match &tree.windows[0].root.children[0].call {
RawCall::Annotation(annotation) => annotation.cursor_seen,
_ => None,
}
}
#[test]
fn the_wrapper_records_each_cursor_kind_from_mouse_events() {
let leaf = Leaf::new("x");
let seen = leaf.seen.clone();
let mut element: El<'_> = semantic(leaf).into();
let mut tree = Tree::new(element.as_widget());
let point = Point::new(1.0, 1.0);
assert_eq!(
cursor_after(&mut element, &mut tree, mouse::Cursor::Available(point)),
Some(CursorSeen::Available)
);
assert_eq!(
cursor_after(&mut element, &mut tree, mouse::Cursor::Levitating(point)),
Some(CursorSeen::Levitating)
);
let _ = common::interaction(&element, &tree, mouse::Cursor::Available(point));
let mut recorder = RawRecorder::new();
common::operate(&mut element, &mut recorder);
let RawCall::Annotation(annotation) =
&recorder.into_tree().windows[0].root.children[0].call
else {
panic!("no annotation");
};
assert_eq!(annotation.cursor_seen, Some(CursorSeen::Levitating));
assert_eq!(
cursor_after(&mut element, &mut tree, mouse::Cursor::Unavailable),
Some(CursorSeen::Unavailable)
);
let seen = seen.lock().map(|s| s.cursors.len()).unwrap_or_default();
assert_eq!(seen, 3, "the content still gets every event");
}
#[test]
fn a_fresh_wrapper_reports_no_cursor() {
let annotation = annotation_of!(semantic(Leaf::new("x")).into());
assert_eq!(annotation.cursor_seen, None);
}
#[test]
fn keyboard_events_leave_the_cursor_reading_alone() {
let mut element: El<'_> = semantic(Leaf::new("x")).into();
let mut tree = Tree::new(element.as_widget());
let event = Event::Keyboard(iced_core::keyboard::Event::ModifiersChanged(
iced_core::keyboard::Modifiers::empty(),
));
common::update(&mut element, &mut tree, &event, mouse::Cursor::Unavailable);
let mut recorder = RawRecorder::new();
common::operate(&mut element, &mut recorder);
let RawCall::Annotation(annotation) =
&recorder.into_tree().windows[0].root.children[0].call
else {
panic!("no annotation");
};
assert_eq!(annotation.cursor_seen, None);
}
}