use std::num::NonZeroU16;
use iced_core::keyboard::key::{Code, Named, Physical};
use iced_core::keyboard::{self, Key, Location};
use iced_core::{Event, input_method, mouse, window};
use icedwright_check::clicks::{PressHistory, RecordedPress, place_press};
use icedwright_check::input::{Gesture, gesture_events};
use icedwright_check::{ClickCount, KeyboardLayout};
use icedwright_types::input::{Chord, Keystroke, Modifier, ModifierSet, NamedKey};
use icedwright_types::{Logical, Point, Vector};
use super::error::{ActionError, ActionFailure};
use super::options::Click;
use super::pointer;
use crate::error::{HarnessError, Result};
use crate::harness::{Harness, TestProgram};
#[derive(Debug, Default)]
pub(crate) struct Devices {
pub(crate) history: PressHistory,
pub(crate) layout: KeyboardLayout,
held: ModifierSet,
holding: u32,
}
impl Devices {
pub(crate) fn pointer_held(&self) -> bool {
self.holding > 0
}
pub(crate) fn hold(&mut self) {
self.holding += 1;
}
pub(crate) fn release(&mut self) {
self.holding = self.holding.saturating_sub(1);
}
pub(crate) fn held(&self) -> ModifierSet {
self.held
}
}
impl<P: TestProgram> Harness<P> {
pub fn mouse(&mut self) -> Mouse<'_, P> {
Mouse { harness: self }
}
pub fn keyboard(&mut self) -> Keyboard<'_, P> {
Keyboard { harness: self }
}
pub fn ime(&mut self) -> Ime<'_, P> {
Ime { harness: self }
}
fn focused_window(&self) -> Result<window::Id> {
Ok(self.focused().ok_or(HarnessError::NoWindow)?)
}
}
#[must_use]
pub struct Mouse<'h, P: TestProgram> {
harness: &'h mut Harness<P>,
}
impl<P: TestProgram> std::fmt::Debug for Mouse<'_, P> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Mouse").finish_non_exhaustive()
}
}
impl<P: TestProgram> Mouse<'_, P> {
pub fn move_to(&mut self, to: impl Into<Logical<Point>>, steps: NonZeroU16) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
let from = super::engine::pointer(h, window);
let layout = h.devices.layout.clone();
let batches = gesture_events(
&Gesture::Move {
to: to.into(),
steps,
},
from,
&layout,
);
pointer::send_frames(h, window, batches)
}
pub fn down(&mut self, button: mouse::Button) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
let at = super::engine::pointer(h, window).ok_or_else(|| {
ActionError::new("mouse().down", "the pointer", ActionFailure::NoPointer)
})?;
place_fixed(h, window, button, at, "mouse().down")?;
let _ = super::engine::deliver(
h,
window,
vec![Event::Mouse(mouse::Event::ButtonPressed(button))],
true,
)?;
Ok(())
}
pub fn up(&mut self, button: mouse::Button) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
let _ = super::engine::deliver(
h,
window,
vec![Event::Mouse(mouse::Event::ButtonReleased(button))],
true,
)?;
Ok(())
}
pub fn click(&mut self, at: impl Into<Logical<Point>>, options: Click) -> Result {
let at = at.into();
let h = &mut *self.harness;
let window = h.focused_window()?;
let tree = h.tree_of(window)?;
let ordinal = window_ordinal(h, window)?;
let label = format!("the point {},{}", at.0.x.round(), at.0.y.round());
if options.count != ClickCount::Single
&& let Some(id) = tree.hit_test(ordinal, at.0)
&& let Some(node) = tree.get(id)
{
icedwright_check::clicks::multi_click_allowed(&tree, &node.path).map_err(
|refused| {
ActionError::new(
"mouse().click",
label.clone(),
ActionFailure::Refused(refused),
)
},
)?;
}
place_fixed(h, window, options.button, at, "mouse().click")?;
let from = super::engine::pointer(h, window);
let layout = h.devices.layout.clone();
let gesture = Gesture::Click {
at,
button: options.button,
count: options.count,
modifiers: options.modifiers,
};
h.devices.hold();
let sent = pointer::send_click(
h,
window,
gesture_events(&gesture, from, &layout),
options.count,
);
h.devices.release();
sent?;
h.run_until_settled()
}
pub fn wheel(&mut self, delta: impl Into<Logical<Vector>>) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
let at = super::engine::pointer(h, window).ok_or_else(|| {
ActionError::new("mouse().wheel", "the pointer", ActionFailure::NoPointer)
})?;
let layout = h.devices.layout.clone();
let batches = gesture_events(
&Gesture::Wheel {
at,
delta: delta.into(),
},
Some(at),
&layout,
);
pointer::send_frames(h, window, batches)
}
pub fn leave(&mut self) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
let _ = super::engine::deliver(
h,
window,
vec![Event::Mouse(mouse::Event::CursorLeft)],
true,
)?;
Ok(())
}
#[must_use]
pub fn position(&self) -> Option<Logical<Point>> {
let window = self.harness.focused()?;
super::engine::pointer(self.harness, window)
}
}
fn window_ordinal<P: TestProgram>(
h: &Harness<P>,
window: window::Id,
) -> Result<icedwright_protocol::WindowId> {
Ok(icedwright_protocol::WindowId(h.set.get(window)?.ordinal))
}
fn place_fixed<P: TestProgram>(
h: &mut Harness<P>,
window: window::Id,
button: mouse::Button,
at: Logical<Point>,
action: &'static str,
) -> Result {
let tree = h.tree_of(window)?;
let ordinal = window_ordinal(h, window)?;
let label = format!("the point {},{}", at.0.x.round(), at.0.y.round());
if let Some(id) = tree.hit_test(ordinal, at.0)
&& let Some(node) = tree.get(id)
{
place_press(&h.devices.history, &tree, &node.path, button, at, true)
.map_err(|refused| ActionError::new(action, label, ActionFailure::Refused(refused)))?;
}
h.devices
.history
.record(RecordedPress::at(&tree, ordinal, button, at.0));
Ok(())
}
#[must_use]
pub struct Keyboard<'h, P: TestProgram> {
harness: &'h mut Harness<P>,
}
impl<P: TestProgram> std::fmt::Debug for Keyboard<'_, P> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Keyboard").finish_non_exhaustive()
}
}
fn modifier_of(key: Keystroke) -> Option<Modifier> {
match key {
Keystroke::Named(NamedKey::Shift) => Some(Modifier::Shift),
Keystroke::Named(NamedKey::Control) => Some(Modifier::Control),
Keystroke::Named(NamedKey::Alt) => Some(Modifier::Alt),
Keystroke::Named(NamedKey::Super | NamedKey::Meta) => Some(Modifier::Meta),
_ => None,
}
}
fn modifier_event(modifier: Modifier, down: bool, held: ModifierSet) -> Event {
let (named, code) = match modifier {
Modifier::Shift => (Named::Shift, Code::ShiftLeft),
Modifier::Alt => (Named::Alt, Code::AltLeft),
Modifier::Meta => (Named::Super, Code::SuperLeft),
_ => (Named::Control, Code::ControlLeft),
};
let key = Key::Named(named);
let physical_key = Physical::Code(code);
Event::Keyboard(if down {
keyboard::Event::KeyPressed {
key: key.clone(),
modified_key: key,
physical_key,
location: Location::Left,
modifiers: held.into(),
text: None,
repeat: false,
}
} else {
keyboard::Event::KeyReleased {
key: key.clone(),
modified_key: key,
physical_key,
location: Location::Left,
modifiers: held.into(),
}
})
}
fn is_modifier_key(key: &Key) -> bool {
matches!(
key,
Key::Named(Named::Shift | Named::Control | Named::Alt | Named::Super | Named::AltGraph)
)
}
fn key_event(
key: Keystroke,
held: ModifierSet,
layout: &KeyboardLayout,
down: bool,
) -> Option<Event> {
let batches = gesture_events(&Gesture::Chord(Chord::new(held, key)), None, layout);
batches.into_iter().flatten().find(|event| match event {
Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) if down => !is_modifier_key(key),
Event::Keyboard(keyboard::Event::KeyReleased { key, .. }) if !down => !is_modifier_key(key),
_ => false,
})
}
impl<P: TestProgram> Keyboard<'_, P> {
#[track_caller]
pub fn press(&mut self, chord: Chord) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
pointer::send_keys(
h,
window,
&Gesture::Chord(chord),
icedwright_types::VirtualDuration::ZERO,
None,
)
}
pub fn down(&mut self, key: Keystroke) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
let events = match modifier_of(key) {
Some(modifier) => {
let held = h.devices.held.with(modifier);
h.devices.held = held;
vec![
Event::Keyboard(keyboard::Event::ModifiersChanged(held.into())),
modifier_event(modifier, true, held),
]
}
None => key_event(key, h.devices.held, &h.devices.layout, true)
.into_iter()
.collect(),
};
let _ = super::engine::deliver(h, window, events, true)?;
Ok(())
}
pub fn up(&mut self, key: Keystroke) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
let events = match modifier_of(key) {
Some(modifier) => {
let before = h.devices.held;
let after: ModifierSet = before.iter().filter(|m| *m != modifier).collect();
h.devices.held = after;
vec![
modifier_event(modifier, false, before),
Event::Keyboard(keyboard::Event::ModifiersChanged(after.into())),
]
}
None => key_event(key, h.devices.held, &h.devices.layout, false)
.into_iter()
.collect(),
};
let _ = super::engine::deliver(h, window, events, true)?;
Ok(())
}
#[track_caller]
pub fn type_text(&mut self, text: &str) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
pointer::send_keys(
h,
window,
&Gesture::Type(text.to_owned()),
icedwright_types::VirtualDuration::ZERO,
None,
)
}
pub fn insert_text(&mut self, text: &str) -> Result {
let h = &mut *self.harness;
let window = h.focused_window()?;
pointer::send_keys(
h,
window,
&Gesture::Commit(text.to_owned()),
icedwright_types::VirtualDuration::ZERO,
None,
)
}
pub fn layout(&mut self, layout: KeyboardLayout) {
self.harness.devices.layout = layout;
}
#[must_use]
pub fn held(&self) -> ModifierSet {
self.harness.devices.held()
}
}
#[must_use]
pub struct Ime<'h, P: TestProgram> {
harness: &'h mut Harness<P>,
}
impl<P: TestProgram> std::fmt::Debug for Ime<'_, P> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Ime").finish_non_exhaustive()
}
}
fn ime_window<P: TestProgram>(h: &Harness<P>, action: &'static str) -> Result<window::Id> {
let window = h.focused_window()?;
if matches!(
h.input_method(window)?,
iced_core::InputMethod::Enabled { .. }
) {
return Ok(window);
}
let title = h.window_info(window)?.title.clone();
Err(ActionError::new(
action,
"the focused window",
ActionFailure::ImeNotEnabled { window: title },
)
.into())
}
impl<P: TestProgram> Ime<'_, P> {
fn send(&mut self, action: &'static str, events: Vec<input_method::Event>) -> Result {
let h = &mut *self.harness;
let window = ime_window(h, action)?;
let events = events.into_iter().map(Event::InputMethod).collect();
let _ = super::engine::deliver(h, window, events, true)?;
Ok(())
}
pub fn open(&mut self) -> Result {
self.send("ime().open", vec![input_method::Event::Opened])
}
pub fn preedit(&mut self, text: &str, cursor: Option<std::ops::Range<usize>>) -> Result {
self.send(
"ime().preedit",
vec![input_method::Event::Preedit(text.to_owned(), cursor)],
)
}
pub fn commit(&mut self, text: &str) -> Result {
self.send(
"ime().commit",
vec![input_method::Event::Commit(text.to_owned())],
)
}
pub fn close(&mut self) -> Result {
self.send("ime().close", vec![input_method::Event::Closed])
}
pub fn compose(&mut self, steps: &[&str], result: &str) -> Result {
let h = &mut *self.harness;
let window = ime_window(h, "ime().compose")?;
let gesture = Gesture::Compose {
steps: steps.iter().map(|s| (*s).to_owned()).collect(),
result: result.to_owned(),
};
pointer::send_keys(
h,
window,
&gesture,
icedwright_types::VirtualDuration::ZERO,
None,
)
}
pub fn requested(&self) -> Result<iced_core::InputMethod> {
let window = self.harness.focused_window()?;
Ok(self.harness.input_method(window)?.clone())
}
}