icedwright-probe 0.1.4

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
Documentation
//! Running [`RawRecorder`] as a `task::widget` operation over every window of a live app.

use std::any::Any;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};

use iced_core::widget::operation::{Focusable, Outcome, Scrollable, TextInput};
use iced_core::widget::{Id, Operation};
use iced_core::{Rectangle, Vector, window};
use icedwright_protocol::{Generation, RawTree, WindowId};

use crate::RawRecorder;

/// A finished recording: the tree, and which window each of its `WindowId`s was.
pub type Recording = (RawTree, Vec<(window::Id, WindowId)>);

/// Where a [`Collect`] leaves its recording when the shell finishes it.
pub type Slot = Arc<Mutex<Option<Recording>>>;

/// The app's generation, which the probe raises and each collection reads as it runs.
///
/// Generations rise only in `update`, and the shell rebuilds every window's view after each
/// `update` before it runs any widget operation, so the generation a collection reads is the
/// one its tree shows. The app's own messages that were already queued when it ran are
/// handled before its recording comes back, so by then the generation can be higher than
/// the tree.
#[derive(Debug, Default)]
pub struct Generations {
    current: AtomicU64,
    read: Mutex<Option<Generation>>,
}

impl Generations {
    /// The generation now.
    #[must_use]
    pub fn current(&self) -> Generation {
        Generation(self.current.load(Ordering::Relaxed))
    }

    /// Raises the generation by one and returns the new one.
    pub fn raise(&self) -> Generation {
        Generation(self.current.fetch_add(1, Ordering::Relaxed) + 1)
    }

    fn note_read(&self) {
        *self.read.lock().unwrap_or_else(PoisonError::into_inner) = Some(self.current());
    }

    /// The generation the last collection read, once.
    pub fn take_read(&self) -> Option<Generation> {
        self.read
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
    }
}

/// Delegates every callback to a [`RawRecorder`] and, when the shell finishes the operation,
/// notes the generation it read and leaves the recording in its slot before yielding `()`,
/// so `task::widget(..).map(..)` can read it.
#[derive(Debug)]
pub struct Collect {
    // `finish` takes `&self`, so the recorder sits behind a lock it can be taken out of.
    recorder: Mutex<Option<RawRecorder>>,
    slot: Slot,
    generations: Arc<Generations>,
}

impl Collect {
    /// An empty recording into `slot`, reading the generation from `generations`.
    #[must_use]
    pub fn new(slot: Slot, generations: Arc<Generations>) -> Self {
        Self {
            recorder: Mutex::new(Some(RawRecorder::new())),
            slot,
            generations,
        }
    }

    fn with(&mut self, f: impl FnOnce(&mut RawRecorder)) {
        let recorder = self
            .recorder
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner);
        if let Some(recorder) = recorder.as_mut() {
            f(recorder);
        }
    }
}

/// Takes the recording out of a slot.
pub fn take(slot: &Slot) -> Option<Recording> {
    slot.lock().unwrap_or_else(PoisonError::into_inner).take()
}

impl Operation for Collect {
    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
        self.with(|recorder| recorder.traverse(operate));
    }

    fn container(&mut self, id: Option<&Id>, bounds: Rectangle) {
        self.with(|recorder| recorder.container(id, bounds));
    }

    fn scrollable(
        &mut self,
        id: Option<&Id>,
        bounds: Rectangle,
        content_bounds: Rectangle,
        translation: Vector,
        state: &mut dyn Scrollable,
    ) {
        self.with(|recorder| recorder.scrollable(id, bounds, content_bounds, translation, state));
    }

    fn focusable(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) {
        self.with(|recorder| recorder.focusable(id, bounds, state));
    }

    fn text_input(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn TextInput) {
        self.with(|recorder| recorder.text_input(id, bounds, state));
    }

    fn text(&mut self, id: Option<&Id>, bounds: Rectangle, text: &str) {
        self.with(|recorder| recorder.text(id, bounds, text));
    }

    fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) {
        self.with(|recorder| recorder.custom(id, bounds, state));
    }

    fn finish(&self) -> Outcome<()> {
        let recorder = self
            .recorder
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        let Some(recorder) = recorder else {
            return Outcome::None;
        };
        let ids: Vec<_> = recorder
            .window_ids()
            .iter()
            .map(|(window, id)| (*window, *id))
            .collect();
        let tree = recorder.into_tree();
        self.generations.note_read();
        *self.slot.lock().unwrap_or_else(PoisonError::into_inner) = Some((tree, ids));
        Outcome::Some(())
    }
}

#[cfg(test)]
mod tests {
    use iced_core::widget::operation::Outcome;

    use super::*;
    use crate::WindowMarker;

    #[test]
    fn two_windows_with_markers_give_two_recordings_in_the_slot() {
        let slot: Slot = Arc::default();
        let mut collect = Collect::new(Arc::clone(&slot), Arc::default());
        let first = window::Id::unique();
        let second = window::Id::unique();
        let bounds = Rectangle::new(iced_core::Point::ORIGIN, iced_core::Size::new(10.0, 10.0));
        collect.custom(None, bounds, &mut WindowMarker(first));
        collect.text(None, bounds, "one");
        collect.custom(None, bounds, &mut WindowMarker(second));
        collect.text(None, bounds, "two");
        assert!(matches!(collect.finish(), Outcome::Some(())));
        let Some((tree, ids)) = take(&slot) else {
            panic!("nothing recorded");
        };
        assert_eq!(tree.windows.len(), 2);
        let mut ids = ids;
        ids.sort_by_key(|(_, id)| *id);
        assert_eq!(ids, vec![(first, WindowId(0)), (second, WindowId(1))]);
        assert!(matches!(collect.finish(), Outcome::None));
    }

    #[test]
    fn a_collection_notes_the_generation_it_ran_at_not_a_later_one() {
        let generations = Arc::new(Generations::default());
        let _ = generations.raise();
        let collect = Collect::new(Arc::default(), Arc::clone(&generations));
        assert!(matches!(collect.finish(), Outcome::Some(())));
        assert_eq!(generations.raise(), Generation(2));
        assert_eq!(generations.take_read(), Some(Generation(1)));
        assert_eq!(generations.take_read(), None);
    }
}