ferri-pdf 0.1.6

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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
//! HTML loading, stylesheet discovery, and styled document construction.
mod content;
mod controls;
pub(crate) mod counters;
mod element_images;
mod embedded;
pub(crate) mod encoding;
pub(crate) mod first_letter;
mod first_line;
mod first_page;
mod formatting;
pub(crate) mod frames;
mod frameset;
mod generated;
mod inline;
mod lists;
pub(crate) mod mathml;
mod media;
mod metadata;
mod navigation;
mod page;
pub(crate) mod ruby;
pub(crate) mod scroll_markers;
mod semantics;
mod strings;
mod stylesheets;
pub(crate) mod svg;
mod tables;

use crate::dom::DocumentTree;
use crate::resources::{ResourceError, ResourceResolver};
use crate::style::{PrintSettings, SourceDiagnostic, StyleError, Stylesheet};

pub(crate) use content::record_text_limit;
pub(crate) use counters::CounterSnapshot;
pub(crate) use element_images::{ElementMeasurements, ElementState, ShapeSamples};
#[cfg(test)]
pub(crate) use formatting::{
    ATOMIC_INLINE_DEPTH, BOX_DEPTH, MAX_FORMATTING_DEPTH, POSITIONED_DEPTH,
};
pub(crate) use formatting::{
    BlockBox, BlockContent, Footnotes, InitialLetterBox, MAX_FORMATTING_WORK, PageBox,
    PageFootnoteArea, PageMarginBox,
};
pub(crate) use frames::{Frame, FrameDocument};
pub(crate) use generated::{GeneratedValues, InlineFootnotePlacement, PageStart, Paginated};
pub(crate) use inline::{
    Anchor, CaseRun, InlineBox, MAX_INLINE_TEXT_BYTES, OBJECT_REPLACEMENT_CHARACTER, OffsetMap,
    Paragraph, is_css_whitespace, narrow_width, transform_text,
};
pub(crate) use metadata::DocumentMetadata;
pub(crate) use navigation::{Bookmark, BoxNavigation, Heading, LinkTarget, Navigation};
pub(crate) use page::{PageBoundary, PageContent, page_axes};
pub(crate) use semantics::{InlineEvent, SemanticEvent};
pub(crate) use strings::{RunningElement, RunningStringAssignment};

#[derive(Debug, thiserror::Error)]
pub(crate) enum DocumentError {
    #[error("{0}")]
    Image(#[from] crate::images::ImageError),
    #[error("{0}")]
    Style(#[from] StyleError),
    #[error("{0}")]
    Resource(#[from] ResourceError),
    #[error("{0}")]
    Formatting(String),
}

/// Recoverable input/source diagnostics retained with the rendering result.
#[derive(Debug, thiserror::Error)]
pub enum DocumentDiagnostic {
    #[error("{0}")]
    UnavailableImage(#[from] crate::images::ImageFailure),
    #[error("image omitted during PDF encoding: {error}")]
    ImageDecode { error: String },
    #[error("{0}")]
    Css(crate::style::StyleDiagnostic),
    #[error("{0}")]
    Degraded(crate::style::Degradation),
    #[error("{0}; the document content past it is ignored")]
    TreeLimit(crate::dom::DomError),
    #[error("{0}")]
    Layout(#[from] crate::layout::LayoutDiagnostic),
    #[error("{0}")]
    Paint(#[from] crate::writer::PaintDiagnostic),
    #[error("decoding {reference:?} as {encoding} replaced malformed byte sequences")]
    Decoding {
        base: crate::resources::ResourceBase,
        reference: Option<String>,
        encoding: String,
    },
    #[error("embedded resource {reference} is unavailable: {error}")]
    UnavailableEmbedded {
        base: crate::resources::ResourceBase,
        reference: String,
        #[source]
        error: ResourceError,
    },
    #[error("nested navigables beyond {limit} levels show nothing")]
    NavigableDepth { limit: usize },
    #[error("nested document {reference} of type {media_type} has no renderer and shows nothing")]
    UnrenderedDocument {
        reference: String,
        media_type: String,
    },
    #[error("{0}")]
    UnavailableFont(#[from] crate::fonts::FontFailure),
    #[error("stylesheet {reference} is unavailable: {error}")]
    UnavailableSource {
        base: crate::resources::ResourceBase,
        reference: String,
        #[source]
        error: ResourceError,
    },
    #[error("optional restyling past the {limit}-unit formatting work budget was skipped")]
    SkippedFormattingWork { limit: usize },
    /// Formatting kept within one of its limits by changing or leaving out what exceeds it.
    #[error("{resource} exceeds {limit}: {fallback}")]
    FormattingLimit {
        resource: &'static str,
        limit: usize,
        fallback: LimitFallback,
    },
}

impl DocumentDiagnostic {
    /// Whether a limit left author content out of the PDF or rendered it wrongly, rather than
    /// the input being recovered as the specifications' error handling says.
    pub fn loses_content(&self) -> bool {
        match self {
            Self::TreeLimit(_) | Self::NavigableDepth { .. } => true,
            Self::Degraded(degradation) => degradation.loses_content(),
            Self::Layout(diagnostic) => diagnostic.loses_content(),
            Self::Paint(diagnostic) => diagnostic.loses_content(),
            Self::FormattingLimit { fallback, .. } => fallback.loses_content(),
            Self::UnavailableImage(failure) => failure.error.loses_content(),
            Self::ImageDecode { .. }
            | Self::Css(_)
            | Self::Decoding { .. }
            | Self::UnavailableEmbedded { .. }
            | Self::UnrenderedDocument { .. }
            | Self::UnavailableFont(_)
            | Self::UnavailableSource { .. }
            | Self::SkippedFormattingWork { .. } => false,
        }
    }
}

/// What formatting does with the content past one of its limits.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LimitFallback {
    /// Elements nested deeper generate no boxes of their own; their content stays.
    FlattenedNesting,
    /// SVG elements nested deeper are placed beside their parents.
    FlattenedSvgNesting,
    /// The document content past the limit is left out.
    TruncatedContent,
    /// Paragraph text past the limit is left out.
    TruncatedText,
    /// A `text-transform` expanding text past the limit is not applied.
    UntransformedText,
    /// Counters past the limit are no longer evaluated and read as zero.
    UnevaluatedCounters,
    /// The SVG content after the limit is left out.
    OmittedSvgNodes,
    /// SVG resources referenced deeper are left out, as invalid references are.
    OmittedSvgReferences,
}
impl LimitFallback {
    /// Whether the fallback leaves author content out or renders it wrongly.
    pub fn loses_content(self) -> bool {
        match self {
            Self::TruncatedContent
            | Self::TruncatedText
            | Self::UnevaluatedCounters
            | Self::OmittedSvgNodes
            | Self::OmittedSvgReferences => true,
            Self::FlattenedNesting | Self::FlattenedSvgNesting | Self::UntransformedText => false,
        }
    }
}
impl std::fmt::Display for LimitFallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::FlattenedNesting => {
                "elements nested deeper generate no boxes of their own, their contents lying in the deepest box"
            }
            Self::FlattenedSvgNesting => "elements nested deeper are placed beside their parents",
            Self::TruncatedContent => "the document content past it is left out",
            Self::TruncatedText => "text past it is left out",
            Self::UntransformedText => "text transforms expanding past it are not applied",
            Self::UnevaluatedCounters => {
                "counters past it are no longer evaluated and read as zero"
            }
            Self::OmittedSvgNodes => "the content after them is left out",
            Self::OmittedSvgReferences => {
                "resources referenced deeper are left out as invalid references are"
            }
        })
    }
}

/// Records, once, that formatting skipped optional work past its budget's `limit`.
fn record_skipped_work(diagnostics: &mut Vec<DocumentDiagnostic>, limit: Option<usize>) {
    if let Some(limit) = limit
        && !diagnostics
            .iter()
            .any(|known| matches!(known, DocumentDiagnostic::SkippedFormattingWork { .. }))
    {
        diagnostics.push(DocumentDiagnostic::SkippedFormattingWork { limit });
    }
}

/// An owned document whose text and style ranges have been resolved together.
pub(crate) struct StyledDocument {
    root: BlockBox,
    /// Footnote element boxes in document order (CSS GCPM 3 ยง2.2).
    footnotes: Footnotes,
    styles: Stylesheet,
    diagnostics: Vec<DocumentDiagnostic>,
    navigation: Navigation,
    running_strings: Vec<RunningStringAssignment>,
    generated: generated::GeneratedReferences,
    source: std::rc::Rc<FormattingSource>,
    metadata: DocumentMetadata,
    canvas: crate::graphics::BoxDecoration,
    pages: page::PageProvider,
    svg_definitions: svg::SvgDefinitions,
    /// The document's counters where each page starts (CSS Page 3 ยง6.1).
    page_counters: std::collections::HashMap<usize, CounterSnapshot>,
    /// The scroll marker groups whose active markers layout determines (CSS Overflow 5
    /// ยง3.1.8).
    scroll_markers: scroll_markers::ScrollMarkerGroups,
    /// What the last layout measured of the content of intrinsically sized pages, and the
    /// first page sized to it.
    page_content: PageContent,
    first_page: std::sync::Arc<PageBox>,
    /// What the last layout measured of the `element()` images the next formatting resolves,
    /// and the renderings it measured, which floats' shapes sample.
    element_measurements: Box<ElementMeasurements>,
    element_renderings: Box<crate::layout::ElementRenderings>,
}

struct FormattingSource {
    html: DocumentTree,
    embedded: embedded::EmbeddedContent,
    base: crate::resources::ResourceBase,
    source_base: crate::resources::ResourceBase,
    document_url: Option<crate::resources::Url>,
    capture_fragment_targets: bool,
}

impl FormattingSource {
    fn build(
        &self,
        styles: &mut Stylesheet,
        values: GeneratedValues,
        (images, elements, definitions): (
            &std::rc::Rc<std::cell::RefCell<crate::images::ImageCache>>,
            &ElementMeasurements,
            &svg::SvgDefinitions,
        ),
        resolver: &dyn ResourceResolver,
    ) -> Result<formatting::Formatted, DocumentError> {
        let navigation = || {
            navigation::NavigationBuilder::new(
                &self.html,
                &self.base,
                self.capture_fragment_targets,
                self.document_url.clone(),
                &self.source_base,
            )
        };
        formatting::build(
            &formatting::Input {
                html: &self.html,
                embedded: &self.embedded,
                images,
                elements,
                definitions,
                work_limit: MAX_FORMATTING_WORK,
            },
            styles,
            (&self.base, resolver),
            &navigation,
            values,
        )
    }
}

/// Borrowed inputs shared by string and byte document parsing.
#[derive(Clone, Copy)]
pub(crate) struct ParseOptions<'a> {
    pub base: &'a crate::resources::ResourceBase,
    pub additional: &'a [String],
    pub user: &'a [String],
    pub settings: &'a PrintSettings,
    /// Retain targets and unresolved fragment intents for a multipart rendering job.
    pub capture_fragment_targets: bool,
    pub presentation: crate::style::Presentation,
    /// Document URLs of the navigables containing this document's, outermost first; empty for
    /// the printed document.
    pub ancestors: &'a [Option<crate::resources::Url>],
}

struct HtmlInput {
    tree: DocumentTree,
    encoding: String,
    diagnostics: Vec<DocumentDiagnostic>,
}

impl StyledDocument {
    #[cfg(test)]
    pub(crate) fn parse(
        html: &str,
        base: &crate::resources::ResourceBase,
        additional: &[String],
        resolver: &dyn ResourceResolver,
    ) -> Result<Self, DocumentError> {
        Self::parse_with_origins(html, base, additional, &[], resolver)
    }

    #[cfg(test)]
    pub(crate) fn parse_with_work_limit(
        html: &str,
        work_limit: usize,
    ) -> Result<Self, DocumentError> {
        Self::from_input(
            HtmlInput {
                tree: DocumentTree::parse(html),
                encoding: "UTF-8".into(),
                diagnostics: Vec::new(),
            },
            &ParseOptions {
                base: &crate::resources::ResourceBase::default(),
                additional: &[],
                user: &[],
                settings: &PrintSettings::default(),
                capture_fragment_targets: false,
                presentation: crate::style::Presentation::Paged,
                ancestors: &[],
            },
            &crate::resources::FileResolver::default(),
            work_limit,
        )
    }

    #[cfg(test)]
    pub(crate) fn parse_with_origins(
        html: &str,
        base: &crate::resources::ResourceBase,
        additional: &[String],
        user: &[String],
        resolver: &dyn ResourceResolver,
    ) -> Result<Self, DocumentError> {
        Self::parse_with_settings(
            html,
            base,
            additional,
            user,
            &PrintSettings::default(),
            resolver,
        )
    }

    pub(crate) fn parse_with_settings(
        html: &str,
        base: &crate::resources::ResourceBase,
        additional: &[String],
        user: &[String],
        settings: &PrintSettings,
        resolver: &dyn ResourceResolver,
    ) -> Result<Self, DocumentError> {
        Self::parse_with_options(
            html,
            &ParseOptions {
                base,
                additional,
                user,
                settings,
                capture_fragment_targets: false,
                presentation: crate::style::Presentation::Paged,
                ancestors: &[],
            },
            resolver,
        )
    }

    pub(crate) fn parse_with_options(
        html: &str,
        options: &ParseOptions<'_>,
        resolver: &dyn ResourceResolver,
    ) -> Result<Self, DocumentError> {
        options.settings.validate()?;
        Self::from_input(
            HtmlInput {
                tree: DocumentTree::parse(html),
                encoding: "UTF-8".into(),
                diagnostics: Vec::new(),
            },
            options,
            resolver,
            MAX_FORMATTING_WORK,
        )
    }

    /// A nested navigable's document, already decoded from `encoding`.
    pub(crate) fn parse_decoded(
        html: &str,
        encoding: &str,
        options: &ParseOptions<'_>,
        resolver: &dyn ResourceResolver,
    ) -> Result<Self, DocumentError> {
        options.settings.validate()?;
        Self::from_input(
            HtmlInput {
                tree: DocumentTree::parse(html),
                encoding: encoding.into(),
                diagnostics: Vec::new(),
            },
            options,
            resolver,
            MAX_FORMATTING_WORK,
        )
    }

    pub(crate) fn parse_bytes_with_settings(
        bytes: &[u8],
        base: &crate::resources::ResourceBase,
        additional: &[String],
        user: &[String],
        settings: &PrintSettings,
        resolver: &dyn ResourceResolver,
    ) -> Result<Self, DocumentError> {
        Self::parse_bytes_with_options(
            bytes,
            &ParseOptions {
                base,
                additional,
                user,
                settings,
                capture_fragment_targets: false,
                presentation: crate::style::Presentation::Paged,
                ancestors: &[],
            },
            resolver,
        )
    }

    pub(crate) fn parse_bytes_with_options(
        bytes: &[u8],
        options: &ParseOptions<'_>,
        resolver: &dyn ResourceResolver,
    ) -> Result<Self, DocumentError> {
        options.settings.validate()?;
        let (decoded, html) = encoding::decode_document(bytes, None);
        let mut diagnostics = Vec::new();
        if decoded.had_errors {
            diagnostics.push(DocumentDiagnostic::Decoding {
                base: options.base.clone(),
                reference: None,
                encoding: decoded.encoding.clone(),
            });
        }
        Self::from_input(
            HtmlInput {
                tree: html,
                encoding: decoded.encoding,
                diagnostics,
            },
            options,
            resolver,
            MAX_FORMATTING_WORK,
        )
    }

    fn from_input(
        input: HtmlInput,
        options: &ParseOptions<'_>,
        resolver: &dyn ResourceResolver,
        work_limit: usize,
    ) -> Result<Self, DocumentError> {
        let ParseOptions {
            base,
            additional,
            user,
            settings,
            capture_fragment_targets,
            presentation,
            ancestors,
        } = *options;
        let HtmlInput {
            tree: mut html,
            encoding: document_encoding,
            mut diagnostics,
        } = input;
        diagnostics.extend(
            std::mem::take(&mut html.limits)
                .into_iter()
                .map(DocumentDiagnostic::TreeLimit),
        );
        let sources = stylesheets::discover(&html, base, &document_encoding, additional, user);
        html.set_document_urls(sources.document_url.clone(), sources.base.resolve("")?);
        let base = &sources.base;
        let mut styles = Stylesheet::prepare(
            &html,
            &sources,
            resolver,
            settings,
            presentation,
            encoding::stylesheet,
        )?;
        let images = std::rc::Rc::new(std::cell::RefCell::new(
            crate::images::ImageCache::with_fonts(styles.fonts.clone()),
        ));
        let mut navigables = ancestors.to_vec();
        navigables.push(sources.document_url.clone());
        let (embedded, embedding) = embedded::resolve(
            &mut html,
            &embedded::Embedder {
                base,
                navigable: frames::Navigable {
                    settings: settings.clone(),
                    user: user.to_vec(),
                    ancestors: navigables,
                },
                resolver,
            },
            &mut images.borrow_mut(),
        )?;
        diagnostics.extend(embedding);
        let links = || {
            navigation::NavigationBuilder::new(
                &html,
                base,
                capture_fragment_targets,
                sources.document_url.clone(),
                options.base,
            )
        };
        let formatting::Formatted {
            root,
            footnotes,
            navigation: links,
            strings,
            generated,
            canvas,
            pages,
            svg_definitions,
            page_counters,
            scroll_markers,
            skipped_work,
            diagnostics: formatting_diagnostics,
            ..
        } = formatting::build(
            &formatting::Input {
                html: &html,
                embedded: &embedded,
                images: &images,
                elements: &ElementMeasurements::default(),
                definitions: &svg::SvgDefinitions::default(),
                work_limit,
            },
            &mut styles,
            (base, resolver),
            &links,
            Default::default(),
        )?;
        record_skipped_work(&mut diagnostics, skipped_work);
        diagnostics.extend(formatting_diagnostics);
        diagnostics.extend(
            styles
                .take_source_diagnostics()
                .into_iter()
                .map(|diagnostic| match diagnostic {
                    SourceDiagnostic::Decoding {
                        base,
                        reference,
                        encoding,
                    } => DocumentDiagnostic::Decoding {
                        base,
                        reference: Some(reference),
                        encoding,
                    },
                    SourceDiagnostic::Unavailable {
                        base,
                        reference,
                        error,
                    } => DocumentDiagnostic::UnavailableSource {
                        base,
                        reference,
                        error,
                    },
                }),
        );
        diagnostics.extend(
            styles
                .take_diagnostics()
                .into_iter()
                .map(DocumentDiagnostic::Css),
        );
        let first_page = PageContent::default().size(
            pages.first(),
            0,
            crate::style::logical::Flow::used(root.style()),
        )?;
        Ok(Self {
            root,
            footnotes,
            styles,
            diagnostics,
            navigation: links.finish(&html, &generated)?,
            running_strings: strings.finish(&html)?,
            generated,
            metadata: DocumentMetadata::from_html(&html),
            canvas,
            pages,
            svg_definitions,
            page_counters: page_counters.into_iter().collect(),
            scroll_markers,
            element_measurements: Box::default(),
            element_renderings: Box::default(),
            first_page,
            page_content: PageContent::default(),
            source: std::rc::Rc::new(FormattingSource {
                html,
                embedded,
                base: base.clone(),
                source_base: options.base.clone(),
                document_url: sources.document_url,
                capture_fragment_targets,
            }),
        })
    }

    /// `destinations` holds the page index of each destination.
    pub(crate) fn resolve_generated(
        &self,
        destinations: &[Option<usize>],
        paginated: Paginated<'_>,
    ) -> Result<Option<GeneratedValues>, DocumentError> {
        let values = self.generated.resolve(
            &self.source.html,
            &mut |owner| {
                self.navigation
                    .element_destinations
                    .get(&owner)
                    .and_then(|index| destinations.get(*index))
                    .copied()
                    .flatten()
            },
            paginated,
        )?;
        Ok((!self.generated.matches(&values)).then_some(values))
    }

    /// Creates independent formatting state for a borrowed deferred-layout request.
    #[cfg(test)]
    pub(crate) fn fork_for_layout(
        &self,
        values: GeneratedValues,
        container_sizes: std::collections::HashMap<
            crate::dom::ElementId,
            crate::style::ContainerMeasurement,
        >,
        anchor_frames: crate::style::anchor_values::AnchorFrameMap,
        resolver: &dyn ResourceResolver,
    ) -> Result<Self, DocumentError> {
        let source = self.source.clone();
        let mut styles = self.styles.fork_for_layout();
        if !self.styles.query_sizes().settled(&container_sizes) {
            styles.query_sizes_mut().measured(container_sizes);
        }
        styles.anchor_frames_mut().measured(anchor_frames);
        let formatting::Formatted {
            root,
            footnotes,
            navigation,
            strings,
            generated,
            canvas,
            pages,
            svg_definitions,
            page_counters,
            scroll_markers,
            skipped_work,
            diagnostics: formatting_diagnostics,
            ..
        } = source.build(
            &mut styles,
            values,
            (
                &self.pages.images(),
                &self.element_measurements,
                &self.svg_definitions,
            ),
            resolver,
        )?;
        let first_page = self.page_content.size(
            pages.first(),
            0,
            crate::style::logical::Flow::used(root.style()),
        )?;
        let mut diagnostics = formatting_diagnostics;
        record_skipped_work(&mut diagnostics, skipped_work);
        Ok(Self {
            root,
            footnotes,
            styles,
            diagnostics,
            navigation: navigation.finish(&source.html, &generated)?,
            running_strings: strings.finish(&source.html)?,
            generated,
            metadata: self.metadata.clone(),
            canvas,
            pages,
            svg_definitions,
            page_counters: page_counters.into_iter().collect(),
            scroll_markers,
            element_measurements: self.element_measurements.clone(),
            element_renderings: self.element_renderings.clone(),
            first_page,
            page_content: self.page_content.clone(),
            source,
        })
    }

    /// The generated values the current formatting resolved.
    pub(crate) fn generated_values(&self) -> GeneratedValues {
        self.generated.values()
    }

    /// Restyling uses the query container sizes a layout measured.
    pub(crate) fn measured_containers(
        &mut self,
        sizes: std::collections::HashMap<crate::dom::ElementId, crate::style::ContainerMeasurement>,
    ) {
        self.styles.query_sizes_mut().measured(sizes);
    }

    pub(crate) fn measured_anchors(&mut self, frames: crate::style::anchor_values::AnchorFrameMap) {
        self.styles.anchor_frames_mut().measured(frames);
    }

    /// Reformatting resolves `element()` images against what a layout measured of them, and
    /// the next layout's floats sample the `renderings` it measured.
    pub(crate) fn measured_elements(
        &mut self,
        measurements: Box<ElementMeasurements>,
        renderings: Box<crate::layout::ElementRenderings>,
    ) {
        self.element_measurements = measurements;
        self.element_renderings = renderings;
    }

    /// The renderings the last layout measured.
    pub(crate) fn element_renderings(&self) -> &crate::layout::ElementRenderings {
        &self.element_renderings
    }

    /// The `element()` images of the current formatting.
    pub(crate) fn element_images(&self) -> &element_images::ElementImages {
        self.pages.elements()
    }

    pub(crate) fn reformat(
        &mut self,
        values: GeneratedValues,
        resolver: &dyn ResourceResolver,
    ) -> Result<(), DocumentError> {
        let source = &self.source;
        let formatting::Formatted {
            root,
            footnotes,
            navigation,
            strings,
            generated,
            canvas,
            pages,
            svg_definitions,
            page_counters,
            scroll_markers,
            skipped_work,
            diagnostics,
            ..
        } = source.build(
            &mut self.styles,
            values,
            (
                &self.pages.images(),
                &self.element_measurements,
                &self.svg_definitions,
            ),
            resolver,
        )?;
        record_skipped_work(&mut self.diagnostics, skipped_work);
        self.navigation = navigation.finish(&source.html, &generated)?;
        self.running_strings = strings.finish(&source.html)?;
        self.root = root;
        self.footnotes = footnotes;
        self.generated = generated;
        self.canvas = canvas;
        self.pages = pages;
        self.size_first_page()?;
        self.svg_definitions = svg_definitions;
        self.page_counters = page_counters.into_iter().collect();
        self.scroll_markers = scroll_markers;
        for diagnostic in diagnostics {
            self.diagnose(diagnostic);
        }
        for diagnostic in self.styles.take_diagnostics() {
            if !self.diagnostics.iter().any(
                |known| matches!(known, DocumentDiagnostic::Css(known) if *known == diagnostic),
            ) {
                self.diagnostics.push(DocumentDiagnostic::Css(diagnostic));
            }
        }
        Ok(())
    }

    /// Records `diagnostic` of a formatting, unless an earlier formatting reported the limit
    /// it reports.
    fn diagnose(&mut self, diagnostic: DocumentDiagnostic) {
        let repeated = self.diagnostics.iter().any(|known| {
            matches!(
                (known, &diagnostic),
                (
                    DocumentDiagnostic::FormattingLimit {
                        resource: known,
                        fallback: known_fallback,
                        ..
                    },
                    DocumentDiagnostic::FormattingLimit {
                        resource, fallback, ..
                    },
                ) if known == resource && known_fallback == fallback
            )
        });
        if !repeated {
            self.diagnostics.push(diagnostic);
        }
    }

    /// Omits `target`, a formatting box of the document, with the content after it in
    /// document order where `following`; whether the document holds `target`.
    pub(crate) fn omit(&mut self, target: *const BlockBox, following: bool) -> bool {
        std::iter::once(&mut self.root)
            .chain(self.footnotes.bodies.iter_mut().map(|body| &mut body.block))
            .any(|tree| tree.omit(target, following))
            || self
                .running_strings
                .iter_mut()
                .filter_map(|assignment| assignment.element.as_mut())
                .any(|element| element.omit(target, following))
    }

    pub(crate) fn omit_content(&mut self) {
        self.root.omit_content();
        for body in &mut self.footnotes.bodies {
            body.block.omit_content();
        }
        self.running_strings
            .iter_mut()
            .filter_map(|assignment| assignment.element.as_mut())
            .for_each(RunningElement::omit_content);
    }

    /// Retains what the layout of this document degraded.
    pub(crate) fn record_layout(
        &mut self,
        diagnostics: impl IntoIterator<Item = crate::layout::LayoutDiagnostic>,
    ) {
        for diagnostic in diagnostics.into_iter().map(DocumentDiagnostic::Layout) {
            if !self.diagnostics.iter().any(|known| {
                matches!((known, &diagnostic), (DocumentDiagnostic::Layout(known), DocumentDiagnostic::Layout(new)) if known == new)
            }) {
                self.diagnostics.push(diagnostic);
            }
        }
    }

    pub(crate) fn into_diagnostics(mut self) -> Vec<DocumentDiagnostic> {
        self.diagnostics.extend(
            self.styles
                .take_degradations()
                .into_iter()
                .map(DocumentDiagnostic::Degraded),
        );
        self.diagnostics
            .extend(self.source.embedded.take_diagnostics());
        self.diagnostics.extend(
            self.pages
                .images()
                .borrow_mut()
                .take_failures()
                .into_iter()
                .map(DocumentDiagnostic::UnavailableImage),
        );
        self.diagnostics.extend(
            self.styles
                .fonts
                .take_failures()
                .into_iter()
                .map(DocumentDiagnostic::UnavailableFont),
        );
        let limited = self.pages.images().borrow_mut().take_limited();
        for diagnostic in limited {
            self.diagnose(diagnostic);
        }
        self.diagnostics
    }

    /// The first page, sized to the content the last layout measured.
    pub(crate) fn page_box(&self) -> &PageBox {
        &self.first_page
    }

    /// The page at `index`, sized to the content the last layout measured.
    pub(crate) fn sized_page(
        &self,
        page: &std::sync::Arc<PageBox>,
        index: usize,
    ) -> Result<std::sync::Arc<PageBox>, DocumentError> {
        self.page_content.size(
            page,
            index,
            crate::style::logical::Flow::used(self.root.style()),
        )
    }

    pub(crate) fn page_content(&self) -> &PageContent {
        &self.page_content
    }

    /// Later layouts size pages to the content a layout measured.
    pub(crate) fn measured_pages(&mut self, content: PageContent) -> Result<(), DocumentError> {
        self.page_content = content;
        self.size_first_page()
    }

    fn size_first_page(&mut self) -> Result<(), DocumentError> {
        self.first_page = self.sized_page(self.pages.first(), 0)?;
        Ok(())
    }

    /// See [`page::PageProvider::margin_images`].
    pub(crate) fn margin_images(
        &self,
        output: &crate::style::GeneratedOutput,
        style: &crate::style::Style,
        resolver: &dyn ResourceResolver,
    ) -> Vec<inline::GeneratedImage> {
        self.pages.margin_images(output, style, resolver)
    }

    /// See [`page::PageProvider::margin_replacement`].
    pub(crate) fn margin_replacement(
        &self,
        image: &crate::paint::BackgroundImage,
        style: &crate::style::Style,
        resolver: &dyn ResourceResolver,
    ) -> std::sync::Arc<crate::images::Image> {
        self.pages.margin_replacement(image, style, resolver)
    }

    pub(crate) fn resolve_page(
        &self,
        request: crate::style::PageRequest,
        resolver: &dyn ResourceResolver,
    ) -> Result<std::sync::Arc<PageBox>, DocumentError> {
        self.pages
            .resolve(&self.styles, self.root.style(), request, resolver)
    }

    pub(crate) fn root(&self) -> &BlockBox {
        &self.root
    }
    pub(crate) fn root_element(&self) -> crate::dom::ElementId {
        self.source.html.root_element().id()
    }
    pub(crate) fn scroll_marker_groups(&self) -> &scroll_markers::ScrollMarkerGroups {
        &self.scroll_markers
    }
    /// Whether the scroll markers' positions styling took are `states`.
    pub(crate) fn scroll_markers_settled(&self, states: &crate::dom::ScrollMarkerStates) -> bool {
        *self.source.html.scroll_markers.borrow() == *states
    }
    /// Restyling takes the scroll markers' positions a layout determined.
    pub(crate) fn measured_scroll_markers(&self, states: crate::dom::ScrollMarkerStates) {
        *self.source.html.scroll_markers.borrow_mut() = states;
    }
    pub(crate) fn footnotes(&self) -> &Footnotes {
        &self.footnotes
    }
    pub(crate) fn styles(&self) -> &Stylesheet {
        &self.styles
    }
    pub(crate) fn navigation(&self) -> &Navigation {
        &self.navigation
    }
    /// Document-order string assignments with element values captured and page values deferred.
    pub(crate) fn running_strings(&self) -> &[RunningStringAssignment] {
        &self.running_strings
    }
    pub(crate) fn metadata(&self) -> &DocumentMetadata {
        &self.metadata
    }
    /// The document's counters where `page` starts, as its page-margin boxes see them (CSS
    /// Page 3 ยง6.1); none before pagination tells where pages start.
    pub(crate) fn page_counters(&self, page: usize) -> Option<&CounterSnapshot> {
        self.page_counters.get(&page)
    }
    /// The SVG filters and masks that `url()` references in the document can name.
    pub(crate) fn svg_definitions(&self) -> svg::SvgDefinitions {
        self.svg_definitions.clone()
    }
    pub(crate) fn canvas_background(&self) -> &crate::graphics::BoxDecoration {
        &self.canvas
    }
}

#[cfg(test)]
mod tests;