use std::num::NonZeroU16;
use std::ops::Bound;
use std::path::PathBuf;
use iced_core::event::Status;
use iced_core::{Event, mouse, window};
use icedwright_check::actionability::{ActionKind, Cover, NotActionable, obscured_by};
use icedwright_check::clicks::{RecordedPress, multi_click_allowed, place_press};
use icedwright_check::input::{Gesture, gesture_events};
use icedwright_check::{ActionReport, ClickCount};
use icedwright_protocol::WindowId;
use icedwright_semantics::{Kind, Node, NodePath, OperationKind, SemanticTree, Value};
use icedwright_types::input::{Chord, Keystroke, ModifierSet, NamedKey};
use icedwright_types::role::Capabilities;
use icedwright_types::{Checked, Logical, Point, Rect, Role, StateName, VirtualDuration};
use super::engine::{
self, Found, Plan, Probe, Ready, Subject, actionable, deliver, find, no_refusal,
};
use super::error::{ActionError, ActionFailure};
use super::ops::{FocusOrdinal, SelectAllOrdinal};
use super::options::{Click, Drag, Hover, OptionMatch, Type};
use crate::error::Result;
use crate::harness::{Harness, TestProgram, delayed_tooltip_under};
const MULTI_CLICK_GAP: VirtualDuration = VirtualDuration::from_millis(50);
const SELECT_OVERSHOOT: f32 = 20.0;
pub(crate) fn send_frames<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
batches: Vec<Vec<Event>>,
) -> Result {
let _ = send_batches(h, window, batches, false)?;
Ok(())
}
fn send_batches<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
batches: Vec<Vec<Event>>,
no_wait_after: bool,
) -> Result<Vec<Status>> {
let count = batches.len();
let mut statuses = Vec::new();
for (index, batch) in batches.into_iter().enumerate() {
let last = index + 1 == count;
statuses.extend(deliver(h, window, batch, !(last && no_wait_after))?);
if !last {
h.next_frame()?;
}
}
Ok(statuses)
}
pub(crate) fn send_click<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
batches: Vec<Vec<Event>>,
count: ClickCount,
) -> Result<Vec<Status>> {
send_click_batches(h, window, batches, count, false)
}
fn send_click_batches<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
batches: Vec<Vec<Event>>,
count: ClickCount,
no_wait_after: bool,
) -> Result<Vec<Status>> {
let total = batches.len();
let mut statuses = Vec::new();
let mut presses = 0usize;
for (index, batch) in batches.into_iter().enumerate() {
let is_press = batch
.iter()
.any(|e| matches!(e, Event::Mouse(mouse::Event::ButtonPressed(_))));
if is_press {
if presses > 0 && count != ClickCount::Single {
let until = h.now() + MULTI_CLICK_GAP;
let _ = h.advance_until(until, |_| false)?;
}
presses += 1;
}
let last = index + 1 == total;
statuses.extend(deliver(h, window, batch, !(last && no_wait_after))?);
}
Ok(statuses)
}
pub(crate) fn send_keys<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
gesture: &Gesture,
delay: VirtualDuration,
layout: Option<&icedwright_check::KeyboardLayout>,
) -> Result {
let layout = layout.cloned().unwrap_or_else(|| h.devices.layout.clone());
let batches = gesture_events(gesture, None, &layout);
let count = batches.len();
for (index, batch) in batches.into_iter().enumerate() {
let _ = deliver(h, window, batch, true)?;
if index + 1 < count && delay > VirtualDuration::ZERO {
let until = h.now() + delay;
let _ = h.advance_until(until, |_| false)?;
}
}
Ok(())
}
fn chord(modifiers: ModifierSet, key: Keystroke) -> Gesture {
Gesture::Chord(Chord::new(modifiers, key))
}
fn named(key: NamedKey) -> Keystroke {
Keystroke::Named(key)
}
fn report_from(ready: &Ready) -> ActionReport {
ActionReport {
point: Some(ready.point),
scrolls: ready.scrolls.clone(),
statuses: ready.statuses.clone(),
frames_waited: ready.attempts.saturating_sub(1),
..ActionReport::default()
}
}
pub(crate) fn with_pointer<P: TestProgram>(
h: &mut Harness<P>,
no_wait_after: bool,
run: impl FnOnce(&mut Harness<P>) -> Result<(ActionReport, Option<window::Id>)>,
) -> Result<ActionReport> {
let first_message = h.messages.len();
h.devices.hold();
let result = run(h);
h.devices.release();
let (mut report, window) = match result {
Ok(done) => done,
Err(error) => {
let _ = h.run_until_settled();
return Err(error);
}
};
let leaves = |h: &Harness<P>| {
window
.and_then(|w| h.real_clock_deadline(w).ok())
.map_or(0, |d| d.tooltip_leaves)
};
let before = leaves(h);
if !no_wait_after {
h.run_until_settled()?;
}
report.cursor_left = leaves(h) > before;
report.messages = h
.messages
.get(first_message..)
.unwrap_or_default()
.iter()
.map(|record| record.debug.clone())
.collect();
Ok(report)
}
fn refused(
action: &'static str,
subject: &Subject,
refusal: icedwright_check::ClickRefused,
) -> crate::Error {
ActionError::new(action, subject.describe(), ActionFailure::Refused(refusal)).into()
}
fn failed(action: &'static str, subject: &Subject, reason: ActionFailure) -> crate::Error {
ActionError::new(action, subject.describe(), reason).into()
}
pub(crate) fn click<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
options: &Click,
action: &'static str,
kind: ActionKind,
) -> Result<ActionReport> {
with_pointer(h, options.no_wait_after, |h| {
click_held(h, subject, options, action, kind)
})
}
fn click_held<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
options: &Click,
action: &'static str,
kind: ActionKind,
) -> Result<(ActionReport, Option<window::Id>)> {
let plan = Plan {
kind,
position: options.position,
force: options.force,
trial: options.trial,
timeout: options.timeout.unwrap_or(h.default_timeout()),
steps: options.steps,
probe: Probe::Pointer,
};
let multi = options.count != ClickCount::Single;
let history = h.devices.history.clone();
let refuse = |found: &Found| {
if multi {
multi_click_allowed(&found.tree, found.path()).map_err(ActionFailure::Refused)?;
}
if options.force || options.trial {
return Ok(());
}
let Some(aim) = aim(&found.node, options.position) else {
return Ok(());
};
place_press(
&history,
&found.tree,
found.path(),
options.button,
aim,
options.position.is_some(),
)
.map(|_| ())
.map_err(ActionFailure::Refused)
};
let ready = actionable(h, subject, &plan, action, &refuse)?;
let window = ready.found.window;
let mut report = report_from(&ready);
if options.trial {
return Ok((report, Some(window)));
}
let placement = place_press(
&h.devices.history,
&ready.found.tree,
ready.found.path(),
options.button,
ready.point,
options.position.is_some(),
)
.map_err(|refusal| refused(action, subject, refusal))?;
report.point = Some(placement.point);
report.nudged_from = placement.nudged_from;
let from = engine::pointer(h, window);
let layout = h.devices.layout.clone();
let gesture = Gesture::Click {
at: placement.point,
button: options.button,
count: options.count,
modifiers: options.modifiers,
};
let first_message = h.messages.len();
let statuses = send_click_batches(
h,
window,
gesture_events(&gesture, from, &layout),
options.count,
options.no_wait_after,
)?;
h.devices.history.record(RecordedPress::at(
&ready.found.tree,
ready.found.ordinal(),
options.button,
placement.point.0,
));
let captured = statuses.contains(&Status::Captured);
if !captured && h.messages.len() == first_message {
report
.warnings
.push("nothing captured the click and no message was produced".to_owned());
}
report.statuses.extend(statuses);
Ok((report, Some(window)))
}
fn aim(node: &Node, position: Option<Logical<Point>>) -> Option<Logical<Point>> {
if let Some(Logical(offset)) = position {
return Some(Logical(Point::new(
node.bounds.x + offset.x,
node.bounds.y + offset.y,
)));
}
icedwright_check::actionability::visible_part(node).map(|visible| Logical(visible.center()))
}
fn delayed_trigger(tree: &SemanticTree, window: WindowId, point: Point) -> Option<NodePath> {
if !delayed_tooltip_under(tree, window, point) {
return None;
}
let hit = tree.hit_test(window, point)?;
std::iter::once(hit)
.chain(tree.ancestors(hit))
.filter_map(|id| tree.get(id))
.find(|node| node.tooltip.is_some())
.map(|node| node.path.clone())
}
pub(crate) fn hover<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
options: &Hover,
) -> Result<ActionReport> {
with_pointer(h, false, |h| {
let plan = Plan {
kind: ActionKind::Hover,
position: options.position,
force: options.force,
trial: options.trial,
timeout: options.timeout.unwrap_or(h.default_timeout()),
steps: options.steps,
probe: Probe::Pointer,
};
let ready = actionable(h, subject, &plan, "hover", &no_refusal)?;
let window = ready.found.window;
let report = report_from(&ready);
if options.trial {
return Ok((report, Some(window)));
}
if options.force {
let from = engine::pointer(h, window);
let layout = h.devices.layout.clone();
let moves = gesture_events(
&Gesture::Move {
to: ready.point,
steps: options.steps,
},
from,
&layout,
);
send_frames(h, window, moves)?;
}
let tree = h.tree_of(window)?;
if let Some(trigger) = delayed_trigger(&tree, ready.found.ordinal(), ready.point.0) {
return Err(failed(
"hover",
subject,
ActionFailure::RealClockTooltip { trigger },
));
}
Ok((report, Some(window)))
})
}
fn attached<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
timeout: VirtualDuration,
action: &'static str,
refuse: engine::Refusal<'_>,
) -> Result<Ready> {
let plan = Plan::new(ActionKind::Focus, timeout, Probe::None);
actionable(h, subject, &plan, action, refuse)
}
fn focusable(found: &Found) -> std::result::Result<(), ActionFailure> {
if found.node.focusable_ordinal.is_some() {
return Ok(());
}
Err(ActionFailure::NotFocusable {
node: found.path().clone(),
})
}
fn ensure_focus<P: TestProgram>(h: &mut Harness<P>, found: &Found) -> Result {
if found.node.states.focused == Some(true) {
return Ok(());
}
let Some(ordinal) = found.node.focusable_ordinal else {
return Ok(());
};
let _ = h.operate(found.window, FocusOrdinal::new(ordinal))?;
Ok(())
}
pub(crate) fn focus<P: TestProgram>(h: &mut Harness<P>, subject: &Subject) -> Result<ActionReport> {
let timeout = h.default_timeout();
let ready = attached(h, subject, timeout, "focus", &focusable)?;
ensure_focus(h, &ready.found)?;
Ok(report_from(&ready))
}
pub(crate) fn press<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
pressed: Chord,
) -> Result<ActionReport> {
let timeout = h.default_timeout();
let ready = attached(h, subject, timeout, "press", &no_refusal)?;
ensure_focus(h, &ready.found)?;
send_keys(
h,
ready.found.window,
&Gesture::Chord(pressed),
VirtualDuration::ZERO,
None,
)?;
Ok(report_from(&ready))
}
fn editable<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
action: &'static str,
timeout: VirtualDuration,
) -> Result<Ready> {
let plan = Plan::new(ActionKind::Fill, timeout, Probe::Editable);
let ready = actionable(h, subject, &plan, action, &focusable)?;
ensure_focus(h, &ready.found)?;
Ok(ready)
}
fn select_all<P: TestProgram>(
h: &mut Harness<P>,
found: &Found,
report: &mut ActionReport,
) -> Result {
let selected = match found.node.focusable_ordinal {
Some(ordinal) => h
.operate(found.window, SelectAllOrdinal::new(ordinal))?
.unwrap_or(false),
None => false,
};
if selected {
return Ok(());
}
report
.warnings
.push("selected the value with ControlOrMeta+A".to_owned());
send_keys(
h,
found.window,
&chord(ModifierSet::CONTROL_OR_META, Keystroke::Character('a')),
VirtualDuration::ZERO,
None,
)
}
fn ime_enabled<P: TestProgram>(h: &Harness<P>, window: window::Id) -> Result<bool> {
Ok(matches!(
h.input_method(window)?,
iced_core::InputMethod::Enabled { .. }
))
}
pub(crate) fn fill<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
text: &str,
) -> Result<ActionReport> {
with_pointer(h, false, |h| {
let timeout = h.default_timeout();
let ready = editable(h, subject, "fill", timeout)?;
let mut report = report_from(&ready);
select_all(h, &ready.found, &mut report)?;
let window = ready.found.window;
if ime_enabled(h, window)? {
send_keys(
h,
window,
&Gesture::Commit(text.to_owned()),
VirtualDuration::ZERO,
None,
)?;
} else {
report.warnings.push(
"the field asked for no input method, so the text was typed key by key".to_owned(),
);
send_keys(
h,
window,
&chord(ModifierSet::NONE, named(NamedKey::Delete)),
VirtualDuration::ZERO,
None,
)?;
send_keys(
h,
window,
&Gesture::Type(text.to_owned()),
VirtualDuration::ZERO,
None,
)?;
}
Ok((report, Some(window)))
})
}
pub(crate) fn clear<P: TestProgram>(h: &mut Harness<P>, subject: &Subject) -> Result<ActionReport> {
with_pointer(h, false, |h| {
let timeout = h.default_timeout();
let ready = editable(h, subject, "clear", timeout)?;
let mut report = report_from(&ready);
select_all(h, &ready.found, &mut report)?;
let window = ready.found.window;
send_keys(
h,
window,
&chord(ModifierSet::NONE, named(NamedKey::Delete)),
VirtualDuration::ZERO,
None,
)?;
Ok((report, Some(window)))
})
}
pub(crate) fn press_sequentially<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
text: &str,
options: &Type,
) -> Result<ActionReport> {
with_pointer(h, false, |h| {
let timeout = options.timeout.unwrap_or(h.default_timeout());
let ready = editable(h, subject, "press_sequentially", timeout)?;
let window = ready.found.window;
send_keys(
h,
window,
&Gesture::Type(text.to_owned()),
options.delay,
options.layout.as_ref(),
)?;
Ok((report_from(&ready), Some(window)))
})
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Toggle {
pub(crate) action: &'static str,
pub(crate) state: StateName,
pub(crate) want: bool,
}
impl Toggle {
fn read(self, node: &Node) -> Option<bool> {
let states = &node.states;
match self.state {
StateName::Checked => states.checked.map(|c| c == Checked::True),
StateName::Pressed => states.pressed,
StateName::Expanded => states.expanded,
StateName::Selected => states.selected,
_ => None,
}
}
}
fn disclosure(found: &Found) -> Option<NodePath> {
if found.node.role != Role::TreeItem {
return None;
}
found
.node
.children
.iter()
.filter_map(|id| found.tree.get(*id))
.find(|child| child.role == Role::Button)
.map(|child| child.path.clone())
}
pub(crate) fn toggle<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
toggle: Toggle,
) -> Result<ActionReport> {
let timeout = h.default_timeout();
let unknown = |found: &Found| match toggle.read(&found.node) {
Some(_) => Ok(()),
None => Err(ActionFailure::StateUnknown {
node: found.path().clone(),
state: toggle.state,
}),
};
let ready = attached(h, subject, timeout, toggle.action, &unknown)?;
if toggle.read(&ready.found.node) == Some(toggle.want) {
let mut report = report_from(&ready);
report.point = None;
return Ok(report);
}
let target = match (toggle.state, disclosure(&ready.found)) {
(StateName::Expanded, Some(path)) => subject.at(path, ready.found.window),
_ => subject.clone(),
};
let report = click(h, &target, &Click::new(), toggle.action, ActionKind::Toggle)?;
let reads = h.wait_for(timeout, |h| {
matches!(find(h, subject), Ok(Ok(found)) if toggle.read(&found.node) == Some(toggle.want))
})?;
if reads {
return Ok(report);
}
Err(failed(
toggle.action,
subject,
ActionFailure::StateDidNotChange {
node: ready.found.path().clone(),
state: toggle.state.to_string(),
wanted: if toggle.want { "true" } else { "false" }.to_owned(),
},
))
}
const OPTION_ROLES: &[Role] = &[
Role::ListOption,
Role::Tab,
Role::RadioButton,
Role::MenuItem,
Role::MenuItemRadio,
];
fn options_of<'t>(tree: &'t SemanticTree, container: &Node) -> Vec<&'t Node> {
let own: Vec<&Node> = tree
.descendants(container.id)
.filter_map(|id| tree.get(id))
.filter(|n| OPTION_ROLES.contains(&n.role))
.collect();
if !own.is_empty() {
return own;
}
tree.iter()
.filter(|n| n.window == container.window)
.filter(|n| matches!(n.layer, icedwright_semantics::Layer::Overlay(_)))
.filter(|n| OPTION_ROLES.contains(&n.role))
.collect()
}
fn option_value(node: &Node) -> Option<&str> {
node.props
.get("value")
.map(String::as_str)
.or(match &node.value {
Some(Value::Text(text)) => Some(text.as_str()),
_ => None,
})
}
fn pick(tree: &SemanticTree, container: &Node, wanted: &OptionMatch) -> Option<NodePath> {
options_of(tree, container)
.into_iter()
.enumerate()
.find(|(index, n)| {
wanted.picks(
*index,
n.name.as_deref(),
tree.text_content(n.id),
option_value(n),
)
})
.map(|(_, n)| n.path.clone())
}
pub(crate) fn select_option<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
wanted: &OptionMatch,
) -> Result<ActionReport> {
let timeout = h.default_timeout();
let ready = attached(h, subject, timeout, "select_option", &no_refusal)?;
let window = ready.found.window;
if let Some(path) = pick(&ready.found.tree, &ready.found.node, wanted) {
return click(
h,
&subject.at(path, window),
&Click::new(),
"select_option",
ActionKind::SelectOption,
);
}
let mut report = click(
h,
subject,
&Click::new(),
"select_option",
ActionKind::SelectOption,
)?;
let mut picked = None;
let mut seen = Vec::new();
let _ = h.wait_for(timeout, |h| {
let Ok(Ok(found)) = find(h, subject) else {
return false;
};
seen = options_of(&found.tree, &found.node)
.iter()
.map(|n| {
n.name
.clone()
.unwrap_or_else(|| found.tree.text_content(n.id).to_owned())
})
.collect();
picked = pick(&found.tree, &found.node, wanted);
picked.is_some()
})?;
let Some(path) = picked else {
return Err(failed(
"select_option",
subject,
ActionFailure::NoOptions {
node: ready.found.path().clone(),
wanted: wanted.to_string(),
found: seen,
},
));
};
let chosen = click(
h,
&subject.at(path, window),
&Click::new(),
"select_option",
ActionKind::SelectOption,
)?;
report.statuses.extend(chosen.statuses);
report.messages.extend(chosen.messages);
report.point = chosen.point;
report.cursor_left |= chosen.cursor_left;
Ok(report)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Range {
pub(crate) now: f64,
pub(crate) min: f64,
pub(crate) max: f64,
pub(crate) step: Option<f64>,
}
impl Range {
fn of(node: &Node) -> Option<Self> {
let Some(Value::Number {
now,
min: Some(min),
max: Some(max),
step,
}) = node.value
else {
return None;
};
Some(Self {
now,
min,
max,
step,
})
}
pub(crate) fn admits(&self, value: f64) -> bool {
if !value.is_finite() || value < self.min || value > self.max {
return false;
}
let Some(step) = self.step.filter(|s| *s > 0.0) else {
return true;
};
let steps = (value - self.min) / step;
(steps - steps.round()).abs() < 1e-9
}
fn fraction(&self, value: f64) -> f32 {
let span = self.max - self.min;
if span <= 0.0 {
return 0.0;
}
((value - self.min) / span).clamp(0.0, 1.0) as f32
}
}
pub(crate) fn slider_points(
bounds: Rect,
range: &Range,
value: f64,
) -> (Logical<Point>, Logical<Point>) {
let vertical = bounds.height > bounds.width;
let from = range.fraction(range.now);
let to = range.fraction(value);
if vertical {
let inside =
|f: f32| (bounds.height * (1.0 - f)).clamp(0.5, (bounds.height - 0.5).max(0.5));
let press = Point::new(bounds.width / 2.0, inside(from));
let target = Point::new(
bounds.x + bounds.width / 2.0,
bounds.y + bounds.height * (1.0 - to),
);
return (Logical(press), Logical(target));
}
let inside = |f: f32| (bounds.width * f).clamp(0.5, (bounds.width - 0.5).max(0.5));
let press = Point::new(inside(from), bounds.height / 2.0);
let target = Point::new(bounds.x + bounds.width * to, bounds.y + bounds.height / 2.0);
(Logical(press), Logical(target))
}
fn value_reads(node: &Node, value: f64) -> bool {
Range::of(node).is_some_and(|range| (range.now - value).abs() <= 1e-9 * value.abs().max(1.0))
}
pub(crate) fn set_value<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
value: f64,
) -> Result<ActionReport> {
let timeout = h.default_timeout();
let in_range = |found: &Found| {
let Some(range) = Range::of(&found.node) else {
return Err(ActionFailure::NoRange {
node: found.path().clone(),
});
};
if range.admits(value) {
return Ok(());
}
Err(ActionFailure::ValueOutOfRange {
value,
min: range.min,
max: range.max,
step: range.step,
})
};
let ready = attached(h, subject, timeout, "set_value", &in_range)?;
if value_reads(&ready.found.node, value) {
let mut report = report_from(&ready);
report.point = None;
return Ok(report);
}
let report = if ready
.found
.node
.role
.capabilities()
.contains(Capabilities::EDITABLE)
{
let mut report = fill(h, subject, &value.to_string())?;
send_keys(
h,
ready.found.window,
&chord(ModifierSet::NONE, named(NamedKey::Enter)),
VirtualDuration::ZERO,
None,
)?;
report.point = None;
report
} else {
drag_slider(h, subject, &ready.found, value, timeout)?
};
let reads = h.wait_for(
timeout,
|h| matches!(find(h, subject), Ok(Ok(found)) if value_reads(&found.node, value)),
)?;
if reads {
return Ok(report);
}
Err(failed(
"set_value",
subject,
ActionFailure::StateDidNotChange {
node: ready.found.path().clone(),
state: "value".to_owned(),
wanted: value.to_string(),
},
))
}
fn drag_slider<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
found: &Found,
value: f64,
timeout: VirtualDuration,
) -> Result<ActionReport> {
let Some(range) = Range::of(&found.node) else {
return Err(failed(
"set_value",
subject,
ActionFailure::NoRange {
node: found.path().clone(),
},
));
};
let (press, target) = slider_points(found.node.bounds, &range, value);
with_pointer(h, false, |h| {
let mut plan = Plan::new(ActionKind::SetValue, timeout, Probe::Pointer);
plan.position = Some(press);
let ready = actionable(h, subject, &plan, "set_value", &no_refusal)?;
let window = ready.found.window;
let placement = place_press(
&h.devices.history,
&ready.found.tree,
ready.found.path(),
mouse::Button::Left,
ready.point,
true,
)
.map_err(|refusal| refused("set_value", subject, refusal))?;
let mut report = report_from(&ready);
let from = engine::pointer(h, window);
let layout = h.devices.layout.clone();
let gesture = Gesture::Drag {
from: placement.point,
to: target,
steps: drag_steps(),
modifiers: ModifierSet::NONE,
};
report.statuses.extend(send_batches(
h,
window,
gesture_events(&gesture, from, &layout),
false,
)?);
h.devices.history.record(RecordedPress::at(
&ready.found.tree,
ready.found.ordinal(),
mouse::Button::Left,
placement.point.0,
));
Ok((report, Some(window)))
})
}
fn drag_steps() -> NonZeroU16 {
Drag::default().steps
}
pub(crate) fn drag_to<P: TestProgram>(
h: &mut Harness<P>,
source: &Subject,
target: &Subject,
options: &Drag,
) -> Result<ActionReport> {
with_pointer(h, false, |h| {
let timeout = options.timeout.unwrap_or(h.default_timeout());
let mut plan = Plan::new(ActionKind::DragSource, timeout, Probe::Pointer);
plan.position = options.source;
plan.force = options.force;
let from = actionable(h, source, &plan, "drag_to", &no_refusal)?;
let mut drop_plan = Plan::new(ActionKind::DragTarget, timeout, Probe::Deferred);
drop_plan.position = options.target;
drop_plan.force = options.force;
let to = actionable(h, target, &drop_plan, "drag_to", &no_refusal)?;
let window = from.found.window;
let placement = place_press(
&h.devices.history,
&from.found.tree,
from.found.path(),
mouse::Button::Left,
from.point,
options.source.is_some(),
)
.map_err(|refusal| refused("drag_to", source, refusal))?;
let mut report = report_from(&from);
report.nudged_from = placement.nudged_from;
let pointer = engine::pointer(h, window);
let layout = h.devices.layout.clone();
let gesture = Gesture::Drag {
from: placement.point,
to: to.point,
steps: options.steps,
modifiers: options.modifiers,
};
let mut batches = gesture_events(&gesture, pointer, &layout);
let release = batches.pop().unwrap_or_default();
let last_move = batches.pop().unwrap_or_default();
for batch in batches {
report.statuses.extend(deliver(h, window, batch, true)?);
h.next_frame()?;
}
let probed = h.send_probed(window, &last_move)?;
report.statuses.extend(probed.statuses.iter().copied());
let cover = if options.force {
Cover::Clear
} else {
obscured_by(&probed.tree, to.found.path(), to.point, &probed.cursors)
};
h.next_frame()?;
report.statuses.extend(deliver(h, window, release, true)?);
h.devices.history.record(RecordedPress::at(
&from.found.tree,
from.found.ordinal(),
mouse::Button::Left,
placement.point.0,
));
let by = match cover {
Cover::Clear => return Ok((report, Some(window))),
Cover::Covered(by) | Cover::PossiblyCovered { subtree: by } => by,
};
Err(failed(
"drag_to",
target,
ActionFailure::NotActionable(NotActionable::Covered {
node: to.found.path().clone(),
by,
layer: to.found.node.layer,
at: to.point,
}),
))
})
}
pub(crate) fn drop_files<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
paths: Vec<PathBuf>,
) -> Result<ActionReport> {
with_pointer(h, false, |h| {
h.check_file_drops()?;
let timeout = h.default_timeout();
let plan = Plan::new(ActionKind::DragTarget, timeout, Probe::Pointer);
let ready = actionable(h, subject, &plan, "drop_files", &no_refusal)?;
let window = ready.found.window;
let mut events: Vec<window::Event> = paths
.iter()
.cloned()
.map(window::Event::FileHovered)
.collect();
events.extend(paths.into_iter().map(window::Event::FileDropped));
h.window_events(window, events)?;
Ok((report_from(&ready), Some(window)))
})
}
pub(crate) fn scroll<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
delta: Logical<icedwright_types::Vector>,
) -> Result<ActionReport> {
with_pointer(h, false, |h| {
let timeout = h.default_timeout();
let plan = Plan::new(ActionKind::Scroll, timeout, Probe::Pointer);
let ready = actionable(h, subject, &plan, "scroll", &no_refusal)?;
let window = ready.found.window;
let mut report = report_from(&ready);
let layout = h.devices.layout.clone();
let batches = gesture_events(
&Gesture::Wheel {
at: ready.point,
delta,
},
Some(ready.point),
&layout,
);
report
.statuses
.extend(send_batches(h, window, batches, false)?);
Ok((report, Some(window)))
})
}
pub(crate) fn scroll_into_view<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
) -> Result<ActionReport> {
let timeout = h.default_timeout();
let plan = Plan::new(ActionKind::Hover, timeout, Probe::Deferred);
let ready = actionable(h, subject, &plan, "scroll_into_view", &no_refusal)?;
let mut report = report_from(&ready);
report.point = None;
Ok(report)
}
fn is_text_field(node: &Node) -> bool {
node.role.capabilities().contains(Capabilities::EDITABLE)
|| matches!(node.kind, Kind::Inferred(OperationKind::TextInput))
}
pub(crate) fn char_span(
text: &str,
start: Bound<&usize>,
end: Bound<&usize>,
) -> Option<(usize, usize)> {
let from = match start {
Bound::Included(s) => *s,
Bound::Excluded(s) => s.checked_add(1)?,
Bound::Unbounded => 0,
};
let to = match end {
Bound::Included(e) => e.checked_add(1)?,
Bound::Excluded(e) => *e,
Bound::Unbounded => text.len(),
};
let before = text.get(..from)?;
let inside = text.get(from..to)?;
Some((before.chars().count(), inside.chars().count()))
}
fn field_text(found: &Found) -> String {
match &found.node.value {
Some(Value::Text(text)) => text.clone(),
_ => found.tree.text_content(found.node.id).to_owned(),
}
}
pub(crate) fn select_text<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
range: Option<(Bound<usize>, Bound<usize>)>,
) -> Result<ActionReport> {
let timeout = h.default_timeout();
let ready = attached(h, subject, timeout, "select_text", &no_refusal)?;
if is_text_field(&ready.found.node) {
return select_by_keys(h, subject, &ready, range);
}
let node = &ready.found.node;
let Some(visible) = icedwright_check::actionability::visible_part(node) else {
return drag_text(
h,
subject,
node.bounds,
(Point::ORIGIN, Point::ORIGIN),
timeout,
);
};
let ends = match range {
None => {
let y = visible.y + visible.height / 2.0;
(
Point::new(visible.x + 0.5, y),
Point::new(visible.x + visible.width + SELECT_OVERSHOOT, y),
)
}
Some((start, end)) => {
let Some(geometry) = &node.text_geometry else {
return Err(failed(
"select_text_range",
subject,
ActionFailure::NoTextGeometry {
node: node.path.clone(),
},
));
};
let text = ready.found.tree.text_content(node.id);
let (Some(from), Some(to)) = (byte_start(start), byte_end(end, text.len())) else {
return Err(bad_range(subject, text, start, end));
};
let (Some(a), Some(b)) = (geometry.caret(from), geometry.caret(to)) else {
return Err(bad_range(subject, text, start, end));
};
let line = node.text_size.unwrap_or(0.0) / 2.0 + 1.0;
let at = |p: Point| Point::new(node.bounds.x + p.x, node.bounds.y + p.y + line);
(at(a), at(b))
}
};
drag_text(h, subject, node.bounds, ends, timeout)
}
fn byte_start(start: Bound<usize>) -> Option<usize> {
match start {
Bound::Included(s) => Some(s),
Bound::Excluded(s) => s.checked_add(1),
Bound::Unbounded => Some(0),
}
}
fn byte_end(end: Bound<usize>, len: usize) -> Option<usize> {
match end {
Bound::Included(e) => e.checked_add(1),
Bound::Excluded(e) => Some(e),
Bound::Unbounded => Some(len),
}
}
fn bad_range(
subject: &Subject,
text: &str,
start: Bound<usize>,
end: Bound<usize>,
) -> crate::Error {
failed(
"select_text_range",
subject,
ActionFailure::BadRange {
text: text.to_owned(),
range: format!("{:?}", (start, end)),
},
)
}
fn select_by_keys<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
ready: &Ready,
range: Option<(Bound<usize>, Bound<usize>)>,
) -> Result<ActionReport> {
if ready.found.node.focusable_ordinal.is_none() {
return Err(failed(
"select_text",
subject,
ActionFailure::NotFocusable {
node: ready.found.path().clone(),
},
));
}
ensure_focus(h, &ready.found)?;
let text = field_text(&ready.found);
let (start, end) = range.unwrap_or((Bound::Unbounded, Bound::Unbounded));
let Some((before, inside)) = char_span(&text, start.as_ref(), end.as_ref()) else {
return Err(bad_range(subject, &text, start, end));
};
let window = ready.found.window;
let none = VirtualDuration::ZERO;
send_keys(
h,
window,
&chord(ModifierSet::NONE, named(NamedKey::Home)),
none,
None,
)?;
for _ in 0..before {
send_keys(
h,
window,
&chord(ModifierSet::NONE, named(NamedKey::ArrowRight)),
none,
None,
)?;
}
for _ in 0..inside {
send_keys(
h,
window,
&chord(ModifierSet::SHIFT, named(NamedKey::ArrowRight)),
none,
None,
)?;
}
let mut report = report_from(ready);
report.point = None;
Ok(report)
}
fn drag_text<P: TestProgram>(
h: &mut Harness<P>,
subject: &Subject,
bounds: Rect,
(from, to): (Point, Point),
timeout: VirtualDuration,
) -> Result<ActionReport> {
with_pointer(h, false, |h| {
let mut plan = Plan::new(ActionKind::SelectText, timeout, Probe::Pointer);
plan.position = Some(Logical(Point::new(from.x - bounds.x, from.y - bounds.y)));
let ready = actionable(h, subject, &plan, "select_text", &no_refusal)?;
let window = ready.found.window;
let placement = place_press(
&h.devices.history,
&ready.found.tree,
ready.found.path(),
mouse::Button::Left,
ready.point,
true,
)
.map_err(|refusal| refused("select_text", subject, refusal))?;
let mut report = report_from(&ready);
let pointer = engine::pointer(h, window);
let layout = h.devices.layout.clone();
let gesture = Gesture::Drag {
from: placement.point,
to: Logical(to),
steps: drag_steps(),
modifiers: ModifierSet::NONE,
};
report.statuses.extend(send_batches(
h,
window,
gesture_events(&gesture, pointer, &layout),
false,
)?);
h.devices.history.record(RecordedPress::at(
&ready.found.tree,
ready.found.ordinal(),
mouse::Button::Left,
placement.point.0,
));
Ok((report, Some(window)))
})
}