use std::num::NonZeroU16;
use std::sync::Arc;
use iced_core::event::Status;
use iced_core::{Event, window};
use icedwright_check::actionability::{
self, ActionKind, ActionRequest, Enabled, Frames, LayerCursors, NotActionable,
};
use icedwright_check::input::{Gesture, gesture_events};
use icedwright_check::scroll::{ScrollAlign, ScrollStep, scroll_into_view};
use icedwright_locator::{AnyRole, Locator};
use icedwright_protocol::WindowId;
use icedwright_semantics::{Node, NodePath, SemanticTree};
use icedwright_types::{Logical, Point, VirtualDuration};
use super::error::{ActionError, ActionFailure, Blocker};
use super::ops::ScrollOrdinal;
use crate::error::{HarnessError, Result};
use crate::harness::{Harness, TestProgram};
#[derive(Debug, Clone)]
pub(crate) struct Subject {
pub(crate) locator: Locator<AnyRole>,
pub(crate) window: Option<window::Id>,
pub(crate) path: Option<NodePath>,
}
impl Subject {
pub(crate) fn new(locator: Locator<AnyRole>, window: Option<window::Id>) -> Self {
Self {
locator,
window,
path: None,
}
}
pub(crate) fn at(&self, path: NodePath, window: window::Id) -> Self {
Self {
locator: self.locator.clone(),
window: Some(window),
path: Some(path),
}
}
pub(crate) fn describe(&self) -> String {
let locator = self.locator.to_rust_string("");
match &self.path {
Some(path) => format!("{path} (from {locator})"),
None => locator,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Found {
pub(crate) tree: Arc<SemanticTree>,
pub(crate) node: Node,
pub(crate) window: window::Id,
}
impl Found {
pub(crate) fn ordinal(&self) -> WindowId {
self.node.window
}
pub(crate) fn path(&self) -> &NodePath {
&self.node.path
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Probe {
Pointer,
Editable,
Deferred,
None,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Plan {
pub(crate) kind: ActionKind,
pub(crate) position: Option<Logical<Point>>,
pub(crate) force: bool,
pub(crate) trial: bool,
pub(crate) timeout: VirtualDuration,
pub(crate) steps: NonZeroU16,
pub(crate) probe: Probe,
}
impl Plan {
pub(crate) fn new(kind: ActionKind, timeout: VirtualDuration, probe: Probe) -> Self {
Self {
kind,
position: None,
force: false,
trial: false,
timeout,
steps: NonZeroU16::MIN,
probe,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Ready {
pub(crate) found: Found,
pub(crate) point: Logical<Point>,
pub(crate) attempts: u32,
pub(crate) scrolls: Vec<ScrollStep>,
pub(crate) statuses: Vec<Status>,
}
enum Miss {
Blocked(Blocker),
Refused(ActionFailure),
}
pub(crate) type Refusal<'a> = &'a dyn Fn(&Found) -> std::result::Result<(), ActionFailure>;
pub(crate) fn no_refusal(_: &Found) -> std::result::Result<(), ActionFailure> {
Ok(())
}
pub(crate) fn window_of<P: TestProgram>(h: &Harness<P>, ordinal: WindowId) -> Option<window::Id> {
h.set
.windows
.values()
.find(|state| WindowId(state.ordinal) == ordinal)
.map(|state| state.info.id)
}
pub(crate) fn pointer<P: TestProgram>(
h: &Harness<P>,
window: window::Id,
) -> Option<Logical<Point>> {
match h.surfaces.get(&window)?.cursor {
iced_core::mouse::Cursor::Available(point) => Some(Logical(Point::new(point.x, point.y))),
_ => None,
}
}
pub(crate) fn find<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
) -> Result<std::result::Result<Found, Blocker>> {
let tree = match subject.window {
Some(window) => h.tree_of(window)?,
None => h.tree()?,
};
let id = match &subject.path {
Some(path) => match tree.find_path(path) {
Some(id) => id,
None => {
return Ok(Err(Blocker::Check(NotActionable::Detached {
node: path.clone(),
})));
}
},
None => match icedwright_locator::resolve(&tree, &subject.locator) {
Ok(id) => id,
Err(error @ icedwright_locator::Error::NotFound { .. }) => {
return Ok(Err(Blocker::NotAttached(error)));
}
Err(error) => return Err(error.into()),
},
};
let Some(node) = tree.get(id).cloned() else {
return Err(HarnessError::NoWindow.into());
};
let window = window_of(h, node.window).ok_or(HarnessError::NoWindow)?;
Ok(Ok(Found { tree, node, window }))
}
pub(crate) fn deliver<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
batch: Vec<Event>,
settle: bool,
) -> Result<Vec<Status>> {
h.check_live()?;
let (statuses, _) = h.deliver_input(window, batch, true, false)?;
if settle {
h.run_until_settled()?;
}
Ok(statuses)
}
fn probe_move<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
to: Logical<Point>,
steps: NonZeroU16,
statuses: &mut Vec<Status>,
) -> Result<crate::harness::Probed> {
let from = pointer(h, window);
let layout = h.devices.layout.clone();
let mut batches = gesture_events(&Gesture::Move { to, steps }, from, &layout);
let last = batches.pop().unwrap_or_default();
for batch in batches {
statuses.extend(deliver(h, window, batch, true)?);
h.next_frame()?;
}
let probed = h.send_probed(window, &last)?;
statuses.extend(probed.statuses.iter().copied());
Ok(probed)
}
fn apply_scrolls<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
steps: &[ScrollStep],
) -> Result {
for step in steps {
let offset = iced_core::Vector::new(step.offset.x, step.offset.y);
let _ = h.operate(window, ScrollOrdinal::to(step.ordinal, offset))?;
let reached = h
.operate(window, ScrollOrdinal::read(step.ordinal))?
.flatten();
let missed =
reached.is_some_and(|t| (t.x - offset.x).abs() > 0.5 || (t.y - offset.y).abs() > 0.5);
if missed {
let anchored = step.end_anchored();
let anchored = iced_core::Vector::new(anchored.x, anchored.y);
let _ = h.operate(window, ScrollOrdinal::to(step.ordinal, anchored))?;
}
}
Ok(())
}
fn animating<P: TestProgram>(h: &Harness<P>) -> bool {
h.next_wake_up().is_some()
}
pub(crate) fn covered_by_own_ancestor(
tree: &SemanticTree,
target: &NodePath,
by: &NodePath,
) -> bool {
let (Some(target), Some(by)) = (tree.find_path(target), tree.find_path(by)) else {
return false;
};
target == by || tree.ancestors(target).any(|ancestor| ancestor == by)
}
pub(crate) fn actionable<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
plan: &Plan,
action: &'static str,
refuse: Refusal<'_>,
) -> Result<Ready> {
let deadline = h.now() + plan.timeout;
let began = h.real_now();
let mut attempts = 0u32;
let mut scrolls = Vec::new();
let mut statuses = Vec::new();
loop {
h.run_until_settled()?;
attempts += 1;
let blocker = match attempt(h, subject, plan, refuse, &mut scrolls, &mut statuses)? {
Ok((found, point)) => {
return Ok(Ready {
found,
point,
attempts,
scrolls,
statuses,
});
}
Err(Miss::Refused(reason)) => {
return Err(ActionError::new(action, subject.describe(), reason).into());
}
Err(Miss::Blocked(blocker)) => blocker,
};
let give_up =
h.has_exited() || h.now() >= deadline || h.wait(deadline, began)?.ceiling_reached;
if give_up {
let reason = ActionFailure::Timeout {
timeout: plan.timeout,
attempts,
last: Box::new(blocker),
};
return Err(ActionError::new(action, subject.describe(), reason).into());
}
}
}
fn attempt<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
plan: &Plan,
refuse: Refusal<'_>,
scrolls: &mut Vec<ScrollStep>,
statuses: &mut Vec<Status>,
) -> Result<std::result::Result<(Found, Logical<Point>), Miss>> {
let mut found = match find(h, subject)? {
Ok(found) => found,
Err(blocker) => return Ok(Err(Miss::Blocked(blocker))),
};
if let Err(reason) = refuse(&found) {
return Ok(Err(Miss::Refused(reason)));
}
for _ in 0..3 {
let steps = scroll_into_view(&found.node, ScrollAlign::Nearest);
if steps.is_empty() {
break;
}
apply_scrolls(h, found.window, &steps)?;
scrolls.extend(steps);
found = match find(h, subject)? {
Ok(found) => found,
Err(blocker) => return Ok(Err(Miss::Blocked(blocker))),
};
}
let checks = plan.kind.checks();
let previous = if checks.stable && !plan.force && animating(h) {
let before = found.tree.clone();
h.next_frame()?;
found = match find(h, subject)? {
Ok(found) => found,
Err(blocker) => return Ok(Err(Miss::Blocked(blocker))),
};
before
} else {
found.tree.clone()
};
let mut request = ActionRequest::new(plan.kind);
if let Some(position) = plan.position {
request = request.at(position);
}
if plan.force {
request = request.force();
}
let path = found.path().clone();
let none = LayerCursors::new();
let first = actionability::check(
Frames {
current: &found.tree,
previous: &previous,
cursors: &none,
},
&path,
&request,
);
let defer_covers = !plan.trial && matches!(plan.probe, Probe::Pointer | Probe::Deferred);
let (point, enabled) = match first {
Ok(ready) => (ready.point, ready.enabled),
Err(NotActionable::Covered { at, .. } | NotActionable::PossiblyCovered { at, .. })
if defer_covers =>
{
let enabled = if found.node.states.disabled.is_some() {
Enabled::Known
} else {
Enabled::Probe
};
(at, enabled)
}
Err(error) => return Ok(Err(Miss::Blocked(Blocker::Check(error)))),
};
let probe = match plan.probe {
Probe::Editable
if found.node.states.readonly.is_none() && found.node.states.disabled.is_none() =>
{
true
}
Probe::Pointer => true,
Probe::Editable | Probe::Deferred | Probe::None => false,
};
if plan.trial || plan.force || !probe {
return Ok(Ok((found, point)));
}
let probed = probe_move(h, found.window, point, plan.steps, statuses)?;
let after = actionability::check(
Frames {
current: &probed.tree,
previous: &found.tree,
cursors: &probed.cursors,
},
&path,
&request,
);
if let Err(error) = after {
let error = match error {
NotActionable::Covered { ref by, .. }
if covered_by_own_ancestor(&probed.tree, &path, by) =>
{
let interaction = h.mouse_interaction(found.window)?;
match actionability::confirm_pointer(&probed.tree, &path, point, interaction) {
Err(gap @ NotActionable::UnannotatedScrim { .. }) => gap,
_ => error,
}
}
error => error,
};
return Ok(Err(Miss::Blocked(Blocker::Check(error))));
}
let interaction = h.mouse_interaction(found.window)?;
match actionability::confirm_pointer(&probed.tree, &path, point, interaction) {
Ok(()) => {}
Err(NotActionable::NotEditable { .. }) if plan.probe != Probe::Editable => {}
Err(NotActionable::Disabled { .. }) if !checks.enabled || enabled == Enabled::Known => {}
Err(error) => return Ok(Err(Miss::Blocked(Blocker::Check(error)))),
}
let Some(node) = probed.tree.node_at(&path).cloned() else {
return Ok(Err(Miss::Blocked(Blocker::Check(
NotActionable::Detached { node: path },
))));
};
let found = Found {
tree: probed.tree.clone(),
node,
window: found.window,
};
Ok(Ok((found, point)))
}