Skip to main content

f_office_paint/
sink.rs

1//! The one walk of a page's items in painting order ([`Page::painted`]), and the page sink: one
2//! set of drawing calls that an output of pages implements, which [`Page::replay`] makes. An
3//! output that must hold its state open across a group's items, such as a PDF writer that
4//! draws the group in a form of its own, walks [`Page::painted`] itself.
5
6use crate::{GlyphRun, GradientItem, GroupClip, ImageItem, Item, Page, PathItem, Rect};
7
8/// An item that output paints, borrowed from its page: one of the five kinds of item that draw,
9/// or the start or the end of a group's clip. A group is never one, because its items paint in
10/// its place, between the start and the end of its clip when it has one.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Painted<'a> {
13    /// Glyphs from one font at one size and color.
14    Glyphs(&'a GlyphRun),
15    /// A filled rectangle.
16    Rect(&'a Rect),
17    /// A filled path.
18    Path(&'a PathItem),
19    /// A path filled with an axial gradient.
20    Gradient(&'a GradientItem),
21    /// An image scaled to fill a rectangle.
22    Image(&'a ImageItem),
23    /// The start of a group's clip, which has area: the items up to the matching
24    /// [`Painted::ClipEnd`] show nothing outside it. Clips nest.
25    ClipStart(&'a GroupClip),
26    /// The end of the clip that the last open [`Painted::ClipStart`] started.
27    ClipEnd,
28}
29
30/// An output of pages, such as the raster: one call for each kind of item that paints.
31/// [`Page::replay`] makes the calls in painting order, so the output never walks the items
32/// itself.
33pub trait PageSink {
34    /// Why the output stops drawing the page.
35    type Error;
36
37    /// Draws glyphs from one font at one size and color.
38    ///
39    /// # Errors
40    ///
41    /// Returns an error when the output cannot draw the run, such as a font that it lacks.
42    fn glyphs(&mut self, run: &GlyphRun) -> Result<(), Self::Error>;
43
44    /// Fills a rectangle.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error when the output cannot fill it.
49    fn rect(&mut self, rect: &Rect) -> Result<(), Self::Error>;
50
51    /// Fills a path.
52    ///
53    /// # Errors
54    ///
55    /// Returns an error when the output cannot fill it.
56    fn path(&mut self, path: &PathItem) -> Result<(), Self::Error>;
57
58    /// Fills a path with an axial gradient.
59    ///
60    /// # Errors
61    ///
62    /// Returns an error when the output cannot fill it.
63    fn gradient(&mut self, gradient: &GradientItem) -> Result<(), Self::Error>;
64
65    /// Draws an image scaled to fill its rectangle.
66    ///
67    /// # Errors
68    ///
69    /// Returns an error when the output cannot draw it.
70    fn image(&mut self, image: &ImageItem) -> Result<(), Self::Error>;
71
72    /// Starts a clip, which has area: the calls up to the matching [`PageSink::clip_end`] show
73    /// nothing outside it, nor outside the clips that are open around it.
74    ///
75    /// # Errors
76    ///
77    /// Returns an error when the output cannot clip.
78    fn clip_start(&mut self, clip: &GroupClip) -> Result<(), Self::Error>;
79
80    /// Ends the clip that the last open [`PageSink::clip_start`] started.
81    ///
82    /// # Errors
83    ///
84    /// Returns an error when the output cannot end the clip.
85    fn clip_end(&mut self) -> Result<(), Self::Error>;
86}
87
88impl Page {
89    /// The items that output paints, in painting order: each group's items take the group's
90    /// place, between the start and the end of its clip. A group whose clip has no area shows
91    /// nothing, so it gives nothing. An output draws them through [`Page::replay`]; callers
92    /// that inspect painted items directly read them here.
93    #[must_use]
94    pub fn painted(&self) -> Vec<Painted<'_>> {
95        let mut painted = Vec::new();
96        for item in &self.items {
97            item.paint_into(&mut painted);
98        }
99        painted
100    }
101
102    /// Sends each item of [`Page::painted`] to `sink`, in order.
103    ///
104    /// # Errors
105    ///
106    /// Returns the first error of the sink, and makes no call after it.
107    pub fn replay<S: PageSink>(&self, sink: &mut S) -> Result<(), S::Error> {
108        self.painted().into_iter().try_for_each(|item| match item {
109            Painted::Glyphs(run) => sink.glyphs(run),
110            Painted::Rect(rect) => sink.rect(rect),
111            Painted::Path(path) => sink.path(path),
112            Painted::Gradient(gradient) => sink.gradient(gradient),
113            Painted::Image(image) => sink.image(image),
114            Painted::ClipStart(clip) => sink.clip_start(clip),
115            Painted::ClipEnd => sink.clip_end(),
116        })
117    }
118}
119
120impl Item {
121    /// Adds the items that output paints for this item to `painted`: the item itself, or the
122    /// items of a group between the start and the end of its clip, or nothing for a group whose
123    /// clip has no area.
124    fn paint_into<'a>(&'a self, painted: &mut Vec<Painted<'a>>) {
125        match self {
126            Self::Glyphs(run) => painted.push(Painted::Glyphs(run)),
127            Self::Rect(rect) => painted.push(Painted::Rect(rect)),
128            Self::Path(path) => painted.push(Painted::Path(path)),
129            Self::Gradient(gradient) => painted.push(Painted::Gradient(gradient)),
130            Self::Image(image) => painted.push(Painted::Image(image)),
131            Self::Group(group) => {
132                if group.shows_nothing() {
133                    return;
134                }
135                let clip = group.clip.as_ref();
136                if let Some(clip) = clip {
137                    painted.push(Painted::ClipStart(clip));
138                }
139                for item in &group.items {
140                    item.paint_into(painted);
141                }
142                if clip.is_some() {
143                    painted.push(Painted::ClipEnd);
144                }
145            }
146        }
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::PageSink;
153    use crate::{
154        FillRule, GlyphRun, GradientItem, Group, GroupClip, GroupPlaces, ImageItem, Item, Page,
155        PathItem, Rect, Rgb,
156    };
157    use f_office_units::Length;
158
159    /// A sink that writes down the left edge of each rectangle, a mark for each path (0) and
160    /// each gradient (9), the left edge of each clip's start as a negative number, and a mark
161    /// for each clip's end (-100), and stops at a rectangle at `stop`.
162    struct Calls {
163        made: Vec<i64>,
164        stop: i64,
165    }
166
167    impl PageSink for Calls {
168        type Error = i64;
169
170        fn glyphs(&mut self, _: &GlyphRun) -> Result<(), i64> {
171            Err(-1)
172        }
173
174        fn rect(&mut self, rect: &Rect) -> Result<(), i64> {
175            let x = rect.x.units();
176            if x == self.stop {
177                return Err(x);
178            }
179            self.made.push(x);
180            Ok(())
181        }
182
183        fn path(&mut self, _: &PathItem) -> Result<(), i64> {
184            self.made.push(0);
185            Ok(())
186        }
187
188        fn gradient(&mut self, _: &GradientItem) -> Result<(), i64> {
189            self.made.push(9);
190            Ok(())
191        }
192
193        fn image(&mut self, _: &ImageItem) -> Result<(), i64> {
194            Err(-2)
195        }
196
197        fn clip_start(&mut self, clip: &GroupClip) -> Result<(), i64> {
198            let left = clip
199                .commands
200                .iter()
201                .flat_map(crate::PathCommand::points)
202                .map(|p| p.x.units());
203            self.made.push(-left.min().unwrap_or_default());
204            Ok(())
205        }
206
207        fn clip_end(&mut self) -> Result<(), i64> {
208            self.made.push(-100);
209            Ok(())
210        }
211    }
212
213    fn clip(x: i64, width: i64) -> GroupClip {
214        let u = Length::from_units;
215        GroupClip::rect(u(x), Length::ZERO, u(width), u(1))
216    }
217
218    fn rect(x: i64) -> Item {
219        Item::Rect(Rect {
220            x: Length::from_units(x),
221            y: Length::ZERO,
222            width: Length::from_units(1),
223            height: Length::from_units(1),
224            color: Rgb::BLACK,
225        })
226    }
227
228    /// Rectangles at 1 to 4, with 2, a path and a gradient in a group inside a group, which
229    /// clips them at 7, and a rectangle at 5 in a group whose clip has no area.
230    fn page() -> Page {
231        let path = Item::Path(PathItem {
232            commands: Vec::new(),
233            color: Rgb::BLACK,
234            fill_rule: FillRule::NonZero,
235        });
236        let origin = crate::Point {
237            x: Length::ZERO,
238            y: Length::ZERO,
239        };
240        let gradient = Item::Gradient(GradientItem::new(
241            Vec::new(),
242            FillRule::NonZero,
243            (origin, origin),
244            Vec::new(),
245        ));
246        Page {
247            width: Length::from_units(10),
248            height: Length::from_units(10),
249            orientation: crate::Orientation::Portrait,
250            items: vec![
251                rect(1),
252                Item::Group(Group::new(vec![
253                    Item::Group(Group {
254                        items: vec![rect(2), path, gradient],
255                        clip: Some(clip(7, 1)),
256                        places: GroupPlaces::Own,
257                    }),
258                    rect(3),
259                ])),
260                rect(4),
261                Item::Group(Group {
262                    items: vec![rect(5)],
263                    clip: Some(clip(8, 0)),
264                    places: GroupPlaces::Own,
265                }),
266            ],
267        }
268    }
269
270    #[test]
271    fn replays_a_groups_items_in_its_place_inside_its_clip() {
272        let mut calls = Calls {
273            made: Vec::new(),
274            stop: 0,
275        };
276        assert_eq!(page().replay(&mut calls), Ok(()));
277        assert_eq!(calls.made, [1, -7, 2, 0, 9, -100, 3, 4]);
278    }
279
280    #[test]
281    fn stops_at_the_first_error_of_the_sink() {
282        let mut calls = Calls {
283            made: Vec::new(),
284            stop: 3,
285        };
286        assert_eq!(page().replay(&mut calls), Err(3));
287        assert_eq!(calls.made, [1, -7, 2, 0, 9, -100]);
288    }
289}