icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! The fakes the harness owns because it performs the runtime actions: the clipboard and the
//! window requests that have no headless meaning.

pub(crate) mod calls;

use iced_core::{clipboard, window};
use icedwright_types::{VirtualDuration, VirtualInstant};

use crate::effects::UntypedTaskId;

/// Who wrote to the clipboard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Writer {
    /// A widget in this window, during `update`.
    Widget(window::Id),
    /// A task, through `clipboard::write`.
    Task(UntypedTaskId),
    /// The test.
    Test,
}

/// One write to the clipboard.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClipboardWrite {
    /// The standard clipboard or the primary selection.
    pub kind: clipboard::Kind,
    /// What was written.
    pub contents: String,
    /// When.
    pub at: VirtualInstant,
    /// Who wrote it.
    pub by: Writer,
    /// Whether the clipboard was denied, so the write was dropped.
    pub denied: bool,
}

/// The clipboard every interface update and clipboard task uses, with the standard clipboard
/// and the primary selection kept apart.
#[derive(Debug, Clone)]
pub struct FakeClipboard {
    standard: Option<String>,
    primary: Option<String>,
    denied: bool,
    writes: Vec<ClipboardWrite>,
    writer: Writer,
    at: VirtualInstant,
}

impl Default for FakeClipboard {
    fn default() -> Self {
        Self {
            standard: None,
            primary: None,
            denied: false,
            writes: Vec::new(),
            writer: Writer::Test,
            at: VirtualInstant::__from_offset(VirtualDuration::ZERO),
        }
    }
}

impl FakeClipboard {
    /// A clipboard holding `text`.
    #[must_use]
    pub fn with_text(text: impl Into<String>) -> Self {
        Self {
            standard: Some(text.into()),
            ..Self::default()
        }
    }

    /// The standard clipboard.
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        self.standard.as_deref()
    }

    /// The primary selection.
    #[must_use]
    pub fn primary(&self) -> Option<&str> {
        self.primary.as_deref()
    }

    /// Sets the standard clipboard, as another app would.
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.standard = Some(text.into());
    }

    /// Sets the primary selection, as another app would.
    pub fn set_primary(&mut self, text: impl Into<String>) {
        self.primary = Some(text.into());
    }

    /// Empties both.
    pub fn clear(&mut self) {
        self.standard = None;
        self.primary = None;
    }

    /// Denied, reads return nothing and writes are dropped, as in a sandboxed session.
    pub fn deny(&mut self, denied: bool) {
        self.denied = denied;
    }

    /// Every write, in order, denied ones included.
    #[must_use]
    pub fn writes(&self) -> &[ClipboardWrite] {
        &self.writes
    }

    /// Who the next writes come from, and when.
    pub(crate) fn attribute(&mut self, writer: Writer, at: VirtualInstant) {
        self.writer = writer;
        self.at = at;
    }

    pub(crate) fn read_kind(&self, kind: clipboard::Kind) -> Option<String> {
        if self.denied {
            return None;
        }
        match kind {
            clipboard::Kind::Standard => self.standard.clone(),
            clipboard::Kind::Primary => self.primary.clone(),
        }
    }

    pub(crate) fn write_kind(&mut self, kind: clipboard::Kind, contents: String) {
        self.writes.push(ClipboardWrite {
            kind,
            contents: contents.clone(),
            at: self.at,
            by: self.writer,
            denied: self.denied,
        });
        if self.denied {
            return;
        }
        match kind {
            clipboard::Kind::Standard => self.standard = Some(contents),
            clipboard::Kind::Primary => self.primary = Some(contents),
        }
    }
}

impl iced_core::Clipboard for FakeClipboard {
    fn read(&self, kind: clipboard::Kind) -> Option<String> {
        self.read_kind(kind)
    }

    fn write(&mut self, kind: clipboard::Kind, contents: String) {
        self.write_kind(kind, contents);
    }
}

/// A window request with no headless meaning, recorded so a test can assert it was asked.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum WindowRequest {
    /// `window::drag`.
    Drag,
    /// `window::drag_resize`.
    DragResize(window::Direction),
    /// `window::show_system_menu`.
    ShowSystemMenu,
    /// `window::request_user_attention`.
    RequestUserAttention(Option<window::UserAttention>),
    /// `window::set_icon`.
    SetIcon,
    /// Mouse passthrough on or off.
    MousePassthrough(bool),
    /// `window::allow_automatic_tabbing`.
    AutomaticTabbing(bool),
}

/// iced's `Direction` and `UserAttention` have no `PartialEq`; both are fieldless enums, so
/// their `Debug` names identify them.
impl PartialEq for WindowRequest {
    fn eq(&self, other: &Self) -> bool {
        use WindowRequest::{
            AutomaticTabbing, Drag, DragResize, MousePassthrough, RequestUserAttention, SetIcon,
            ShowSystemMenu,
        };
        match (self, other) {
            (Drag, Drag) | (ShowSystemMenu, ShowSystemMenu) | (SetIcon, SetIcon) => true,
            (DragResize(a), DragResize(b)) => format!("{a:?}") == format!("{b:?}"),
            (RequestUserAttention(a), RequestUserAttention(b)) => {
                format!("{a:?}") == format!("{b:?}")
            }
            (MousePassthrough(a), MousePassthrough(b))
            | (AutomaticTabbing(a), AutomaticTabbing(b)) => a == b,
            _ => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use iced_core::Clipboard as _;

    #[test]
    fn standard_and_primary_are_separate() {
        let mut clipboard = FakeClipboard::with_text("copied");
        clipboard.write(clipboard::Kind::Primary, "selected".to_owned());
        assert_eq!(clipboard.text(), Some("copied"));
        assert_eq!(clipboard.primary(), Some("selected"));
        assert_eq!(
            clipboard.read(clipboard::Kind::Standard).as_deref(),
            Some("copied")
        );
        assert_eq!(
            clipboard.read(clipboard::Kind::Primary).as_deref(),
            Some("selected")
        );
        clipboard.clear();
        assert_eq!(clipboard.text(), None);
        assert_eq!(clipboard.primary(), None);
    }

    #[test]
    fn deny_drops_writes_records_them_and_reads_nothing() {
        let mut clipboard = FakeClipboard::with_text("kept");
        clipboard.deny(true);
        clipboard.write(clipboard::Kind::Standard, "dropped".to_owned());
        assert_eq!(clipboard.read(clipboard::Kind::Standard), None);
        clipboard.deny(false);
        assert_eq!(clipboard.text(), Some("kept"));
        assert_eq!(clipboard.writes().len(), 1);
        assert!(clipboard.writes()[0].denied);
        assert_eq!(clipboard.writes()[0].contents, "dropped");
    }

    #[test]
    fn writes_carry_their_writer_and_instant() {
        let mut clipboard = FakeClipboard::default();
        let window = window::Id::unique();
        let at = VirtualInstant::__from_offset(VirtualDuration::from_millis(40));
        clipboard.attribute(Writer::Widget(window), at);
        clipboard.write(clipboard::Kind::Standard, "a".to_owned());
        let task = UntypedTaskId::new(7);
        clipboard.attribute(Writer::Task(task), at);
        clipboard.write(clipboard::Kind::Primary, "b".to_owned());
        let by: Vec<Writer> = clipboard.writes().iter().map(|w| w.by).collect();
        assert_eq!(by, vec![Writer::Widget(window), Writer::Task(task)]);
        assert!(clipboard.writes().iter().all(|w| w.at == at));
    }
}