icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! Every action on [`Handle`]. Methods that only make sense for some roles carry a
//! method-level `where` clause naming a capability, so misuse is a compile error.

use std::ops::RangeBounds;
use std::path::PathBuf;

use icedwright_check::ActionReport;
use icedwright_check::ClickCount;
use icedwright_check::actionability::ActionKind;
use icedwright_locator::{IntoLocator, RoleKind};
use icedwright_trace::{CanonicalSelector, SelectorText, StepKind};
use icedwright_types::input::Chord;
use icedwright_types::role::{
    Checkable, Editable, Expandable, Pressable, RangeValue, Selectable, SelectableItem,
};
use icedwright_types::{Logical, StateName, Vector};

use super::engine::Subject;
use super::options::{Click, Drag, Hover, OptionMatch, Type};
use super::pointer::{self, Toggle};
use crate::error::Result;
use crate::harness::{Handle, TestProgram};

/// What an action returns: its [`ActionReport`]. Most tests drop it, which `click()?;` does
/// without a warning; the report itself is `#[must_use]` for code that builds one.
#[derive(Debug, Clone, PartialEq)]
pub struct Done {
    /// What the action did.
    pub report: ActionReport,
}

/// A locator's canonical text, for the trace.
struct Canonical(String);

impl CanonicalSelector for Canonical {
    fn canonical(&self) -> String {
        self.0.clone()
    }
}

fn kind_of(action: &str, subject: &Subject) -> StepKind {
    StepKind::Action {
        action: action.to_owned(),
        locator: Some(SelectorText::of(&Canonical(subject.locator.to_string()))),
        resolved: None,
        point: None,
    }
}

impl<'h, P: TestProgram, R: RoleKind> Handle<'h, P, R> {
    fn subject(&self) -> Subject {
        Subject::new(self.locator.clone().any_role(), self.window)
    }

    #[track_caller]
    fn act(
        &mut self,
        action: &'static str,
        run: impl FnOnce(&mut crate::Harness<P>, &Subject) -> Result<ActionReport>,
    ) -> Result<Done> {
        let subject = self.subject();
        let kind = kind_of(action, &subject);
        self.harness
            .step(|| kind, |h| run(h, &subject))
            .map(|report| Done { report })
    }

    /// Clicks the centre of the node's visible part once it is visible, stable, enabled and
    /// not covered, scrolling it into view first.
    #[track_caller]
    pub fn click(&mut self) -> Result<Done> {
        self.click_with(Click::new())
    }

    /// Clicks with options: another button, a count, a position, held modifiers, `force`,
    /// `trial` or `no_wait_after`.
    #[track_caller]
    pub fn click_with(&mut self, options: Click) -> Result<Done> {
        let (action, kind) = match (options.count, options.button) {
            (ClickCount::Double, _) => ("dblclick", ActionKind::DoubleClick),
            (ClickCount::Triple, _) => ("triple_click", ActionKind::TripleClick),
            (ClickCount::Single, iced_core::mouse::Button::Right) => {
                ("right_click", ActionKind::RightClick)
            }
            (ClickCount::Single, _) => ("click", ActionKind::Click),
        };
        self.act(action, |h, subject| {
            pointer::click(h, subject, &options, action, kind)
        })
    }

    /// A double click. Refused at once unless the node declares that it counts clicks with
    /// the app's clock, since iced counts them with the real one.
    #[track_caller]
    pub fn dblclick(&mut self) -> Result<Done> {
        self.click_with(Click::new().count(ClickCount::Double))
    }

    /// A triple click, refused as [`Handle::dblclick`] is.
    #[track_caller]
    pub fn triple_click(&mut self) -> Result<Done> {
        self.click_with(Click::new().count(ClickCount::Triple))
    }

    /// A right click.
    #[track_caller]
    pub fn right_click(&mut self) -> Result<Done> {
        self.click_with(Click::new().button(iced_core::mouse::Button::Right))
    }

    /// Rests the pointer on the node. Refused over the trigger of a tooltip with a delay.
    #[track_caller]
    pub fn hover(&mut self) -> Result<Done> {
        self.hover_with(Hover::new())
    }

    /// Hovers with options.
    #[track_caller]
    pub fn hover_with(&mut self, options: Hover) -> Result<Done> {
        self.act("hover", |h, subject| pointer::hover(h, subject, &options))
    }

    /// Gives the node keyboard focus through a focus operation, with no press.
    #[track_caller]
    pub fn focus(&mut self) -> Result<Done> {
        self.act("focus", pointer::focus)
    }

    /// Presses a chord with the node focused.
    #[track_caller]
    pub fn press(&mut self, chord: Chord) -> Result<Done> {
        self.act("press", |h, subject| pointer::press(h, subject, chord))
    }

    /// Drags the node onto another, in five frames by default.
    #[track_caller]
    pub fn drag_to<A: RoleKind>(&mut self, target: impl IntoLocator<A>) -> Result<Done> {
        self.drag_with(target, Drag::new())
    }

    /// Drags with options.
    #[track_caller]
    pub fn drag_with<A: RoleKind>(
        &mut self,
        target: impl IntoLocator<A>,
        options: Drag,
    ) -> Result<Done> {
        let target = Subject::new(target.into_locator().any_role(), self.window);
        self.act("drag_to", |h, subject| {
            pointer::drag_to(h, subject, &target, &options)
        })
    }

    /// Moves the pointer over the node and drops files on its window, as a drag from outside
    /// the window does.
    #[track_caller]
    pub fn drop_files(
        &mut self,
        paths: impl IntoIterator<Item = impl Into<PathBuf>>,
    ) -> Result<Done> {
        let paths: Vec<PathBuf> = paths.into_iter().map(Into::into).collect();
        self.act("drop_files", |h, subject| {
            pointer::drop_files(h, subject, paths)
        })
    }

    /// One wheel scroll of `delta` logical pixels at the node.
    #[track_caller]
    pub fn scroll(&mut self, delta: impl Into<Logical<Vector>>) -> Result<Done> {
        let delta = delta.into();
        self.act("scroll", |h, subject| pointer::scroll(h, subject, delta))
    }

    /// Scrolls every ancestor scrollable until the node is in view.
    #[track_caller]
    pub fn scroll_into_view(&mut self) -> Result<Done> {
        self.act("scroll_into_view", pointer::scroll_into_view)
    }

    /// Selects all of the node's text: by keyboard in a text field, by a drag elsewhere.
    #[track_caller]
    pub fn select_text(&mut self) -> Result<Done> {
        self.act("select_text", |h, subject| {
            pointer::select_text(h, subject, None)
        })
    }

    /// Selects a byte range of the node's text.
    #[track_caller]
    pub fn select_text_range(&mut self, range: impl RangeBounds<usize>) -> Result<Done> {
        let bounds = (range.start_bound().cloned(), range.end_bound().cloned());
        self.act("select_text_range", |h, subject| {
            pointer::select_text(h, subject, Some(bounds))
        })
    }

    #[track_caller]
    fn toggle(&mut self, action: &'static str, state: StateName, want: bool) -> Result<Done> {
        let toggle = Toggle {
            action,
            state,
            want,
        };
        self.act(action, |h, subject| pointer::toggle(h, subject, toggle))
    }

    /// Clicks the node if it is not checked, then waits until it is.
    #[track_caller]
    pub fn check(&mut self) -> Result<Done>
    where
        R: Checkable,
    {
        self.toggle("check", StateName::Checked, true)
    }

    /// Clicks the node if it is checked, then waits until it is not.
    #[track_caller]
    pub fn uncheck(&mut self) -> Result<Done>
    where
        R: Checkable,
    {
        self.toggle("uncheck", StateName::Checked, false)
    }

    /// [`Handle::check`] or [`Handle::uncheck`].
    #[track_caller]
    pub fn set_checked(&mut self, checked: bool) -> Result<Done>
    where
        R: Checkable,
    {
        self.toggle("set_checked", StateName::Checked, checked)
    }

    /// Clicks a toggle button if its pressed state differs, then waits for it.
    #[track_caller]
    pub fn press_toggle(&mut self, pressed: bool) -> Result<Done>
    where
        R: Pressable,
    {
        self.toggle("press_toggle", StateName::Pressed, pressed)
    }

    /// Clicks the node, or a tree item's disclosure, if it is collapsed, then waits.
    #[track_caller]
    pub fn expand(&mut self) -> Result<Done>
    where
        R: Expandable,
    {
        self.toggle("expand", StateName::Expanded, true)
    }

    /// Clicks the node if it is expanded, then waits.
    #[track_caller]
    pub fn collapse(&mut self) -> Result<Done>
    where
        R: Expandable,
    {
        self.toggle("collapse", StateName::Expanded, false)
    }

    /// Sets the whole value in one go: focus, select all, one input method commit.
    #[track_caller]
    pub fn fill(&mut self, text: &str) -> Result<Done>
    where
        R: Editable,
    {
        self.act("fill", |h, subject| pointer::fill(h, subject, text))
    }

    /// Empties the field.
    #[track_caller]
    pub fn clear(&mut self) -> Result<Done>
    where
        R: Editable,
    {
        self.act("clear", pointer::clear)
    }

    /// Types into the field key by key, through the keyboard layout.
    #[track_caller]
    pub fn press_sequentially(&mut self, text: &str) -> Result<Done>
    where
        R: Editable,
    {
        self.press_sequentially_with(text, Type::new())
    }

    /// Types with options: a delay between keys or another layout.
    #[track_caller]
    pub fn press_sequentially_with(&mut self, text: &str, options: Type) -> Result<Done>
    where
        R: Editable,
    {
        self.act("press_sequentially", |h, subject| {
            pointer::press_sequentially(h, subject, text, &options)
        })
    }

    /// Opens a combo box, list box or tab list where it opens and picks an option.
    #[track_caller]
    pub fn select_option(&mut self, option: impl Into<OptionMatch>) -> Result<Done>
    where
        R: Selectable,
    {
        let option = option.into();
        self.act("select_option", |h, subject| {
            pointer::select_option(h, subject, &option)
        })
    }

    /// Clicks an option, tab, row or item if it is not selected, then waits until it is.
    #[track_caller]
    pub fn select(&mut self) -> Result<Done>
    where
        R: SelectableItem,
    {
        self.toggle("select", StateName::Selected, true)
    }

    /// Moves a slider or spin button to `value`, which must lie in its range and on its step.
    #[track_caller]
    pub fn set_value(&mut self, value: f64) -> Result<Done>
    where
        R: RangeValue,
    {
        self.act("set_value", |h, subject| {
            pointer::set_value(h, subject, value)
        })
    }
}