Skip to main content

f_office_paint/
lib.rs

1//! Display list.
2//!
3//! A display list is a sequence of pages, and each page holds positioned glyph runs, filled
4//! rectangles, filled paths, paths filled with gradients and images in integer units. It is
5//! the only contract between layout and output: the format crates write display lists, and the
6//! output crates read them without knowing the format.
7//!
8//! Positions are measured from the top left corner of the page, with y growing downwards. A
9//! glyph's position is the point where its baseline starts.
10//!
11//! A group holds the items that a picture draws in its own space, such as the records of a
12//! metafile. Output draws them in their place, and a target's PDF writer leaves them where the
13//! layout puts them.
14//!
15//! [`Page::painted`] gives the items that paint, in painting order, with a group's items in its
16//! place ([`Painted`]), and an output implements [`PageSink`], whose calls [`Page::replay`] makes
17//! for them.
18//!
19//! An image keeps the encoded bytes of its file, and output decodes them when it draws the
20//! image. The bytes are shared, so the pages and items that show the same image hold one copy
21//! of them. The picture decode, the function `decode` that both outputs call, and its first
22//! step `decode_file`, which the writer of pictures again calls too, lie behind the feature
23//! `decode`, which only the output stage turns on: a format crate needs no decoder. The JPEG
24//! files of four components and the CMYK profiles used by decode tests lie behind the feature `files`.
25
26#![deny(clippy::float_arithmetic)]
27
28use std::num::NonZeroU32;
29use std::ops::Range;
30use std::sync::Arc;
31
32use f_office_fonts::FontId;
33use f_office_units::binary32::Binary32;
34use f_office_units::{Length, div_round, div_round_i128};
35
36mod color_effect;
37#[cfg(feature = "decode")]
38mod decode;
39#[cfg(feature = "files")]
40pub mod files;
41pub mod image_header;
42mod image_store;
43mod page_sizes;
44pub mod paper_forms;
45mod sink;
46pub mod stroke;
47#[cfg(feature = "testing")]
48pub mod testing;
49
50pub use color_effect::{ColorEffect, ImageColor};
51pub use image_store::{
52    DEFAULT_IMAGE_BYTES_CACHE, ImageData, ImageId, ImageKey, ImageLoader, ImageRef, LruBytesCache,
53    next_store_id,
54};
55
56#[cfg(feature = "decode")]
57pub use decode::{converts_inks, decode, decode_file, without_profile};
58pub use page_sizes::{GivenSize, PageSizes};
59pub use sink::{PageSink, Painted};
60
61/// The pages of one rendered document.
62#[derive(Clone, Debug, Default, PartialEq, Eq)]
63pub struct DisplayList {
64    /// The pages in order.
65    pages: Vec<Page>,
66}
67
68/// One page.
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct Page {
71    /// Page width.
72    width: Length,
73    /// Page height.
74    height: Length,
75    /// The orientation that the page's section sets, which a writer's page offsets read
76    /// ([`WriterOffset::on_page`]).
77    orientation: Orientation,
78    /// Items in painting order: a later item paints over an earlier one.
79    items: Vec<Item>,
80}
81
82/// The orientation that a page's section sets for the paper, whatever the page's sides: in
83/// DOCX, `w:pgSz/@w:orient` (ECMA-376 Part 1, 17.6.13), portrait when it is missing. A writer
84/// whose page offset follows the page's paper form gives a page in a portrait section no rotated
85/// form ([`paper_forms::ClassRule`]).
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub enum Orientation {
88    /// Portrait (`portrait`), and the orientation of a section that sets none.
89    #[default]
90    Portrait,
91    /// Landscape (`landscape`).
92    Landscape,
93}
94
95impl DisplayList {
96    /// A display list of `pages`, in order. For the format crates, which build display lists;
97    /// it carries no promise.
98    #[must_use]
99    pub const fn new(pages: Vec<Page>) -> Self {
100        Self { pages }
101    }
102
103    /// The pages in order.
104    #[must_use]
105    pub const fn pages(&self) -> &[Page] {
106        self.pages.as_slice()
107    }
108
109    /// The pages in order, out of the list. For the format crates, which build display lists;
110    /// it carries no promise.
111    #[must_use]
112    pub fn into_pages(self) -> Vec<Page> {
113        self.pages
114    }
115}
116
117impl Page {
118    /// A page `width` by `height`, in a section of `orientation`, that paints `items` in order:
119    /// a later item paints over an earlier one. For the format crates, which build pages; it
120    /// carries no promise.
121    #[must_use]
122    pub const fn new(
123        width: Length,
124        height: Length,
125        orientation: Orientation,
126        items: Vec<Item>,
127    ) -> Self {
128        Self {
129            width,
130            height,
131            orientation,
132            items,
133        }
134    }
135
136    /// The orientation that the page's section sets.
137    #[must_use]
138    pub const fn orientation(&self) -> Orientation {
139        self.orientation
140    }
141
142    /// The page's width.
143    #[must_use]
144    pub const fn width(&self) -> Length {
145        self.width
146    }
147
148    /// The page's height.
149    #[must_use]
150    pub const fn height(&self) -> Length {
151        self.height
152    }
153
154    /// The items in painting order: a later item paints over an earlier one.
155    #[must_use]
156    pub const fn items(&self) -> &[Item] {
157        self.items.as_slice()
158    }
159
160    /// The same page with the items that `change` makes of its items, such as the items of a
161    /// header put behind them. Every other property of the page stays, so a change of the
162    /// items names none of them. For the format crates, which build pages; it carries no
163    /// promise.
164    #[must_use]
165    pub fn map_items(self, change: impl FnOnce(Vec<Item>) -> Vec<Item>) -> Self {
166        Self {
167            items: change(self.items),
168            ..self
169        }
170    }
171}
172
173/// One thing to paint.
174#[derive(Clone, Debug, PartialEq, Eq)]
175pub enum Item {
176    /// Glyphs from one font at one size and color.
177    Glyphs(GlyphRun),
178    /// A filled rectangle, such as an underline, a highlight or shading.
179    Rect(Rect),
180    /// A filled path, such as a shape or a border.
181    Path(PathItem),
182    /// A path filled with an axial gradient, such as a bar of a chart.
183    Gradient(GradientItem),
184    /// An image scaled to fill a rectangle, such as a picture.
185    Image(ImageItem),
186    /// Items in painting order, such as the records of a metafile that a picture draws in its
187    /// own space or the text of a text box, with the outline
188    /// outside which they show nothing. A target's PDF writer leaves a picture's own items where
189    /// the layout puts them, and places the page's as the page's ([`Writer::finish`],
190    /// [`GroupPlaces`]).
191    Group(Group),
192}
193
194/// The items of an [`Item::Group`], in painting order, and the outline outside which they
195/// show nothing.
196#[derive(Clone, Debug, PartialEq, Eq)]
197pub struct Group {
198    /// The items, in painting order.
199    pub items: Vec<Item>,
200    /// The outline outside which the items show nothing, or `None` when they show everywhere.
201    /// A clip without area shows nothing.
202    pub clip: Option<GroupClip>,
203    /// Whose items the group holds, which says whether the writer places them.
204    pub places: GroupPlaces,
205}
206
207/// Whose items a group holds, which says whether a target's PDF writer places them
208/// ([`Writer::finish`]).
209#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
210pub enum GroupPlaces {
211    /// A picture's own items, such as the records of a metafile, which the writer writes
212    /// inside the picture: the writer leaves them where
213    /// the layout puts them.
214    #[default]
215    Own,
216    /// The page's items under a clip, such as the text of a text box: the writer places them
217    /// as it places the page's, and stretches the clip's outline as it stretches a path.
218    Page,
219    /// A table cell's items under the cell's clip: the writer places them, and stretches the
220    /// clip's outline, as for [`Self::Page`], and it also moves the clip's points by its
221    /// offsets as it moves a filled rectangle's edges, so that the clip stays on the cell's
222    /// lines and its text.
223    Cell,
224    /// The page's items whose every point the writer places, such as the pictures of an art
225    /// border: as for [`Self::Page`], and it also moves the points of the group's clip and of
226    /// the paths that the group holds by its offsets, as it moves a filled rectangle's edges,
227    /// and writes them with its digits, without holding them on steps.
228    Points,
229    /// Filled rectangles that the writer fills and strokes with an outline `width` wide, such
230    /// as the rectangles of an art border's pictures: the writer places each edge at its own
231    /// place, also between two device dots, by the page entry of its offset, holds the edges on
232    /// steps as it holds a filled rectangle's, and then draws each rectangle as a PDF fills and
233    /// strokes it: the rectangle, and after it the filled outline of its stroke, from half the
234    /// width outside its edges, with round corners, to half the width inside them. The group
235    /// holds filled rectangles only.
236    Stroked {
237        /// The width of the outline around each rectangle.
238        width: Length,
239    },
240}
241
242impl Group {
243    /// A group of a picture's own `items` that shows them everywhere.
244    #[must_use]
245    pub fn new(items: Vec<Item>) -> Self {
246        Self {
247            items,
248            clip: None,
249            places: GroupPlaces::Own,
250        }
251    }
252
253    /// A group of the page's `items` that `clip` cuts, which the writer places as the page's.
254    #[must_use]
255    pub fn of_page(items: Vec<Item>, clip: GroupClip) -> Self {
256        Self {
257            items,
258            clip: Some(clip),
259            places: GroupPlaces::Page,
260        }
261    }
262
263    /// A group of a table cell's `items` that the cell's `clip` cuts, which the writer places
264    /// as the page's, with the clip ([`GroupPlaces::Cell`]).
265    #[must_use]
266    pub fn of_cell(items: Vec<Item>, clip: GroupClip) -> Self {
267        Self {
268            items,
269            clip: Some(clip),
270            places: GroupPlaces::Cell,
271        }
272    }
273
274    /// The items that the writer places as the page's: those of a group of the page's items,
275    /// and none of a picture's own.
276    fn placed_items(&mut self) -> &mut [Item] {
277        match self.places {
278            GroupPlaces::Page
279            | GroupPlaces::Cell
280            | GroupPlaces::Points
281            | GroupPlaces::Stroked { .. } => &mut self.items,
282            GroupPlaces::Own => &mut [],
283        }
284    }
285
286    /// The points of the group's clip and of the paths that it holds, not those of the groups
287    /// in it.
288    fn points_mut(&mut self) -> impl Iterator<Item = &mut Point> {
289        let clip = self.clip.iter_mut().flat_map(|clip| &mut clip.commands);
290        let items = self.items.iter_mut().flat_map(|item| -> Vec<&mut Point> {
291            match item {
292                Item::Path(path) => path
293                    .commands
294                    .iter_mut()
295                    .flat_map(PathCommand::points_mut)
296                    .collect(),
297                Item::Gradient(GradientItem {
298                    commands,
299                    start,
300                    end,
301                    ..
302                }) => commands
303                    .iter_mut()
304                    .flat_map(PathCommand::points_mut)
305                    .chain([start, end])
306                    .collect(),
307                _ => Vec::new(),
308            }
309        });
310        clip.flat_map(PathCommand::points_mut).chain(items)
311    }
312
313    /// Whether the group shows nothing, because its clip has no area.
314    #[must_use]
315    pub fn shows_nothing(&self) -> bool {
316        self.clip.as_ref().is_some_and(|clip| !clip.has_area())
317    }
318}
319
320/// The outline outside which the items of a group show nothing: a path, whose outlines close
321/// as a fill closes them, and the rule that decides which points lie inside it, as a clip path
322/// of a PDF has them.
323#[derive(Clone, Debug, PartialEq, Eq)]
324pub struct GroupClip {
325    /// The outlines of the clip.
326    pub commands: Vec<PathCommand>,
327    /// The rule that decides which points lie inside the outlines.
328    pub fill_rule: FillRule,
329}
330
331impl GroupClip {
332    /// The clip of the rectangle whose top left corner is at `x` and `y`, with `width` and
333    /// `height`.
334    #[must_use]
335    pub fn rect(x: Length, y: Length, width: Length, height: Length) -> Self {
336        let corner = |x, y| PathCommand::LineTo(Point { x, y });
337        Self {
338            commands: vec![
339                PathCommand::MoveTo(Point { x, y }),
340                corner(x + width, y),
341                corner(x + width, y + height),
342                corner(x, y + height),
343                PathCommand::Close,
344            ],
345            fill_rule: FillRule::NonZero,
346        }
347    }
348
349    /// Whether the clip can enclose area: whether the box around its points has both a width
350    /// and a height. A clip without area shows nothing.
351    #[must_use]
352    pub fn has_area(&self) -> bool {
353        let spread = |of: fn(Point) -> Length| {
354            let mut values = self.commands.iter().flat_map(PathCommand::points).map(of);
355            let first = values.next();
356            first.is_some_and(|first| values.any(|value| value != first))
357        };
358        spread(|point| point.x) && spread(|point| point.y)
359    }
360}
361
362impl Item {
363    /// Maps the places and the lengths of this item, and of each item of a group, as a move
364    /// or a scale of the whole item does. `place` maps each glyph's origin, each point of a
365    /// path and of a group's clip, and the top left corner of a rectangle, of an image and of
366    /// an image's clip. `length` maps the size of a glyph run (the length of one em) and the
367    /// width of its outline, and the width and the height of a rectangle, of an image and of
368    /// an image's clip. The colors, the turns, the text and the images stay.
369    pub fn map_places(
370        &mut self,
371        mut place: impl FnMut(Point) -> Point,
372        mut length: impl FnMut(Length) -> Length,
373    ) {
374        self.map_places_with(&mut place, &mut length);
375    }
376
377    /// The first place that [`Self::map_places`] maps, read without a copy: a glyph run's
378    /// first origin, a path's first point, the top left corner of a rectangle or of an image,
379    /// and in a group the first place of its items, else of its clip. `None` for an item with
380    /// no place, such as an empty group.
381    #[must_use]
382    pub fn first_place(&self) -> Option<Point> {
383        let first_point =
384            |commands: &[PathCommand]| commands.iter().flat_map(PathCommand::points).next();
385        match self {
386            Self::Glyphs(run) => run.glyphs.first().map(|glyph| Point {
387                x: glyph.x,
388                y: glyph.y,
389            }),
390            Self::Rect(rect) => Some(Point {
391                x: rect.x,
392                y: rect.y,
393            }),
394            Self::Path(path) => first_point(&path.commands),
395            Self::Gradient(gradient) => first_point(&gradient.commands),
396            Self::Image(image) => Some(Point {
397                x: image.x,
398                y: image.y,
399            }),
400            Self::Group(group) => group.items.iter().find_map(Self::first_place).or_else(|| {
401                group
402                    .clip
403                    .as_ref()
404                    .and_then(|clip| first_point(&clip.commands))
405            }),
406        }
407    }
408
409    fn map_places_with(
410        &mut self,
411        place: &mut dyn FnMut(Point) -> Point,
412        length: &mut dyn FnMut(Length) -> Length,
413    ) {
414        match self {
415            Self::Glyphs(run) => {
416                run.size = length(run.size);
417                for glyph in &mut run.glyphs {
418                    Point {
419                        x: glyph.x,
420                        y: glyph.y,
421                    } = place(Point {
422                        x: glyph.x,
423                        y: glyph.y,
424                    });
425                }
426                if let Some(outline) = &mut run.outline {
427                    outline.width = length(outline.width);
428                }
429            }
430            Self::Rect(rect) => {
431                Point {
432                    x: rect.x,
433                    y: rect.y,
434                } = place(Point {
435                    x: rect.x,
436                    y: rect.y,
437                });
438                rect.width = length(rect.width);
439                rect.height = length(rect.height);
440            }
441            Self::Path(path) => map_points(&mut path.commands, place),
442            Self::Gradient(gradient) => {
443                map_points(&mut gradient.commands, place);
444                gradient.start = place(gradient.start);
445                gradient.end = place(gradient.end);
446            }
447            Self::Image(image) => {
448                Point {
449                    x: image.x,
450                    y: image.y,
451                } = place(Point {
452                    x: image.x,
453                    y: image.y,
454                });
455                image.width = length(image.width);
456                image.height = length(image.height);
457                if let Some(clip) = &mut image.clip {
458                    clip.map_places_with(place, length);
459                }
460            }
461            Self::Group(group) => {
462                for item in &mut group.items {
463                    item.map_places_with(place, length);
464                }
465                if let Some(clip) = &mut group.clip {
466                    map_points(&mut clip.commands, place);
467                }
468            }
469        }
470    }
471}
472
473/// Maps each point of the path `commands` by `place`.
474fn map_points(commands: &mut [PathCommand], place: &mut dyn FnMut(Point) -> Point) {
475    for point in commands.iter_mut().flat_map(PathCommand::points_mut) {
476        *point = place(*point);
477    }
478}
479
480impl Clip {
481    fn map_places_with(
482        &mut self,
483        place: &mut dyn FnMut(Point) -> Point,
484        length: &mut dyn FnMut(Length) -> Length,
485    ) {
486        Point {
487            x: self.x,
488            y: self.y,
489        } = place(Point {
490            x: self.x,
491            y: self.y,
492        });
493        self.width = length(self.width);
494        self.height = length(self.height);
495    }
496}
497
498/// Glyphs from one font at one size and color.
499#[derive(Clone, Debug, PartialEq, Eq)]
500pub struct GlyphRun {
501    /// The font face in the font database.
502    pub font: FontId,
503    /// The font size, which is the length of one em.
504    pub size: Length,
505    /// The fill color.
506    pub color: Rgb,
507    /// The text that the glyphs show, so that output can carry it for search and copy.
508    pub text: String,
509    /// The glyphs in the order of the text.
510    pub glyphs: Vec<Glyph>,
511    /// The line drawn along the outline of each glyph, over its fill, if any.
512    pub outline: Option<Outline>,
513    /// Whether the glyphs' interiors are filled with [`Self::color`]. `false` for unfilled text
514    /// such as hollow outlined text or gradient-filled text whose fill is painted as a path
515    /// underneath, keeping the run's outline and selectable text.
516    pub filled: bool,
517    /// Whether the text has an effect that the output does not draw, such as a reflection or
518    /// a 3-D format.
519    pub effect: bool,
520    /// How each glyph is turned, scaled or slanted about its origin, as the text of a table
521    /// cell with a text direction turns or a slanted glyph leans: a step along the run goes `xx`
522    /// right and `yx` down, and a step down the glyph goes `xy` right and `yy` down. `None`
523    /// draws the glyphs upright.
524    pub turn: Option<Turn>,
525}
526
527impl GlyphRun {
528    /// The byte range of [`GlyphRun::text`] that `glyph` shows, or `None` when the range does
529    /// not hold whole characters of the text: when it ends before it starts, ends beyond the
530    /// text, or starts or ends inside a character.
531    #[must_use]
532    pub fn glyph_range(&self, glyph: &Glyph) -> Option<Range<usize>> {
533        let start = usize::try_from(glyph.text_start).ok()?;
534        let end = usize::try_from(glyph.text_end).ok()?;
535        self.text.get(start..end).map(|_| start..end)
536    }
537
538    /// The text that `glyph` shows, from [`GlyphRun::glyph_range`].
539    #[must_use]
540    pub fn glyph_text(&self, glyph: &Glyph) -> Option<&str> {
541        self.text.get(self.glyph_range(glyph)?)
542    }
543}
544
545/// A line along the outline of each glyph of a run.
546#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
547pub struct Outline {
548    /// The line width.
549    pub width: Length,
550    /// The line color.
551    pub color: Rgb,
552    /// How the line turns at the corners of the outline.
553    pub join: Join,
554}
555
556/// How a line turns at a corner.
557#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
558pub enum Join {
559    /// A round corner.
560    Round,
561    /// A pointed corner, cut off where the miter would be longer than 10 times the line
562    /// width, PDF's default miter limit.
563    Miter,
564}
565
566/// One positioned glyph.
567#[derive(Clone, Debug, PartialEq, Eq)]
568pub struct Glyph {
569    /// The glyph ID in the font.
570    pub id: u32,
571    /// The x position of the glyph origin.
572    pub x: Length,
573    /// The y position of the baseline.
574    pub y: Length,
575    /// The byte range in [`GlyphRun::text`] that this glyph shows.
576    pub text_start: u32,
577    /// The end of the byte range in [`GlyphRun::text`] that this glyph shows.
578    pub text_end: u32,
579}
580
581/// A filled rectangle.
582#[derive(Clone, Debug, PartialEq, Eq)]
583pub struct Rect {
584    /// Left edge.
585    pub x: Length,
586    /// Top edge.
587    pub y: Length,
588    /// Width.
589    pub width: Length,
590    /// Height.
591    pub height: Length,
592    /// Fill color.
593    pub color: Rgb,
594}
595
596/// A filled path: one or more outlines in page space, filled with one color.
597///
598/// Each outline starts with [`PathCommand::MoveTo`]. An outline that does not end with
599/// [`PathCommand::Close`] is filled as if a straight line closed it, as in PDF and SVG. Output
600/// fills a path with the same anti-aliasing as glyphs.
601#[derive(Clone, Debug, PartialEq, Eq)]
602pub struct PathItem {
603    /// The outlines, as a list of commands.
604    pub commands: Vec<PathCommand>,
605    /// The fill color.
606    pub color: Rgb,
607    /// The rule that decides which points lie inside the path.
608    pub fill_rule: FillRule,
609}
610
611/// A path filled with an axial gradient: each point inside the path takes the color at the
612/// place of its projection on the axis from `start` to `end`, between the colors of the stops,
613/// and the color of the first stop before the start and of the last stop past the end, as an
614/// axial shading of a PDF that extends at both ends paints it (ISO 32000-2, 8.7.4.5.3).
615///
616/// The path's outlines close and fill as those of a [`PathItem`] do.
617#[derive(Clone, Debug, PartialEq, Eq)]
618#[non_exhaustive]
619pub struct GradientItem {
620    /// The outlines, as a list of commands.
621    pub commands: Vec<PathCommand>,
622    /// The rule that decides which points lie inside the path.
623    pub fill_rule: FillRule,
624    /// The start of the axis, the place of [`GradientStop::START`].
625    pub start: Point,
626    /// The end of the axis, the place of [`GradientStop::END`].
627    pub end: Point,
628    /// The stops, in the order of their places. Two stops at one place change the color there
629    /// at once.
630    pub stops: Vec<GradientStop>,
631}
632
633impl GradientItem {
634    /// A path filled with an axial gradient along `axis`, from its start to its end, through
635    /// `stops`.
636    #[must_use]
637    pub fn new(
638        commands: Vec<PathCommand>,
639        fill_rule: FillRule,
640        axis: (Point, Point),
641        stops: Vec<GradientStop>,
642    ) -> Self {
643        Self {
644            commands,
645            fill_rule,
646            start: axis.0,
647            end: axis.1,
648            stops,
649        }
650    }
651
652    /// The color at `place` on the axis, in millionths of the axis from its start: the color of
653    /// the first stop at or before the start, of the last stop at or past the end, and between
654    /// two stops each channel in proportion to the place between theirs, rounded to the nearest
655    /// value, a half up. A place where two stops meet takes the later stop's color. Black for a
656    /// gradient without stops.
657    #[must_use]
658    pub fn color_at(&self, place: i64) -> Rgb {
659        let (Some(first), Some(last)) = (self.stops.first(), self.stops.last()) else {
660            return Rgb::BLACK;
661        };
662        if place < i64::from(first.place) {
663            return first.color;
664        }
665        let after = self
666            .stops
667            .partition_point(|stop| i64::from(stop.place) <= place);
668        let (Some(before), Some(next)) = (
669            after.checked_sub(1).and_then(|at| self.stops.get(at)),
670            self.stops.get(after),
671        ) else {
672            return last.color;
673        };
674        let span = i64::from(next.place) - i64::from(before.place);
675        let along = place - i64::from(before.place);
676        let mix = |from: u8, to: u8| {
677            let from = i64::from(from);
678            let value = from + div_round(along * (i64::from(to) - from), span);
679            u8::try_from(value.clamp(0, 255)).unwrap_or(u8::MAX)
680        };
681        Rgb {
682            r: mix(before.color.r, next.color.r),
683            g: mix(before.color.g, next.color.g),
684            b: mix(before.color.b, next.color.b),
685        }
686    }
687}
688
689/// One stop of a [`GradientItem`]: a place on the axis and its color.
690#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
691#[non_exhaustive]
692pub struct GradientStop {
693    /// The place on the axis, in millionths of the axis from its start
694    /// ([`GradientStop::START`]) to its end ([`GradientStop::END`]).
695    pub place: u32,
696    /// The color at the place.
697    pub color: Rgb,
698}
699
700impl GradientStop {
701    /// The place of the axis's start.
702    pub const START: u32 = 0;
703    /// The place of the axis's end: one million millionths.
704    pub const END: u32 = 1_000_000;
705
706    /// A stop at `place`, in millionths of the axis, with `color`.
707    #[must_use]
708    pub const fn new(place: u32, color: Rgb) -> Self {
709        Self { place, color }
710    }
711}
712
713/// One command of a [`PathItem`]. A curve or line starts at the end point of the command
714/// before it.
715#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
716pub enum PathCommand {
717    /// Starts a new outline at a point.
718    MoveTo(Point),
719    /// A straight line to a point.
720    LineTo(Point),
721    /// A quadratic Bézier curve through a control point to an end point.
722    QuadTo(Point, Point),
723    /// A cubic Bézier curve through two control points to an end point.
724    CubicTo(Point, Point, Point),
725    /// A straight line back to the start of the outline, which ends it.
726    Close,
727}
728
729impl PathCommand {
730    /// The points of this command in order: the point of a move or a line, the control points
731    /// and the end point of a curve, and none for a close.
732    pub fn points_mut(&mut self) -> impl Iterator<Item = &mut Point> {
733        let points = match self {
734            Self::MoveTo(a) | Self::LineTo(a) => [Some(a), None, None],
735            Self::QuadTo(a, b) => [Some(a), Some(b), None],
736            Self::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
737            Self::Close => [None, None, None],
738        };
739        points.into_iter().flatten()
740    }
741
742    /// The points of this command in order, as [`PathCommand::points_mut`] gives them.
743    pub fn points(&self) -> impl Iterator<Item = Point> {
744        let points = match *self {
745            Self::MoveTo(a) | Self::LineTo(a) => [Some(a), None, None],
746            Self::QuadTo(a, b) => [Some(a), Some(b), None],
747            Self::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
748            Self::Close => [None, None, None],
749        };
750        points.into_iter().flatten()
751    }
752}
753
754/// The extent, 1/256 pt rounded up to whole half-EMUs, at or below which a fill paints nothing
755/// in the outputs. A reader of a PDF paints a fill that thin as a line of its own width, at
756/// least a pixel wide (hayro and pdf.js draw a line along the fill's box), so that a PDF cannot
757/// show it as the faint fill that it is; the raster leaves it out, as the PDF writer does.
758pub const THINNEST_FILL: Length = Length::from_units(100);
759
760/// Whether a fill whose box is `across` wide and `down` tall paints: whether both exceed
761/// [`THINNEST_FILL`]. A negative side counts by its size.
762#[must_use]
763pub const fn fill_shows(across: Length, down: Length) -> bool {
764    across.units().abs() > THINNEST_FILL.units() && down.units().abs() > THINNEST_FILL.units()
765}
766
767/// Whether the filled path `commands` paints: whether the box of the points that
768/// [`fill_commands`] gives, with the control points of its curves, passes [`fill_shows`].
769#[must_use]
770pub fn path_shows(commands: &[PathCommand]) -> bool {
771    let drawn = fill_commands(commands);
772    let mut points = drawn.iter().flat_map(PathCommand::points);
773    let Some(first) = points.next() else {
774        return false;
775    };
776    let (low, high) = points.fold((first, first), |(low, high), p| {
777        (
778            Point {
779                x: low.x.min(p.x),
780                y: low.y.min(p.y),
781            },
782            Point {
783                x: high.x.max(p.x),
784                y: high.y.max(p.y),
785            },
786        )
787    });
788    fill_shows(high.x - low.x, high.y - low.y)
789}
790
791/// The commands that every output draws for the filled path `commands`, so that a PDF file
792/// holds the path that the raster draws. A quadratic curve, which PDF does not have, becomes the
793/// cubic curve of [`stroke::quad_as_cubic`], as a stroke of it does; a quadratic curve with no
794/// point before it starts at its control point. A straight line to the point where it
795/// starts is left out: it adds nothing to a fill, and a reader of a PDF can make it longer so
796/// that a stroke of it shows its round cap.
797#[must_use]
798pub fn fill_commands(commands: &[PathCommand]) -> Vec<PathCommand> {
799    let mut current: Option<Point> = None;
800    let mut start: Option<Point> = None;
801    commands
802        .iter()
803        .filter_map(|&command| match command {
804            PathCommand::MoveTo(p) => {
805                (current, start) = (Some(p), Some(p));
806                Some(command)
807            }
808            PathCommand::LineTo(p) => {
809                let empty = current == Some(p);
810                current = Some(p);
811                (!empty).then_some(command)
812            }
813            PathCommand::CubicTo(_, _, p) => {
814                current = Some(p);
815                Some(command)
816            }
817            PathCommand::QuadTo(control, end) => {
818                let from = current.unwrap_or(control);
819                current = Some(end);
820                let [_, first, second, _] = stroke::quad_as_cubic(from, control, end);
821                Some(PathCommand::CubicTo(first, second, end))
822            }
823            PathCommand::Close => {
824                current = start;
825                Some(command)
826            }
827        })
828        .collect()
829}
830
831/// A point on the page.
832#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
833pub struct Point {
834    /// The distance from the left edge of the page.
835    pub x: Length,
836    /// The distance from the top edge of the page.
837    pub y: Length,
838}
839
840/// The rule that decides which points lie inside a path, as PDF and SVG define them.
841#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
842pub enum FillRule {
843    /// A point is inside when the outlines wind around it a number of times other than zero,
844    /// counting each direction with its own sign.
845    #[default]
846    NonZero,
847    /// A point is inside when a ray from it crosses the outlines an odd number of times.
848    EvenOdd,
849}
850
851/// An image scaled to fill a rectangle.
852///
853/// The whole image fills the rectangle at `x` and `y` with `width` and `height`, turned about
854/// its centre by `turn`, and only the part inside `clip` shows, so a cropped picture has a
855/// rectangle larger than its clip. Output draws the formats that it can decode, and leaves out an image in another format, with data
856/// that it cannot decode, or with a side that is not positive.
857#[derive(Clone, Debug, PartialEq, Eq)]
858pub struct ImageItem {
859    /// Left edge of the whole image.
860    pub x: Length,
861    /// Top edge of the whole image.
862    pub y: Length,
863    /// Width of the whole image.
864    pub width: Length,
865    /// Height of the whole image.
866    pub height: Length,
867    /// The rectangle outside which nothing of the image shows, or `None` to show all of it.
868    pub clip: Option<Clip>,
869    /// How the image is turned about the centre of its rectangle, or `None` for an upright
870    /// image.
871    pub turn: Option<Turn>,
872    /// The encoded image.
873    pub image: Image,
874}
875
876/// How an image is turned on the page, as a PDF can rotate, flip or skew its images: the
877/// linear map from the image's upright rectangle to the page, about the rectangle's centre. A
878/// point `u` right of the centre and `v` below it lands `xx u + xy v` right of the centre and
879/// `yx u + yy v` below it, with each entry in millionths ([`Turn::SCALE`]).
880#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
881pub struct Turn {
882    /// How far right a step right goes.
883    pub xx: i32,
884    /// How far down a step right goes.
885    pub yx: i32,
886    /// How far right a step down goes.
887    pub xy: i32,
888    /// How far down a step down goes.
889    pub yy: i32,
890}
891
892impl Turn {
893    /// The units of an entry in one: millionths.
894    pub const SCALE: i32 = 1_000_000;
895}
896
897impl ImageItem {
898    /// The part of the item's clip that lies on its upright rectangle, or `None` without a
899    /// clip or with one that does not meet the rectangle. Nothing of the image shows outside
900    /// either, so the item shows the same with this clip.
901    #[must_use]
902    pub fn shown(&self) -> Option<Clip> {
903        let clip = self.clip?;
904        let end = |start: Length, length: Length| start.units().checked_add(length.units());
905        let left = clip.x.max(self.x).units();
906        let top = clip.y.max(self.y).units();
907        let right = end(clip.x, clip.width)?.min(end(self.x, self.width)?);
908        let bottom = end(clip.y, clip.height)?.min(end(self.y, self.height)?);
909        (left < right && top < bottom).then(|| Clip {
910            x: Length::from_units(left),
911            y: Length::from_units(top),
912            width: Length::from_units(right - left),
913            height: Length::from_units(bottom - top),
914        })
915    }
916}
917
918/// A rectangle outside which an item shows nothing.
919#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
920pub struct Clip {
921    /// Left edge.
922    pub x: Length,
923    /// Top edge.
924    pub y: Length,
925    /// Width.
926    pub width: Length,
927    /// Height.
928    pub height: Length,
929}
930
931/// The encoded payload of an image file with its format. A clone shares inline bytes or copies
932/// only the lightweight lazy [`ImageRef`] handle.
933#[derive(Clone, Debug, PartialEq, Eq, Hash)]
934pub struct Image {
935    /// The format of the bytes.
936    pub format: ImageFormat,
937    /// Inline shared bytes or a lazy [`ImageRef`] handle loaded on demand.
938    pub data: ImageData,
939    /// Multiplier of the file's alpha; [`Opacity::FULL`] preserves the file's alpha.
940    pub opacity: Opacity,
941    /// Color conversion applied to decoded straight RGB, before alpha compositing.
942    pub color: ImageColor,
943    /// How the inks of a JPEG file of four components turn into RGB.
944    pub inks: InkConversion,
945}
946
947/// The opacity of a picture: the multiplier of its file's alpha, a share of
948/// [`f_office_units::scale::DRAWING_WHOLE`] from none to a whole.
949#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
950pub struct Opacity(i64);
951
952impl Opacity {
953    /// The opacity that preserves the file's alpha.
954    pub const FULL: Self = Self(f_office_units::scale::DRAWING_WHOLE);
955
956    /// The opacity of `share` thousandths of a percent, limited to none and a whole, as
957    /// DrawingML limits a fixed alpha modifier before it multiplies the alpha.
958    #[must_use]
959    pub const fn clamped(share: i64) -> Self {
960        let whole = f_office_units::scale::DRAWING_WHOLE;
961        Self(if share < 0 {
962            0
963        } else if share > whole {
964            whole
965        } else {
966            share
967        })
968    }
969
970    /// The product of two opacities, rounded to the nearest thousandth of a percent, a half
971    /// up; it lies between none and a whole, as each of them does.
972    #[must_use]
973    pub const fn times(self, other: Self) -> Self {
974        Self(div_round(
975            self.0 * other.0,
976            f_office_units::scale::DRAWING_WHOLE,
977        ))
978    }
979
980    /// The share, in thousandths of a percent: from 0 to 100,000.
981    #[must_use]
982    pub const fn share(self) -> i64 {
983        self.0
984    }
985}
986
987impl Image {
988    /// Takes the bytes of an image file and detects their format.
989    #[must_use]
990    pub fn new(data: impl Into<Arc<[u8]>>) -> Self {
991        let data = data.into();
992        Self {
993            format: ImageFormat::detect(&data),
994            data: ImageData::Inline(data),
995            opacity: Opacity::FULL,
996            color: ImageColor::Original,
997            inks: InkConversion::EmbeddedProfile,
998        }
999    }
1000
1001    /// Creates an image backed by a lazy [`ImageRef`] handle with detected `format`.
1002    #[must_use]
1003    pub const fn from_ref(format: ImageFormat, image_ref: ImageRef) -> Self {
1004        Self {
1005            format,
1006            data: ImageData::Lazy(image_ref),
1007            opacity: Opacity::FULL,
1008            color: ImageColor::Original,
1009            inks: InkConversion::EmbeddedProfile,
1010        }
1011    }
1012
1013    /// Loads the complete encoded bytes of this image (zero-copy `Arc::clone` for inline bytes,
1014    /// lazy read for [`ImageRef`] handles).
1015    #[must_use]
1016    pub fn load_bytes(&self) -> Option<Arc<[u8]>> {
1017        self.data.bytes()
1018    }
1019
1020    /// Loads the complete encoded bytes together with their effective [`ImageFormat`].
1021    #[must_use]
1022    pub fn load_bytes_with_format(&self) -> Option<(Arc<[u8]>, ImageFormat)> {
1023        self.data.bytes_with_format(self.format)
1024    }
1025
1026    /// Loads up to `max_bytes` leading bytes for header inspection without inflating the full
1027    /// image when backed by a lazy loader.
1028    #[must_use]
1029    pub fn load_prefix(&self, max_bytes: usize) -> Option<Arc<[u8]>> {
1030        self.data.prefix(max_bytes)
1031    }
1032
1033    /// Returns a cache key uniquely identifying this image's encoded source.
1034    #[must_use]
1035    pub fn cache_key(&self) -> ImageKey {
1036        self.data.key()
1037    }
1038}
1039
1040/// How the picture decode turns the ink amounts of a JPEG file of four components (CMYK or
1041/// YCCK) into RGB. The format crate chooses it from the target; the output crates apply it
1042/// without knowing the target.
1043#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1044pub enum InkConversion {
1045    /// Through the CMYK profile that the file embeds, with the perceptual intent, and by the
1046    /// plain conversion, R = (255 − C)(255 − K) / 255 and the same for G and B, for a file
1047    /// without one or whose profile does not read or convert.
1048    #[default]
1049    EmbeddedProfile,
1050    /// Through the ink table, the colors of six amounts of each ink,
1051    /// interpolated multilinear between them, whatever profile the file embeds.
1052    InkTable,
1053}
1054
1055/// The most bytes of one image's RGBA pixels with 8 bits a channel, which the picture decode
1056/// keeps, and the most that its decoder may allocate: 256 MiB, the RGBA pixels of an image of
1057/// 8,192 by 8,192 pixels. The output crates leave a larger image out
1058/// ([`ImageFault::Limit`]), but for a JPEG file of its own colors, which the PDF output writes
1059/// as it is, without a decode; and the JPEG decoder refuses a frame whose coefficient blocks
1060/// need more.
1061pub const MAX_DECODED_BYTES: u64 = 256 << 20;
1062
1063/// The most bytes of the RGBA pixels of one PNG picture that a target's PDF writer cuts or
1064/// resamples before the outputs draw it, and the most that its decoder may allocate: 512 MiB,
1065/// twice [`MAX_DECODED_BYTES`], the default limit of the `image` crate. The writer reads a larger picture than the outputs can draw
1066/// because it writes a smaller one, which the outputs then decode within
1067/// [`MAX_DECODED_BYTES`]. A PNG picture that needs more stays as it is, with a warning.
1068pub const MAX_DECODED_BYTES_TO_WRITE_AGAIN: u64 = 512 << 20;
1069
1070/// The format of an image file.
1071#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1072pub enum ImageFormat {
1073    /// PNG (ISO/IEC 15948).
1074    Png,
1075    /// JPEG (ISO/IEC 10918-1), in a JFIF or Exif file.
1076    Jpeg,
1077    /// GIF.
1078    Gif,
1079    /// Windows bitmap (BMP).
1080    Bmp,
1081    /// TIFF.
1082    Tiff,
1083    /// Windows Enhanced Metafile (EMF), defined by MS-EMF.
1084    Emf,
1085    /// Windows Metafile (WMF), defined by MS-WMF.
1086    Wmf,
1087    /// An effect picture that a layout made: what a part of a page that Word draws as one
1088    /// picture of pixels shows, such as the plot area of a 3-D chart, which the output stage
1089    /// draws into pixels. No file of a document is in this format: [`ImageFormat::detect`]
1090    /// never gives it.
1091    EffectPicture,
1092    /// A format that none of the others matches.
1093    Unknown,
1094}
1095
1096/// Why an output leaves an image of the display list out.
1097#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1098#[non_exhaustive]
1099pub enum ImageFault {
1100    /// The output draws no image of its format.
1101    Format,
1102    /// The image's data does not decode in its format.
1103    Data,
1104    /// The image is larger than the output's limits: its RGBA pixels, or what its decoder
1105    /// allocates, need more bytes than the output's limit, or a side is longer than the output
1106    /// holds.
1107    Limit,
1108}
1109
1110impl std::fmt::Display for ImageFault {
1111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1112        f.write_str(match self {
1113            Self::Format => "the output draws no image of this format",
1114            Self::Data => "its data does not decode",
1115            Self::Limit => "it is larger than the output's limits",
1116        })
1117    }
1118}
1119
1120impl std::fmt::Display for ImageFormat {
1121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1122        f.write_str(match self {
1123            Self::Png => "PNG",
1124            Self::Jpeg => "JPEG",
1125            Self::Gif => "GIF",
1126            Self::Bmp => "BMP",
1127            Self::Tiff => "TIFF",
1128            Self::Emf => "EMF",
1129            Self::Wmf => "WMF",
1130            Self::EffectPicture => "effect picture",
1131            Self::Unknown => "unknown",
1132        })
1133    }
1134}
1135
1136impl ImageFormat {
1137    /// Detects the format from the signature at the start of an image file.
1138    #[must_use]
1139    pub fn detect(data: &[u8]) -> Self {
1140        /// The `EMR_HEADER` record type that starts an EMF file, little-endian (MS-EMF 2.3.4.2).
1141        const EMR_HEADER: [u8; 4] = [1, 0, 0, 0];
1142        /// The `" EMF"` signature at byte 40 of the EMF header record.
1143        const EMF_SIGNATURE: &[u8] = b" EMF";
1144        let starts = |signature: &[u8]| data.starts_with(signature);
1145        if starts(b"\x89PNG\r\n\x1a\n") {
1146            Self::Png
1147        } else if starts(&[0xFF, 0xD8, 0xFF]) {
1148            Self::Jpeg
1149        } else if starts(b"GIF87a") || starts(b"GIF89a") {
1150            Self::Gif
1151        } else if starts(b"BM") {
1152            Self::Bmp
1153        } else if starts(b"II*\0") || starts(b"MM\0*") {
1154            Self::Tiff
1155        } else if starts(&EMR_HEADER) && data.get(40..44) == Some(EMF_SIGNATURE) {
1156            Self::Emf
1157        } else if is_wmf(data) {
1158            Self::Wmf
1159        } else {
1160            Self::Unknown
1161        }
1162    }
1163}
1164
1165/// Whether the data starts a WMF file: either the placeable header's key (MS-WMF 2.3.2.3), or a
1166/// `META_HEADER` record of type 1 or 2 with a header size of 9 words (MS-WMF 2.3.2.2).
1167fn is_wmf(data: &[u8]) -> bool {
1168    data.starts_with(&[0xD7, 0xCD, 0xC6, 0x9A])
1169        || data.starts_with(&[1, 0, 9, 0])
1170        || data.starts_with(&[2, 0, 9, 0])
1171}
1172
1173/// An opaque color.
1174#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1175pub struct Rgb {
1176    /// Red.
1177    pub r: u8,
1178    /// Green.
1179    pub g: u8,
1180    /// Blue.
1181    pub b: u8,
1182}
1183
1184impl Rgb {
1185    /// Black.
1186    pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
1187
1188    /// White.
1189    pub const WHITE: Self = Self {
1190        r: u8::MAX,
1191        g: u8::MAX,
1192        b: u8::MAX,
1193    };
1194
1195    /// Reads a color of six hexadecimal digits of either case, such as `FF0080`: the shared
1196    /// simple type `ST_HexColorRGB` of ECMA-376, `xsd:hexBinary` of three bytes, which
1197    /// WordprocessingML colors and DrawingML's `a:srgbClr` use. Anything else, a sign
1198    /// included, gives `None`.
1199    #[must_use]
1200    pub fn from_hex(text: &str) -> Option<Self> {
1201        let digits = text.as_bytes();
1202        if digits.len() != 6 || !digits.iter().all(u8::is_ascii_hexdigit) {
1203            return None;
1204        }
1205        let value = u32::from_str_radix(text, 16).ok()?;
1206        let [_, r, g, b] = value.to_be_bytes();
1207        Some(Self { r, g, b })
1208    }
1209}
1210
1211/// How far a target's PDF writer moves a place that it writes, across or down one page: the
1212/// offset on a page, which [`WriterOffset::on_page`] gives for the page's size and orientation.
1213#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1214pub enum Offset {
1215    /// The writer moves no place.
1216    #[default]
1217    None,
1218    /// The place from the page's left edge divided by `share`, plus `bias`, rounded to the
1219    /// nearest whole `step`, a half up; `bias` and `step` in half-EMUs.
1220    Share {
1221        /// The divisor of the place.
1222        share: i64,
1223        /// What is added to the divided place, in half-EMUs.
1224        bias: i64,
1225        /// The step to which the offset rounds, in half-EMUs.
1226        step: i64,
1227    },
1228    /// Whole steps of `1/per_inch` inch, as if the page were `steps` steps larger along the
1229    /// place's side: the place times `steps`, divided by the page's side along it, is rounded
1230    /// to the nearest whole `parts` of a step first, and that count of parts is then divided
1231    /// by `parts` and rounded to the nearest step, a half up. `steps` is a fraction of steps.
1232    /// `product` says how the writer takes the product before it rounds it to parts.
1233    Page {
1234        /// The steps that the page's side gains.
1235        steps: Fraction,
1236        /// The parts of a step in which the product is rounded before the division.
1237        parts: i64,
1238        /// How many steps make an inch.
1239        per_inch: i64,
1240        /// How the writer takes the product of the place and the steps.
1241        product: OffsetProduct,
1242    },
1243}
1244
1245/// How a writer whose offset takes whole steps as if the page were larger ([`Offset::Page`])
1246/// takes the product of a place and its page's steps before it rounds the product to parts of
1247/// a step.
1248#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1249pub enum OffsetProduct {
1250    /// The exact product of the place and the steps over the page's side.
1251    #[default]
1252    Exact,
1253    /// The product of the place in whole dots of `1/dots_per_inch` inch, a half up, and the
1254    /// page entry, held as the nearest binary32 number: the page entry is `parts (per_inch /
1255    /// dots_per_inch + steps / D)`, D the page's side in whole dots, held as the nearest
1256    /// binary32 number too, so that the product counts the parts of the whole written place.
1257    /// Its count of parts, rounded a half up and divided by `parts`, rounded a half up, is the
1258    /// written place in steps, and the offset is that place less the dot's place.
1259    Binary32 {
1260        /// How many dots make an inch.
1261        dots_per_inch: i64,
1262    },
1263}
1264
1265/// The offset of a target's PDF writer along one axis, as the target's profile gives it (the
1266/// writer offset): the same offset on every page, or one that each page's size and
1267/// orientation choose. Only the offset on a page ([`Offset`]) moves a place, so an offset that
1268/// no page has chosen cannot move one.
1269#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1270pub enum WriterOffset {
1271    /// The same offset on every page.
1272    EveryPage(Offset),
1273    /// The page form with the steps that a page's size and orientation give ([`PageSizes`]):
1274    /// given steps for some sizes, and the page entry of the page's paper form for the others.
1275    Sizes(&'static PageSizes),
1276}
1277
1278impl WriterOffset {
1279    /// The writer moves no place on any page.
1280    pub const NONE: Self = Self::EveryPage(Offset::None);
1281
1282    /// The offsets across and down a page `width` by `height` half-EMUs in a section of
1283    /// `orientation`: those that [`PageSizes`] gives the page for [`Self::Sizes`], and the same
1284    /// offset on both axes otherwise.
1285    #[must_use]
1286    pub fn on_page(self, width: i64, height: i64, orientation: Orientation) -> (Offset, Offset) {
1287        match self {
1288            Self::Sizes(sizes) => sizes.offsets(width, height, orientation),
1289            Self::EveryPage(offset) => (offset, offset),
1290        }
1291    }
1292}
1293
1294/// The parts of a step in which a profile gives the steps of the page form of a writer's
1295/// offset ([`Offset::Page`]): hundred-thousandths.
1296pub const STEP_PARTS: i64 = 100_000;
1297
1298impl Offset {
1299    /// The offset of a place at `x` from the page's edge, on a page whose side along `x` is
1300    /// `side`, all in half-EMUs.
1301    #[must_use]
1302    pub fn of(self, x: i64, side: i64) -> i64 {
1303        self.of_in(x, side, 1)
1304    }
1305
1306    /// The place at which the writer writes a filled rectangle's edge at `x` on a page whose
1307    /// side along `x` is `side`, all in half-EMUs, where the edge need not lie on a device dot.
1308    /// For a page offset whose product is binary32, it is the edge's own place in dots times
1309    /// the page entry, held as the nearest binary32 number, rounded to whole parts of a step
1310    /// and then to whole steps, each a half up, and taken to the nearest half-EMU: an edge
1311    /// between two dots takes the entry at its own place, not the offset of its nearest dot.
1312    /// For every other offset it is the edge moved by [`Self::of`].
1313    #[must_use]
1314    pub(crate) fn written_place(self, x: i64, side: i64) -> i64 {
1315        if let Self::Page {
1316            steps,
1317            parts,
1318            per_inch,
1319            product: OffsetProduct::Binary32 { dots_per_inch },
1320        } = self
1321            && let Some(place) =
1322                binary32_written_place(x, side, (steps, parts, per_inch), dots_per_inch)
1323        {
1324            return place;
1325        }
1326        x + self.of(x, side)
1327    }
1328
1329    /// The offset of [`Self::of`] in `fraction`ths of a half-EMU, the nearest: the place is
1330    /// whole half-EMUs, and the offset a whole number of the writer's steps, which a
1331    /// half-EMU need not hold (the step of 1/3000 inch is 609.6 half-EMUs).
1332    #[must_use]
1333    pub fn of_in(self, x: i64, side: i64, fraction: i64) -> i64 {
1334        let fraction = i128::from(fraction.max(1));
1335        match self {
1336            Self::None => 0,
1337            Self::Share { share, bias, step } => {
1338                if share <= 0 || step <= 0 {
1339                    return 0;
1340                }
1341                let steps = div_round_i128(
1342                    i128::from(x) + i128::from(bias) * i128::from(share),
1343                    i128::from(step) * i128::from(share),
1344                );
1345                i64::try_from(steps * i128::from(step) * fraction).unwrap_or(0)
1346            }
1347            Self::Page {
1348                steps,
1349                parts,
1350                per_inch,
1351                product,
1352            } => {
1353                if side <= 0 || parts <= 0 || per_inch <= 0 || steps.1 <= 0 {
1354                    return 0;
1355                }
1356                if let OffsetProduct::Binary32 { dots_per_inch } = product {
1357                    return binary32_page_offset(
1358                        x,
1359                        side,
1360                        (steps, parts, per_inch),
1361                        (dots_per_inch, fraction),
1362                    )
1363                    .unwrap_or(0);
1364                }
1365                // The product rounds before the division.
1366                let parts = i128::from(parts);
1367                let product = div_round_i128(
1368                    i128::from(x) * i128::from(steps.0) * parts,
1369                    i128::from(steps.1) * i128::from(side),
1370                );
1371                let n = div_round_i128(product, parts);
1372                let inch = i128::from(Length::UNITS_PER_INCH);
1373                i64::try_from(div_round_i128(n * inch * fraction, i128::from(per_inch)))
1374                    .unwrap_or(0)
1375            }
1376        }
1377    }
1378}
1379
1380/// The offset of [`OffsetProduct::Binary32`] of a place at `x` on a page whose side along `x` is
1381/// `side`, both in half-EMUs, with the page form's `steps`, `parts` and `per_inch`: the written
1382/// place of the place's whole dot less the dot's place, in `fraction`ths of a half-EMU. `None`
1383/// where a count does not fit or a number is not positive.
1384fn binary32_page_offset(
1385    x: i64,
1386    side: i64,
1387    (steps, parts, per_inch): (Fraction, i64, i64),
1388    (dots_per_inch, fraction): (i64, i128),
1389) -> Option<i64> {
1390    if dots_per_inch <= 0 {
1391        return None;
1392    }
1393    let inch = i128::from(Length::UNITS_PER_INCH);
1394    let dpi = i128::from(dots_per_inch);
1395    let dots = i64::try_from(div_round_i128(i128::from(side) * dpi, inch)).ok()?;
1396    let place = i64::try_from(div_round_i128(i128::from(x) * dpi, inch)).ok()?;
1397    let entry = page_entry(dots, (steps, parts, per_inch), dpi)?;
1398    // The whole parts of the written place, then its whole steps, each a half up.
1399    let written_parts = i128::from(entry.times(place).whole(false));
1400    let written = div_round_i128(written_parts, parts.into());
1401    // The written place less the dot's place, in half-EMUs: (written / per_inch - place / dpi)
1402    // inches.
1403    let difference = written
1404        .checked_mul(dpi)?
1405        .checked_sub(i128::from(place).checked_mul(per_inch.into())?)?;
1406    i64::try_from(div_round_i128(
1407        difference.checked_mul(inch)?.checked_mul(fraction)?,
1408        i128::from(per_inch).checked_mul(dpi)?,
1409    ))
1410    .ok()
1411}
1412
1413/// The written place of [`Offset::written_place`] for [`OffsetProduct::Binary32`]: the place at
1414/// `x` in dots, `x dpi / inch`, times the page entry of the page's side `side`, held as the
1415/// nearest binary32 number, in whole parts and then whole steps, each a half up, back in
1416/// half-EMUs, the nearest. `None` where a count does not fit or a number is not positive.
1417fn binary32_written_place(
1418    x: i64,
1419    side: i64,
1420    (steps, parts, per_inch): (Fraction, i64, i64),
1421    dots_per_inch: i64,
1422) -> Option<i64> {
1423    if dots_per_inch <= 0 || parts <= 0 || per_inch <= 0 {
1424        return None;
1425    }
1426    let inch = i128::from(Length::UNITS_PER_INCH);
1427    let dpi = i128::from(dots_per_inch);
1428    let dots = i64::try_from(div_round_i128(i128::from(side) * dpi, inch)).ok()?;
1429    let entry = page_entry(dots, (steps, parts, per_inch), dpi)?;
1430    // entry * x dpi / inch, with the entry as its mantissa times a power of two.
1431    let (mantissa, exponent) = (i128::from(entry.mantissa()), entry.exponent());
1432    let mut numerator = mantissa.checked_mul(i128::from(x))?.checked_mul(dpi)?;
1433    let mut denominator = inch;
1434    let shift = exponent.unsigned_abs();
1435    if exponent >= 0 {
1436        numerator = numerator.checked_mul(1_i128.checked_shl(shift)?)?;
1437    } else {
1438        denominator = denominator.checked_mul(1_i128.checked_shl(shift)?)?;
1439    }
1440    let product = Binary32::nearest(numerator, denominator);
1441    let written_parts = i128::from(product.whole(false));
1442    let written = div_round_i128(written_parts, parts.into());
1443    i64::try_from(div_round_i128(
1444        written.checked_mul(inch)?,
1445        i128::from(per_inch),
1446    ))
1447    .ok()
1448}
1449
1450/// The page entry of a side of `dots` whole dots, `dpi` to the inch, with the page form's
1451/// `steps`, `parts` and `per_inch`: `parts (per_inch / dpi + steps / dots)`, held as the nearest
1452/// binary32 number. `None` where the side is not positive or a count does not fit.
1453fn page_entry(
1454    dots: i64,
1455    (steps, parts, per_inch): (Fraction, i64, i64),
1456    dpi: i128,
1457) -> Option<Binary32> {
1458    if dots <= 0 {
1459        return None;
1460    }
1461    // parts (per_inch / dpi + c / D) = parts (per_inch D c.1 + c.0 dpi) / (dpi D c.1).
1462    let (gain, over) = (i128::from(steps.0), i128::from(steps.1));
1463    let numerator = i128::from(per_inch)
1464        .checked_mul(dots.into())?
1465        .checked_mul(over)?
1466        .checked_add(gain.checked_mul(dpi)?)?
1467        .checked_mul(parts.into())?;
1468    let denominator = dpi.checked_mul(dots.into())?.checked_mul(over)?;
1469    Some(Binary32::nearest(numerator, denominator))
1470}
1471
1472/// Moves a filled rectangle's left and right edges by the writer's horizontal offset `across`
1473/// of each edge's place, on a page `width` wide.
1474fn offset_rect(rect: &mut Rect, across: Offset, width: Length) {
1475    let right = rect.x.units() + rect.width.units();
1476    let left = rect.x.units() + across.of(rect.x.units(), width.units());
1477    let right = right + across.of(right, width.units());
1478    rect.x = Length::from_units(left);
1479    rect.width = Length::from_units(right - left);
1480}
1481
1482/// A number as a fraction: its numerator and its denominator, which is positive.
1483pub type Fraction = (i64, i64);
1484
1485/// The most page heights for which a writer holds a factor of its stretch
1486/// ([`Writer::with_stretch_factors`]).
1487pub const STRETCH_HEIGHTS: usize = 16;
1488
1489/// How a target's PDF writer writes the numbers of a page that it decides itself, such as the
1490/// page size, and the files of its pictures. Layout gives each page its exact size, and the
1491/// output stage applies the writer to the finished display list. The target's profile says
1492/// which writer it uses.
1493#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1494pub struct Writer {
1495    page_step: i64,
1496    vertical_stretch: i64,
1497    glyph_stretch_step: Option<Length>,
1498    stretch_offset: Fraction,
1499    stretch_factors: [(i64, Fraction); STRETCH_HEIGHTS],
1500    stretch_heights: usize,
1501    digits: Option<NonZeroU32>,
1502    least_decimals: u32,
1503    rectangle_steps: Option<NonZeroU32>,
1504    baseline_steps: Option<NonZeroU32>,
1505    picture_digits: Option<NonZeroU32>,
1506    horizontal_offset: WriterOffset,
1507    vertical_offset: WriterOffset,
1508    jpeg_quality: Option<JpegQuality>,
1509    jpeg_share: Option<JpegShare>,
1510    jpeg_sample: Option<JpegSample>,
1511    picture_density: Option<PictureDensity>,
1512    palette_density: Option<PaletteDensity>,
1513    picture_crop: PictureCrop,
1514    alpha_mix: AlphaMix,
1515    linear_limit: LinearLimit,
1516}
1517
1518/// How a writer mixes the colors of a picture with an alpha when it resamples the picture
1519/// ([`Writer::with_alpha_mix`]).
1520#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1521pub enum AlphaMix {
1522    /// Each color as it is, whatever its alpha.
1523    Plain,
1524    /// Each color weighted by its alpha: the writer multiplies each color by its alpha over
1525    /// 255, rounds it to a whole level, resamples it with the alpha, and divides each new
1526    /// color by its new alpha. A clear pixel's color then adds nothing, and a color whose new
1527    /// alpha is 0 is 0.
1528    Weighted,
1529}
1530
1531/// How a writer writes a cropped picture, a picture whose crop shows only its visible part
1532/// ([`Writer::with_picture_crop`]).
1533#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1534pub enum PictureCrop {
1535    /// Its whole file, under a clip to the visible part.
1536    WholeFileUnderClip,
1537    /// The pixels of its visible part only, at the visible part's place and size and with no
1538    /// clip. The writer rounds the visible part's left and top edges and its size to the
1539    /// nearest whole pixels of the file, a half up, and resamples the part as a picture of its
1540    /// own. A side of the visible part beyond the file ends at the file's edge
1541    /// ([`ImageItem::shown`]).
1542    VisiblePart,
1543    /// The pixels of its visible part only, as [`Self::VisiblePart`], except that a part that
1544    /// the mean of the area resamples comes from the whole file at the part's scale: on each
1545    /// axis, the written count over the part's count. The writer resamples the whole file by
1546    /// the mean of the area to its count times that scale, rounded to the nearest whole pixel,
1547    /// a half up, and takes written pixel `x` at the place of the part's first pixel times the
1548    /// scale, plus `x`, by the linear interpolation.
1549    VisiblePartAtScale,
1550}
1551
1552impl PictureCrop {
1553    /// Whether the writer keeps only the pixels of a cropped picture's visible part.
1554    #[must_use]
1555    pub const fn keeps_visible_part(self) -> bool {
1556        !matches!(self, Self::WholeFileUnderClip)
1557    }
1558}
1559
1560/// The quality of the tables of ITU-T T.81 Annex K at which a writer writes a JPEG picture
1561/// again: 1 to 100.
1562#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1563pub struct JpegQuality(u8);
1564
1565impl JpegQuality {
1566    /// The quality `quality`, or `None` outside 1 to 100.
1567    #[must_use]
1568    pub const fn new(quality: u8) -> Option<Self> {
1569        if quality >= 1 && quality <= 100 {
1570            Some(Self(quality))
1571        } else {
1572            None
1573        }
1574    }
1575
1576    /// The quality, from 1 to 100.
1577    #[must_use]
1578    pub const fn get(self) -> u8 {
1579        self.0
1580    }
1581}
1582
1583/// The share of a picture's color under Flate below which a writer writes a picture that is not
1584/// JPEG as a JPEG file ([`Writer::with_jpeg_share`]), in thousandths.
1585#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1586pub struct JpegShare(u16);
1587
1588impl JpegShare {
1589    /// The share of `thousandths` of a whole, or `None` outside 1 to 1,000.
1590    #[must_use]
1591    pub const fn new(thousandths: u16) -> Option<Self> {
1592        if thousandths >= 1 && thousandths <= 1000 {
1593            Some(Self(thousandths))
1594        } else {
1595            None
1596        }
1597    }
1598
1599    /// The share in thousandths, from 1 to 1,000.
1600    #[must_use]
1601    pub const fn thousandths(self) -> u16 {
1602        self.0
1603    }
1604
1605    /// Whether a JPEG file of `jpeg` bytes is smaller than this share of a Flate stream of
1606    /// `flate` bytes.
1607    #[must_use]
1608    pub fn takes(self, jpeg: usize, flate: usize) -> bool {
1609        let (Ok(jpeg), Ok(flate)) = (u128::try_from(jpeg), u128::try_from(flate)) else {
1610            return false;
1611        };
1612        jpeg * 1000 < u128::from(self.0) * flate
1613    }
1614}
1615
1616/// The second test of a writer that writes a picture that its JPEG share takes as a JPEG file
1617/// ([`Writer::with_jpeg_sample`]). The picture stays a JPEG file when its color under Flate is
1618/// at least the whole share of its raw color, or when the estimate from its sample reaches both
1619/// the sample share of its color under Flate and the floor in bytes; else it stays lossless. The
1620/// sample is [`Self::STRIPS`] strips of [`Self::ROWS`] rows ([`Self::strips`]), and the estimate
1621/// is the sum of the strips' colors under Flate, each strip compressed on its own, times the
1622/// picture's height over the sample's [`Self::STRIPS`] times [`Self::ROWS`] rows.
1623#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1624pub struct JpegSample {
1625    share: u16,
1626    floor: u32,
1627    whole: u16,
1628}
1629
1630impl JpegSample {
1631    /// The strips of the sample.
1632    pub const STRIPS: usize = 16;
1633    /// The rows of each strip of the sample.
1634    pub const ROWS: usize = 8;
1635
1636    /// The test with the sample share and the whole share in thousandths, each from 1 to 1,000,
1637    /// and the floor in bytes, at least 1; `None` outside them.
1638    #[must_use]
1639    pub const fn new(share: u16, floor: u32, whole: u16) -> Option<Self> {
1640        if share >= 1 && share <= 1000 && whole >= 1 && whole <= 1000 && floor >= 1 {
1641            Some(Self {
1642                share,
1643                floor,
1644                whole,
1645            })
1646        } else {
1647            None
1648        }
1649    }
1650
1651    /// The rows of each strip of the sample of a picture `height` rows high: from the row
1652    /// `k * height / STRIPS`, rounded down, for `k` from 0 to `STRIPS - 1`, [`Self::ROWS`] rows
1653    /// or as many as the picture has below it. The strips of a picture below `STRIPS` times
1654    /// `ROWS` rows overlap.
1655    pub fn strips(height: usize) -> impl Iterator<Item = std::ops::Range<usize>> {
1656        (0..Self::STRIPS).map(move |k| {
1657            let start = k.saturating_mul(height) / Self::STRIPS;
1658            start..start.saturating_add(Self::ROWS).min(height)
1659        })
1660    }
1661
1662    /// Whether a picture `height` rows high whose sample takes `sample` bytes under Flate and
1663    /// whose color takes `flate` bytes under Flate of `raw` raw bytes stays a JPEG file.
1664    #[must_use]
1665    pub fn takes(self, sample: usize, height: usize, (flate, raw): (usize, usize)) -> bool {
1666        let (Ok(sample), Ok(height), Ok(flate), Ok(raw), Ok(rows)) = (
1667            u128::try_from(sample),
1668            u128::try_from(height),
1669            u128::try_from(flate),
1670            u128::try_from(raw),
1671            u128::try_from(Self::STRIPS * Self::ROWS),
1672        ) else {
1673            return false;
1674        };
1675        let estimate = sample * height;
1676        flate * 1000 >= u128::from(self.whole) * raw
1677            || (estimate * 1000 >= u128::from(self.share) * flate * rows
1678                && estimate >= u128::from(self.floor) * rows)
1679    }
1680}
1681
1682/// The density to which a writer resamples a dense picture: a direction whose pixels lie at
1683/// `limit_ppi` per inch of its drawn size or closer gets the most pixels below `ppi` per inch
1684/// ([`Writer::resampled_size`]).
1685#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1686pub struct PictureDensity {
1687    /// The density from which a direction is resampled, in pixels per inch.
1688    pub limit_ppi: NonZeroU32,
1689    /// The density below which a resampled direction stays, in pixels per inch.
1690    pub ppi: NonZeroU32,
1691}
1692
1693/// The class of a PNG picture file of a palette that a writer with a palette density
1694/// resamples by limits of its own ([`PaletteDensity`]). Each class has no `tRNS` chunk. A file
1695/// of another kind, a palette with a `tRNS` chunk, a palette of 2 bits and a palette of more
1696/// than 1 bit whose entries are all gray have no class.
1697#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1698pub enum PaletteClass {
1699    /// A palette of 1 bit, with gray or color entries.
1700    OneBit,
1701    /// A palette of 4 bits with an entry that is not gray.
1702    FourBitColor,
1703    /// A palette of 8 bits with an entry that is not gray.
1704    EightBitColor,
1705}
1706
1707/// The limits and the density with which a writer resamples a PNG picture of a palette of a
1708/// class ([`PaletteClass`]) in place of those of its picture density ([`PictureDensity`]): a
1709/// direction is dense from its class's limit per inch, a dense direction of a 1-bit palette
1710/// gets the most pixels below `one_bit_ppi` per inch, each found by the file's pixel under its
1711/// centre ([`Resampler::CentrePixel`]), and a dense direction of another class gets the most
1712/// pixels below the picture density's pixels per inch, found by the filter.
1713#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1714pub struct PaletteDensity {
1715    /// The density from which a direction of a 1-bit palette is resampled, in pixels per inch.
1716    pub one_bit_limit_ppi: NonZeroU32,
1717    /// The density below which a resampled direction of a 1-bit palette stays, in pixels per
1718    /// inch.
1719    pub one_bit_ppi: NonZeroU32,
1720    /// The density from which a direction of a 4-bit color palette is resampled, in pixels per
1721    /// inch.
1722    pub four_bits_limit_ppi: NonZeroU32,
1723    /// The density from which a direction of an 8-bit color palette is resampled, in pixels per
1724    /// inch.
1725    pub eight_bits_limit_ppi: NonZeroU32,
1726}
1727
1728/// How a writer finds the pixels of a picture that it resamples.
1729#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1730pub enum Resampler {
1731    /// Its filter, which mixes the file's pixels that each new pixel covers: the linear
1732    /// interpolation for the pictures that the limit names, else the mean of the covered area.
1733    Filter(LinearLimit),
1734    /// Each new pixel takes the file's pixel under its centre.
1735    CentrePixel,
1736}
1737
1738/// The pictures that a writer's filter resamples by the linear interpolation; it takes the mean
1739/// of the covered area for the others ([`Writer::with_linear_limit`]).
1740#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1741pub enum LinearLimit {
1742    /// The pictures of at most this many source pixels.
1743    Pixels(NonZeroU32),
1744    /// The pictures with no side of more than this many source pixels.
1745    Side(NonZeroU32),
1746}
1747
1748impl LinearLimit {
1749    /// Whether the filter resamples a picture of `pixels` (across, down) by the linear
1750    /// interpolation.
1751    #[must_use]
1752    pub fn takes_linear(self, (width, height): (usize, usize)) -> bool {
1753        let most = |count: NonZeroU32| usize::try_from(count.get()).unwrap_or(usize::MAX);
1754        match self {
1755            Self::Pixels(count) => width.saturating_mul(height) <= most(count),
1756            Self::Side(count) => width.max(height) <= most(count),
1757        }
1758    }
1759}
1760
1761/// The limit of a new writer: the linear interpolation up to 2^17 source pixels.
1762const DEFAULT_LINEAR_LIMIT: LinearLimit = match NonZeroU32::new(1 << 17) {
1763    Some(count) => LinearLimit::Pixels(count),
1764    None => LinearLimit::Pixels(NonZeroU32::MIN),
1765};
1766
1767impl Writer {
1768    /// A writer that rounds the page size to whole steps of `page_step`, or `None` when the
1769    /// step is not positive.
1770    #[must_use]
1771    pub const fn new(page_step: Length) -> Option<Self> {
1772        if page_step.units() > 0 {
1773            Some(Self {
1774                page_step: page_step.units(),
1775                vertical_stretch: 0,
1776                glyph_stretch_step: None,
1777                stretch_offset: (0, 1),
1778                stretch_factors: [(0, (1, 1)); STRETCH_HEIGHTS],
1779                stretch_heights: 0,
1780                digits: None,
1781                least_decimals: 0,
1782                rectangle_steps: None,
1783                baseline_steps: None,
1784                picture_digits: None,
1785                horizontal_offset: WriterOffset::NONE,
1786                vertical_offset: WriterOffset::NONE,
1787                jpeg_quality: None,
1788                jpeg_share: None,
1789                jpeg_sample: None,
1790                picture_density: None,
1791                palette_density: None,
1792                picture_crop: PictureCrop::WholeFileUnderClip,
1793                alpha_mix: AlphaMix::Plain,
1794                linear_limit: DEFAULT_LINEAR_LIMIT,
1795            })
1796        } else {
1797            None
1798        }
1799    }
1800
1801    /// The same writer, which writes the file of each JPEG picture of a page again as a
1802    /// baseline JPEG file with the quantization tables of ITU-T T.81 Annex K scaled to
1803    /// `quality`, its chroma halved across and down, or keeps each file for `None`. This
1804    /// crate holds no decoder, so the output stage writes the files ([`Self::jpeg_quality`]).
1805    #[must_use]
1806    pub const fn with_jpeg_quality(self, quality: Option<JpegQuality>) -> Self {
1807        Self {
1808            jpeg_quality: quality,
1809            ..self
1810        }
1811    }
1812
1813    /// The quality at which the writer writes each JPEG picture of a page again, or `None`
1814    /// when it keeps each file ([`Self::with_jpeg_quality`]).
1815    #[must_use]
1816    pub const fn jpeg_quality(&self) -> Option<JpegQuality> {
1817        self.jpeg_quality
1818    }
1819
1820    /// The same writer, which writes an opaque PNG picture without a palette as a JPEG file at
1821    /// its JPEG quality ([`Self::with_jpeg_quality`]) when that file is smaller than `share` of
1822    /// the picture's color under Flate, and keeps it lossless otherwise, or keeps every such
1823    /// picture lossless for `None`. The output stage writes the files ([`Self::jpeg_share`]).
1824    #[must_use]
1825    pub const fn with_jpeg_share(self, share: Option<JpegShare>) -> Self {
1826        Self {
1827            jpeg_share: share,
1828            ..self
1829        }
1830    }
1831
1832    /// The share of the color under Flate below which the writer writes an opaque PNG picture
1833    /// as a JPEG file, or `None` when it keeps each one lossless ([`Self::with_jpeg_share`]).
1834    #[must_use]
1835    pub const fn jpeg_share(&self) -> Option<JpegShare> {
1836        self.jpeg_share
1837    }
1838
1839    /// The same writer, which keeps a picture that its JPEG share takes ([`Self::jpeg_share`])
1840    /// a JPEG file only when `sample` takes it too, and writes it lossless otherwise, or which
1841    /// asks no second test for `None` ([`Self::jpeg_sample`]).
1842    #[must_use]
1843    pub const fn with_jpeg_sample(self, sample: Option<JpegSample>) -> Self {
1844        Self {
1845            jpeg_sample: sample,
1846            ..self
1847        }
1848    }
1849
1850    /// The second test of a picture that the JPEG share takes, or `None` when the writer asks
1851    /// none ([`Self::with_jpeg_sample`]).
1852    #[must_use]
1853    pub const fn jpeg_sample(&self) -> Option<JpegSample> {
1854        self.jpeg_sample
1855    }
1856
1857    /// The same writer, which writes a picture whose pixels lie as close as the density's
1858    /// limit per inch across or down, or closer, with fewer pixels in that direction: the most
1859    /// that stay below the density's pixels per inch ([`Self::resampled_size`]). `None` keeps
1860    /// every picture's pixels.
1861    #[must_use]
1862    pub const fn with_picture_density(self, density: Option<PictureDensity>) -> Self {
1863        Self {
1864            picture_density: density,
1865            ..self
1866        }
1867    }
1868
1869    /// The same writer, which resamples a PNG picture of a palette of a class by the limits and
1870    /// the density of `density` ([`PaletteDensity`]). `None` resamples it as any other picture.
1871    /// A writer without a picture density keeps every picture's pixels, also with a palette
1872    /// density.
1873    #[must_use]
1874    pub const fn with_palette_density(self, density: Option<PaletteDensity>) -> Self {
1875        Self {
1876            palette_density: density,
1877            ..self
1878        }
1879    }
1880
1881    /// The same writer, which writes a cropped picture as `crop` says ([`PictureCrop`]).
1882    #[must_use]
1883    pub const fn with_picture_crop(self, crop: PictureCrop) -> Self {
1884        Self {
1885            picture_crop: crop,
1886            ..self
1887        }
1888    }
1889
1890    /// How the writer writes a cropped picture ([`Self::with_picture_crop`]). This crate holds
1891    /// no decoder, so the output stage cuts the files.
1892    #[must_use]
1893    pub const fn picture_crop(&self) -> PictureCrop {
1894        self.picture_crop
1895    }
1896
1897    /// The same writer, which mixes the colors of a picture with an alpha as `mix` says when
1898    /// it resamples the picture ([`AlphaMix`]).
1899    #[must_use]
1900    pub const fn with_alpha_mix(self, mix: AlphaMix) -> Self {
1901        Self {
1902            alpha_mix: mix,
1903            ..self
1904        }
1905    }
1906
1907    /// How the writer mixes the colors of a picture with an alpha when it resamples it
1908    /// ([`Self::with_alpha_mix`]). This crate holds no decoder, so the output stage resamples
1909    /// the files.
1910    #[must_use]
1911    pub const fn alpha_mix(&self) -> AlphaMix {
1912        self.alpha_mix
1913    }
1914
1915    /// The same writer, whose filter resamples the pictures that `limit` names by the linear
1916    /// interpolation and the others by the mean of the covered area ([`LinearLimit`]). A new
1917    /// writer takes the linear interpolation up to 2^17 source pixels.
1918    #[must_use]
1919    pub const fn with_linear_limit(self, limit: LinearLimit) -> Self {
1920        Self {
1921            linear_limit: limit,
1922            ..self
1923        }
1924    }
1925
1926    /// The significant digits with which the writer writes a glyph's baseline, and a
1927    /// rectangle's bottom edge and height ([`Self::with_digits`]); `None` keeps them exact.
1928    #[must_use]
1929    pub const fn digits(&self) -> Option<NonZeroU32> {
1930        self.digits
1931    }
1932
1933    /// The least decimals with which the writer prints a glyph's baseline and a rectangle's
1934    /// numbers ([`Self::with_least_decimals`]).
1935    #[must_use]
1936    pub const fn least_decimals(&self) -> u32 {
1937        self.least_decimals
1938    }
1939
1940    /// The steps per inch on which the writer holds a filled rectangle's edges
1941    /// ([`Self::with_rectangle_steps`]); `None` holds the exact edges.
1942    #[must_use]
1943    pub const fn rectangle_steps(&self) -> Option<NonZeroU32> {
1944        self.rectangle_steps
1945    }
1946
1947    /// The steps per inch whose whole count the writer converts to the points of a glyph's
1948    /// baseline ([`Self::with_baseline_steps`]); `None` holds the baseline's own points.
1949    #[must_use]
1950    pub const fn baseline_steps(&self) -> Option<NonZeroU32> {
1951        self.baseline_steps
1952    }
1953
1954    /// The pixel size at which the writer writes a picture of `pixels` that fills `size` on
1955    /// the page, or `None` when it keeps the picture's pixels: with a limit
1956    /// ([`Self::with_picture_density`]), a direction whose pixels lie at the limit per inch of
1957    /// its size or closer gets the largest pixel count below the writer's density on that
1958    /// size, and a direction that is less dense than the limit keeps its pixels, even when it
1959    /// is denser than the writer's density. The size is the one at which the picture is drawn,
1960    /// with no cut to whole twips of its own. A PNG picture of a palette of a `palette` class
1961    /// takes the limit and the density of the writer's palette density, when it has one
1962    /// ([`Self::with_palette_density`]). The answer also says how the writer finds the new
1963    /// pixels, its filter with the writer's limit ([`Self::with_linear_limit`]) for every class
1964    /// but a 1-bit palette.
1965    #[must_use]
1966    pub fn resampled_size(
1967        &self,
1968        pixels: (usize, usize),
1969        size: (Length, Length),
1970        palette: Option<PaletteClass>,
1971    ) -> Option<((usize, usize), Resampler)> {
1972        let density = self.picture_density?;
1973        let filter = Resampler::Filter(self.linear_limit);
1974        let (limit_ppi, ppi, resampler) = match (self.palette_density, palette) {
1975            (Some(palettes), Some(PaletteClass::OneBit)) => (
1976                palettes.one_bit_limit_ppi,
1977                palettes.one_bit_ppi,
1978                Resampler::CentrePixel,
1979            ),
1980            (Some(palettes), Some(PaletteClass::FourBitColor)) => {
1981                (palettes.four_bits_limit_ppi, density.ppi, filter)
1982            }
1983            (Some(palettes), Some(PaletteClass::EightBitColor)) => {
1984                (palettes.eight_bits_limit_ppi, density.ppi, filter)
1985            }
1986            _ => (density.limit_ppi, density.ppi, filter),
1987        };
1988        let inch = i128::from(Length::UNITS_PER_INCH);
1989        // A direction is dense when count * inch >= limit * size, and then gets the largest
1990        // count below the density on its size: count * inch < ppi * size. Another direction
1991        // keeps its count.
1992        let written = |count: usize, length: Length| {
1993            let units = i128::from(length.units());
1994            let pixels = i128::try_from(count).unwrap_or(i128::MAX);
1995            if pixels * inch < i128::from(limit_ppi.get()) * units {
1996                return count;
1997            }
1998            let most = (i128::from(ppi.get()) * units - 1) / inch;
1999            usize::try_from(most).map_or(count, |most| most.min(count))
2000        };
2001        let (width, height) = size;
2002        if width.units() <= 0 || height.units() <= 0 {
2003            return None;
2004        }
2005        let new = (written(pixels.0, width), written(pixels.1, height));
2006        (new != pixels && new.0 > 0 && new.1 > 0).then_some((new, resampler))
2007    }
2008
2009    /// The writer that places every point of a page as if the page were `steps` page steps
2010    /// taller: a point at `y` from the page's top goes to `y (H + s) / H`, with `H` the page's
2011    /// height and `s` the steps' length.
2012    #[must_use]
2013    pub const fn with_vertical_stretch(self, steps: i64) -> Self {
2014        Self {
2015            vertical_stretch: steps,
2016            ..self
2017        }
2018    }
2019
2020    /// The same writer, which rounds how far its vertical stretch moves a glyph's baseline, and
2021    /// a filled rectangle's top and bottom edges, to the nearest whole `step`, a half step up,
2022    /// and places them at their layout place plus that rounded distance. Other items, and all
2023    /// items for `None`, move by the exact stretch. `None` when the step is not positive.
2024    #[must_use]
2025    pub const fn with_glyph_stretch_step(self, step: Option<Length>) -> Option<Self> {
2026        match step {
2027            Some(step) if step.units() <= 0 => None,
2028            Some(step) => Some(Self {
2029                glyph_stretch_step: Some(step),
2030                ..self
2031            }),
2032            None => Some(Self {
2033                glyph_stretch_step: None,
2034                ..self
2035            }),
2036        }
2037    }
2038
2039    /// The same writer, which counts the steps of a glyph's baseline, and of a filled
2040    /// rectangle's top and bottom edges, on a page whose written height `factors` names as
2041    /// `round(s × r + offset)`, a half up, with `s` the exact stretch in steps and `r` the
2042    /// height's factor, each a fraction. On a page of another height, it rounds `s` itself
2043    /// ([`Self::with_glyph_stretch_step`]). `None` when `factors` names more than
2044    /// [`STRETCH_HEIGHTS`] heights, or a fraction has no positive denominator.
2045    #[must_use]
2046    pub fn with_stretch_factors(
2047        self,
2048        offset: Fraction,
2049        factors: &[(Length, Fraction)],
2050    ) -> Option<Self> {
2051        if factors.len() > STRETCH_HEIGHTS
2052            || offset.1 <= 0
2053            || factors.iter().any(|(_, factor)| factor.1 <= 0)
2054        {
2055            return None;
2056        }
2057        let mut table = [(0, (1, 1)); STRETCH_HEIGHTS];
2058        for (slot, (height, factor)) in table.iter_mut().zip(factors) {
2059            *slot = (height.units(), *factor);
2060        }
2061        Some(Self {
2062            stretch_offset: offset,
2063            stretch_factors: table,
2064            stretch_heights: factors.len(),
2065            ..self
2066        })
2067    }
2068
2069    /// The factor and offset with which the writer counts the steps of its stretch on a page
2070    /// whose written height is `height` ([`Self::with_stretch_factors`]): those of the table,
2071    /// or a factor of 1 and no offset for a height that it does not name.
2072    fn stretch_factor(&self, height: Length) -> (Fraction, Fraction) {
2073        self.stretch_factors
2074            .iter()
2075            .take(self.stretch_heights)
2076            .find(|(written, _)| *written == height.units())
2077            .map_or(((1, 1), (0, 1)), |(_, factor)| {
2078                (*factor, self.stretch_offset)
2079            })
2080    }
2081
2082    /// The same writer, which writes a glyph's baseline, and a rectangle's bottom edge and
2083    /// height, as their distances from the page's bottom edge in points, subtracted in single
2084    /// precision and printed with `digits` significant digits, a half rounded up, and places
2085    /// them there. `None` keeps the places exact.
2086    #[must_use]
2087    pub const fn with_digits(self, digits: Option<NonZeroU32>) -> Self {
2088        Self { digits, ..self }
2089    }
2090
2091    /// The same writer, which prints each number of a glyph's baseline and of a filled
2092    /// rectangle with its digits ([`Self::with_digits`]) but with at least `decimals` decimals:
2093    /// from 1,000 pt, where five significant digits leave one decimal, a writer with 2 prints
2094    /// a distance of 1,007.88 pt as `1007.88`. Zero leaves the significant digits alone. The
2095    /// digits of pictures ([`Self::with_picture_digits`]) keep no least decimals.
2096    #[must_use]
2097    pub const fn with_least_decimals(self, decimals: u32) -> Self {
2098        Self {
2099            least_decimals: decimals,
2100            ..self
2101        }
2102    }
2103
2104    /// The same writer, which holds each edge of a filled rectangle as the single-precision
2105    /// product of its whole steps of `1/per_inch` inch and the step in points in single
2106    /// precision, and writes with its digits the left edge, the bottom edge from the page's
2107    /// foot, and the width and height as differences of those edges subtracted in single
2108    /// precision. `None` keeps the single-precision numbers of the exact edge, width and
2109    /// height.
2110    #[must_use]
2111    pub const fn with_rectangle_steps(self, per_inch: Option<NonZeroU32>) -> Self {
2112        Self {
2113            rectangle_steps: per_inch,
2114            ..self
2115        }
2116    }
2117
2118    /// The same writer, which holds a glyph's baseline as its whole count of steps of
2119    /// `1/per_inch` inch and converts the count to points in single precision, the count
2120    /// divided by `per_inch` and the quotient multiplied by 72, before it subtracts the
2121    /// baseline from the page's height and prints it with its digits. `None` holds the
2122    /// baseline's own points in single precision.
2123    #[must_use]
2124    pub const fn with_baseline_steps(self, per_inch: Option<NonZeroU32>) -> Self {
2125        Self {
2126            baseline_steps: per_inch,
2127            ..self
2128        }
2129    }
2130
2131    /// The same writer, which writes an upright image's matrix as it writes a rectangle with
2132    /// `digits` significant digits ([`Self::with_digits`]): its left edge, width, height and
2133    /// bottom edge, and places the image there ([`Self::place_pictures`]). `None` keeps the
2134    /// image's place exact.
2135    #[must_use]
2136    pub const fn with_picture_digits(self, digits: Option<NonZeroU32>) -> Self {
2137        Self {
2138            picture_digits: digits,
2139            ..self
2140        }
2141    }
2142
2143    /// Places each upright image of a display list where the writer writes its matrix with its
2144    /// picture digits ([`Self::with_picture_digits`]) on its page. The output stage calls this
2145    /// after it has written the pictures' files again, so that a cropped picture drawn at its
2146    /// clip is placed as it is drawn. The images inside a group keep their places, as in
2147    /// [`Self::finish`].
2148    pub fn place_pictures(&self, list: &mut DisplayList) {
2149        let Some(digits) = self.picture_digits else {
2150            return;
2151        };
2152        for page in &mut list.pages {
2153            for item in &mut page.items {
2154                if let Item::Image(image) = item
2155                    && image.turn.is_none()
2156                {
2157                    (image.x, image.y, image.width, image.height) = written_box(
2158                        page.height,
2159                        (image.x, image.y, image.width, image.height),
2160                        (digits.get(), 0),
2161                    );
2162                }
2163            }
2164        }
2165    }
2166
2167    /// The same writer, which moves the left and right edges of a filled rectangle right by
2168    /// `offset` of each edge's place from the page's left edge, as the writer offsets a text
2169    /// object's start.
2170    #[must_use]
2171    pub const fn with_horizontal_offset(self, offset: WriterOffset) -> Self {
2172        Self {
2173            horizontal_offset: offset,
2174            ..self
2175        }
2176    }
2177
2178    /// The same writer, which moves a glyph's baseline, and a filled rectangle's top and
2179    /// bottom edges, down by `offset` of each place from the page's top edge, after its
2180    /// vertical stretch.
2181    #[must_use]
2182    pub const fn with_vertical_offset(self, offset: WriterOffset) -> Self {
2183        Self {
2184            vertical_offset: offset,
2185            ..self
2186        }
2187    }
2188
2189    /// The writer's offsets across and down a page `width` by `height` in a section of
2190    /// `orientation` ([`Self::with_horizontal_offset`], [`Self::with_vertical_offset`],
2191    /// [`WriterOffset::on_page`]).
2192    fn page_offsets(
2193        &self,
2194        width: Length,
2195        height: Length,
2196        orientation: Orientation,
2197    ) -> (Offset, Offset) {
2198        let (width, height) = (width.units(), height.units());
2199        (
2200            self.horizontal_offset.on_page(width, height, orientation).0,
2201            self.vertical_offset.on_page(width, height, orientation).1,
2202        )
2203    }
2204
2205    /// The offsets across and down with which the writer places the items of a page `width` by
2206    /// `height` in a section of `orientation`; unstable helper behind the `development` feature.
2207    #[cfg(feature = "development")]
2208    #[must_use]
2209    pub fn development_page_offsets(
2210        &self,
2211        width: Length,
2212        height: Length,
2213        orientation: Orientation,
2214    ) -> (Offset, Offset) {
2215        self.page_offsets(width, height, orientation)
2216    }
2217
2218    /// The page side that the writer writes: `length` rounded to the nearest whole step, a half
2219    /// step up. A page side lies within [`Length::FILE_LIMIT`], as every page of the DOCX layout
2220    /// does, since its reader bounds the page size there, so the rounding fits an `i64`.
2221    #[must_use]
2222    pub const fn page_side(&self, length: Length) -> Length {
2223        let step = self.page_step;
2224        Length::from_units(div_round(length.units(), step) * step)
2225    }
2226
2227    /// Gives every page of a display list the size that the writer writes, and places its
2228    /// points as the writer's vertical stretch, offsets and digits say. The items of a group of
2229    /// a picture's own items keep their places: the writer writes them inside the picture,
2230    /// where none of these reach them. The items of a group of the page's items, such as the
2231    /// text of a text box under its clip, take the page's places.
2232    pub fn finish(&self, list: &mut DisplayList) {
2233        for page in &mut list.pages {
2234            page.width = self.page_side(page.width);
2235            page.height = self.page_side(page.height);
2236            let extra = self.vertical_stretch * self.page_step;
2237            if extra != 0 && page.height.units() > 0 {
2238                let (factor, offset) = self.stretch_factor(page.height);
2239                let stretch = Stretch {
2240                    taller: page.height.units() + extra,
2241                    height: page.height.units(),
2242                    glyph_step: self.glyph_stretch_step,
2243                    factor,
2244                    offset,
2245                };
2246                for item in &mut page.items {
2247                    stretch.item(item);
2248                }
2249            }
2250            self.offset_items(page);
2251            if let Some(digits) = self.digits {
2252                let digits = (digits.get(), self.least_decimals);
2253                for item in &mut page.items {
2254                    self.write_digits(page.height, digits, item);
2255                }
2256            }
2257            stroke_items(&mut page.items);
2258        }
2259    }
2260
2261    /// Moves the filled rectangles of a page by the writer's horizontal and vertical offsets,
2262    /// its glyphs' baselines by the vertical one, and the points of a table cell's clip
2263    /// ([`GroupPlaces::Cell`]) and of a group whose every point the writer places
2264    /// ([`GroupPlaces::Points`]) as a rectangle's edges, and each edge of a stroked rectangle
2265    /// ([`GroupPlaces::Stroked`]) at its own place.
2266    fn offset_items(&self, page: &mut Page) {
2267        let (width, height) = (page.width, page.height);
2268        let (across, down_offset) = self.page_offsets(width, height, page.orientation);
2269        let down =
2270            |y: Length| Length::from_units(y.units() + down_offset.of(y.units(), height.units()));
2271        let place = |point: &mut Point| {
2272            let x = point.x.units();
2273            point.x = Length::from_units(x + across.of(x, width.units()));
2274            point.y = down(point.y);
2275        };
2276        offset_all(&mut page.items, &|item| match item {
2277            Item::Rect(rect) => {
2278                offset_rect(rect, across, width);
2279                let bottom = Length::from_units(rect.y.units() + rect.height.units());
2280                let top = down(rect.y);
2281                let bottom = down(bottom);
2282                rect.y = top;
2283                rect.height = Length::from_units(bottom.units() - top.units());
2284            }
2285            Item::Glyphs(run) => {
2286                for glyph in &mut run.glyphs {
2287                    glyph.y = down(glyph.y);
2288                }
2289            }
2290            Item::Group(group) if group.places == GroupPlaces::Cell => {
2291                let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
2292                clip.flat_map(PathCommand::points_mut).for_each(place);
2293            }
2294            Item::Group(group) if group.places == GroupPlaces::Points => {
2295                group.points_mut().for_each(place);
2296            }
2297            Item::Group(group) if matches!(group.places, GroupPlaces::Stroked { .. }) => {
2298                place_edges(&mut group.items, (across, down_offset), (width, height));
2299            }
2300            Item::Path(_) | Item::Gradient(_) | Item::Image(_) | Item::Group(_) => {}
2301        });
2302    }
2303
2304    /// Places a glyph run's baselines, or a filled rectangle's edges, where the writer writes
2305    /// them with `digits`, its significant digits and least decimals, on a page of `height`.
2306    fn write_digits(&self, height: Length, digits: (u32, u32), item: &mut Item) {
2307        match item {
2308            Item::Glyphs(run) => {
2309                for glyph in &mut run.glyphs {
2310                    glyph.y = match self.baseline_steps {
2311                        Some(per_inch) => {
2312                            counted_y(height, glyph.y, digits, i64::from(per_inch.get()))
2313                        }
2314                        None => written_y(height, glyph.y, digits),
2315                    };
2316                }
2317            }
2318            Item::Rect(rect) => {
2319                let exact = (rect.x, rect.y, rect.width, rect.height);
2320                (rect.x, rect.y, rect.width, rect.height) = self
2321                    .rectangle_steps
2322                    .and_then(|steps| held_box(height, exact, (digits, i64::from(steps.get()))))
2323                    .unwrap_or_else(|| written_box(height, exact, digits));
2324            }
2325            Item::Group(group) => {
2326                if group.places == GroupPlaces::Points {
2327                    for point in group.points_mut() {
2328                        *point = written_point(height, *point, digits);
2329                    }
2330                }
2331                for item in group.placed_items() {
2332                    self.write_digits(height, digits, item);
2333                }
2334            }
2335            Item::Path(_) | Item::Gradient(_) | Item::Image(_) => {}
2336        }
2337    }
2338}
2339
2340/// Runs `place` on each of `items` and on each item of a group of the page's items in them,
2341/// but for the rectangles of a stroked group ([`GroupPlaces::Stroked`]), which `place` places
2342/// with their group.
2343fn offset_all(items: &mut [Item], place: &dyn Fn(&mut Item)) {
2344    for item in items {
2345        if let Item::Group(group) = item
2346            && !matches!(group.places, GroupPlaces::Stroked { .. })
2347        {
2348            offset_all(group.placed_items(), place);
2349        }
2350        place(item);
2351    }
2352}
2353
2354/// Places the edges of each rectangle of a stroked group's `items` ([`GroupPlaces::Stroked`])
2355/// where the writer writes them with its offsets across and down ([`Offset::written_place`]),
2356/// on a page `width` by `height`.
2357fn place_edges(
2358    items: &mut [Item],
2359    (across, down): (Offset, Offset),
2360    (width, height): (Length, Length),
2361) {
2362    for item in items {
2363        let Item::Rect(rect) = item else {
2364            continue;
2365        };
2366        let (left, top) = (rect.x.units(), rect.y.units());
2367        let (right, bottom) = (left + rect.width.units(), top + rect.height.units());
2368        let (left, right) = (
2369            across.written_place(left, width.units()),
2370            across.written_place(right, width.units()),
2371        );
2372        let (top, bottom) = (
2373            down.written_place(top, height.units()),
2374            down.written_place(bottom, height.units()),
2375        );
2376        rect.x = Length::from_units(left);
2377        rect.y = Length::from_units(top);
2378        rect.width = Length::from_units(right - left);
2379        rect.height = Length::from_units(bottom - top);
2380    }
2381}
2382
2383/// Draws each rectangle of a stroked group in `items` ([`GroupPlaces::Stroked`]), at any depth,
2384/// as a PDF fills and then strokes it: the rectangle, then the filled outline of its stroke
2385/// ([`stroke_outline`]) in its color.
2386fn stroke_items(items: &mut [Item]) {
2387    for item in items {
2388        let Item::Group(group) = item else {
2389            continue;
2390        };
2391        if let GroupPlaces::Stroked { width } = group.places {
2392            let half = Length::from_units(div_round(width.units(), 2));
2393            group.items = std::mem::take(&mut group.items)
2394                .into_iter()
2395                .flat_map(|item| match item {
2396                    Item::Rect(rect) => {
2397                        let outline = stroke_outline(&rect, half);
2398                        vec![Item::Rect(rect), Item::Path(outline)]
2399                    }
2400                    other => vec![other],
2401                })
2402                .collect();
2403        }
2404        stroke_items(&mut group.items);
2405    }
2406}
2407
2408/// The part of a circle's radius at which a cubic Bézier curve that draws a quarter of the
2409/// circle has its control points, `4/3 tan(Ï€/8)`, in billionths.
2410const QUARTER_ARC_ARM: i64 = 552_284_750;
2411
2412/// The filled outline of the stroke of `rect` with a round join, `half` its width on each side
2413/// of the edges: the outer outline, the rectangle grown by `half` with a quarter circle at each
2414/// corner, and the inner one through the ends of the edges moved `half` inward, which the
2415/// nonzero rule leaves empty inside them. A rectangle no wider or taller than the stroke has the
2416/// outer outline alone. The outlines run as the reader of a PDF expands a filled and stroked
2417/// rectangle's stroke, from the left end of the bottom edge.
2418fn stroke_outline(rect: &Rect, half: Length) -> PathItem {
2419    let (left, top) = (rect.x, rect.y);
2420    let (right, bottom) = (rect.x + rect.width, rect.y + rect.height);
2421    let (outer_left, outer_top) = (left - half, top - half);
2422    let (outer_right, outer_bottom) = (right + half, bottom + half);
2423    let start = Point {
2424        x: left,
2425        y: outer_bottom,
2426    };
2427    // Each side of the outer outline as its end, the corner of the grown box after it and the
2428    // start of the next side, between which a quarter circle turns.
2429    let sides = [
2430        [
2431            (right, outer_bottom),
2432            (outer_right, outer_bottom),
2433            (outer_right, bottom),
2434        ],
2435        [
2436            (outer_right, top),
2437            (outer_right, outer_top),
2438            (right, outer_top),
2439        ],
2440        [
2441            (left, outer_top),
2442            (outer_left, outer_top),
2443            (outer_left, top),
2444        ],
2445        [
2446            (outer_left, bottom),
2447            (outer_left, outer_bottom),
2448            (left, outer_bottom),
2449        ],
2450    ];
2451    let mut commands = vec![PathCommand::MoveTo(start)];
2452    for [(end_x, end_y), (corner_x, corner_y), (next_x, next_y)] in sides {
2453        let end = Point { x: end_x, y: end_y };
2454        commands.push(PathCommand::LineTo(end));
2455        commands.push(quarter_arc(
2456            end,
2457            Point {
2458                x: corner_x,
2459                y: corner_y,
2460            },
2461            Point {
2462                x: next_x,
2463                y: next_y,
2464            },
2465        ));
2466    }
2467    commands.push(PathCommand::Close);
2468    if rect.width > half + half && rect.height > half + half {
2469        let inner = [
2470            (left, bottom - half),
2471            (left + half, bottom),
2472            (left + half, top),
2473            (left, top + half),
2474            (right, top + half),
2475            (right - half, top),
2476            (right - half, bottom),
2477            (right, bottom - half),
2478            (left, bottom - half),
2479        ];
2480        for (index, (x, y)) in inner.into_iter().enumerate() {
2481            let point = Point { x, y };
2482            commands.push(if index == 0 {
2483                PathCommand::MoveTo(point)
2484            } else {
2485                PathCommand::LineTo(point)
2486            });
2487        }
2488        commands.push(PathCommand::Close);
2489    }
2490    PathItem {
2491        commands,
2492        color: rect.color,
2493        fill_rule: FillRule::NonZero,
2494    }
2495}
2496
2497/// The cubic Bézier curve of a quarter circle from `from` to `to`, whose tangents meet at
2498/// `corner`: each control point lies on its end's tangent, `QUARTER_ARC_ARM` of the way to the
2499/// corner.
2500fn quarter_arc(from: Point, corner: Point, to: Point) -> PathCommand {
2501    let arm = |distance: Length| {
2502        Length::from_units(div_round(
2503            distance.units().saturating_mul(QUARTER_ARC_ARM),
2504            1_000_000_000,
2505        ))
2506    };
2507    let toward = |point: Point| Point {
2508        x: point.x + arm(corner.x - point.x),
2509        y: point.y + arm(corner.y - point.y),
2510    };
2511    PathCommand::CubicTo(toward(from), toward(to), to)
2512}
2513
2514/// A single-precision number of the page coordinates as its significand and the power of two
2515/// that divides it, `significand * 2^-shift`, which the writer's printing reads.
2516fn fraction(number: Binary32) -> (i128, u32) {
2517    let (mantissa, exponent) = (i128::from(number.mantissa()), number.exponent());
2518    match u32::try_from(exponent) {
2519        Ok(up) => (mantissa << up, 0),
2520        Err(_) => (mantissa, exponent.unsigned_abs()),
2521    }
2522}
2523
2524/// `a` less `b`, both single-precision numbers, subtracted in single precision, or `None` when
2525/// the difference is not positive.
2526fn single_less(a: Binary32, b: Binary32) -> Option<Binary32> {
2527    let ((a, a_shift), (b, b_shift)) = (fraction(a), fraction(b));
2528    let shift = a_shift.max(b_shift);
2529    let exact = (a << (shift - a_shift)) - (b << (shift - b_shift));
2530    single(exact, 1_i128 << shift)
2531}
2532
2533/// A place `units` from the page's left or top edge as a writer holds it on steps of
2534/// `1/per_inch` inch: the single-precision product of its whole number of steps, the nearest,
2535/// and the step in points as a single-precision number. A place at the edge is zero.
2536fn held(units: i64, per_inch: i64) -> Option<Binary32> {
2537    let inch = i128::from(Length::UNITS_PER_INCH);
2538    let per_inch = i128::from(per_inch);
2539    let steps = div_round_i128(i128::from(units) * per_inch, inch);
2540    if steps == 0 {
2541        return Some(Binary32::ZERO);
2542    }
2543    let (step, shift) = fraction(single(72, per_inch)?);
2544    single(steps * step, 1_i128 << shift)
2545}
2546
2547/// A rectangle's left edge, top edge, width and height as a writer that holds its edges on
2548/// steps of `1/per_inch` inch writes them on a page of `height` ([`held`]): its left edge, its
2549/// bottom edge from the page's foot (the page's height, a single-precision number, less the
2550/// bottom edge), its width (the right edge less the left edge) and its height (the bottom edge
2551/// less the top edge), each subtracted in single precision and printed with `digits`
2552/// ([`Digits`]), a half rounded up. It places the edges where a reader of the PDF puts them,
2553/// the written corner plus the written width and height, each rounded to the nearest half-EMU.
2554/// `None` when a number is not positive.
2555fn held_box(
2556    height: Length,
2557    (x, y, width, tall): (Length, Length, Length, Length),
2558    (digits, per_inch): (Digits, i64),
2559) -> Option<(Length, Length, Length, Length)> {
2560    let point = i128::from(Length::UNITS_PER_POINT);
2561    let written = |number: Binary32| {
2562        let (significand, shift) = fraction(number);
2563        decimal(
2564            significand,
2565            shift,
2566            significant_decimals(significand, shift, digits),
2567        )
2568    };
2569    let edge = |units: i64| held(units, per_inch);
2570    let (left, right) = (edge(x.units())?, edge(x.units() + width.units())?);
2571    let (top, bottom) = (edge(y.units())?, edge(y.units() + tall.units())?);
2572    let foot = written(single_less(
2573        single(i128::from(height.units()), point)?,
2574        bottom,
2575    )?);
2576    let (left, across) = (written(left), written(single_less(right, left)?));
2577    let down = written(single_less(bottom, top)?);
2578    let (left_units, right_units) = (
2579        decimal_units(left)?,
2580        decimal_units(decimal_sum(left, across))?,
2581    );
2582    let bottom_units = height.units() - decimal_units(foot)?;
2583    let top_units = height.units() - decimal_units(decimal_sum(foot, down))?;
2584    Some((
2585        Length::from_units(left_units),
2586        Length::from_units(top_units),
2587        Length::from_units(right_units - left_units),
2588        Length::from_units(bottom_units - top_units),
2589    ))
2590}
2591
2592/// A point of a path or a clip, from the top left corner of a page of `height`, as the writer
2593/// writes it with `digits` ([`Digits`]): its distance from the left edge as a single-precision
2594/// number, and its height as [`written_y`] writes a baseline, each printed with `digits`. The
2595/// writer holds no point on steps, also when it holds a rectangle's edges so: a point between
2596/// two steps stays between them. A point at or below the bottom edge keeps its height.
2597fn written_point(height: Length, point: Point, digits: Digits) -> Point {
2598    let unit = i128::from(Length::UNITS_PER_POINT);
2599    let x = single(i128::from(point.x.units()), unit)
2600        .map(fraction)
2601        .and_then(|(significand, shift)| printed(significand, shift, digits))
2602        .map_or(point.x, Length::from_units);
2603    Point {
2604        x,
2605        y: written_y(height, point.y, digits),
2606    }
2607}
2608
2609/// How a writer prints a number of points: with a count of significant digits, but with at
2610/// least a count of decimals ([`Writer::with_digits`], [`Writer::with_least_decimals`]).
2611type Digits = (u32, u32);
2612
2613/// The baseline `y` from the top of a page of `height` as the writer writes it: its distance
2614/// from the bottom edge in points, which the writer subtracts in single precision (the height
2615/// less the baseline, each a single-precision number, and the difference rounded to one),
2616/// printed with `digits` ([`Digits`]) and a half rounded up. A baseline at or below the bottom
2617/// edge, or one too far for the page sizes that the writer meets, stays.
2618fn written_y(height: Length, y: Length, digits: Digits) -> Length {
2619    let point = i128::from(Length::UNITS_PER_POINT);
2620    // A single-precision number is `significand * 2^-shift`, with a significand of 24 bits,
2621    // rounded to the nearest, a half to the even significand, as the processor rounds it.
2622    let difference = match (
2623        single(i128::from(height.units()), point),
2624        single(i128::from(y.units()), point),
2625    ) {
2626        (Some(top), Some(low)) => single_less(top, low),
2627        _ => single(i128::from(height.units() - y.units()), point),
2628    };
2629    let Some((significand, shift)) = difference.map(fraction) else {
2630        return y;
2631    };
2632    printed(significand, shift, digits)
2633        .map_or(y, |units| Length::from_units(height.units() - units))
2634}
2635
2636/// The baseline `y` from the top of a page of `height` as a writer writes it that holds the
2637/// baseline as its whole count `n` of steps of `1/per_inch` inch, the nearest: the points
2638/// `(n / per_inch) × 72`, each step in single precision, subtracted from the page's height in
2639/// single precision and printed with `digits` ([`Digits`]), a half up. Where the distance from
2640/// the foot lies on a half of its last printed decimal, the single-precision numbers of the
2641/// quotient and the product decide its side: on a page of 792 pt, the baseline 582.925 pt
2642/// (23,317 steps of 1/2880 inch) is written 209.07 pt, where [`written_y`] writes 209.08 pt.
2643/// A baseline between two steps, which only an error of the layout gives, and a baseline at
2644/// the top edge or at or below the bottom edge are written as [`written_y`] writes them: a
2645/// nearest count would move a baseline between two steps by up to half a step.
2646fn counted_y(height: Length, y: Length, digits: Digits, per_inch: i64) -> Length {
2647    let point = i128::from(Length::UNITS_PER_POINT);
2648    let inch = i128::from(Length::UNITS_PER_INCH);
2649    let per_inch = i128::from(per_inch);
2650    let scaled = i128::from(y.units()) * per_inch;
2651    if scaled % inch != 0 {
2652        return written_y(height, y, digits);
2653    }
2654    let count = scaled / inch;
2655    let points = single(count, per_inch)
2656        .map(fraction)
2657        .and_then(|(significand, shift)| single(significand * 72, 1_i128 << shift));
2658    let difference = single(i128::from(height.units()), point)
2659        .zip(points)
2660        .and_then(|(top, low)| single_less(top, low));
2661    let Some((significand, shift)) = difference.map(fraction) else {
2662        return written_y(height, y, digits);
2663    };
2664    printed(significand, shift, digits)
2665        .map_or(y, |units| Length::from_units(height.units() - units))
2666}
2667
2668/// A rectangle's left edge, top edge, width and height as the writer writes them on a page of
2669/// `height`: its left edge and width, held as single-precision numbers, and its height, and
2670/// its bottom edge as [`written_y`] writes a baseline, each printed with `digits`
2671/// ([`Digits`]), a half rounded up.
2672fn written_box(
2673    height: Length,
2674    (x, y, width, tall): (Length, Length, Length, Length),
2675    digits: Digits,
2676) -> (Length, Length, Length, Length) {
2677    let point = i128::from(Length::UNITS_PER_POINT);
2678    let written = |length: Length| {
2679        single(i128::from(length.units()), point)
2680            .map(fraction)
2681            .and_then(|(significand, shift)| printed(significand, shift, digits))
2682            .map_or(length, Length::from_units)
2683    };
2684    let written_tall = written(tall);
2685    let bottom = written_y(height, Length::from_units(y.units() + tall.units()), digits);
2686    (
2687        written(x),
2688        Length::from_units(bottom.units() - written_tall.units()),
2689        written(width),
2690        written_tall,
2691    )
2692}
2693
2694/// The single-precision number `significand * 2^-shift` points printed with `digits`
2695/// significant digits, but with at least `least` decimals, a half up on its exact value, in
2696/// half-EMUs. A number below one point gets the decimals of a number of one digit before the
2697/// point.
2698fn printed(significand: i128, shift: u32, (digits, least): Digits) -> Option<i64> {
2699    let whole = (significand >> shift).max(1);
2700    let decimals = digits.saturating_sub(whole.ilog10() + 1).max(least);
2701    decimal_units(decimal(significand, shift, decimals))
2702}
2703
2704/// The decimals with which a writer prints the single-precision number `significand *
2705/// 2^-shift` points with `digits` significant digits, counted from its first digit that is
2706/// not zero, also below one point: 0.47998 has five. A number of one point or more gets at
2707/// least `least` decimals.
2708fn significant_decimals(significand: i128, shift: u32, (digits, least): Digits) -> u32 {
2709    let whole = significand >> shift;
2710    if whole > 0 {
2711        return digits.saturating_sub(whole.ilog10() + 1).max(least);
2712    }
2713    let mut decimals = digits;
2714    let mut scaled = significand * 10;
2715    while significand > 0 && scaled < 1 << shift {
2716        decimals += 1;
2717        scaled *= 10;
2718    }
2719    decimals
2720}
2721
2722/// A number as a writer prints it: a whole number of `scale`ths of a point, and `scale`.
2723type Decimal = (i128, i128);
2724
2725/// The single-precision number `significand * 2^-shift` points printed with `decimals`
2726/// decimals, a half up on its exact value.
2727fn decimal(significand: i128, shift: u32, decimals: u32) -> Decimal {
2728    let scale = i128::from(f_office_units::scale::TENTHS).pow(decimals);
2729    (
2730        (significand * scale * 2 + (1 << shift)) >> (shift + 1),
2731        scale,
2732    )
2733}
2734
2735/// The sum of two printed numbers, exact.
2736fn decimal_sum((a, a_scale): Decimal, (b, b_scale): Decimal) -> Decimal {
2737    let scale = a_scale.max(b_scale);
2738    (a * (scale / a_scale) + b * (scale / b_scale), scale)
2739}
2740
2741/// A printed number of points in half-EMUs, the nearest, a half up.
2742fn decimal_units((value, scale): Decimal) -> Option<i64> {
2743    let point = i128::from(Length::UNITS_PER_POINT);
2744    i64::try_from(div_round_i128(value * point, scale)).ok()
2745}
2746
2747/// The single-precision number nearest to `numerator / denominator`, both positive, or `None`
2748/// outside the range that the page coordinates use, from 2^-41 up to 2^24. Writers that hold a
2749/// number in single precision compute with it, without float arithmetic.
2750#[must_use]
2751pub fn single(numerator: i128, denominator: i128) -> Option<Binary32> {
2752    if numerator <= 0 || denominator <= 0 {
2753        return None;
2754    }
2755    // The power of two below the quotient, so that the significand gets its 24 bits.
2756    let mut exponent =
2757        i32::try_from(numerator.ilog2()).ok()? - i32::try_from(denominator.ilog2()).ok()?;
2758    let below = if exponent >= 0 {
2759        numerator < denominator << exponent
2760    } else {
2761        numerator << -exponent < denominator
2762    };
2763    if below {
2764        exponent -= 1;
2765    }
2766    let shift = u32::try_from(i32::try_from(Binary32::BITS).ok()? - 1 - exponent).ok()?;
2767    if shift > u32::BITS * 2 {
2768        return None;
2769    }
2770    Some(Binary32::nearest(numerator, denominator))
2771}
2772
2773/// How a writer moves the points of one page down: each `y` times `taller / height`, and a
2774/// glyph's baseline by that distance in whole `glyph_step`s when it has a step, counted
2775/// with the page's stretch factor and offset ([`Writer::with_stretch_factors`]).
2776struct Stretch {
2777    taller: i64,
2778    height: i64,
2779    glyph_step: Option<Length>,
2780    factor: Fraction,
2781    offset: Fraction,
2782}
2783
2784impl Stretch {
2785    /// A glyph's baseline `y` plus the distance that the stretch moves it in whole glyph steps:
2786    /// the exact distance in steps times the factor, plus the offset, rounded to the nearest
2787    /// whole step, a half step up; the exact stretch without a step.
2788    fn glyph_y(&self, y: Length) -> Length {
2789        let Some(glyph_step) = self.glyph_step else {
2790            return self.y(y);
2791        };
2792        let distance = i128::from(y.units()) * i128::from(self.taller - self.height);
2793        let per_step = i128::from(self.height) * i128::from(glyph_step.units());
2794        let (factor, of) = (i128::from(self.factor.0), i128::from(self.factor.1));
2795        let (offset, by) = (i128::from(self.offset.0), i128::from(self.offset.1));
2796        // round(distance / per_step × factor / of + offset / by), with a half up: the floor of
2797        // (2 distance factor by + 2 offset of per_step + of by per_step) / (2 of by per_step).
2798        let whole = of * by * per_step;
2799        let steps = div_round_i128(distance * factor * by + offset * of * per_step, whole);
2800        let moved = i64::try_from(steps * i128::from(glyph_step.units())).unwrap_or(i64::MAX);
2801        Length::from_units(y.units().saturating_add(moved))
2802    }
2803
2804    /// `y` times `taller / height`, to the nearest unit.
2805    fn y(&self, y: Length) -> Length {
2806        let product = i128::from(y.units()) * i128::from(self.taller);
2807        let height = i128::from(self.height);
2808        let rounded = div_round_i128(product, height);
2809        Length::from_units(i64::try_from(rounded).unwrap_or(i64::MAX))
2810    }
2811
2812    /// The new top and height of a filled rectangle, whose top and bottom edges move as a
2813    /// glyph's baseline does ([`Self::glyph_y`]).
2814    fn stepped_span(&self, (top, height): (Length, Length)) -> (Length, Length) {
2815        let new_top = self.glyph_y(top);
2816        let bottom = self.glyph_y(Length::from_units(top.units() + height.units()));
2817        (
2818            new_top,
2819            Length::from_units(bottom.units() - new_top.units()),
2820        )
2821    }
2822
2823    fn point(&self, point: &mut Point) {
2824        point.y = self.y(point.y);
2825    }
2826
2827    /// Moves the points of an item down; glyphs keep their size.
2828    fn item(&self, item: &mut Item) {
2829        match item {
2830            Item::Glyphs(run) => {
2831                for glyph in &mut run.glyphs {
2832                    glyph.y = self.glyph_y(glyph.y);
2833                }
2834            }
2835            Item::Rect(rect) => (rect.y, rect.height) = self.stepped_span((rect.y, rect.height)),
2836            Item::Path(path) => {
2837                for point in path.commands.iter_mut().flat_map(PathCommand::points_mut) {
2838                    self.point(point);
2839                }
2840            }
2841            Item::Gradient(gradient) => {
2842                let axis = [&mut gradient.start, &mut gradient.end];
2843                let outline = gradient
2844                    .commands
2845                    .iter_mut()
2846                    .flat_map(PathCommand::points_mut);
2847                for point in outline.chain(axis) {
2848                    self.point(point);
2849                }
2850            }
2851            // The writer draws a picture, with its clip, at its layout place and size; the
2852            // page's items under a clip stretch as the page's, with the clip.
2853            Item::Group(group) => {
2854                if group.places != GroupPlaces::Own {
2855                    let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
2856                    for point in clip.flat_map(PathCommand::points_mut) {
2857                        self.point(point);
2858                    }
2859                }
2860                for item in group.placed_items() {
2861                    self.item(item);
2862                }
2863            }
2864            Item::Image(_) => {}
2865        }
2866    }
2867}
2868
2869#[cfg(test)]
2870mod tests {
2871    use std::sync::Arc;
2872
2873    use f_office_units::Length;
2874
2875    use super::{
2876        DEFAULT_LINEAR_LIMIT, DisplayList, Glyph, GlyphRun, Image, ImageFormat, JpegQuality,
2877        LinearLimit, Offset, OffsetProduct, Orientation, Page, PaletteClass, PaletteDensity,
2878        PictureDensity, Resampler, Rgb, Writer, WriterOffset,
2879    };
2880
2881    #[test]
2882    fn takes_the_linear_interpolation_up_to_a_count_or_up_to_a_side() {
2883        let count = |n| std::num::NonZeroU32::new(n).unwrap();
2884        let (pixels, side) = (
2885            LinearLimit::Pixels(count(1 << 17)),
2886            LinearLimit::Side(count(419)),
2887        );
2888        let cases = [
2889            (pixels, (400, 327), true),
2890            (pixels, (400, 328), false),
2891            (pixels, (480, 270), true),
2892            (side, (419, 419), true),
2893            (side, (420, 100), false),
2894            (side, (100, 420), false),
2895            (side, (480, 270), false),
2896        ];
2897        for (limit, size, linear) in cases {
2898            assert_eq!(limit.takes_linear(size), linear, "{limit:?} {size:?}");
2899        }
2900        assert_eq!(DEFAULT_LINEAR_LIMIT, pixels);
2901    }
2902
2903    #[test]
2904    fn answers_with_the_filter_of_its_own_limit() {
2905        let side = LinearLimit::Side(std::num::NonZeroU32::new(419).unwrap());
2906        let density = PictureDensity {
2907            limit_ppi: std::num::NonZeroU32::new(275).unwrap(),
2908            ppi: std::num::NonZeroU32::new(200).unwrap(),
2909        };
2910        let writer = Writer::new(Length::from_units(10))
2911            .unwrap()
2912            .with_picture_density(Some(density))
2913            .with_linear_limit(side);
2914        let inch = Length::from_units(Length::UNITS_PER_INCH);
2915        let answer = writer.resampled_size((600, 600), (inch, inch), None);
2916        assert_eq!(answer, Some(((199, 199), Resampler::Filter(side))));
2917    }
2918
2919    #[test]
2920    fn a_filled_path_draws_quadratic_curves_as_cubic_curves_of_whole_units() {
2921        use super::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
2922        let at = |x, y| super::Point {
2923            x: Length::from_units(x),
2924            y: Length::from_units(y),
2925        };
2926        let commands = [
2927            MoveTo(at(0, 0)),
2928            QuadTo(at(30, 10), at(31, 0)),
2929            Close,
2930            QuadTo(at(3, 3), at(6, 0)),
2931            LineTo(at(9, 9)),
2932        ];
2933        // Two thirds of 30 and 10 are 20 and 6.67; of -1 and 10, -0.67 and 6.67. After the
2934        // close, the curve starts at the start of the outline.
2935        let expected = vec![
2936            MoveTo(at(0, 0)),
2937            CubicTo(at(20, 7), at(30, 7), at(31, 0)),
2938            Close,
2939            CubicTo(at(2, 2), at(4, 2), at(6, 0)),
2940            LineTo(at(9, 9)),
2941        ];
2942        assert_eq!(super::fill_commands(&commands), expected);
2943        assert_eq!(
2944            super::fill_commands(&[QuadTo(at(3, 3), at(6, 0))]),
2945            vec![CubicTo(at(3, 3), at(4, 2), at(6, 0))]
2946        );
2947    }
2948
2949    #[test]
2950    fn a_filled_path_leaves_out_lines_to_their_own_start() {
2951        use super::PathCommand::{Close, LineTo, MoveTo};
2952        let at = |x, y| super::Point {
2953            x: Length::from_units(x),
2954            y: Length::from_units(y),
2955        };
2956        let commands = [
2957            MoveTo(at(5, 5)),
2958            LineTo(at(5, 5)),
2959            LineTo(at(9, 5)),
2960            LineTo(at(9, 5)),
2961            LineTo(at(9, 9)),
2962            Close,
2963            LineTo(at(5, 5)),
2964            LineTo(at(7, 7)),
2965        ];
2966        // After the close, the outline starts again at its first point.
2967        let expected = vec![
2968            MoveTo(at(5, 5)),
2969            LineTo(at(9, 5)),
2970            LineTo(at(9, 9)),
2971            Close,
2972            LineTo(at(7, 7)),
2973        ];
2974        assert_eq!(super::fill_commands(&commands), expected);
2975    }
2976
2977    #[test]
2978    fn a_fill_at_most_the_thinnest_fill_across_paints_nothing() {
2979        use super::PathCommand::{Close, CubicTo, LineTo, MoveTo};
2980        let at = |x, y| super::Point {
2981            x: Length::from_units(x),
2982            y: Length::from_units(y),
2983        };
2984        let bar = |across| {
2985            [
2986                MoveTo(at(0, 0)),
2987                LineTo(at(across, 0)),
2988                LineTo(at(across, 5000)),
2989                LineTo(at(0, 5000)),
2990                Close,
2991            ]
2992        };
2993        assert!(!super::path_shows(&bar(100)));
2994        assert!(super::path_shows(&bar(101)));
2995        assert!(!super::fill_shows(
2996            Length::from_units(5000),
2997            Length::from_units(-100)
2998        ));
2999        assert!(super::fill_shows(
3000            Length::from_units(5000),
3001            Length::from_units(-101)
3002        ));
3003        // The control points of a curve widen the box, as a reader of a PDF measures it.
3004        let bowed = [
3005            MoveTo(at(0, 0)),
3006            CubicTo(at(150, 1000), at(150, 4000), at(0, 5000)),
3007            Close,
3008        ];
3009        assert!(super::path_shows(&bowed));
3010        assert!(!super::path_shows(&[]));
3011    }
3012
3013    /// Places `item` where `writer`, which has digits, writes it with its digits and least
3014    /// decimals on a page of `height`.
3015    fn write_digits(writer: &Writer, height: Length, item: &mut super::Item) {
3016        let digits = (writer.digits().unwrap().get(), writer.least_decimals());
3017        writer.write_digits(height, digits, item);
3018    }
3019
3020    #[test]
3021    fn gives_the_text_of_a_glyph_only_on_whole_characters() {
3022        let run = GlyphRun {
3023            font: f_office_fonts::FontId::from_index(0),
3024            size: Length::ZERO,
3025            color: Rgb::BLACK,
3026            text: "a\u{e9}".to_owned(),
3027            glyphs: Vec::new(),
3028            outline: None,
3029            filled: true,
3030            effect: false,
3031            turn: None,
3032        };
3033        let glyph = |text_start, text_end| Glyph {
3034            id: 0,
3035            x: Length::ZERO,
3036            y: Length::ZERO,
3037            text_start,
3038            text_end,
3039        };
3040        assert_eq!(run.glyph_text(&glyph(0, 1)), Some("a"));
3041        assert_eq!(run.glyph_range(&glyph(1, 3)), Some(1..3));
3042        assert_eq!(run.glyph_text(&glyph(1, 3)), Some("\u{e9}"));
3043        assert_eq!(run.glyph_text(&glyph(1, 1)), Some(""));
3044        // Inside the two bytes of the second character, backwards, and beyond the text.
3045        for (start, end) in [(1, 2), (2, 3), (1, 0), (0, 4)] {
3046            assert_eq!(run.glyph_range(&glyph(start, end)), None, "{start}..{end}");
3047            assert_eq!(run.glyph_text(&glyph(start, end)), None, "{start}..{end}");
3048        }
3049    }
3050
3051    /// `count` as a count that is not zero.
3052    fn non_zero(count: u32) -> std::num::NonZeroU32 {
3053        std::num::NonZeroU32::new(count).unwrap()
3054    }
3055
3056    /// The picture density with the limit `limit_ppi` and `ppi` pixels per inch.
3057    fn density(limit_ppi: u32, ppi: u32) -> PictureDensity {
3058        PictureDensity {
3059            limit_ppi: non_zero(limit_ppi),
3060            ppi: non_zero(ppi),
3061        }
3062    }
3063
3064    #[test]
3065    fn reads_six_hexadecimal_digits_only() {
3066        let rgb = |r, g, b| Some(Rgb { r, g, b });
3067        assert_eq!(Rgb::from_hex("FF0080"), rgb(255, 0, 128));
3068        assert_eq!(Rgb::from_hex("1f3864"), rgb(31, 56, 100));
3069        for wrong in [
3070            "+FFFFF", "+F+F+F", "-FFFFF", "FFFFF", "FFFFFFF", "GGGGGG", " FFFFF", "auto",
3071        ] {
3072            assert_eq!(Rgb::from_hex(wrong), None, "{wrong}");
3073        }
3074    }
3075
3076    /// A glyph run, a rectangle, a path of each command and a clipped image, each with the
3077    /// places `(1, 2)`, `(3, 4)`, ... and the lengths 10, 20, ..., in a group: the places are
3078    /// `at(n)` and the lengths `by(n)`.
3079    fn every_kind(at: impl Fn(i64) -> super::Point, by: impl Fn(i64) -> Length) -> super::Item {
3080        use super::{
3081            Clip, FillRule, Glyph, GlyphRun, Group, GroupClip, GroupPlaces, ImageItem, Item, Join,
3082            Outline, PathCommand, PathItem, Rect,
3083        };
3084        let glyph = |n: i64| Glyph {
3085            id: 1,
3086            x: at(n).x,
3087            y: at(n).y,
3088            text_start: 0,
3089            text_end: 1,
3090        };
3091        let run = GlyphRun {
3092            font: f_office_fonts::FontId::from_index(0),
3093            size: by(1),
3094            color: Rgb::BLACK,
3095            text: "a".to_owned(),
3096            glyphs: vec![glyph(1), glyph(2)],
3097            outline: Some(Outline {
3098                width: by(2),
3099                color: Rgb::BLACK,
3100                join: Join::Round,
3101            }),
3102            filled: true,
3103            effect: false,
3104            turn: None,
3105        };
3106        let rect = Rect {
3107            x: at(3).x,
3108            y: at(3).y,
3109            width: by(3),
3110            height: by(4),
3111            color: Rgb::BLACK,
3112        };
3113        let path = PathItem {
3114            commands: vec![
3115                PathCommand::MoveTo(at(4)),
3116                PathCommand::LineTo(at(5)),
3117                PathCommand::QuadTo(at(6), at(7)),
3118                PathCommand::CubicTo(at(8), at(9), at(10)),
3119                PathCommand::Close,
3120            ],
3121            color: Rgb::BLACK,
3122            fill_rule: FillRule::NonZero,
3123        };
3124        let image = ImageItem {
3125            x: at(11).x,
3126            y: at(11).y,
3127            width: by(5),
3128            height: by(6),
3129            clip: Some(Clip {
3130                x: at(12).x,
3131                y: at(12).y,
3132                width: by(7),
3133                height: by(8),
3134            }),
3135            turn: None,
3136            image: Image::new(vec![0]),
3137        };
3138        Item::Group(Group::new(vec![
3139            Item::Glyphs(run),
3140            Item::Group(Group {
3141                items: vec![Item::Rect(rect), Item::Path(path)],
3142                clip: Some(GroupClip {
3143                    commands: vec![
3144                        PathCommand::MoveTo(at(13)),
3145                        PathCommand::LineTo(at(14)),
3146                        PathCommand::QuadTo(at(15), at(16)),
3147                        PathCommand::Close,
3148                    ],
3149                    fill_rule: FillRule::EvenOdd,
3150                }),
3151                places: GroupPlaces::Own,
3152            }),
3153            Item::Image(image),
3154        ]))
3155    }
3156
3157    #[test]
3158    fn maps_every_place_and_length_of_an_item_and_of_the_items_of_its_groups() {
3159        use super::Point;
3160        let u = Length::from_units;
3161        let at = |n: i64| Point {
3162            x: u(2 * n - 1),
3163            y: u(2 * n),
3164        };
3165        let mut item = every_kind(at, |n| u(10 * n));
3166        // Each place moves one unit right and doubles down; each length triples.
3167        item.map_places(
3168            |p| Point {
3169                x: p.x + u(1),
3170                y: p.y * 2,
3171            },
3172            |v| v * 3,
3173        );
3174        let mapped = |n: i64| Point {
3175            x: u(2 * n),
3176            y: u(4 * n),
3177        };
3178        assert_eq!(item, every_kind(mapped, |n| u(30 * n)));
3179    }
3180
3181    #[test]
3182    fn gives_the_pages_and_the_parts_that_it_was_built_from() {
3183        use super::Point;
3184        let u = Length::from_units;
3185        let at = |n: i64| Point { x: u(n), y: u(n) };
3186        let items = vec![every_kind(at, u), every_kind(at, |n| u(2 * n))];
3187        let landscape = Orientation::Landscape;
3188        let page = Page::new(u(300), u(400), landscape, items.clone());
3189        assert_eq!((page.width(), page.height()), (u(300), u(400)));
3190        assert_eq!(page.orientation(), landscape);
3191        assert_eq!(page.items(), items.as_slice());
3192        let empty = Page::new(u(5), u(6), Orientation::Portrait, Vec::new());
3193        let list = DisplayList::new(vec![page.clone(), empty.clone()]);
3194        assert_eq!(list.pages(), [page.clone(), empty.clone()].as_slice());
3195        assert_eq!(list.into_pages(), vec![page.clone(), empty]);
3196        let fewer = page.map_items(|mut kept| {
3197            kept.truncate(1);
3198            kept
3199        });
3200        assert_eq!(
3201            fewer,
3202            Page::new(u(300), u(400), landscape, items[..1].to_vec())
3203        );
3204    }
3205
3206    #[test]
3207    fn writes_the_page_size_in_whole_steps() {
3208        assert_eq!(Writer::new(Length::ZERO), None);
3209        let step = Length::from_units(Length::UNITS_PER_DOT);
3210        let writer = Writer::new(step).unwrap();
3211        // An A4 page, 15,120,000 units wide, is 2,480.3 dots; half a dot rounds up.
3212        let page = |width, height| Page {
3213            width: Length::from_units(width),
3214            height: Length::from_units(height),
3215            orientation: Orientation::Portrait,
3216            items: Vec::new(),
3217        };
3218        let mut list = DisplayList {
3219            pages: vec![page(15_120_000, 3048 + 6096 * 3)],
3220        };
3221        writer.finish(&mut list);
3222        assert_eq!(list.pages[0].width.units(), 2480 * 6096);
3223        assert_eq!(list.pages[0].height.units(), 4 * 6096);
3224    }
3225
3226    #[test]
3227    fn keeps_the_picture_files_unless_it_has_a_jpeg_quality() {
3228        let writer = Writer::new(Length::from_units(10)).unwrap();
3229        assert_eq!(writer.jpeg_quality(), None);
3230        let quality = JpegQuality::new(75);
3231        assert_eq!(writer.with_jpeg_quality(quality).jpeg_quality(), quality);
3232        assert_eq!(writer.with_jpeg_quality(None), writer);
3233    }
3234
3235    #[test]
3236    fn keeps_an_opacity_between_none_and_a_whole() {
3237        use super::Opacity;
3238        assert_eq!(Opacity::clamped(-5).share(), 0);
3239        assert_eq!(Opacity::clamped(150_000), Opacity::FULL);
3240        assert_eq!(Opacity::FULL.share(), 100_000);
3241        // 50% of 50.001% is 25.0005%, which rounds a half up.
3242        let half = Opacity::clamped(50_000);
3243        assert_eq!(half.times(Opacity::clamped(50_001)).share(), 25_001);
3244        assert_eq!(Opacity::FULL.times(half), half);
3245    }
3246
3247    #[test]
3248    fn takes_a_jpeg_quality_of_1_to_100_only() {
3249        assert_eq!(JpegQuality::new(1).map(JpegQuality::get), Some(1));
3250        assert_eq!(JpegQuality::new(100).map(JpegQuality::get), Some(100));
3251        assert_eq!(JpegQuality::new(0), None);
3252        assert_eq!(JpegQuality::new(101), None);
3253        assert_eq!(JpegQuality::new(255), None);
3254    }
3255
3256    #[test]
3257    fn resamples_pictures_denser_than_the_limit_below_its_density() {
3258        let inches =
3259            |hundredths: i64| Length::from_units(Length::UNITS_PER_INCH * hundredths / 100);
3260        let size = (
3261            inches(150),
3262            Length::from_units(Length::UNITS_PER_POINT * 81),
3263        );
3264        let writer = Writer::new(Length::from_units(10)).unwrap();
3265        assert_eq!(writer.resampled_size((600, 450), size, None), None);
3266        let writer = writer.with_picture_density(Some(density(275, 200)));
3267        let filter = |pixels| Some((pixels, Resampler::Filter(DEFAULT_LINEAR_LIMIT)));
3268        // 275 ppi stays, 276 ppi becomes 299 by 224 pixels for 1.5 by 1.125 inches.
3269        assert_eq!(writer.resampled_size((412, 309), size, None), None);
3270        assert_eq!(
3271            writer.resampled_size((414, 311), size, None),
3272            filter((299, 224))
3273        );
3274        assert_eq!(
3275            writer.resampled_size((600, 450), size, None),
3276            filter((299, 224))
3277        );
3278        // 1.25 by 0.9375 inches: 249 by 187 pixels, the most below 200 ppi.
3279        let size = (
3280            inches(125),
3281            Length::from_units(Length::UNITS_PER_POINT * 135 / 2),
3282        );
3283        assert_eq!(
3284            writer.resampled_size((500, 375), size, None),
3285            filter((249, 187))
3286        );
3287        // Never more pixels than the picture has.
3288        assert_eq!(
3289            writer.resampled_size((600, 100), size, None),
3290            filter((249, 100))
3291        );
3292        assert_eq!(
3293            writer.resampled_size((600, 450), (Length::from_units(0), size.1), None),
3294            None
3295        );
3296    }
3297
3298    #[test]
3299    fn resamples_a_palette_of_a_class_by_the_limits_of_its_class() {
3300        // One inch across and 0.3 inch down; the pixels give each class's density on both.
3301        let size = (
3302            Length::from_units(Length::UNITS_PER_INCH),
3303            Length::from_units(Length::UNITS_PER_INCH * 3 / 10),
3304        );
3305        let palettes = PaletteDensity {
3306            one_bit_limit_ppi: non_zero(750),
3307            one_bit_ppi: non_zero(600),
3308            four_bits_limit_ppi: non_zero(562),
3309            eight_bits_limit_ppi: non_zero(395),
3310        };
3311        let writer = Writer::new(Length::from_units(10))
3312            .unwrap()
3313            .with_picture_density(Some(density(275, 200)));
3314        let (centre, filter) = (
3315            Resampler::CentrePixel,
3316            Resampler::Filter(DEFAULT_LINEAR_LIMIT),
3317        );
3318        let classes = [
3319            (
3320                Some(PaletteClass::OneBit),
3321                749_usize,
3322                750_usize,
3323                (599, 179),
3324                centre,
3325            ),
3326            (
3327                Some(PaletteClass::FourBitColor),
3328                561,
3329                562,
3330                (199, 59),
3331                filter,
3332            ),
3333            (
3334                Some(PaletteClass::EightBitColor),
3335                394,
3336                395,
3337                (199, 59),
3338                filter,
3339            ),
3340            (None, 274, 275, (199, 59), filter),
3341        ];
3342        let with = writer.with_palette_density(Some(palettes));
3343        for (class, kept, dense, new, resampler) in classes {
3344            // The pixels down at a density below `kept` and at `dense` or above.
3345            let (kept, dense) = ((kept, kept * 3 / 10), (dense, (dense * 3).div_ceil(10)));
3346            assert_eq!(with.resampled_size(kept, size, class), None);
3347            let written = with.resampled_size(dense, size, class);
3348            assert_eq!(written, Some((new, resampler)));
3349            // Without a palette density, every class takes the picture density.
3350            let general = writer.resampled_size(dense, size, class);
3351            assert_eq!(general, Some(((199, 59), filter)));
3352        }
3353        // Without a picture density, the palette density resamples nothing.
3354        let none = Writer::new(Length::from_units(10))
3355            .unwrap()
3356            .with_palette_density(Some(palettes));
3357        let one_bit = Some(PaletteClass::OneBit);
3358        assert_eq!(none.resampled_size((900, 270), size, one_bit), None);
3359    }
3360
3361    /// The written sizes of a half-inch square of each of `pixels` with the density
3362    /// `limit_ppi` and `ppi`.
3363    fn half_inch_sizes(
3364        limit_ppi: u32,
3365        ppi: u32,
3366        pixels: &[(usize, usize)],
3367    ) -> Vec<Option<(usize, usize)>> {
3368        let half = Length::from_units(Length::UNITS_PER_POINT * 36);
3369        let writer = Writer::new(Length::from_units(10))
3370            .unwrap()
3371            .with_picture_density(Some(density(limit_ppi, ppi)));
3372        pixels
3373            .iter()
3374            .map(|&pixels| writer.resampled_size(pixels, (half, half), None))
3375            .map(|written| written.map(|(pixels, _)| pixels))
3376            .collect()
3377    }
3378
3379    #[test]
3380    fn resamples_only_the_directions_denser_than_a_limit_of_275_ppi() {
3381        // Half-inch squares: a writer with this limit writes
3382        // 290 by 260 ppi as 99 by 130 pixels and 290 by 276 ppi as 99 by 99.
3383        assert_eq!(
3384            half_inch_sizes(275, 200, &[(145, 130), (130, 145), (145, 138), (145, 137)]),
3385            [
3386                Some((99, 130)),
3387                Some((130, 99)),
3388                Some((99, 99)),
3389                Some((99, 137))
3390            ]
3391        );
3392    }
3393
3394    #[test]
3395    fn resamples_only_the_directions_at_a_limit_of_450_ppi_or_denser() {
3396        // The writer with this limit and 300 ppi keeps 446 ppi and writes 450 by 350 ppi as
3397        // 149 by 175 pixels.
3398        assert_eq!(
3399            half_inch_sizes(
3400                450,
3401                300,
3402                &[(223, 223), (225, 225), (225, 175), (200, 225), (225, 150)]
3403            ),
3404            [
3405                None,
3406                Some((149, 149)),
3407                Some((149, 175)),
3408                Some((200, 149)),
3409                Some((149, 150))
3410            ]
3411        );
3412    }
3413
3414    /// The written pixels across of `pixels` drawn across `units`, and 30 pixels down 0.15
3415    /// inch, with the density `limit_ppi` and `ppi`, or the pixels when the writer keeps them.
3416    fn across(limit_ppi: u32, ppi: u32, pixels: usize, units: i64) -> usize {
3417        let writer = Writer::new(Length::from_units(10))
3418            .unwrap()
3419            .with_picture_density(Some(density(limit_ppi, ppi)));
3420        let size = (
3421            Length::from_units(units),
3422            Length::from_emus(137_160).unwrap(),
3423        );
3424        writer
3425            .resampled_size((pixels, 30), size, None)
3426            .map_or(pixels, |(written, _)| written.0)
3427    }
3428
3429    #[test]
3430    fn tests_and_resamples_the_drawn_size_itself() {
3431        // Each case: limit and density in ppi, pixels across, drawn size in length units
3432        // (1,270 to a twip), written pixels.
3433        let cases = [
3434            // 225 pixels drawn on 720 twips are
3435            // 450 ppi and get 149 pixels at 300 ppi and 99 at 200 ppi; on 721 twips they stay
3436            // at 450 ppi and get 100 at 200 ppi.
3437            (450, 300, 225, 914_400, 149),
3438            (450, 300, 225, 915_670, 225),
3439            (275, 200, 225, 914_400, 99),
3440            (275, 200, 225, 915_670, 100),
3441            // A direction exactly at the limit is resampled, and one unit more keeps it: 275
3442            // pixels on an inch.
3443            (275, 200, 275, 1_828_800, 199),
3444            (275, 200, 275, 1_828_801, 275),
3445            // 211 pixels step up from 93 to 94 pixels past 573,024 units
3446            // at 300 ppi, and from 101 to 102 past 932,688 units at 200 ppi, before the next
3447            // whole twip; they are at 450 ppi on 857,504 units, and below it past them.
3448            (450, 300, 211, 573_024, 93),
3449            (450, 300, 211, 573_025, 94),
3450            (275, 200, 211, 932_688, 101),
3451            (275, 200, 211, 932_689, 102),
3452            (450, 300, 211, 857_504, 140),
3453            (450, 300, 211, 857_505, 211),
3454        ];
3455        for (limit, ppi, pixels, units, written) in cases {
3456            assert_eq!(
3457                across(limit, ppi, pixels, units),
3458                written,
3459                "{pixels} on {units}"
3460            );
3461        }
3462    }
3463
3464    #[test]
3465    fn stretches_glyphs_and_rectangles_down_by_the_steps_of_the_page() {
3466        use super::Item;
3467        let page = stretched();
3468        let Item::Glyphs(run) = &page.items[0] else {
3469            panic!("no glyphs")
3470        };
3471        assert_eq!(
3472            (run.glyphs[0].x.units(), run.glyphs[0].y.units()),
3473            (500, 402)
3474        );
3475        assert_eq!(run.size.units(), 120);
3476        let Item::Rect(rect) = &page.items[1] else {
3477            panic!("no rect")
3478        };
3479        let units = [rect.x, rect.y, rect.width, rect.height].map(Length::units);
3480        assert_eq!(units, [100, 201, 300, 402]);
3481        // The page keeps its size.
3482        assert_eq!((page.width.units(), page.height.units()), (1000, 2000));
3483    }
3484
3485    #[test]
3486    fn stretches_paths_down_and_leaves_pictures_and_everything_without_a_stretch() {
3487        use super::{Item, PathCommand, Point};
3488        let page = stretched();
3489        let Item::Path(path) = &page.items[2] else {
3490            panic!("no path")
3491        };
3492        let corner = Point {
3493            x: Length::from_units(1000),
3494            y: Length::from_units(2010),
3495        };
3496        assert_eq!(path.commands[0], PathCommand::MoveTo(corner));
3497        // A picture and its clip keep their layout place and size.
3498        assert_eq!(page.items[3], sample_page().items[3]);
3499        let mut plain = DisplayList {
3500            pages: vec![sample_page()],
3501        };
3502        Writer::new(Length::from_units(10))
3503            .unwrap()
3504            .finish(&mut plain);
3505        assert_eq!(plain.pages[0], sample_page());
3506    }
3507
3508    #[test]
3509    fn holds_a_quotient_as_the_nearest_single_precision_number() {
3510        use super::{fraction, single};
3511        // Significands and powers of two as single-precision numbers hold the quotients:
3512        // 744.975 is 744.9749755859375, 434.125 is exact, 1/3 and 2/3 round up, and half of
3513        // 2^24 + 1 is a tie that goes to the even significand.
3514        let cases = [
3515            ((744_975, 1000), Some((12_205_670, 14))),
3516            ((434_125, 1000), Some((14_225_408, 15))),
3517            ((1, 3), Some((11_184_811, 25))),
3518            ((2, 3), Some((11_184_811, 24))),
3519            ((123_456_789, 25_400), Some((9_954_311, 11))),
3520            ((16_777_217, 2), Some((8_388_608, 0))),
3521            ((16_777_217, 1), None),
3522            ((0, 1), None),
3523            // 2^24 - 1/2 rounds up to 2^24 and stays in the range.
3524            (((1 << 25) - 1, 2), Some((1 << 24, 0))),
3525        ];
3526        for ((numerator, denominator), expected) in cases {
3527            assert_eq!(
3528                single(numerator, denominator).map(fraction),
3529                expected,
3530                "{numerator}/{denominator}"
3531            );
3532        }
3533    }
3534
3535    #[test]
3536    fn writes_a_baseline_from_the_bottom_with_significant_digits() {
3537        use super::written_y;
3538        // Baselines on a page of 792 pt, written with five digits: the
3539        // distance 434.125 pt is a half and rounds up to 434.13 pt; 744.975 pt is held as
3540        // 744.97498 and goes down to 744.97 pt; 709.725 pt likewise goes to 709.72 pt; a
3541        // distance below 100 pt keeps three decimals. The baseline 586.425 pt is held as
3542        // 586.424988, so the distance, subtracted in single precision, is 205.575012 and rounds
3543        // up to 205.58 pt, where the exact 205.575 pt held as 205.574997 would go down.
3544        let point =
3545            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3546        let page = point(792_000);
3547        assert_eq!(written_y(page, point(357_875), (5, 0)), point(357_870));
3548        assert_eq!(written_y(page, point(47_025), (5, 0)), point(47_030));
3549        assert_eq!(written_y(page, point(82_275), (5, 0)), point(82_280));
3550        assert_eq!(written_y(page, point(741_025), (5, 0)), point(741_025));
3551        assert_eq!(written_y(page, point(800_000), (5, 0)), point(800_000));
3552        assert_eq!(written_y(page, point(586_425), (5, 0)), point(586_420));
3553    }
3554
3555    #[test]
3556    fn writes_a_baseline_from_its_count_of_steps() {
3557        use super::{counted_y, written_y};
3558        // On a page of 792 pt, a baseline whose distance from the foot lies on a half of its
3559        // last decimal takes the side of the single-precision points of its count of steps of
3560        // 1/2880 inch: 582.925 pt is 23,317 steps, whose points lie just above the half, so
3561        // the distance 209.075 pt is written 209.07 pt; 273.825 pt gives 518.18 pt. Both go
3562        // the other way from the baseline's own points. 587.925 pt and 586.425 pt
3563        // (205.58 pt) go the same way, and so does a half that binary numbers hold exactly.
3564        let point =
3565            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3566        let page = point(792_000);
3567        let counted = |y: i64| counted_y(page, point(y), (5, 2), 2_880);
3568        let written = |y: i64| written_y(page, point(y), (5, 2));
3569        let pairs = [582_925, 273_825].map(|y| (counted(y), written(y)));
3570        assert_eq!(pairs[0], (point(582_930), point(582_920)));
3571        assert_eq!(pairs[1], (point(273_820), point(273_830)));
3572        for same in [587_925, 586_425, 357_875, 744_975, 300_000] {
3573            assert_eq!(counted(same), written(same), "{same}");
3574        }
3575    }
3576
3577    #[test]
3578    fn writes_a_baseline_off_the_steps_from_its_own_points() {
3579        use super::{counted_y, written_y};
3580        // A baseline at the top, below the foot or between two steps is written as the
3581        // baseline's own points: 582.938 pt keeps 209.06 pt, where the nearest count, 23,318
3582        // steps (582.95 pt), would give 209.05 pt.
3583        let point =
3584            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3585        let page = point(792_000);
3586        let counted = |y: i64| counted_y(page, point(y), (5, 2), 2_880);
3587        let written = |y: i64| written_y(page, point(y), (5, 2));
3588        for y in [0, 800_000, 582_938] {
3589            assert_eq!(counted(y), written(y), "{y}");
3590        }
3591        assert_eq!(counted(582_938), point(582_940));
3592    }
3593
3594    #[test]
3595    fn writes_glyph_baselines_from_their_counts_where_the_writer_holds_steps() {
3596        use super::{Glyph, GlyphRun, Item};
3597        let point =
3598            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3599        let glyphs = || {
3600            Item::Glyphs(GlyphRun {
3601                font: f_office_fonts::FontId::from_index(0),
3602                size: point(11_000),
3603                color: Rgb::BLACK,
3604                text: "a".to_owned(),
3605                glyphs: vec![Glyph {
3606                    id: 1,
3607                    x: point(72_000),
3608                    y: point(582_925),
3609                    text_start: 0,
3610                    text_end: 1,
3611                }],
3612                outline: None,
3613                filled: true,
3614                effect: false,
3615                turn: None,
3616            })
3617        };
3618        let baseline = |writer: &Writer| {
3619            let mut item = glyphs();
3620            write_digits(writer, point(792_000), &mut item);
3621            let Item::Glyphs(run) = item else {
3622                unreachable!()
3623            };
3624            run.glyphs[0].y
3625        };
3626        let writer = Writer::new(Length::from_units(10))
3627            .unwrap()
3628            .with_digits(Some(non_zero(5)))
3629            .with_least_decimals(2);
3630        let counting = writer.with_baseline_steps(Some(non_zero(2_880)));
3631        assert_eq!(counting.baseline_steps(), Some(non_zero(2_880)));
3632        assert_eq!(writer.baseline_steps(), None);
3633        assert_eq!(baseline(&counting), point(582_930));
3634        assert_eq!(baseline(&writer), point(582_920));
3635    }
3636
3637    #[test]
3638    fn writes_a_baseline_from_1000_pt_with_the_least_decimals() {
3639        use super::written_y;
3640        // A baseline 576.12 pt below the top of a page of 1,584 pt lies 1,007.88 pt above its
3641        // foot. Five significant digits print it as 1007.9, and two least decimals as 1007.88.
3642        let point =
3643            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
3644        let page = point(1_584_000);
3645        assert_eq!(written_y(page, point(576_120), (5, 0)), point(576_100));
3646        assert_eq!(written_y(page, point(576_120), (5, 2)), point(576_120));
3647        // A distance whose second decimal is a 0 is the same with one or two.
3648        assert_eq!(written_y(page, point(576_400), (5, 2)), point(576_400));
3649        // Two least decimals change no number below 1,000 pt: on a Letter page, 434.125 pt
3650        // above the foot still rounds up to 434.13 pt, and 50.975 pt keeps three decimals.
3651        let letter = point(792_000);
3652        assert_eq!(written_y(letter, point(357_875), (5, 2)), point(357_870));
3653        assert_eq!(written_y(letter, point(741_025), (5, 2)), point(741_025));
3654    }
3655
3656    #[test]
3657    fn offsets_a_rectangles_edges_as_a_text_objects_start() {
3658        // With a target's offset (1/2400 of the place plus 18 half-EMUs, on 635 half-EMUs), a
3659        // left edge at 66.5 pt moves by 0.025 pt to 66.525 pt, and a right edge at 186.75 pt by
3660        // 0.075 pt.
3661        let writer = Writer::new(Length::from_units(10))
3662            .unwrap()
3663            .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
3664                share: 2_400,
3665                bias: 18,
3666                step: 635,
3667            }));
3668        let point = |thousandths: i64| Length::from_units(thousandths * 254 / 10);
3669        let (width, height) = (point(612_000), point(792_000));
3670        let across = |writer: Writer, x: Length| {
3671            Length::from_units(
3672                writer
3673                    .page_offsets(width, height, Orientation::Portrait)
3674                    .0
3675                    .of(x.units(), width.units()),
3676            )
3677        };
3678        assert_eq!(across(writer, point(66_500)), point(25));
3679        assert_eq!(across(writer, point(186_750)), point(75));
3680        assert_eq!(
3681            across(Writer::new(Length::from_units(10)).unwrap(), point(66_500)),
3682            point(0)
3683        );
3684    }
3685
3686    /// The page form of Word for Windows's writer with the steps `c` hundred-thousandths and
3687    /// the product rounded in `parts` of a step first.
3688    const fn page_form(c: i64, parts: i64) -> Offset {
3689        Offset::Page {
3690            steps: (c, 100_000),
3691            parts,
3692            per_inch: 3_000,
3693            product: OffsetProduct::Exact,
3694        }
3695    }
3696
3697    /// The page form of [`page_form`] with the product of the dot and the page entry held in
3698    /// binary32, for dots of 1/600 inch.
3699    const fn binary32_page_form(c: i64) -> Offset {
3700        Offset::Page {
3701            steps: (c, 100_000),
3702            parts: 16,
3703            per_inch: 3_000,
3704            product: OffsetProduct::Binary32 { dots_per_inch: 600 },
3705        }
3706    }
3707
3708    #[test]
3709    fn rounds_the_product_of_the_dot_and_the_page_entry_in_binary32() {
3710        // Across a Letter page 5,100 dots wide with c = 4.72515, the page entry is the binary32
3711        // number nearest 16 (5 + c / 5,100), 80.0148239. The exact rule changes from 3 to 4
3712        // steps at the dot 3,744; with the product of the dot 3,743 and the entry held in
3713        // binary32 it already gives 4 steps there, 0.096 pt, as Word does.
3714        let offset = |c, k: i64| binary32_page_form(c).of(k * DOT, LETTER);
3715        assert_eq!(page_form(472_515, 16).of(3_743 * DOT, LETTER), 1_829);
3716        assert_eq!(offset(472_515, 3_743), 2_438);
3717        assert_eq!(offset(472_515, 3_742), 1_829);
3718        // Elsewhere both take the same steps: the dots 1,585 and 1,586 change from 1 to 2.
3719        for k in [600, 1_585, 1_586, 2_664, 2_665, 3_744] {
3720            assert_eq!(
3721                offset(472_515, k),
3722                page_form(472_515, 16).of(k * DOT, LETTER)
3723            );
3724        }
3725        // A place inside a dot takes its dot's offset, and no page gives none.
3726        assert_eq!(
3727            binary32_page_form(472_515).of(3_743 * DOT + 1_000, LETTER),
3728            2_438
3729        );
3730        assert_eq!(binary32_page_form(472_515).of(3_743 * DOT, 0), 0);
3731    }
3732
3733    /// A dot of 1/600 inch in half-EMUs; a step of 1/3000 inch is 609.6 half-EMUs, so that one
3734    /// step rounds to 610 half-EMUs and two to 1,219.
3735    const DOT: i64 = 3_048;
3736
3737    /// The width of a Letter page, 12,240 twips, in half-EMUs.
3738    const LETTER: i64 = 12_240 * 1_270;
3739
3740    #[test]
3741    fn offsets_a_place_by_whole_steps_as_if_the_page_were_larger() {
3742        // The page form writes a dot k of 1/600 inch as 5 k + round(round(16 k c / D) / 16)
3743        // in 1/3000 inch, D the page's side in dots: on a Letter page 5,100 dots wide, with
3744        // c = 4.72515, that gives the dots 600, 646 and 692 one step and the dot 0 none.
3745        for k in [600, 646, 692] {
3746            assert_eq!(page_form(472_515, 16).of(k * DOT, LETTER), 610);
3747        }
3748        assert_eq!(page_form(472_515, 16).of(0, LETTER), 0);
3749        assert_eq!(Offset::None.of(1_585 * DOT, LETTER), 0);
3750    }
3751
3752    #[test]
3753    fn rounds_the_product_of_the_page_form_before_the_division() {
3754        // With c = 4.73073 the dot 1,585 gives 23.52 sixteenths, 24 rounded, which is 1.5
3755        // steps and rounds up to two, where the quotient 1.470 would round to one; the dot
3756        // 1,583 gives 23.49 sixteenths, 23 rounded.
3757        assert_eq!(page_form(473_073, 16).of(1_585 * DOT, LETTER), 1_219);
3758        assert_eq!(page_form(473_073, 16).of(1_583 * DOT, LETTER), 610);
3759        assert_eq!(page_form(473_073, 1).of(1_585 * DOT, LETTER), 610);
3760        assert_eq!(page_form(473_073, 0).of(1_585 * DOT, LETTER), 0);
3761    }
3762
3763    #[test]
3764    fn writes_a_rectangle_with_significant_digits() {
3765        // A rule 0.5 pt high on a page of 842 pt, 646.7032 pt from the top: its bottom edge
3766        // lies 194.7968 pt above the page's foot and is written as 194.8 pt, so the rule moves
3767        // to 646.7 pt; its width of
3768        // 357.652 pt is written as 357.65 pt.
3769        use super::Item;
3770        let u = Length::from_units;
3771        let writer = Writer::new(u(10)).unwrap().with_digits(Some(non_zero(5)));
3772        let mut rect = Item::Rect(super::Rect {
3773            x: u(3_023_870),
3774            y: u(16_426_262),
3775            width: u(9_084_361),
3776            height: u(12_700),
3777            color: super::Rgb::BLACK,
3778        });
3779        write_digits(&writer, u(842 * 25_400), &mut rect);
3780        let Item::Rect(rect) = rect else {
3781            unreachable!()
3782        };
3783        assert_eq!(
3784            (
3785                rect.x.units(),
3786                rect.y.units(),
3787                rect.width.units(),
3788                rect.height.units()
3789            ),
3790            (3_023_870, 16_426_180, 9_084_310, 12_700)
3791        );
3792    }
3793
3794    #[test]
3795    fn writes_a_rectangle_from_its_edges_on_the_steps() {
3796        // A rule 0.48 pt high and wide, at 13,172 and 21,198 steps of 1/3000 inch from the left
3797        // and top edges of a Letter page (316.128 and 508.752 pt). Its height and width are
3798        // written as 0.47998 and 0.48001 pt: the differences of the single-precision products of
3799        // its edges' steps and 0.024. A reader puts its top 508.75002 pt from the
3800        // page's top, at the nearest half-EMU.
3801        use super::Item;
3802        let u = Length::from_units;
3803        let writer = Writer::new(u(10))
3804            .unwrap()
3805            .with_digits(Some(non_zero(5)))
3806            .with_rectangle_steps(Some(non_zero(3_000)));
3807        let rect = |x, y, width, height| {
3808            Item::Rect(super::Rect {
3809                x: u(x),
3810                y: u(y),
3811                width: u(width),
3812                height: u(height),
3813                color: super::Rgb::BLACK,
3814            })
3815        };
3816        let mut rule = rect(8_029_651, 12_922_301, 12_192, 12_192);
3817        write_digits(&writer, u(792 * 25_400), &mut rule);
3818        let Item::Rect(rule) = rule else {
3819            unreachable!()
3820        };
3821        let edges = |r: &super::Rect| (r.x.units(), r.y.units(), r.width.units(), r.height.units());
3822        assert_eq!(edges(&rule), (8_029_702, 12_922_251, 12_192, 12_191));
3823        // A rectangle with an edge before the page's left edge keeps the single-precision
3824        // numbers of its exact size.
3825        let mut wide = rect(-25_400, 12_922_301, 50_800, 12_192);
3826        write_digits(&writer, u(792 * 25_400), &mut wide);
3827        let Item::Rect(wide) = wide else {
3828            unreachable!()
3829        };
3830        assert_eq!(edges(&wide).2, 50_800);
3831        assert_eq!(writer.rectangle_steps(), Some(non_zero(3_000)));
3832        // The same rule 42,609 steps from the left edge of a wide page (1,022.616 pt): five
3833        // significant digits print its left edge as 1022.6, and two least decimals as 1022.62.
3834        // Its other numbers lie below 1,000 pt and stay.
3835        let far = || rect(25_974_446, 12_922_301, 12_192, 12_192);
3836        let written = |writer: Writer| {
3837            let mut item = far();
3838            write_digits(&writer, u(792 * 25_400), &mut item);
3839            let Item::Rect(written) = item else {
3840                unreachable!()
3841            };
3842            edges(&written)
3843        };
3844        let (left, top, _, tall) = written(writer);
3845        assert_eq!((left, top, tall), (25_974_040, 12_922_251, 12_191));
3846        let (left, top, _, tall) = written(writer.with_least_decimals(2));
3847        assert_eq!((left, top, tall), (25_974_548, 12_922_251, 12_191));
3848    }
3849
3850    #[test]
3851    fn writes_an_upright_image_with_significant_digits() {
3852        // A picture of 36 by 48 pt on a page of 792 pt, 66.25193 pt from the top: its bottom
3853        // edge lies 677.74807 pt above the page's foot and is written as 677.75 pt, so the
3854        // picture moves up to 66.25 pt.
3855        use super::{ImageItem, Item, Turn};
3856        let u = Length::from_units;
3857        let image = |turn| {
3858            Item::Image(ImageItem {
3859                x: u(1_143_000),
3860                y: u(1_682_799),
3861                width: u(914_400),
3862                height: u(1_219_200),
3863                clip: None,
3864                turn,
3865                image: Image::new(vec![0]),
3866            })
3867        };
3868        // A turned image keeps its place: its matrix is not a rectangle's numbers.
3869        let turn = Turn {
3870            xx: 0,
3871            xy: -Turn::SCALE,
3872            yx: Turn::SCALE,
3873            yy: 0,
3874        };
3875        let placed = |writer: Writer| {
3876            let mut list = DisplayList {
3877                pages: vec![Page {
3878                    width: u(612 * 25_400),
3879                    height: u(792 * 25_400),
3880                    orientation: Orientation::Portrait,
3881                    items: vec![image(None), image(Some(turn))],
3882                }],
3883            };
3884            writer.finish(&mut list);
3885            writer.place_pictures(&mut list);
3886            list.pages[0]
3887                .items
3888                .iter()
3889                .map(|item| match item {
3890                    Item::Image(image) => (image.x, image.y, image.width, image.height),
3891                    _ => unreachable!(),
3892                })
3893                .collect::<Vec<_>>()
3894        };
3895        let exact = (u(1_143_000), u(1_682_799), u(914_400), u(1_219_200));
3896        let writer = Writer::new(u(10)).unwrap();
3897        assert_eq!(
3898            placed(writer.with_picture_digits(Some(non_zero(5)))),
3899            [
3900                (u(1_143_000), u(1_682_750), u(914_400), u(1_219_200)),
3901                exact
3902            ]
3903        );
3904        // The digits of glyphs and rectangles leave images where they are.
3905        assert_eq!(
3906            placed(writer.with_digits(Some(non_zero(5)))),
3907            [exact, exact]
3908        );
3909    }
3910
3911    #[test]
3912    fn rounds_the_stretch_of_a_glyph_to_whole_steps() {
3913        use super::Item;
3914        // The glyph's baseline and the rectangle's top after a stretch of one step of 10 units
3915        // on a page 2,000 units high, with glyph steps of `step` units.
3916        let moved = |step: Option<i64>| {
3917            let writer = Writer::new(Length::from_units(10))
3918                .unwrap()
3919                .with_vertical_stretch(1)
3920                .with_glyph_stretch_step(step.map(Length::from_units))
3921                .unwrap();
3922            let mut list = DisplayList {
3923                pages: vec![sample_page()],
3924            };
3925            writer.finish(&mut list);
3926            let (Item::Glyphs(run), Item::Rect(rect)) =
3927                (&list.pages[0].items[0], &list.pages[0].items[1])
3928            else {
3929                panic!("no glyphs or rect")
3930            };
3931            (run.glyphs[0].y.units(), rect.y.units())
3932        };
3933        // The exact stretch moves the baseline at 400 units by 2 units: 2/3 of a step of 3
3934        // rounds to one step, 2/5 of a step of 5 to none, and half a step of 4 up. The
3935        // rectangle's top at 200 units moves by 1 unit, which rounds to no step of 3, 4 or 5.
3936        assert_eq!(moved(None), (402, 201));
3937        assert_eq!(moved(Some(3)), (403, 200));
3938        assert_eq!(moved(Some(5)), (400, 200));
3939        assert_eq!(moved(Some(4)), (404, 200));
3940    }
3941
3942    #[test]
3943    fn refuses_a_glyph_stretch_step_that_is_not_positive() {
3944        let writer = Writer::new(Length::from_units(10)).unwrap();
3945        assert_eq!(writer.with_glyph_stretch_step(Some(Length::ZERO)), None);
3946        assert_eq!(
3947            writer.with_glyph_stretch_step(Some(Length::from_units(-4))),
3948            None
3949        );
3950        assert_eq!(writer.with_glyph_stretch_step(None), Some(writer));
3951    }
3952
3953    /// A writer with a stretch of one step of 10 units and glyph steps of 4 units.
3954    fn stepping_writer() -> Writer {
3955        Writer::new(Length::from_units(10))
3956            .unwrap()
3957            .with_vertical_stretch(1)
3958            .with_glyph_stretch_step(Some(Length::from_units(4)))
3959            .unwrap()
3960    }
3961
3962    /// The glyph's baseline at 400 units and the rectangle's top at 200 units of
3963    /// [`sample_page`], 2,000 units high, after [`stepping_writer`] with a stretch offset and
3964    /// stretch factors: half a step and a quarter of one before the factor and the offset.
3965    fn moved(offset: super::Fraction, factors: &[(Length, super::Fraction)]) -> (i64, i64) {
3966        use super::Item;
3967        let mut list = DisplayList {
3968            pages: vec![sample_page()],
3969        };
3970        stepping_writer()
3971            .with_stretch_factors(offset, factors)
3972            .unwrap()
3973            .finish(&mut list);
3974        let (Item::Glyphs(run), Item::Rect(rect)) =
3975            (&list.pages[0].items[0], &list.pages[0].items[1])
3976        else {
3977            panic!("no glyphs or rect")
3978        };
3979        (run.glyphs[0].y.units(), rect.y.units())
3980    }
3981
3982    #[test]
3983    fn counts_the_steps_of_the_stretch_with_the_factor_and_offset_of_the_page_height() {
3984        let u = Length::from_units;
3985        let page = u(2000);
3986        assert_eq!(moved((0, 1), &[]), (404, 200));
3987        // A factor below 1 takes the half step below a half, and an offset up again.
3988        assert_eq!(moved((0, 1), &[(page, (99, 100))]), (400, 200));
3989        assert_eq!(moved((1, 100), &[(page, (99, 100))]), (404, 200));
3990        assert_eq!(moved((-1, 100), &[(page, (1, 1))]), (400, 200));
3991        // A factor of 2 doubles both: a whole step, and half a step rounded up.
3992        assert_eq!(moved((0, 1), &[(page, (2, 1))]), (404, 204));
3993        // The factor of another page height leaves the page on the rounding of the exact
3994        // stretch, without the offset.
3995        assert_eq!(moved((-1, 100), &[(u(3000), (2, 1))]), (404, 200));
3996    }
3997
3998    #[test]
3999    fn holds_no_stretch_factors_without_denominators_or_beyond_its_heights() {
4000        use super::STRETCH_HEIGHTS;
4001        let writer = stepping_writer();
4002        let page = Length::from_units(2000);
4003        assert_eq!(writer.with_stretch_factors((0, 0), &[]), None);
4004        assert_eq!(writer.with_stretch_factors((0, 1), &[(page, (1, 0))]), None);
4005        let many = [(page, (1, 1)); STRETCH_HEIGHTS + 1];
4006        assert_eq!(writer.with_stretch_factors((0, 1), &many), None);
4007    }
4008
4009    #[test]
4010    fn leaves_the_items_of_a_group_where_the_layout_puts_them() {
4011        use super::Item;
4012        // The sample page's items in a group, after a writer with a stretch, glyph steps, an
4013        // offset of rectangles' edges and five digits: they keep every place, and output
4014        // paints them in their order.
4015        let grouped = || {
4016            let mut page = sample_page();
4017            page.items = vec![Item::Group(super::Group::new(page.items))];
4018            page
4019        };
4020        let writer = Writer::new(Length::from_units(10))
4021            .unwrap()
4022            .with_vertical_stretch(1)
4023            .with_glyph_stretch_step(Some(Length::from_units(3)))
4024            .unwrap()
4025            .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
4026                share: 2,
4027                bias: 0,
4028                step: 10,
4029            }))
4030            .with_digits(Some(non_zero(5)));
4031        let mut list = DisplayList {
4032            pages: vec![grouped()],
4033        };
4034        writer.finish(&mut list);
4035        assert_eq!(list.pages[0], grouped());
4036        let sample = sample_page();
4037        assert_eq!(list.pages[0].painted(), sample.painted());
4038    }
4039
4040    #[test]
4041    fn places_the_items_of_a_group_of_the_page_as_the_pages_items() {
4042        use super::{Group, GroupClip, Item};
4043        // The sample page's items in a group of the page's items under a clip, after a writer
4044        // with a stretch, glyph steps, an offset of rectangles' edges and five digits: they
4045        // take the places that they take outside a group, and the clip stretches as a path.
4046        let writer = Writer::new(Length::from_units(10))
4047            .unwrap()
4048            .with_vertical_stretch(1)
4049            .with_glyph_stretch_step(Some(Length::from_units(3)))
4050            .unwrap()
4051            .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
4052                share: 2,
4053                bias: 0,
4054                step: 10,
4055            }))
4056            .with_digits(Some(non_zero(5)));
4057        let u = Length::from_units;
4058        let mut plain = DisplayList {
4059            pages: vec![sample_page()],
4060        };
4061        writer.finish(&mut plain);
4062        let mut page = sample_page();
4063        let clip = GroupClip::rect(u(0), u(1000), u(500), u(1000));
4064        page.items = vec![Item::Group(Group::of_page(page.items, clip))];
4065        let mut grouped = DisplayList { pages: vec![page] };
4066        writer.finish(&mut grouped);
4067        let placed = DisplayList {
4068            pages: vec![Page {
4069                items: vec![Item::Group(Group::of_page(
4070                    plain.pages[0].items.clone(),
4071                    GroupClip::rect(u(0), u(1005), u(500), u(1005)),
4072                ))],
4073                ..plain.pages.remove(0)
4074            }],
4075        };
4076        assert_eq!(grouped, placed);
4077    }
4078
4079    #[test]
4080    fn moves_the_clip_of_a_table_cell_with_the_offsets_of_the_cells_items() {
4081        use super::{Group, GroupClip, Item, Rect, Rgb};
4082        // A cell's clip over a filled rectangle with the same edges, after a writer with an
4083        // offset across and down: the clip's edges stay on the rectangle's. A text box's clip
4084        // keeps its place.
4085        let offset = WriterOffset::EveryPage(Offset::Share {
4086            share: 2,
4087            bias: 0,
4088            step: 10,
4089        });
4090        let writer = Writer::new(Length::from_units(10))
4091            .unwrap()
4092            .with_horizontal_offset(offset)
4093            .with_vertical_offset(offset);
4094        let u = Length::from_units;
4095        let (x, y, width, height) = (u(300), u(900), u(200), u(400));
4096        let fill = Item::Rect(Rect {
4097            x,
4098            y,
4099            width,
4100            height,
4101            color: Rgb::BLACK,
4102        });
4103        let clip = GroupClip::rect(x, y, width, height);
4104        let page = |group: fn(Vec<Item>, GroupClip) -> Group| Page {
4105            width: u(1000),
4106            height: u(2000),
4107            items: vec![Item::Group(group(vec![fill.clone()], clip.clone()))],
4108            ..sample_page()
4109        };
4110        let mut list = DisplayList {
4111            pages: vec![page(Group::of_cell), page(Group::of_page)],
4112        };
4113        writer.finish(&mut list);
4114        let group = |page: &Page| match &page.items[0] {
4115            Item::Group(group) => group.clone(),
4116            _ => unreachable!("the page holds one group"),
4117        };
4118        let cell = group(&list.pages[0]);
4119        let Item::Rect(moved) = &cell.items[0] else {
4120            unreachable!("the group holds one rectangle")
4121        };
4122        assert_ne!((moved.x, moved.y), (x, y));
4123        assert_eq!(
4124            cell.clip,
4125            Some(GroupClip::rect(moved.x, moved.y, moved.width, moved.height))
4126        );
4127        assert_eq!(group(&list.pages[1]).clip, Some(clip));
4128    }
4129
4130    #[test]
4131    fn moves_every_point_of_a_group_of_points_as_a_rectangles_edges() {
4132        use super::{Group, GroupClip, GroupPlaces, Item, PathItem, Rect, Rgb};
4133        // A path and a clip with the edges of a filled rectangle, in a group whose every point
4134        // the writer places, after a writer with an offset across and down: their points stay
4135        // on the rectangle's edges. In a group of the page's items, the path keeps its place.
4136        let offset = WriterOffset::EveryPage(Offset::Share {
4137            share: 2,
4138            bias: 0,
4139            step: 10,
4140        });
4141        let writer = Writer::new(Length::from_units(10))
4142            .unwrap()
4143            .with_horizontal_offset(offset)
4144            .with_vertical_offset(offset);
4145        let u = Length::from_units;
4146        let (x, y, width, height) = (u(300), u(900), u(200), u(400));
4147        let fill = Item::Rect(Rect {
4148            x,
4149            y,
4150            width,
4151            height,
4152            color: Rgb::BLACK,
4153        });
4154        let outline = |x, y, width, height| GroupClip::rect(x, y, width, height).commands;
4155        let path = Item::Path(PathItem {
4156            commands: outline(x, y, width, height),
4157            color: Rgb::BLACK,
4158            fill_rule: super::FillRule::NonZero,
4159        });
4160        let page = |places| Page {
4161            width: u(1000),
4162            height: u(2000),
4163            items: vec![Item::Group(Group {
4164                items: vec![fill.clone(), path.clone()],
4165                clip: Some(GroupClip::rect(x, y, width, height)),
4166                places,
4167            })],
4168            ..sample_page()
4169        };
4170        let mut list = DisplayList {
4171            pages: vec![page(GroupPlaces::Points), page(GroupPlaces::Page)],
4172        };
4173        writer.finish(&mut list);
4174        let items = |page: &Page| match &page.items[0] {
4175            Item::Group(group) => (group.items.clone(), group.clip.clone()),
4176            _ => unreachable!("the page holds one group"),
4177        };
4178        let (moved, clip) = items(&list.pages[0]);
4179        let [Item::Rect(rect), Item::Path(drawn)] = moved.as_slice() else {
4180            unreachable!("the group holds a rectangle and a path")
4181        };
4182        assert_ne!((rect.x, rect.y), (x, y));
4183        let edges = outline(rect.x, rect.y, rect.width, rect.height);
4184        assert_eq!(drawn.commands, edges);
4185        assert_eq!(clip.map(|clip| clip.commands), Some(edges));
4186        let (kept, _) = items(&list.pages[1]);
4187        assert_eq!(kept[1], path);
4188    }
4189
4190    /// The writer offset of a Letter page of Word for Windows across: 4.72515 steps over the
4191    /// page, in sixteenths of a step, with a binary32 product of dots of 1/600 inch.
4192    const LETTER_ACROSS: Offset = Offset::Page {
4193        steps: (472_515, 100_000),
4194        parts: 16,
4195        per_inch: 3_000,
4196        product: super::OffsetProduct::Binary32 { dots_per_inch: 600 },
4197    };
4198
4199    #[test]
4200    fn writes_an_edge_between_two_dots_by_the_entry_at_its_own_place() {
4201        // On a Letter page 612 pt wide, an edge 0.04 dot past dot 4,700 is written at step
4202        // 23,505 by the entry at its own place, where the offset of its nearest dot moves it to
4203        // 0.2 step past step 23,504; on a whole dot both give the same place.
4204        let side = 612 * 25_400;
4205        let between = 4_700 * 3_048 + 122;
4206        assert_eq!(LETTER_ACROSS.written_place(between, side), 14_328_648);
4207        assert_eq!(between + LETTER_ACROSS.of(between, side), 14_328_160);
4208        let dot = 4_800 * 3_048;
4209        assert_eq!(LETTER_ACROSS.written_place(dot, side), 14_632_838);
4210        assert_eq!(dot + LETTER_ACROSS.of(dot, side), 14_632_838);
4211        // Every other offset moves the edge as it moves a whole dot.
4212        let share = Offset::Share {
4213            share: 2,
4214            bias: 0,
4215            step: 10,
4216        };
4217        assert_eq!(
4218            share.written_place(between, side),
4219            between + share.of(between, side)
4220        );
4221    }
4222
4223    /// The items that the writer draws from a group of `places` on a Letter page of Word for
4224    /// Windows that holds two rectangles whose left edges lie 0.04 dot past dot 4,700: one dot
4225    /// wide, and four dots wide.
4226    fn drawn_rectangles(places: super::GroupPlaces) -> Vec<super::Item> {
4227        use super::{Group, Item, Rect};
4228        let u = Length::from_units;
4229        let writer = Writer::new(u(1))
4230            .unwrap()
4231            .with_horizontal_offset(WriterOffset::EveryPage(LETTER_ACROSS));
4232        let rect = Rect {
4233            x: u(4_700 * 3_048 + 122),
4234            y: u(9_000_000),
4235            width: u(3_048),
4236            height: u(50_000),
4237            color: Rgb::BLACK,
4238        };
4239        let wide = Rect {
4240            width: u(4 * 3_048),
4241            ..rect.clone()
4242        };
4243        let mut list = DisplayList {
4244            pages: vec![Page {
4245                width: u(612 * 25_400),
4246                height: u(792 * 25_400),
4247                items: vec![Item::Group(Group {
4248                    items: vec![Item::Rect(rect), Item::Rect(wide)],
4249                    clip: None,
4250                    places,
4251                })],
4252                ..sample_page()
4253            }],
4254        };
4255        writer.finish(&mut list);
4256        match &list.pages[0].items[0] {
4257            Item::Group(group) => group.items.clone(),
4258            _ => unreachable!("the page holds one group"),
4259        }
4260    }
4261
4262    #[test]
4263    fn draws_a_stroked_rectangle_and_then_its_stroke_after_placing_its_edges() {
4264        use super::{FillRule, GroupPlaces, Item, PathCommand, Point};
4265        // A rectangle one dot wide whose edges lie 0.04 dot past dots 4,700 and 4,701 of a
4266        // Letter page, stroked 0.14 pt wide: its edges go to steps 23,505 and 23,510, and its
4267        // stroke's outline follows it, 0.07 pt outside the edges; it is narrower than the stroke,
4268        // so the outline has no inner part. In a group of points, the left edge takes the offset
4269        // of its nearest dot instead.
4270        let u = Length::from_units;
4271        let stroked = drawn_rectangles(GroupPlaces::Stroked { width: u(3_556) });
4272        let [Item::Rect(placed), Item::Path(outline), ..] = stroked.as_slice() else {
4273            unreachable!("each rectangle and then its stroke's outline")
4274        };
4275        assert_eq!(placed.x, u(14_328_648));
4276        assert_eq!(placed.width, u(14_331_696 - 14_328_648));
4277        assert_eq!((placed.y, placed.height), (u(9_000_000), u(50_000)));
4278        assert_eq!(
4279            (outline.color, outline.fill_rule),
4280            (Rgb::BLACK, FillRule::NonZero)
4281        );
4282        let (right, below) = (u(14_331_696), u(9_050_000) + u(1_778));
4283        let at = |x, y| Point { x, y };
4284        // The outer outline starts at the left end of the bottom edge, 0.07 pt below it, and its
4285        // corner's quarter circle has its arms 982 units long.
4286        assert_eq!(
4287            outline.commands[..3],
4288            [
4289                PathCommand::MoveTo(at(u(14_328_648), below)),
4290                PathCommand::LineTo(at(right, below)),
4291                PathCommand::CubicTo(
4292                    at(right + u(982), below),
4293                    at(right + u(1_778), u(9_050_000) + u(982)),
4294                    at(right + u(1_778), u(9_050_000)),
4295                ),
4296            ]
4297        );
4298        assert_eq!(outline.commands.len(), 10);
4299        let points = drawn_rectangles(GroupPlaces::Points);
4300        let [Item::Rect(nearest), Item::Rect(_)] = points.as_slice() else {
4301            unreachable!("a group of points draws the rectangles alone")
4302        };
4303        assert_eq!(nearest.x, u(14_328_160));
4304    }
4305
4306    #[test]
4307    fn draws_the_inner_outline_of_the_stroke_of_a_rectangle_wider_than_the_stroke() {
4308        use super::{GroupPlaces, Item, PathCommand, Point};
4309        // A rectangle four dots wide, stroked 0.14 pt wide: the inner outline of its stroke
4310        // starts 0.07 pt above the left end of its bottom edge and goes through the ends of its
4311        // edges moved 0.07 pt inward.
4312        let u = Length::from_units;
4313        let stroked = drawn_rectangles(GroupPlaces::Stroked { width: u(3_556) });
4314        let [_, _, Item::Rect(wide), Item::Path(outline)] = stroked.as_slice() else {
4315            unreachable!("each rectangle and then its stroke's outline")
4316        };
4317        let (left, right, bottom) = (wide.x, wide.x + wide.width, u(9_050_000));
4318        assert_eq!(left, u(14_328_648));
4319        let at = |x, y| Point { x, y };
4320        assert_eq!(
4321            outline.commands[10..13],
4322            [
4323                PathCommand::MoveTo(at(left, bottom - u(1_778))),
4324                PathCommand::LineTo(at(left + u(1_778), bottom)),
4325                PathCommand::LineTo(at(left + u(1_778), u(9_000_000))),
4326            ]
4327        );
4328        assert_eq!(
4329            outline.commands[17],
4330            PathCommand::LineTo(at(right, bottom - u(1_778)))
4331        );
4332        assert_eq!(outline.commands.len(), 20);
4333    }
4334
4335    #[test]
4336    fn writes_every_point_of_a_group_of_points_with_the_writers_digits() {
4337        use super::{Group, GroupPlaces, Item, PathCommand, PathItem, Point, Rgb};
4338        // A point at 123.4567 pt across and 700.1234 pt down a page of 792 pt, written with
4339        // five digits: 123.46 pt across, and its height as a baseline.
4340        let u = Length::from_units;
4341        let point = Point {
4342            x: u(3_135_800),
4343            y: u(17_783_134),
4344        };
4345        let height = u(792 * 25_400);
4346        let page = Page {
4347            width: u(612 * 25_400),
4348            height,
4349            items: vec![Item::Group(Group {
4350                items: vec![Item::Path(PathItem {
4351                    commands: vec![PathCommand::MoveTo(point), PathCommand::Close],
4352                    color: Rgb::BLACK,
4353                    fill_rule: super::FillRule::NonZero,
4354                })],
4355                clip: None,
4356                places: GroupPlaces::Points,
4357            })],
4358            ..sample_page()
4359        };
4360        let written = |steps: Option<u32>| {
4361            let writer = Writer::new(Length::from_units(1))
4362                .unwrap()
4363                .with_digits(Some(non_zero(5)))
4364                .with_rectangle_steps(steps.map(non_zero));
4365            let mut list = DisplayList {
4366                pages: vec![page.clone()],
4367            };
4368            writer.finish(&mut list);
4369            match &list.pages[0].items[0] {
4370                Item::Group(group) => match &group.items[0] {
4371                    Item::Path(path) => path.commands[0].points().next(),
4372                    _ => None,
4373                },
4374                _ => None,
4375            }
4376        };
4377        let plain = written(None).unwrap();
4378        assert_eq!(plain.x, u(3_135_884));
4379        assert_eq!(plain.y, super::written_y(height, point.y, (5, 0)));
4380        // A writer that holds a rectangle's edges on steps of 1/3000 inch holds no point: on
4381        // steps, the point would lie at 29,172 steps down, 700.128 pt.
4382        assert_eq!(written(Some(3_000)), Some(plain));
4383    }
4384
4385    /// [`sample_page`] after a writer with a step of 10 units and a vertical stretch of one
4386    /// step: y grows by 1/200, and x stays.
4387    fn stretched() -> Page {
4388        let writer = Writer::new(Length::from_units(10))
4389            .unwrap()
4390            .with_vertical_stretch(1);
4391        let mut list = DisplayList {
4392            pages: vec![sample_page()],
4393        };
4394        writer.finish(&mut list);
4395        list.pages.remove(0)
4396    }
4397
4398    /// A page of 1,000 by 2,000 units with a glyph, a rectangle, a path and a clipped image.
4399    fn sample_page() -> Page {
4400        use super::{Clip, Glyph, GlyphRun, ImageItem, Item, PathCommand, PathItem, Point, Rect};
4401        let u = Length::from_units;
4402        let glyph = Glyph {
4403            id: 1,
4404            x: u(500),
4405            y: u(400),
4406            text_start: 0,
4407            text_end: 1,
4408        };
4409        let items = vec![
4410            Item::Glyphs(GlyphRun {
4411                font: f_office_fonts::FontId::from_index(0),
4412                size: u(120),
4413                color: super::Rgb::default(),
4414                text: "a".to_owned(),
4415                glyphs: vec![glyph],
4416                outline: None,
4417                filled: true,
4418                effect: false,
4419                turn: None,
4420            }),
4421            Item::Rect(Rect {
4422                x: u(100),
4423                y: u(200),
4424                width: u(300),
4425                height: u(400),
4426                color: super::Rgb::default(),
4427            }),
4428            Item::Path(PathItem {
4429                commands: vec![PathCommand::MoveTo(Point {
4430                    x: u(1000),
4431                    y: u(2000),
4432                })],
4433                color: super::Rgb::default(),
4434                fill_rule: super::FillRule::NonZero,
4435            }),
4436            Item::Image(ImageItem {
4437                x: u(0),
4438                y: u(0),
4439                width: u(1000),
4440                height: u(2000),
4441                clip: Some(Clip {
4442                    x: u(100),
4443                    y: u(200),
4444                    width: u(100),
4445                    height: u(200),
4446                }),
4447                turn: None,
4448                image: Image::new(vec![0]),
4449            }),
4450        ];
4451        Page {
4452            width: u(1000),
4453            height: u(2000),
4454            orientation: Orientation::Portrait,
4455            items,
4456        }
4457    }
4458
4459    #[test]
4460    fn detects_formats_from_their_signatures() {
4461        let mut emf = vec![1, 0, 0, 0];
4462        emf.resize(40, 0);
4463        emf.extend_from_slice(b" EMF");
4464        let cases: [(&[u8], ImageFormat); 12] = [
4465            (b"\x89PNG\r\n\x1a\nrest", ImageFormat::Png),
4466            (&[0xFF, 0xD8, 0xFF, 0xE0], ImageFormat::Jpeg),
4467            (b"GIF89a", ImageFormat::Gif),
4468            (b"GIF87a", ImageFormat::Gif),
4469            (b"BM", ImageFormat::Bmp),
4470            (b"II*\0", ImageFormat::Tiff),
4471            (b"MM\0*", ImageFormat::Tiff),
4472            (&emf, ImageFormat::Emf),
4473            (&[0xD7, 0xCD, 0xC6, 0x9A], ImageFormat::Wmf),
4474            (&[1, 0, 9, 0], ImageFormat::Wmf),
4475            (&[2, 0, 9, 0], ImageFormat::Wmf),
4476            (&[1, 0, 0, 0], ImageFormat::Unknown),
4477        ];
4478        for (data, format) in cases {
4479            assert_eq!(ImageFormat::detect(data), format, "{data:?}");
4480        }
4481        assert_eq!(ImageFormat::detect(&emf[..43]), ImageFormat::Unknown);
4482        assert_eq!(ImageFormat::detect(b""), ImageFormat::Unknown);
4483    }
4484
4485    #[test]
4486    fn shares_the_bytes_of_an_image() {
4487        let image = Image::new(vec![0xFF, 0xD8, 0xFF]);
4488        assert_eq!(image.format, ImageFormat::Jpeg);
4489        let copy = image.clone();
4490        assert!(Arc::ptr_eq(
4491            image.data.inline_bytes().unwrap(),
4492            copy.data.inline_bytes().unwrap()
4493        ));
4494    }
4495
4496    #[test]
4497    fn shows_the_part_of_a_clip_that_lies_on_the_image() {
4498        let length = Length::from_units;
4499        let clip = |x, y, width, height| super::Clip {
4500            x: length(x),
4501            y: length(y),
4502            width: length(width),
4503            height: length(height),
4504        };
4505        let item = |clip| super::ImageItem {
4506            x: length(100),
4507            y: length(200),
4508            width: length(80),
4509            height: length(40),
4510            clip,
4511            turn: None,
4512            image: Image::new(vec![0xFF, 0xD8, 0xFF]),
4513        };
4514        // A clip beyond the image's right edge, from a crop below zero, and inside its bottom.
4515        assert_eq!(
4516            item(Some(clip(100, 200, 100, 30))).shown(),
4517            Some(clip(100, 200, 80, 30))
4518        );
4519        // A clip around the whole image shows all of it.
4520        assert_eq!(
4521            item(Some(clip(90, 190, 100, 60))).shown(),
4522            Some(clip(100, 200, 80, 40))
4523        );
4524        assert_eq!(item(Some(clip(180, 200, 10, 40))).shown(), None);
4525        assert_eq!(item(None).shown(), None);
4526    }
4527
4528    #[test]
4529    fn first_place_is_the_first_place_that_map_places_maps() {
4530        use super::{Group, GroupPlaces, Item, Rect};
4531        let rect = |y| {
4532            Item::Rect(Rect {
4533                x: Length::from_units(1),
4534                y: Length::from_units(y),
4535                width: Length::from_units(2),
4536                height: Length::from_units(3),
4537                color: Rgb::BLACK,
4538            })
4539        };
4540        let group = |items| {
4541            Item::Group(Group {
4542                items,
4543                clip: None,
4544                places: GroupPlaces::Own,
4545            })
4546        };
4547        let empty = group(Vec::new());
4548        let nested = group(vec![empty.clone(), rect(5), rect(7)]);
4549        for item in [rect(4), empty, nested] {
4550            let mut mapped = None;
4551            item.clone().map_places(
4552                |place| {
4553                    mapped.get_or_insert(place);
4554                    place
4555                },
4556                |length| length,
4557            );
4558            assert_eq!(item.first_place(), mapped);
4559        }
4560    }
4561
4562    /// A gradient from black at 100,000 millionths through a red of 201, 10, 0 and, at the same
4563    /// place 500,000, blue, to white at the end.
4564    fn four_stops() -> super::GradientItem {
4565        use super::{FillRule, GradientItem, GradientStop, Point};
4566        let origin = Point {
4567            x: Length::ZERO,
4568            y: Length::ZERO,
4569        };
4570        let stops = vec![
4571            GradientStop::new(100_000, Rgb::BLACK),
4572            GradientStop::new(
4573                500_000,
4574                Rgb {
4575                    r: 201,
4576                    g: 10,
4577                    b: 0,
4578                },
4579            ),
4580            GradientStop::new(500_000, Rgb { r: 0, g: 0, b: 255 }),
4581            GradientStop::new(GradientStop::END, Rgb::WHITE),
4582        ];
4583        GradientItem::new(Vec::new(), FillRule::NonZero, (origin, origin), stops)
4584    }
4585
4586    #[test]
4587    fn gives_the_color_of_a_gradient_between_its_stops_and_beyond_its_ends() {
4588        let gradient = four_stops();
4589        assert_eq!(gradient.color_at(-5), Rgb::BLACK);
4590        assert_eq!(gradient.color_at(50_000), Rgb::BLACK);
4591        assert_eq!(gradient.color_at(2_000_000), Rgb::WHITE);
4592        // A half of 201 rounds up and a half of 10 is 5.
4593        assert_eq!(gradient.color_at(300_000), Rgb { r: 101, g: 5, b: 0 });
4594        assert_eq!(
4595            gradient.color_at(750_000),
4596            Rgb {
4597                r: 128,
4598                g: 128,
4599                b: 255
4600            }
4601        );
4602    }
4603
4604    #[test]
4605    fn gives_the_later_color_where_two_stops_meet_and_black_without_stops() {
4606        let gradient = four_stops();
4607        assert_eq!(
4608            gradient.color_at(499_999),
4609            Rgb {
4610                r: 201,
4611                g: 10,
4612                b: 0
4613            }
4614        );
4615        assert_eq!(gradient.color_at(500_000), Rgb { r: 0, g: 0, b: 255 });
4616        let mut empty = gradient;
4617        empty.stops.clear();
4618        assert_eq!(empty.color_at(0), Rgb::BLACK);
4619    }
4620
4621    #[test]
4622    fn moves_the_axis_of_a_gradient_with_its_outline() {
4623        use super::{FillRule, GradientItem, Item, PathCommand, Point};
4624        let at = |x, y| Point {
4625            x: Length::from_units(x),
4626            y: Length::from_units(y),
4627        };
4628        let mut item = Item::Gradient(GradientItem::new(
4629            vec![PathCommand::MoveTo(at(1, 2)), PathCommand::LineTo(at(3, 4))],
4630            FillRule::NonZero,
4631            (at(0, 0), at(10, 0)),
4632            Vec::new(),
4633        ));
4634        item.map_places(
4635            |p| Point {
4636                x: p.x + Length::from_units(100),
4637                y: p.y,
4638            },
4639            |length| length,
4640        );
4641        let Item::Gradient(moved) = &item else {
4642            panic!("not a gradient");
4643        };
4644        assert_eq!(moved.commands[0], PathCommand::MoveTo(at(101, 2)));
4645        assert_eq!((moved.start, moved.end), (at(100, 0), at(110, 0)));
4646        assert_eq!(item.first_place(), Some(at(101, 2)));
4647    }
4648}