f-office-paint 0.2.4

Display list: the contract between layout and output.
Documentation
//! The one walk of a page's items in painting order ([`Page::painted`]), and the page sink: one
//! set of drawing calls that an output of pages implements, which [`Page::replay`] makes. An
//! output that must hold its state open across a group's items, such as a PDF writer that
//! draws the group in a form of its own, walks [`Page::painted`] itself.

use crate::{GlyphRun, GradientItem, GroupClip, ImageItem, Item, Page, PathItem, Rect};

/// An item that output paints, borrowed from its page: one of the five kinds of item that draw,
/// or the start or the end of a group's clip. A group is never one, because its items paint in
/// its place, between the start and the end of its clip when it has one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Painted<'a> {
    /// Glyphs from one font at one size and color.
    Glyphs(&'a GlyphRun),
    /// A filled rectangle.
    Rect(&'a Rect),
    /// A filled path.
    Path(&'a PathItem),
    /// A path filled with an axial gradient.
    Gradient(&'a GradientItem),
    /// An image scaled to fill a rectangle.
    Image(&'a ImageItem),
    /// The start of a group's clip, which has area: the items up to the matching
    /// [`Painted::ClipEnd`] show nothing outside it. Clips nest.
    ClipStart(&'a GroupClip),
    /// The end of the clip that the last open [`Painted::ClipStart`] started.
    ClipEnd,
}

/// An output of pages, such as the raster: one call for each kind of item that paints.
/// [`Page::replay`] makes the calls in painting order, so the output never walks the items
/// itself.
pub trait PageSink {
    /// Why the output stops drawing the page.
    type Error;

    /// Draws glyphs from one font at one size and color.
    ///
    /// # Errors
    ///
    /// Returns an error when the output cannot draw the run, such as a font that it lacks.
    fn glyphs(&mut self, run: &GlyphRun) -> Result<(), Self::Error>;

    /// Fills a rectangle.
    ///
    /// # Errors
    ///
    /// Returns an error when the output cannot fill it.
    fn rect(&mut self, rect: &Rect) -> Result<(), Self::Error>;

    /// Fills a path.
    ///
    /// # Errors
    ///
    /// Returns an error when the output cannot fill it.
    fn path(&mut self, path: &PathItem) -> Result<(), Self::Error>;

    /// Fills a path with an axial gradient.
    ///
    /// # Errors
    ///
    /// Returns an error when the output cannot fill it.
    fn gradient(&mut self, gradient: &GradientItem) -> Result<(), Self::Error>;

    /// Draws an image scaled to fill its rectangle.
    ///
    /// # Errors
    ///
    /// Returns an error when the output cannot draw it.
    fn image(&mut self, image: &ImageItem) -> Result<(), Self::Error>;

    /// Starts a clip, which has area: the calls up to the matching [`PageSink::clip_end`] show
    /// nothing outside it, nor outside the clips that are open around it.
    ///
    /// # Errors
    ///
    /// Returns an error when the output cannot clip.
    fn clip_start(&mut self, clip: &GroupClip) -> Result<(), Self::Error>;

    /// Ends the clip that the last open [`PageSink::clip_start`] started.
    ///
    /// # Errors
    ///
    /// Returns an error when the output cannot end the clip.
    fn clip_end(&mut self) -> Result<(), Self::Error>;
}

impl Page {
    /// The items that output paints, in painting order: each group's items take the group's
    /// place, between the start and the end of its clip. A group whose clip has no area shows
    /// nothing, so it gives nothing. An output draws them through [`Page::replay`]; callers
    /// that inspect painted items directly read them here.
    #[must_use]
    pub fn painted(&self) -> Vec<Painted<'_>> {
        let mut painted = Vec::new();
        for item in &self.items {
            item.paint_into(&mut painted);
        }
        painted
    }

    /// Sends each item of [`Page::painted`] to `sink`, in order.
    ///
    /// # Errors
    ///
    /// Returns the first error of the sink, and makes no call after it.
    pub fn replay<S: PageSink>(&self, sink: &mut S) -> Result<(), S::Error> {
        self.painted().into_iter().try_for_each(|item| match item {
            Painted::Glyphs(run) => sink.glyphs(run),
            Painted::Rect(rect) => sink.rect(rect),
            Painted::Path(path) => sink.path(path),
            Painted::Gradient(gradient) => sink.gradient(gradient),
            Painted::Image(image) => sink.image(image),
            Painted::ClipStart(clip) => sink.clip_start(clip),
            Painted::ClipEnd => sink.clip_end(),
        })
    }
}

impl Item {
    /// Adds the items that output paints for this item to `painted`: the item itself, or the
    /// items of a group between the start and the end of its clip, or nothing for a group whose
    /// clip has no area.
    fn paint_into<'a>(&'a self, painted: &mut Vec<Painted<'a>>) {
        match self {
            Self::Glyphs(run) => painted.push(Painted::Glyphs(run)),
            Self::Rect(rect) => painted.push(Painted::Rect(rect)),
            Self::Path(path) => painted.push(Painted::Path(path)),
            Self::Gradient(gradient) => painted.push(Painted::Gradient(gradient)),
            Self::Image(image) => painted.push(Painted::Image(image)),
            Self::Group(group) => {
                if group.shows_nothing() {
                    return;
                }
                let clip = group.clip.as_ref();
                if let Some(clip) = clip {
                    painted.push(Painted::ClipStart(clip));
                }
                for item in &group.items {
                    item.paint_into(painted);
                }
                if clip.is_some() {
                    painted.push(Painted::ClipEnd);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::PageSink;
    use crate::{
        FillRule, GlyphRun, GradientItem, Group, GroupClip, GroupPlaces, ImageItem, Item, Page,
        PathItem, Rect, Rgb,
    };
    use f_office_units::Length;

    /// A sink that writes down the left edge of each rectangle, a mark for each path (0) and
    /// each gradient (9), the left edge of each clip's start as a negative number, and a mark
    /// for each clip's end (-100), and stops at a rectangle at `stop`.
    struct Calls {
        made: Vec<i64>,
        stop: i64,
    }

    impl PageSink for Calls {
        type Error = i64;

        fn glyphs(&mut self, _: &GlyphRun) -> Result<(), i64> {
            Err(-1)
        }

        fn rect(&mut self, rect: &Rect) -> Result<(), i64> {
            let x = rect.x.units();
            if x == self.stop {
                return Err(x);
            }
            self.made.push(x);
            Ok(())
        }

        fn path(&mut self, _: &PathItem) -> Result<(), i64> {
            self.made.push(0);
            Ok(())
        }

        fn gradient(&mut self, _: &GradientItem) -> Result<(), i64> {
            self.made.push(9);
            Ok(())
        }

        fn image(&mut self, _: &ImageItem) -> Result<(), i64> {
            Err(-2)
        }

        fn clip_start(&mut self, clip: &GroupClip) -> Result<(), i64> {
            let left = clip
                .commands
                .iter()
                .flat_map(crate::PathCommand::points)
                .map(|p| p.x.units());
            self.made.push(-left.min().unwrap_or_default());
            Ok(())
        }

        fn clip_end(&mut self) -> Result<(), i64> {
            self.made.push(-100);
            Ok(())
        }
    }

    fn clip(x: i64, width: i64) -> GroupClip {
        let u = Length::from_units;
        GroupClip::rect(u(x), Length::ZERO, u(width), u(1))
    }

    fn rect(x: i64) -> Item {
        Item::Rect(Rect {
            x: Length::from_units(x),
            y: Length::ZERO,
            width: Length::from_units(1),
            height: Length::from_units(1),
            color: Rgb::BLACK,
        })
    }

    /// Rectangles at 1 to 4, with 2, a path and a gradient in a group inside a group, which
    /// clips them at 7, and a rectangle at 5 in a group whose clip has no area.
    fn page() -> Page {
        let path = Item::Path(PathItem {
            commands: Vec::new(),
            color: Rgb::BLACK,
            fill_rule: FillRule::NonZero,
        });
        let origin = crate::Point {
            x: Length::ZERO,
            y: Length::ZERO,
        };
        let gradient = Item::Gradient(GradientItem::new(
            Vec::new(),
            FillRule::NonZero,
            (origin, origin),
            Vec::new(),
        ));
        Page {
            width: Length::from_units(10),
            height: Length::from_units(10),
            orientation: crate::Orientation::Portrait,
            items: vec![
                rect(1),
                Item::Group(Group::new(vec![
                    Item::Group(Group {
                        items: vec![rect(2), path, gradient],
                        clip: Some(clip(7, 1)),
                        places: GroupPlaces::Own,
                    }),
                    rect(3),
                ])),
                rect(4),
                Item::Group(Group {
                    items: vec![rect(5)],
                    clip: Some(clip(8, 0)),
                    places: GroupPlaces::Own,
                }),
            ],
        }
    }

    #[test]
    fn replays_a_groups_items_in_its_place_inside_its_clip() {
        let mut calls = Calls {
            made: Vec::new(),
            stop: 0,
        };
        assert_eq!(page().replay(&mut calls), Ok(()));
        assert_eq!(calls.made, [1, -7, 2, 0, 9, -100, 3, 4]);
    }

    #[test]
    fn stops_at_the_first_error_of_the_sink() {
        let mut calls = Calls {
            made: Vec::new(),
            stop: 3,
        };
        assert_eq!(page().replay(&mut calls), Err(3));
        assert_eq!(calls.made, [1, -7, 2, 0, 9, -100]);
    }
}