icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! One window's interface: its cache, renderer and what its last update reported, and the
//! pure decisions made from them.

use iced_core::input_method::InputMethod;
use iced_core::window::RedrawRequest;
use iced_core::{Element, Size, mouse};
use iced_runtime::UserInterface;
use iced_runtime::user_interface::{self, Cache};
use icedwright_probe::HitProbe;
use icedwright_protocol::WindowId;
use icedwright_semantics::{Layer, SemanticTree};
use icedwright_types::Point;

use crate::harness::TestProgram;
use crate::time::{Clock, RealDeadline, VirtualClock, WindowRedraw};

pub(crate) type Interface<'a, P> = UserInterface<
    'a,
    <P as iced_program::Program>::Message,
    <P as iced_program::Program>::Theme,
    <P as iced_program::Program>::Renderer,
>;

/// A window's interface between turns.
pub(crate) struct Surface<P: TestProgram> {
    pub(crate) cache: Option<Cache>,
    pub(crate) renderer: P::Renderer,
    pub(crate) cursor: mouse::Cursor,
    pub(crate) redraw: WindowRedraw,
    pub(crate) mouse_interaction: mouse::Interaction,
    pub(crate) input_method: InputMethod,
    pub(crate) theme: P::Theme,
    pub(crate) deadlines: RealDeadline,
}

impl<P: TestProgram> Surface<P> {
    pub(crate) fn new(renderer: P::Renderer, theme: P::Theme) -> Self {
        Self {
            cache: Some(Cache::default()),
            renderer,
            cursor: mouse::Cursor::Unavailable,
            redraw: WindowRedraw::default(),
            mouse_interaction: mouse::Interaction::None,
            input_method: InputMethod::Disabled,
            theme,
            deadlines: RealDeadline::default(),
        }
    }

    /// Records what an update reported, for a redraw when `redraw` is on and for input
    /// otherwise. Returns whether the layout changed.
    pub(crate) fn record(
        &mut self,
        state: user_interface::State,
        clock: &VirtualClock,
        redraw: bool,
    ) -> bool {
        let user_interface::State::Updated {
            mouse_interaction,
            redraw_request,
            input_method,
            has_layout_changed,
        } = state
        else {
            return true;
        };
        self.mouse_interaction = mouse_interaction;
        self.input_method = input_method;
        match redraw_request {
            RedrawRequest::NextFrame => self.redraw.frame = true,
            RedrawRequest::At(at) => match clock.classify(at) {
                Clock::Virtual(at) => {
                    let timer = if redraw {
                        &mut self.redraw.timer
                    } else {
                        &mut self.redraw.input_timer
                    };
                    *timer = Some(timer.map_or(at, |t| t.min(at)));
                }
                Clock::Real => {
                    self.redraw.real = true;
                    self.deadlines.redraws = self.deadlines.redraws.saturating_add(1);
                }
            },
            RedrawRequest::Wait => {}
        }
        has_layout_changed
    }
}

/// Builds the window's interface from its cache, wrapped in the probe root, runs `f`, and
/// keeps the cache. A `UserInterface` borrows the view, which borrows the state, so it cannot
/// outlive one use.
pub(crate) fn with_ui<P: TestProgram, T>(
    program: &P,
    state: &P::State,
    id: iced_core::window::Id,
    size: Size,
    cache: &mut Option<Cache>,
    renderer: &mut P::Renderer,
    f: impl FnOnce(&mut Interface<'_, P>, &mut P::Renderer) -> T,
) -> T {
    let mut ui = crate::watchdog::app_call("view", || {
        let view: Element<'_, P::Message, P::Theme, P::Renderer> =
            HitProbe::new(program.view(state, id)).into();
        UserInterface::build(view, size, cache.take().unwrap_or_default(), renderer)
    });
    let out = f(&mut ui, renderer);
    *cache = Some(ui.into_cache());
    out
}

/// Collects the probe root's [`LayerCursor`](icedwright_probe::LayerCursor) readings: which
/// kind of cursor each layer was handed for the last mouse event.
#[derive(Debug, Default)]
pub(crate) struct CursorReadings {
    readings: Vec<icedwright_probe::LayerCursor>,
}

impl CursorReadings {
    pub(crate) fn into_layers(self) -> icedwright_check::actionability::LayerCursors {
        self.readings
            .into_iter()
            .filter_map(|reading| {
                let layer = match reading.depth {
                    0 => Layer::Base,
                    depth => Layer::Overlay(depth),
                };
                reading.seen.map(|seen| (layer, seen))
            })
            .fold(
                icedwright_check::actionability::LayerCursors::new(),
                |cursors, (layer, seen)| cursors.with(layer, seen),
            )
    }
}

impl iced_core::widget::Operation for CursorReadings {
    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn iced_core::widget::Operation)) {
        operate(self);
    }

    fn custom(
        &mut self,
        _id: Option<&iced_core::widget::Id>,
        _bounds: iced_core::Rectangle,
        state: &mut dyn std::any::Any,
    ) {
        if let Some(reading) = state.downcast_ref::<icedwright_probe::LayerCursor>() {
            self.readings.push(*reading);
        }
    }
}

/// Whether the pointer at `point` rests on a node with a tooltip whose overlay is not open.
/// Such a tooltip is treated as delayed: a zero-delay one opens in the event that hovered it,
/// so it is open by the end of a settled turn.
pub(crate) fn delayed_tooltip_under(tree: &SemanticTree, window: WindowId, point: Point) -> bool {
    let Some(hit) = tree.hit_test(window, point) else {
        return false;
    };
    let wanted: Vec<&str> = std::iter::once(hit)
        .chain(tree.ancestors(hit))
        .filter_map(|id| tree.get(id))
        .filter_map(|node| node.tooltip.as_deref())
        .collect();
    if wanted.is_empty() {
        return false;
    }
    let open = tree
        .iter()
        .filter(|node| node.window == window && matches!(node.layer, Layer::Overlay(_)))
        .any(|node| {
            let text = tree.text_content(node.id);
            wanted
                .iter()
                .any(|tip| node.name.as_deref() == Some(*tip) || text.contains(*tip))
        });
    !open
}

/// Why iced's time backend cannot run on the virtual clock, from its executor's type name.
pub(crate) fn non_tokio_backend(executor: &'static str) -> Option<&'static str> {
    executor
        .starts_with("iced_futures::backend::native::smol")
        .then_some(executor)
}

#[cfg(test)]
mod tests {
    use super::*;
    use icedwright_semantics::TreeBuilder;
    use icedwright_types::role;

    #[test]
    fn the_backend_check_names_smol_and_passes_the_rest() {
        assert_eq!(
            non_tokio_backend("iced_futures::backend::native::smol::Executor"),
            Some("iced_futures::backend::native::smol::Executor")
        );
        for name in [
            "tokio::runtime::runtime::Runtime",
            "futures_executor::thread_pool::ThreadPool",
            "iced_futures::backend::null::Executor",
            "icedwright::runtime::HarnessExecutor",
        ] {
            assert_eq!(non_tokio_backend(name), None, "{name}");
        }
    }

    #[test]
    fn a_tooltip_trigger_under_the_pointer_with_its_overlay_closed_is_delayed() {
        let tree = TreeBuilder::window("App")
            .child(role::Button, "Save", |b| {
                b.tooltip("Saves the note").bounds(10.0, 10.0, 80.0, 30.0)
            })
            .build();
        let window = tree.get(tree.roots()[0]).unwrap().window;
        assert!(delayed_tooltip_under(&tree, window, Point::new(20.0, 20.0)));
        assert!(!delayed_tooltip_under(
            &tree,
            window,
            Point::new(200.0, 200.0)
        ));
    }

    #[test]
    fn an_open_tooltip_is_left_alone() {
        let tree = TreeBuilder::window("App")
            .child(role::Button, "Save", |b| {
                b.tooltip("Saves the note").bounds(10.0, 10.0, 80.0, 30.0)
            })
            .overlay(1, |o| {
                o.child(role::Tooltip, "Saves the note", |b| {
                    b.bounds(10.0, 45.0, 120.0, 20.0)
                })
            })
            .build();
        let window = tree.get(tree.roots()[0]).unwrap().window;
        assert!(!delayed_tooltip_under(
            &tree,
            window,
            Point::new(20.0, 20.0)
        ));
    }
}