ferri-pdf 0.1.7

HTML and CSS to PDF renderer for print, in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! CSS Backgrounds 3 layers: computed value lists, image sizing, tiling and painting areas.
use crate::paint::gradient::{Gradient, ResolvedGradient};
use crate::paint::{
    AbsoluteColor, Border, BoxPaint, Clip, Color, LengthPercentage, POINTS_PER_PIXEL, Rect,
};
use crate::paint::{ImageInfo, ImageRendering, NaturalDimensions};
use serde::Serialize;
use std::convert::Infallible;
use std::sync::Arc;

/// Tolerance for `space` counting tiles that fit exactly.
const SPACE_FIT_TOLERANCE: f32 = 1.0e-4;
pub(crate) const INITIAL_IMAGE_SCALE: f32 = 1.0;
/// One image pixel per CSS pixel.
const INITIAL_RESOLUTION: f32 = 1.0;
/// Mix weights are fractions of the whole.
const WHOLE: f32 = 1.0;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[expect(
    clippy::enum_variant_names,
    reason = "variants name the CSS border-box, padding-box and content-box keywords"
)]
pub enum BoxArea {
    #[default]
    BorderBox,
    PaddingBox,
    ContentBox,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[expect(
    clippy::enum_variant_names,
    reason = "variants name the CSS repeat and no-repeat keywords"
)]
pub enum Repeat {
    #[default]
    Repeat,
    Space,
    Round,
    NoRepeat,
}
/// A layer's `background-clip` (CSS Backgrounds 4 §2.8): a box, or within the border box the
/// union of the area its border paints and the geometry of its text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum BackgroundClip {
    Box(BoxArea),
    Painted { border_area: bool, text: bool },
}
impl Default for BackgroundClip {
    fn default() -> Self {
        Self::Box(BoxArea::BorderBox)
    }
}
impl BackgroundClip {
    /// The box the painting area lies within.
    pub fn area(self) -> BoxArea {
        match self {
            Self::Box(area) => area,
            Self::Painted { .. } => BoxArea::BorderBox,
        }
    }
    /// Whether the layer paints only within the glyphs of the box's text.
    pub fn text(self) -> bool {
        matches!(self, Self::Painted { text: true, .. })
    }
}
/// `local` behaves as `scroll` because paged boxes never scroll.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub enum Attachment {
    #[default]
    Scroll,
    Fixed,
    Local,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum SizeComponent {
    Auto,
    Value(LengthPercentage),
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum BackgroundSize {
    Cover,
    Contain,
    Explicit([SizeComponent; 2]),
}
impl Default for BackgroundSize {
    fn default() -> Self {
        Self::Explicit([const { SizeComponent::Auto }; 2])
    }
}
/// One axis of a `<position>`: an offset from the start edge or from the end edge.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PositionComponent {
    pub from_end: bool,
    pub offset: LengthPercentage,
}
impl PositionComponent {
    /// The initial `background-position` component, `0%`.
    pub const START: Self = Self {
        from_end: false,
        offset: LengthPercentage::Percentage(0.0),
    };
    /// Center alignment, initially used by object-position and gradient positions.
    pub const CENTER: Self = Self {
        from_end: false,
        offset: LengthPercentage::Percentage(0.5),
    };
    /// Top-left offsets with explicit length and percentage terms for computed-value comparisons.
    #[must_use]
    pub fn canonical(&self) -> Self {
        use crate::paint::Calculation;
        let offset = Calculation::from(&self.offset);
        let offset = if self.from_end {
            Calculation::Sum(vec![Calculation::Percentage(1.0), offset.negate()]).simplify()
        } else {
            offset
        };
        Self {
            from_end: false,
            offset: Calculation::Sum(vec![
                Calculation::Value(0.0),
                Calculation::Percentage(0.0),
                offset,
            ])
            .into(),
        }
    }
    /// Offset within `free` space; percentages align that point of the object and the area.
    pub fn resolve(&self, free: f32) -> f32 {
        let offset = self.offset.resolve(free);
        if self.from_end { free - offset } else { offset }
    }
}
/// Horizontal and vertical components.
pub(crate) type Position = [PositionComponent; 2];

#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(bound(serialize = ""))]
pub enum BackgroundImage<I = Infallible> {
    None,
    /// Absolute reference that the document builder loads into `Image`; `resolution` is the
    /// natural resolution in dots per CSS pixel that `image-set()` gives a raster image (CSS
    /// Images 4 §2.4), which `image-resolution` does not override.
    Url {
        url: String,
        resolution: Option<f32>,
        /// Accumulated zoom of the image's natural dimensions, independent of density.
        scale: f32,
        /// The `image()` notation that wrote the URL, if any.
        #[serde(skip_serializing_if = "Option::is_none")]
        function: Option<ImageFunction>,
    },
    Image {
        #[serde(skip)]
        image: I,
        resolution: f32,
        scale: f32,
        /// The `image-rendering` of the element whose property loaded it.
        rendering: ImageRendering,
    },
    Gradient(Gradient),
    /// A solid-color image with no natural dimensions (CSS Images 4 §2.5.3).
    Color(AbsoluteColor),
    /// An invalid image (CSS Images 4 §2.1), which renders as a transparent image with no
    /// natural dimensions unless its context treats it as `none`.
    Invalid,
    /// `cross-fade()`: the weighted average of images and solid colours (CSS Images 4 §2.6).
    CrossFade(Vec<FadeLayer<I>>),
    /// `element()`: the element with this ID as an image (CSS Images 4 §2.7), which the
    /// document builder resolves into `Image`.
    Element(Arc<str>),
}

/// One `<cf-image>` of `cross-fade()`: an image, a colour as a solid-colour image, and the
/// fraction of it the result retains, with omitted percentages already distributed.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(bound(serialize = ""))]
pub struct FadeLayer<I = Infallible> {
    pub image: BackgroundImage<I>,
    pub percentage: f32,
}

/// The annotations `image()` adds to a URL (CSS Images 4 §2.5).
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct ImageFunction {
    /// `rtl` or `ltr`: the image's directionality, if it has one (§2.5.4).
    pub rtl: Option<bool>,
    /// The solid color rendered when the URL is an invalid image (§2.5.1).
    pub fallback: Option<AbsoluteColor>,
}

/// An image a box's values reference: a URL to load, or the ID `element()` names.
#[derive(Clone, Copy, Debug)]
pub enum ImageReference<'a> {
    Url(ImageRequest<'a>),
    Element(&'a str),
}

/// An image URL to load for a box.
#[derive(Clone, Copy, Debug)]
pub struct ImageRequest<'a> {
    pub url: &'a str,
    /// Written in `image()`: the image is optional, and a fragment it does not understand
    /// makes it invalid (CSS Images 4 §2.5.2).
    pub function: Option<&'a ImageFunction>,
    /// `image-set()` chose the image's natural resolution.
    pub resolved: bool,
}

/// Computed background longhands; layer `i` uses item `i` of each list, cycling short lists.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(bound(serialize = ""))]
pub struct Backgrounds<I = Infallible> {
    pub images: Vec<BackgroundImage<I>>,
    /// `background-position-x` and `background-position-y`, which cycle independently.
    pub positions: [Vec<PositionComponent>; 2],
    pub sizes: Vec<BackgroundSize>,
    pub repeats: Vec<[Repeat; 2]>,
    pub origins: Vec<BoxArea>,
    pub clips: Vec<BackgroundClip>,
    pub attachments: Vec<Attachment>,
    pub blend_modes: Vec<crate::paint::BlendMode>,
}
impl<I> Default for Backgrounds<I> {
    fn default() -> Self {
        Self {
            images: vec![BackgroundImage::None],
            positions: [
                vec![PositionComponent::START],
                vec![PositionComponent::START],
            ],
            sizes: vec![BackgroundSize::default()],
            repeats: vec![[Repeat::Repeat; 2]],
            origins: vec![BoxArea::PaddingBox],
            clips: vec![BackgroundClip::default()],
            attachments: vec![Attachment::Scroll],
            blend_modes: vec![crate::paint::BlendMode::Normal],
        }
    }
}
pub(crate) fn cycle<T>(values: &[T], index: usize) -> &T {
    &values[index % values.len()]
}
impl<I> Backgrounds<I> {
    pub fn has_images(&self) -> bool {
        self.images
            .iter()
            .any(|image| !matches!(image, BackgroundImage::None))
    }
    /// The background colour is clipped like the bottom layer.
    pub fn color_clip(&self) -> BackgroundClip {
        *cycle(&self.clips, self.images.len() - 1)
    }
    /// Whether any layer, or the colour, paints only within the box's text.
    pub fn clips_to_text(&self) -> bool {
        self.clips.iter().any(|clip| clip.text())
    }
    /// Treats `fixed` layers as `scroll`, as in a transformed box or its descendants
    /// (CSS Transforms 1 §6).
    pub fn scroll_fixed(backgrounds: &mut Arc<Self>)
    where
        I: Clone,
    {
        if backgrounds.attachments.contains(&Attachment::Fixed) {
            for attachment in &mut Arc::make_mut(backgrounds).attachments {
                if *attachment == Attachment::Fixed {
                    *attachment = Attachment::Scroll;
                }
            }
        }
    }
    /// Replaces every `Url` image with the image `load` returns for it, scaled by
    /// `rendering`, copying shared lists only when one is present.
    pub(crate) fn resolve_images<E>(
        backgrounds: &mut Arc<Self>,
        rendering: ImageRendering,
        mut load: impl FnMut(&ImageReference<'_>) -> Result<Option<I>, E>,
    ) -> Result<(), E>
    where
        I: Clone,
    {
        if !backgrounds
            .images
            .iter()
            .any(BackgroundImage::needs_loading)
        {
            return Ok(());
        }
        for image in &mut Arc::make_mut(backgrounds).images {
            image.load(rendering, &mut load)?;
        }
        Ok(())
    }
}
impl<I> BackgroundImage<I> {
    /// Neither `none` nor an invalid image, which contexts with error handling treat as
    /// `none` (CSS Images 4 §2.1).
    pub fn is_displayable(&self) -> bool {
        !matches!(self, Self::None | Self::Invalid)
    }
    /// Whether the image is, or combines, a `url()` or `element()` that the document builder
    /// loads.
    pub fn needs_loading(&self) -> bool {
        match self {
            Self::Url { .. } | Self::Element(_) => true,
            Self::CrossFade(layers) => layers.iter().any(|layer| layer.image.needs_loading()),
            Self::None
            | Self::Image { .. }
            | Self::Gradient(_)
            | Self::Color(_)
            | Self::Invalid => false,
        }
    }
    /// Replaces a `Url` or `Element` with the image `load` returns for it, which is `None`
    /// when it could not be loaded without aborting the document: an `image()` URL then
    /// renders its fallback color, else the image is invalid (CSS Images 4 §2.5.1, §2.7).
    pub(crate) fn load<E>(
        &mut self,
        rendering: ImageRendering,
        load: &mut impl FnMut(&ImageReference<'_>) -> Result<Option<I>, E>,
    ) -> Result<(), E> {
        if let Self::CrossFade(layers) = self {
            for layer in layers {
                layer.image.load(rendering, load)?;
            }
        }
        if let Self::Element(id) = self {
            *self = match load(&ImageReference::Element(id))? {
                Some(image) => Self::Image {
                    image,
                    resolution: INITIAL_RESOLUTION,
                    scale: INITIAL_IMAGE_SCALE,
                    rendering,
                },
                None => Self::Invalid,
            };
            return Ok(());
        }
        if let Self::Url {
            url,
            resolution,
            scale,
            function,
        } = self
        {
            let request = ImageRequest {
                url,
                function: function.as_ref(),
                resolved: resolution.is_some(),
            };
            *self = match load(&ImageReference::Url(request))? {
                Some(image) => Self::Image {
                    image,
                    resolution: resolution.unwrap_or(INITIAL_RESOLUTION),
                    scale: *scale,
                    rendering,
                },
                None => function
                    .and_then(|function| function.fallback)
                    .map_or(Self::Invalid, Self::Color),
            };
        }
        Ok(())
    }
}

impl Backgrounds<Infallible> {
    pub fn with_image_type<I>(&self) -> Backgrounds<I> {
        Backgrounds {
            images: self
                .images
                .iter()
                .map(BackgroundImage::with_image_type)
                .collect(),
            positions: self.positions.clone(),
            sizes: self.sizes.clone(),
            repeats: self.repeats.clone(),
            origins: self.origins.clone(),
            clips: self.clips.clone(),
            attachments: self.attachments.clone(),
            blend_modes: self.blend_modes.clone(),
        }
    }
}

impl BackgroundImage<Infallible> {
    pub fn with_image_type<I>(&self) -> BackgroundImage<I> {
        match self {
            Self::None => BackgroundImage::None,
            Self::Url {
                url,
                resolution,
                scale,
                function,
            } => BackgroundImage::Url {
                url: url.clone(),
                resolution: *resolution,
                scale: *scale,
                function: *function,
            },
            Self::Gradient(gradient) => BackgroundImage::Gradient(gradient.clone()),
            Self::Color(color) => BackgroundImage::Color(*color),
            Self::Invalid => BackgroundImage::Invalid,
            Self::CrossFade(layers) => BackgroundImage::CrossFade(
                layers
                    .iter()
                    .map(|layer| FadeLayer {
                        image: layer.image.with_image_type(),
                        percentage: layer.percentage,
                    })
                    .collect(),
            ),
            Self::Element(id) => BackgroundImage::Element(id.clone()),
            Self::Image { image, .. } => match *image {},
        }
    }
}

/// A `url()` image that reached painting without being loaded.
#[derive(Debug)]
pub struct UnresolvedImage(pub String);
impl std::fmt::Display for UnresolvedImage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "background image {} was not loaded", self.0)
    }
}
impl std::error::Error for UnresolvedImage {}

pub(crate) enum Source<'a, I> {
    /// A loaded image, natural resolution in dots per CSS pixel, used size scale, and
    /// scaling.
    Image(&'a I, f32, f32, ImageRendering),
    Gradient(&'a Gradient),
    Color(Color),
    /// `cross-fade()` arguments with their normalized weights, and the weight of the
    /// transparent black that makes the weights sum to one (CSS Images 4 §2.6).
    CrossFade(Vec<(Self, f32)>, f32),
}

impl<'a, I: ImageInfo> Source<'a, I> {
    /// The source an image paints from, `None` for `none`.
    pub(crate) fn of(image: &'a BackgroundImage<I>) -> Result<Option<Self>, UnresolvedImage> {
        Ok(Some(match image {
            BackgroundImage::None => return Ok(None),
            BackgroundImage::Url { url, .. } => return Err(UnresolvedImage(url.clone())),
            BackgroundImage::Element(id) => {
                return Err(UnresolvedImage(format!("element(#{id})")));
            }
            BackgroundImage::Image {
                image,
                resolution,
                scale,
                rendering,
            } => Self::Image(image, *resolution, *scale, *rendering),
            BackgroundImage::Gradient(gradient) => Self::Gradient(gradient),
            BackgroundImage::Color(color) => Self::Color(color.used()),
            BackgroundImage::Invalid => Self::Color(Color::TRANSPARENT),
            BackgroundImage::CrossFade(layers) => {
                let percentages: Vec<f32> = layers.iter().map(|layer| layer.percentage).collect();
                let (weights, leftover) = crate::paint::normalize_mix(&percentages, false);
                let mut sources = Vec::with_capacity(layers.len());
                for (layer, weight) in layers.iter().zip(weights) {
                    sources.extend(Self::of(&layer.image)?.map(|source| (source, weight)));
                }
                Self::CrossFade(sources, leftover)
            }
        }))
    }
    /// Natural dimensions in points; generated images have none. `area` is the default object
    /// size of the image's context, which sizes the images a `cross-fade()` averages.
    pub(crate) fn natural(&self, area: [f32; 2]) -> NaturalDimensions {
        match self {
            Self::Image(image, resolution, scale, _) => natural_points(*image, *resolution, *scale),
            Self::Gradient(_) | Self::Color(_) => NaturalDimensions::default(),
            Self::CrossFade(sources, leftover) => cross_fade_natural(sources, *leftover, area),
        }
    }
    /// The image drawn into a tile of `size`, `None` when a gradient has no area.
    pub(crate) fn tile(&self, size: [f32; 2]) -> Option<TileImage<'a, I>> {
        Some(match self {
            Self::Image(image, _, scale, rendering) => TileImage::Image(image, *scale, *rendering),
            Self::Gradient(gradient) => TileImage::Gradient(gradient.resolve(size)?),
            Self::Color(color) => TileImage::Color(*color),
            // Every argument is rescaled to the result's size (CSS Images 4 §2.6.2).
            Self::CrossFade(sources, leftover) => TileImage::CrossFade(
                sources
                    .iter()
                    .map(|(source, weight)| Some((source.tile(size)?, *weight)))
                    .collect::<Option<_>>()?,
                *leftover,
            ),
        })
    }
}

/// CSS Images 4 §2.6.1: the average, weighted by their percentages, of the concrete object
/// sizes in `area` of the arguments with natural dimensions; none when no argument has them
/// or the arguments retain nothing.
fn cross_fade_natural<I: ImageInfo>(
    sources: &[(Source<'_, I>, f32)],
    leftover: f32,
    area: [f32; 2],
) -> NaturalDimensions {
    if leftover >= WHOLE {
        return NaturalDimensions::default();
    }
    let mut total = 0.0;
    let mut sum = [0.0; 2];
    for (source, weight) in sources {
        let natural = source.natural(area);
        if natural.width.is_none() && natural.height.is_none() {
            continue;
        }
        let size = image_size(&BackgroundSize::default(), natural, area);
        total += weight;
        sum = [sum[0] + weight * size[0], sum[1] + weight * size[1]];
    }
    if total <= 0.0 {
        return NaturalDimensions::default();
    }
    let [width, height] = sum.map(|value| value / total);
    NaturalDimensions {
        width: Some(width),
        height: Some(height),
        ratio: (height > 0.0).then_some(width / height),
    }
}

/// Content of one tile.
#[derive(Clone, Debug)]
pub enum TileImage<'a, I = Infallible> {
    /// An image, its used size scale, and its scaling.
    Image(&'a I, f32, ImageRendering),
    Gradient(ResolvedGradient),
    /// A solid-color image.
    Color(Color),
    /// `cross-fade()` arguments filling the tile, each weighted, and the weight of transparent
    /// black; the weights sum to one.
    CrossFade(Vec<(Self, f32)>, f32),
}
/// One background layer ready to paint.
#[derive(Clone, Debug)]
pub struct LayerPaint<'a, I = Infallible> {
    pub image: TileImage<'a, I>,
    /// Background painting area.
    pub clip: Clip,
    /// The part of the painting area the layer paints.
    pub painted: BackgroundClip,
    /// The tile placed by `background-position`; repeated axes tile from it both ways.
    pub tile: Rect,
    /// Distance between tile origins, including `space` gaps.
    pub step: [f32; 2],
    pub repeat: [bool; 2],
    /// How the layer blends with the layers and colour below it (Compositing 1 §3.4.3).
    pub blend: crate::paint::BlendMode,
}

/// Natural dimensions in points; a raster image's pixels span `1 / resolution` CSS pixels.
pub(crate) fn natural_points<I: ImageInfo>(
    image: &I,
    resolution: f32,
    zoom: f32,
) -> NaturalDimensions {
    let natural = image.natural_size();
    let scale = if image.is_raster() {
        POINTS_PER_PIXEL / resolution
    } else {
        POINTS_PER_PIXEL
    } * zoom;
    NaturalDimensions {
        width: natural.width.map(|width| width * scale),
        height: natural.height.map(|height| height * scale),
        ratio: natural.ratio,
    }
}

fn contain(area: [f32; 2], ratio: f32, cover: bool) -> [f32; 2] {
    let width_limited = area[0] / ratio <= area[1];
    if width_limited == cover {
        [area[1] * ratio, area[1]]
    } else {
        [area[0], area[0] / ratio]
    }
}

/// `background-size` and the CSS Images 3 default sizing algorithm, before `round`;
/// natural dimensions are in points.
pub(crate) fn image_size(
    size: &BackgroundSize,
    natural: NaturalDimensions,
    area: [f32; 2],
) -> [f32; 2] {
    let NaturalDimensions {
        width,
        height,
        ratio,
    } = natural;
    let resolve = |component: &SizeComponent, basis: f32| match component {
        SizeComponent::Auto => None,
        SizeComponent::Value(value) => Some(value.resolve(basis)),
    };
    match size {
        BackgroundSize::Cover | BackgroundSize::Contain => ratio.map_or(area, |ratio| {
            contain(area, ratio, *size == BackgroundSize::Cover)
        }),
        BackgroundSize::Explicit([x, y]) => match (resolve(x, area[0]), resolve(y, area[1])) {
            (Some(x), Some(y)) => [x, y],
            (Some(x), None) => [x, ratio.map(|r| x / r).or(height).unwrap_or(area[1])],
            (None, Some(y)) => [ratio.map(|r| y * r).or(width).unwrap_or(area[0]), y],
            (None, None) => match (width, height, ratio) {
                (Some(x), Some(y), _) => [x, y],
                (Some(x), None, Some(r)) => [x, x / r],
                (None, Some(y), Some(r)) => [y * r, y],
                (Some(x), None, None) => [x, area[1]],
                (None, Some(y), None) => [area[0], y],
                (None, None, Some(r)) => contain(area, r, false),
                (None, None, None) => area,
            },
        },
    }
}

/// Second and third `round` steps of CSS Backgrounds 3 §3.9.
pub(crate) fn rounded_size(
    mut tile: [f32; 2],
    size: &BackgroundSize,
    repeat: [Repeat; 2],
    area: [f32; 2],
) -> [f32; 2] {
    let original = tile;
    for axis in 0..2 {
        if repeat[axis] == Repeat::Round && tile[axis] > 0.0 {
            tile[axis] = area[axis] / (area[axis] / tile[axis]).round().max(1.0);
        }
    }
    if let BackgroundSize::Explicit(components) = size {
        for axis in 0..2 {
            let other = 1 - axis;
            if repeat[axis] == Repeat::Round
                && repeat[other] != Repeat::Round
                && components[other] == SizeComponent::Auto
                && original[axis] > 0.0
            {
                tile[other] = original[other] * tile[axis] / original[axis];
            }
        }
    }
    tile
}

/// Tile origin, pitch and repetition on one axis.
fn place(
    repeat: Repeat,
    position: &PositionComponent,
    start: f32,
    area: f32,
    tile: f32,
) -> (f32, f32, bool) {
    if repeat == Repeat::Space {
        let count = (area / tile + SPACE_FIT_TOLERANCE).floor();
        if count >= 2.0 {
            return (start, tile + (area - count * tile) / (count - 1.0), true);
        }
    }
    (
        start + position.resolve(area - tile),
        tile,
        matches!(repeat, Repeat::Repeat | Repeat::Round),
    )
}

impl<I> BoxPaint<I> {
    /// Padding without the sliced edges of a fragment.
    pub(super) fn fragment_padding(&self) -> [f32; 4] {
        let mut padding = self.padding;
        if self.assembled_box().is_some() {
            return padding;
        }
        for (side, sliced) in padding.iter_mut().zip(self.sliced()) {
            if sliced {
                *side = 0.0;
            }
        }
        padding
    }
    /// The border, padding or content box of this fragment with its curves.
    pub fn box_area(&self, area: BoxArea) -> Clip {
        match area {
            BoxArea::BorderBox => self.box_clip([0.0; 4], [true; 2]),
            BoxArea::PaddingBox => self.inner_clip([0.0; 4], [true; 2]),
            BoxArea::ContentBox => self.inner_clip(self.fragment_padding(), [true; 2]),
        }
    }
    pub fn background_clips(&self) -> crate::paint::BoxAreas<Clip> {
        crate::paint::BoxAreas {
            border: self.box_area(BoxArea::BorderBox),
            padding: self.box_area(BoxArea::PaddingBox),
            content: self.box_area(BoxArea::ContentBox),
        }
    }
    pub fn background_origins(&self) -> crate::paint::BoxAreas<Rect> {
        crate::paint::BoxAreas {
            border: self.positioning_area(BoxArea::BorderBox),
            padding: self.positioning_area(BoxArea::PaddingBox),
            content: self.positioning_area(BoxArea::ContentBox),
        }
    }
    pub(crate) fn background_clip(&self, area: BoxArea) -> Clip {
        self.background_geometry
            .as_ref()
            .map_or_else(|| self.box_area(area), |geometry| geometry.clips.area(area))
    }
    /// Positioning area, taken from `background_box` when another box positions the layers.
    fn positioning_area(&self, area: BoxArea) -> Rect {
        if let Some(origins) = self
            .background_geometry
            .as_ref()
            .and_then(|geometry| geometry.origins)
        {
            return origins.area(area);
        }
        let Some(outer) = self.background_box else {
            return self.box_area(area).rect;
        };
        let borders = self.decoration.borders.map(Border::used_width);
        let insets: [f32; 4] = match area {
            BoxArea::BorderBox => [0.0; 4],
            BoxArea::PaddingBox => borders,
            BoxArea::ContentBox => std::array::from_fn(|side| borders[side] + self.padding[side]),
        };
        Rect {
            x: outer.x + insets[3],
            y: outer.y + insets[0],
            width: outer.width - insets[1] - insets[3],
            height: outer.height - insets[0] - insets[2],
        }
    }
}

impl<I: ImageInfo> BoxPaint<I> {
    /// Image layers bottom-most first; `page_area` positions `fixed` layers.
    pub fn background_layers(
        &self,
        page_area: Rect,
    ) -> Result<Vec<LayerPaint<'_, I>>, UnresolvedImage> {
        if !self.draw_background {
            return Ok(Vec::new());
        }
        Ok(self
            .layers(&self.decoration.backgrounds, page_area)?
            .into_iter()
            .map(|(_, layer)| layer)
            .collect())
    }
    /// Mask image layers bottom-most first with their list indices, placed and clipped like
    /// background layers (CSS Masking 1 §7).
    pub fn mask_layers(
        &self,
        page_area: Rect,
    ) -> Result<Vec<(usize, LayerPaint<'_, I>)>, UnresolvedImage> {
        self.layers(&self.decoration.masks.layers, page_area)
    }
    fn layers<'a>(
        &'a self,
        backgrounds: &'a Backgrounds<I>,
        page_area: Rect,
    ) -> Result<Vec<(usize, LayerPaint<'a, I>)>, UnresolvedImage> {
        let page_area = self
            .background_geometry
            .as_ref()
            .and_then(|geometry| geometry.viewport)
            .unwrap_or(page_area);
        place_layers(
            backgrounds,
            |index| {
                if *cycle(&backgrounds.attachments, index) == Attachment::Fixed {
                    page_area
                } else {
                    self.positioning_area(*cycle(&backgrounds.origins, index))
                }
            },
            |index| self.background_clip(cycle(&backgrounds.clips, index).area()),
        )
    }
}

/// The image layers of `backgrounds` bottom-most first, by index: each placed in the
/// positioning area `area` gives it and clipped to the painting area `clip` gives it.
pub(crate) fn place_layers<I: ImageInfo>(
    backgrounds: &Backgrounds<I>,
    area: impl Fn(usize) -> Rect,
    clip: impl Fn(usize) -> Clip,
) -> Result<Vec<(usize, LayerPaint<'_, I>)>, UnresolvedImage> {
    let mut layers = Vec::new();
    for (index, image) in backgrounds.images.iter().enumerate().rev() {
        let Some(source) = Source::of(image)? else {
            continue;
        };
        let area = area(index);
        let extent = [area.width, area.height];
        let natural = source.natural(extent);
        let size = cycle(&backgrounds.sizes, index);
        let repeat = *cycle(&backgrounds.repeats, index);
        let tile = rounded_size(image_size(size, natural, extent), size, repeat, extent);
        if !(tile[0] > 0.0 && tile[1] > 0.0 && tile.iter().all(|v| v.is_finite())) {
            continue;
        }
        let [position_x, position_y] = &backgrounds.positions;
        let (x, step_x, repeat_x) = place(
            repeat[0],
            cycle(position_x, index),
            area.x,
            extent[0],
            tile[0],
        );
        let (y, step_y, repeat_y) = place(
            repeat[1],
            cycle(position_y, index),
            area.y,
            extent[1],
            tile[1],
        );
        let Some(image) = source.tile(tile) else {
            continue;
        };
        layers.push((
            index,
            LayerPaint {
                image,
                clip: clip(index),
                painted: *cycle(&backgrounds.clips, index),
                tile: Rect {
                    x,
                    y,
                    width: tile[0],
                    height: tile[1],
                },
                step: [step_x, step_y],
                repeat: [repeat_x, repeat_y],
                blend: *cycle(&backgrounds.blend_modes, index),
            },
        ));
    }
    Ok(layers)
}