icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! [`ActionError`]: why an action was not sent, or did not take.

use std::fmt;

use icedwright_check::{ClickRefused, NotActionable};
use icedwright_semantics::NodePath;
use icedwright_types::{StateName, VirtualDuration};

/// An action that was not sent, or that the app did not take. Its `Display` is the full
/// message: a heading naming the action and the locator, then the reason.
#[derive(Debug, thiserror::Error)]
#[error("{}", self.message())]
#[non_exhaustive]
pub struct ActionError {
    /// The action, such as `click`.
    pub action: &'static str,
    /// The locator it was aimed at, as Rust, or the point for a raw mouse action.
    pub target: String,
    /// Why.
    pub reason: ActionFailure,
}

/// Why an action failed. Refusals describe the test rather than the app and are returned on
/// the first attempt; the rest come after waiting.
#[derive(Debug)]
#[non_exhaustive]
pub enum ActionFailure {
    /// The node never became actionable within the timeout.
    Timeout {
        /// The timeout, in virtual time.
        timeout: VirtualDuration,
        /// How many attempts ran.
        attempts: u32,
        /// The last thing that kept it from acting.
        last: Box<Blocker>,
    },
    /// Click separation or the multi-click rule refused the press.
    Refused(ClickRefused),
    /// A hover would rest on the trigger of a tooltip that opens after a real-time delay.
    RealClockTooltip {
        /// The trigger.
        trigger: NodePath,
    },
    /// The node cannot take focus.
    NotFocusable {
        /// The node.
        node: NodePath,
    },
    /// The action clicked, and the state did not change.
    StateDidNotChange {
        /// The node.
        node: NodePath,
        /// The state or value waited for.
        state: String,
        /// What it should have read.
        wanted: String,
    },
    /// A check that failed after the input was sent, such as a drop target that something
    /// covered by the end of the drag.
    NotActionable(NotActionable),
    /// The state the action reads is not reported by any source.
    StateUnknown {
        /// The node.
        node: NodePath,
        /// The state.
        state: StateName,
    },
    /// The node has no numeric value range.
    NoRange {
        /// The node.
        node: NodePath,
    },
    /// The value is outside the node's range or off its step.
    ValueOutOfRange {
        /// The value asked for.
        value: f64,
        /// The lowest value.
        min: f64,
        /// The highest value.
        max: f64,
        /// The step, when one is reported.
        step: Option<f64>,
    },
    /// A byte range of a node with no caret geometry.
    NoTextGeometry {
        /// The node.
        node: NodePath,
    },
    /// The byte range is not on character boundaries of the node's text.
    BadRange {
        /// The text.
        text: String,
        /// The range, printed.
        range: String,
    },
    /// The options never appeared after opening the node.
    NoOptions {
        /// The node.
        node: NodePath,
        /// The option asked for.
        wanted: String,
        /// The options that are there, by name.
        found: Vec<String>,
    },
    /// The pointer is outside the window, so there is nothing to press.
    NoPointer,
    /// Input method events were sent to a window whose widgets have not enabled the input
    /// method, which winit never does.
    ImeNotEnabled {
        /// The window's title.
        window: String,
    },
}

/// What kept a node from acting on the last attempt.
#[derive(Debug)]
#[non_exhaustive]
pub enum Blocker {
    /// The locator matched nothing.
    NotAttached(icedwright_locator::Error),
    /// A check did not pass.
    Check(NotActionable),
}

impl fmt::Display for Blocker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Blocker::NotAttached(error) => write!(f, "not attached: {error}"),
            Blocker::Check(check) => write!(f, "{check}"),
        }
    }
}

impl ActionError {
    pub(crate) fn new(
        action: &'static str,
        target: impl Into<String>,
        reason: ActionFailure,
    ) -> Self {
        Self {
            action,
            target: target.into(),
            reason,
        }
    }

    /// Whether the action was refused because of what the test asked, not the app's state.
    #[must_use]
    pub fn is_refusal(&self) -> bool {
        matches!(
            self.reason,
            ActionFailure::Refused(_) | ActionFailure::RealClockTooltip { .. }
        )
    }

    fn message(&self) -> String {
        let verb = match &self.reason {
            ActionFailure::Refused(ClickRefused::RealClockClickCount { .. })
            | ActionFailure::RealClockTooltip { .. } => "is not supported yet",
            ActionFailure::StateDidNotChange { .. } => "did not take",
            _ => "was not sent",
        };
        let mut out = format!("{} on {} {verb}\n\n", self.action, self.target);
        for line in self.reason.to_string().lines() {
            if line.is_empty() {
                out.push('\n');
            } else {
                out.push_str("  ");
                out.push_str(line);
                out.push('\n');
            }
        }
        out
    }
}

impl fmt::Display for ActionFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ActionFailure::Timeout {
                timeout,
                attempts,
                last,
            } => write!(
                f,
                "It did not become actionable within {timeout} of virtual time ({attempts} \
                 attempts). The last attempt found: {last}"
            ),
            ActionFailure::Refused(refused) => write!(f, "{refused}"),
            ActionFailure::RealClockTooltip { trigger } => write!(
                f,
                "{trigger} has a tooltip that opens after a delay. iced's tooltip times that \
                 delay with the real clock (iced_widget/src/tooltip.rs:223), so whether it \
                 shows would depend on how fast this machine is. icedwright never leaves the \
                 pointer resting on such a trigger.\n\nWorks today: a tooltip with a zero \
                 delay.\nWorks everywhere once iced's replaceable clock lands (upstream.md, \
                 clock)."
            ),
            ActionFailure::NotFocusable { node } => write!(
                f,
                "{node} does not report itself as focusable, so it cannot take focus or keys."
            ),
            ActionFailure::StateDidNotChange {
                node,
                state,
                wanted,
            } => write!(
                f,
                "The click was sent, but {state} of {node} never read {wanted}. The app may \
                 not apply the message the widget publishes."
            ),
            ActionFailure::StateUnknown { node, state } => write!(
                f,
                "{state} of {node} is not known: {}",
                icedwright_check::assertion::STATE_REMEDY
            ),
            ActionFailure::NoRange { node } => write!(
                f,
                "{node} reports no numeric value with a range. iced's slider reports nothing \
                 to operations; annotate it with semantic(..).role(role::Slider).range(..)."
            ),
            ActionFailure::ValueOutOfRange {
                value,
                min,
                max,
                step,
            } => {
                write!(f, "{value} is outside the range {min} to {max}")?;
                if let Some(step) = step {
                    write!(f, " or off its step of {step}")?;
                }
                Ok(())
            }
            ActionFailure::NoTextGeometry { node } => write!(
                f,
                "{node} reports no caret positions, so a byte range cannot be turned into \
                 points. iced-cube's selectable text reports them when built with its \
                 icedwright feature."
            ),
            ActionFailure::BadRange { text, range } => {
                write!(f, "{range} is not a range of whole characters in {text:?}")
            }
            ActionFailure::NoOptions {
                node,
                wanted,
                found,
            } => {
                write!(f, "No option matching {wanted} appeared for {node}.")?;
                if found.is_empty() {
                    write!(
                        f,
                        " No options reached the semantic tree at all. iced's own pick_list \
                         menu has no operate (iced_widget/src/overlay/menu.rs), so its options \
                         are invisible to icedwright; annotate the options with \
                         semantic(..).role(role::ListOption), or use iced-cube's select."
                    )
                } else {
                    write!(f, " The options are: {}.", found.join(", "))
                }
            }
            ActionFailure::NotActionable(check) => write!(f, "{check}"),
            ActionFailure::NoPointer => f.write_str(
                "The pointer is outside the window. Move it with mouse().move_to(..) first.",
            ),
            ActionFailure::ImeNotEnabled { window } => write!(
                f,
                "No widget in the window {window:?} has asked for an input method, and winit \
                 only sends input method events to a window that enabled one. Focus a field \
                 that takes text first, for example with click() or focus(); fill() types key \
                 by key into a field that never asks for one."
            ),
        }
    }
}