f-office 0.2.4

Renders Office Open XML documents the way Microsoft Office does.
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
//! Typed rendering fidelity summary derived in one place from layout font records and warnings.

use std::collections::{BTreeMap, BTreeSet};

use f_office_docx::{Drawing, MatchedFont, SubstituteLayout, UnicodeBlock, Warning as DocxWarning};
use f_office_warnings::Name;

use crate::{Warning, Warnings};

/// Overall rendering fidelity of a laid-out document.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FidelityLevel {
    /// Every used font matched natively or with an exact metric stand-in, with zero missing
    /// glyphs, skipped content, or visual approximations.
    #[default]
    Exact,
    /// All text and drawings rendered, but at least one font used a fallback or approximate
    /// metrics, or a visual property was approximated (line breaks or appearance may differ).
    Approximate,
    /// Some text, glyphs, drawings, or document parts could not be rendered faithfully.
    Degraded,
}

impl FidelityLevel {
    /// Stable lowercase identifier for serialization across borders.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Exact => "exact",
            Self::Approximate => "approximate",
            Self::Degraded => "degraded",
        }
    }
}

/// How a font family requested by the document was resolved for rendering.
///
/// Ordered from highest severity (`Missing`) to lowest (`Native`) so sorting puts actionable
/// font issues first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FontMatchKind {
    /// No usable face was available (text or font marks were omitted).
    Missing,
    /// Fell back to another family because neither the requested family nor a metric stand-in
    /// was available.
    Fallback,
    /// Substituted with a width-compatible font whose line breaks may still differ.
    Widths,
    /// Substituted with a metric stand-in made for a different version of the requested family.
    OtherVersion,
    /// Substituted with an exact metric stand-in for the requested family and target version.
    ExactStandIn,
    /// Rendered with the requested family's own native face.
    Native,
}

impl FontMatchKind {
    /// Stable kebab-case identifier for serialization across borders.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Missing => "missing",
            Self::Fallback => "fallback",
            Self::Widths => "widths",
            Self::OtherVersion => "other-version",
            Self::ExactStandIn => "exact-stand-in",
            Self::Native => "native",
        }
    }
}

/// Resolution details for one font family requested by the document.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FontStatus {
    /// The family requested by the document (`None` when text named no font).
    pub asked: Option<Name>,
    /// The family that rendered the text (`None` when missing or unknown).
    pub used: Option<Name>,
    /// The resolved face version, when known.
    pub version: Option<Name>,
    /// How the rendered face relates to the requested family.
    pub match_kind: FontMatchKind,
}

/// Missing (`.notdef`) characters grouped by font and coarse Unicode block, with zero raw text.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MissingGlyphGroup {
    /// The font family that rendered `.notdef`, or `None` when unknown.
    pub font: Option<Name>,
    /// Coarse Unicode script or block of the missing characters.
    pub block: UnicodeBlock,
    /// Number of `.notdef` glyphs in this font and block.
    pub count: u32,
}

/// Category of non-font rendering omission or approximation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OmissionKind {
    /// A chart could not be drawn.
    ChartSkipped,
    /// A picture could not be drawn.
    PictureSkipped,
    /// A SmartArt diagram could not be drawn.
    SmartArtSkipped,
    /// A shape could not be drawn.
    ShapeSkipped,
    /// A document part or its relationships could not be read.
    PartSkipped,
    /// A footnote or endnote reference pointed to a missing note.
    NoteMissing,
    /// Complex-script text could not be shaped and fell back to character mapping.
    ScriptNotShaped,
    /// A font file failed to load.
    FontFileNotRead,
    /// An art page border was omitted because its artwork was not provided.
    ArtBorderNotDrawn,
    /// A tight or through wrap polygon fell back to box wrapping.
    WrapApproximated,
    /// A style, effect, or feature value was approximated.
    FeatureApproximated,
    /// A glyph outline could not be measured for ink bounds.
    InkNotMeasured,
    /// A document limit or malformed value triggered a fallback reading.
    DocumentLimitOrInvalid,
    /// A metafile or DrawingML detail was approximated or skipped.
    DrawingDetailSkipped,
}

impl OmissionKind {
    /// Stable kebab-case identifier for serialization across borders.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ChartSkipped => "chart-skipped",
            Self::PictureSkipped => "picture-skipped",
            Self::SmartArtSkipped => "smartart-skipped",
            Self::ShapeSkipped => "shape-skipped",
            Self::PartSkipped => "part-skipped",
            Self::NoteMissing => "note-missing",
            Self::ScriptNotShaped => "script-not-shaped",
            Self::FontFileNotRead => "font-file-not-read",
            Self::ArtBorderNotDrawn => "art-border-not-drawn",
            Self::WrapApproximated => "wrap-approximated",
            Self::FeatureApproximated => "feature-approximated",
            Self::InkNotMeasured => "ink-not-measured",
            Self::DocumentLimitOrInvalid => "document-limit-or-invalid",
            Self::DrawingDetailSkipped => "drawing-detail-skipped",
        }
    }

    /// Human-readable plural label for UI display.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::ChartSkipped => "Skipped charts",
            Self::PictureSkipped => "Skipped pictures",
            Self::SmartArtSkipped => "Skipped SmartArt diagrams",
            Self::ShapeSkipped => "Skipped shapes",
            Self::PartSkipped => "Skipped document parts",
            Self::NoteMissing => "Missing footnote or endnote targets",
            Self::ScriptNotShaped => "Unshaped complex-script runs",
            Self::FontFileNotRead => "Unreadable font files",
            Self::ArtBorderNotDrawn => "Omitted art page borders",
            Self::WrapApproximated => "Approximated wrap polygons",
            Self::FeatureApproximated => "Approximated styles or features",
            Self::InkNotMeasured => "Unmeasured glyph ink bounds",
            Self::DocumentLimitOrInvalid => "Malformed values or document limits",
            Self::DrawingDetailSkipped => "Approximated vector or DrawingML details",
        }
    }

    /// Whether this omission represents missing or unrendered content (`Degraded`) rather than
    /// an approximation (`Approximate`).
    #[must_use]
    pub const fn is_degraded(self) -> bool {
        matches!(
            self,
            Self::ChartSkipped
                | Self::PictureSkipped
                | Self::SmartArtSkipped
                | Self::ShapeSkipped
                | Self::PartSkipped
                | Self::NoteMissing
                | Self::ScriptNotShaped
                | Self::FontFileNotRead
        )
    }
}

/// Counted summary of one category of rendering omission or approximation.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Omission {
    /// Category of omission or approximation.
    pub kind: OmissionKind,
    /// Total occurrences across the document.
    pub count: u32,
    /// Whether this omission causes `FidelityLevel::Degraded`.
    pub degraded: bool,
}

/// Complete typed rendering fidelity report for a laid-out document.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FidelityReport {
    /// Overall fidelity tier (`Exact`, `Approximate`, or `Degraded`).
    pub level: FidelityLevel,
    /// Every font requested by the document, sorted worst-first (`Missing` -> `Native`).
    pub fonts: Vec<FontStatus>,
    /// Rendered `.notdef` characters grouped by font and Unicode block.
    pub missing_glyphs: Vec<MissingGlyphGroup>,
    /// Counted non-font omissions and approximations.
    pub omissions: Vec<Omission>,
}

impl FidelityReport {
    /// Derives one typed fidelity report from native font matches and accumulated warnings.
    #[must_use]
    pub(crate) fn from_parts(matched_fonts: &[MatchedFont], warnings: &Warnings) -> Self {
        let mut fonts = Vec::new();
        let mut seen_fonts: BTreeSet<(Option<String>, Option<String>, FontMatchKind)> =
            BTreeSet::new();
        let mut non_native_asked: BTreeSet<String> = BTreeSet::new();
        let mut missing_glyph_counts: BTreeMap<(Option<Name>, UnicodeBlock), u32> = BTreeMap::new();
        let mut omission_counts: BTreeMap<OmissionKind, u32> = BTreeMap::new();

        for (warning, count) in warnings.iter() {
            classify_warning(
                warning,
                count,
                &mut fonts,
                &mut seen_fonts,
                &mut non_native_asked,
                &mut missing_glyph_counts,
                &mut omission_counts,
            );
        }

        for matched in matched_fonts {
            let key_asked = matched.asked.as_str().to_ascii_lowercase();
            if non_native_asked.contains(&key_asked) {
                continue;
            }
            push_font(
                FontStatus {
                    asked: Some(matched.asked.clone()),
                    used: matched.used.clone(),
                    version: matched.version.clone(),
                    match_kind: FontMatchKind::Native,
                },
                &mut fonts,
                &mut seen_fonts,
            );
        }

        fonts.sort_by(|a, b| {
            a.match_kind
                .cmp(&b.match_kind)
                .then_with(|| lower_opt(a.asked.as_ref()).cmp(&lower_opt(b.asked.as_ref())))
                .then_with(|| lower_opt(a.used.as_ref()).cmp(&lower_opt(b.used.as_ref())))
        });

        let mut missing_glyphs: Vec<MissingGlyphGroup> = missing_glyph_counts
            .into_iter()
            .map(|((font, block), count)| MissingGlyphGroup { font, block, count })
            .collect();
        missing_glyphs.sort_by(|a, b| {
            b.count
                .cmp(&a.count)
                .then_with(|| lower_opt(a.font.as_ref()).cmp(&lower_opt(b.font.as_ref())))
                .then_with(|| a.block.cmp(&b.block))
        });

        let mut omissions: Vec<Omission> = omission_counts
            .into_iter()
            .map(|(kind, count)| Omission {
                kind,
                count,
                degraded: kind.is_degraded(),
            })
            .collect();
        omissions.sort_by(|a, b| {
            b.degraded
                .cmp(&a.degraded)
                .then_with(|| a.kind.cmp(&b.kind))
        });

        let level = compute_level(&fonts, &missing_glyphs, &omissions);
        Self {
            level,
            fonts,
            missing_glyphs,
            omissions,
        }
    }
}

fn lower_opt(name: Option<&Name>) -> String {
    name.map_or_default(|n| n.as_str().to_ascii_lowercase())
}

fn push_font(
    status: FontStatus,
    out: &mut Vec<FontStatus>,
    seen: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
) {
    let key = (
        status
            .asked
            .as_ref()
            .map(|n| n.as_str().to_ascii_lowercase()),
        status
            .used
            .as_ref()
            .map(|n| n.as_str().to_ascii_lowercase()),
        status.match_kind,
    );
    if seen.insert(key) {
        out.push(status);
    }
}

fn add_omission(omissions: &mut BTreeMap<OmissionKind, u32>, kind: OmissionKind, count: u32) {
    omissions
        .entry(kind)
        .and_modify(|existing| *existing = existing.saturating_add(count))
        .or_insert(count);
}

fn classify_warning(
    warning: &Warning,
    count: u32,
    fonts: &mut Vec<FontStatus>,
    seen_fonts: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
    non_native_asked: &mut BTreeSet<String>,
    missing_glyphs: &mut BTreeMap<(Option<Name>, UnicodeBlock), u32>,
    omissions: &mut BTreeMap<OmissionKind, u32>,
) {
    match warning {
        Warning::Docx(docx) => classify_docx_warning(
            docx,
            count,
            fonts,
            seen_fonts,
            non_native_asked,
            missing_glyphs,
            omissions,
        ),
        Warning::Pdf(_) => add_omission(omissions, OmissionKind::DrawingDetailSkipped, count),
        Warning::PictureNotWrittenAgain { .. } => {
            add_omission(omissions, OmissionKind::FeatureApproximated, count);
        }
        Warning::SignatureBroken | Warning::NoteKept => {}
    }
}

fn classify_docx_warning(
    warning: &DocxWarning,
    count: u32,
    fonts: &mut Vec<FontStatus>,
    seen_fonts: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
    non_native_asked: &mut BTreeSet<String>,
    missing_glyphs: &mut BTreeMap<(Option<Name>, UnicodeBlock), u32>,
    omissions: &mut BTreeMap<OmissionKind, u32>,
) {
    match warning {
        DocxWarning::FontSubstituted {
            asked,
            used,
            version,
            layout,
        } => {
            let match_kind = match layout {
                SubstituteLayout::Exact => FontMatchKind::ExactStandIn,
                SubstituteLayout::OtherVersion { .. } => FontMatchKind::OtherVersion,
                SubstituteLayout::Fallback => FontMatchKind::Fallback,
                _ => FontMatchKind::Widths,
            };
            non_native_asked.insert(asked.as_str().to_ascii_lowercase());
            push_font(
                FontStatus {
                    asked: Some(asked.clone()),
                    used: used.clone(),
                    version: version.clone(),
                    match_kind,
                },
                fonts,
                seen_fonts,
            );
        }
        DocxWarning::TextNotDrawn { asked, .. } | DocxWarning::FontNotFound { asked, .. } => {
            if let Some(name) = asked {
                non_native_asked.insert(name.as_str().to_ascii_lowercase());
            }
            push_font(
                FontStatus {
                    asked: asked.clone(),
                    used: None,
                    version: None,
                    match_kind: FontMatchKind::Missing,
                },
                fonts,
                seen_fonts,
            );
        }
        DocxWarning::GlyphMissing {
            font,
            block,
            count: glyph_count,
        } => {
            let total = glyph_count.saturating_mul(count);
            missing_glyphs
                .entry((font.clone(), *block))
                .and_modify(|existing| *existing = existing.saturating_add(total))
                .or_insert(total);
        }
        DocxWarning::DrawingSkipped { drawing, .. } => {
            let kind = match drawing {
                Drawing::Chart => OmissionKind::ChartSkipped,
                Drawing::Picture => OmissionKind::PictureSkipped,
                Drawing::SmartArt => OmissionKind::SmartArtSkipped,
                _ => OmissionKind::ShapeSkipped,
            };
            add_omission(omissions, kind, count);
        }
        other => {
            if let Some(kind) = omission_kind_of(other) {
                add_omission(omissions, kind, count);
            }
        }
    }
}

fn omission_kind_of(warning: &DocxWarning) -> Option<OmissionKind> {
    Some(match warning {
        DocxWarning::PartSkipped { .. } | DocxWarning::RelationshipsSkipped { .. } => {
            OmissionKind::PartSkipped
        }
        DocxWarning::NoteMissing { .. } => OmissionKind::NoteMissing,
        DocxWarning::ScriptNotShaped { .. } => OmissionKind::ScriptNotShaped,
        DocxWarning::FontFileNotRead { .. } => OmissionKind::FontFileNotRead,
        DocxWarning::ArtBorderNotDrawn { .. } => OmissionKind::ArtBorderNotDrawn,
        DocxWarning::WrapPolygonSkipped { .. } => OmissionKind::WrapApproximated,
        DocxWarning::ValueNotSupported { .. } | DocxWarning::FeatureNotSupported { .. } => {
            OmissionKind::FeatureApproximated
        }
        DocxWarning::InkNotMeasured { .. } => OmissionKind::InkNotMeasured,
        DocxWarning::InvalidValue { .. }
        | DocxWarning::NoteIdRepeated { .. }
        | DocxWarning::UndeclaredPrefix { .. }
        | DocxWarning::LimitReached { .. } => OmissionKind::DocumentLimitOrInvalid,
        DocxWarning::Metafile { .. } | DocxWarning::DrawingMl { .. } => {
            OmissionKind::DrawingDetailSkipped
        }
        _ => return None,
    })
}

fn compute_level(
    fonts: &[FontStatus],
    missing_glyphs: &[MissingGlyphGroup],
    omissions: &[Omission],
) -> FidelityLevel {
    let degraded = !missing_glyphs.is_empty()
        || fonts
            .iter()
            .any(|font| font.match_kind == FontMatchKind::Missing)
        || omissions.iter().any(|omission| omission.degraded);
    if degraded {
        return FidelityLevel::Degraded;
    }
    let approximate = !omissions.is_empty()
        || fonts.iter().any(|font| {
            matches!(
                font.match_kind,
                FontMatchKind::Fallback | FontMatchKind::Widths | FontMatchKind::OtherVersion
            )
        });
    if approximate {
        FidelityLevel::Approximate
    } else {
        FidelityLevel::Exact
    }
}

#[cfg(test)]
mod tests {
    use f_office_docx::testing::{self, WordParts as _};
    use f_office_docx::{Drawing, MatchedFont, Reason, SubstituteLayout, UnicodeBlock};
    use f_office_warnings::Name;

    use super::{
        FidelityLevel, FidelityReport, FontMatchKind, FontStatus, MissingGlyphGroup, Omission,
        OmissionKind,
    };
    use crate::test_fonts::{CARLITO_RUN, carlito};
    use crate::{Document, FontDb, Options, Warning, Warnings};

    fn docx_with(body: &str, theme: bool) -> Vec<u8> {
        let mut pkg = testing::docx(body).plain_styles();
        if theme {
            pkg = pkg
                .relationship(testing::DOCUMENT, "th", "theme", "theme/theme1.xml")
                .part(
                    "word/theme/theme1.xml",
                    r#"<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:themeElements><a:fontScheme name="Test"><a:majorFont><a:latin typeface="Calibri"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#,
                );
        }
        pkg.zip().unwrap()
    }

    #[test]
    fn custom_uninstalled_font_falling_back_to_carlito_is_fallback_not_exact() {
        let rpr = r#"<w:rPr><w:rFonts w:ascii="MyBrandFont" w:hAnsi="MyBrandFont"/></w:rPr>"#;
        let body =
            format!("<w:p><w:pPr>{rpr}</w:pPr><w:r>{rpr}<w:t>Hello custom font</w:t></w:r></w:p>");
        let bytes = docx_with(&body, true);
        let fonts = carlito();
        let opened = Document::open(&bytes, &fonts, &Options::base()).unwrap();
        let report = opened.value.fidelity();

        assert_eq!(report.level, FidelityLevel::Approximate, "{report:?}");
        let custom = report
            .fonts
            .iter()
            .find(|font| font.asked.as_ref().map(Name::as_str) == Some("MyBrandFont"))
            .expect("MyBrandFont must appear in fidelity report");
        assert_eq!(custom.match_kind, FontMatchKind::Fallback);
        assert_ne!(custom.match_kind, FontMatchKind::ExactStandIn);
        assert_eq!(custom.used.as_ref().map(Name::as_str), Some("Carlito"));
    }

    #[test]
    fn native_font_reports_exact_and_native_match_kind() {
        let body = format!(
            "<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:t>Native Carlito text</w:t></w:r></w:p>"
        );
        let bytes = docx_with(&body, false);
        let fonts = carlito();
        let mut options = Options::base();
        options
            .configuration
            .fonts
            .installed
            .insert("Carlito".to_owned(), true);
        let opened = Document::open(&bytes, &fonts, &options).unwrap();
        let report = opened.value.fidelity();

        assert_eq!(report.level, FidelityLevel::Exact, "{report:?}");
        assert_eq!(report.missing_glyphs, []);
        assert_eq!(report.omissions, []);
        assert!(report.fonts.iter().any(|font| {
            font.asked.as_ref().map(Name::as_str) == Some("Carlito")
                && font.used.as_ref().map(Name::as_str) == Some("Carlito")
                && font.match_kind == FontMatchKind::Native
        }));
    }

    #[test]
    fn missing_notdef_glyphs_report_degraded_without_leaking_text() {
        let secret_cjk = "漢字";
        let body = format!(
            "<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:t>Hello {secret_cjk}</w:t></w:r></w:p>"
        );
        let bytes = docx_with(&body, false);
        let fonts = carlito();
        let mut options = Options::base();
        options
            .configuration
            .fonts
            .installed
            .insert("Carlito".to_owned(), true);
        let opened = Document::open(&bytes, &fonts, &options).unwrap();

        // Warning::GlyphMissing must never contain raw document text.
        let glyph_warnings: Vec<_> = opened
            .warnings
            .iter()
            .filter_map(|(warning, _)| match warning {
                Warning::Docx(f_office_docx::Warning::GlyphMissing { font, block, count }) => {
                    assert!(!warning.to_string().contains(secret_cjk));
                    Some((font.clone(), *block, *count))
                }
                _ => None,
            })
            .collect();
        assert_eq!(
            glyph_warnings,
            vec![(Some(Name::new("Carlito")), UnicodeBlock::Cjk, 2)]
        );

        let report = opened.value.fidelity();
        assert_eq!(report.level, FidelityLevel::Degraded);
        assert_eq!(
            report.missing_glyphs,
            vec![MissingGlyphGroup {
                font: Some(Name::new("Carlito")),
                block: UnicodeBlock::Cjk,
                count: 2,
            }]
        );
    }

    #[test]
    fn missing_font_with_empty_font_db_reports_degraded_missing() {
        let rpr = r#"<w:rPr><w:rFonts w:ascii="MyBrandFont" w:hAnsi="MyBrandFont"/></w:rPr>"#;
        let body =
            format!("<w:p><w:pPr>{rpr}</w:pPr><w:r>{rpr}<w:t>No fonts loaded</w:t></w:r></w:p>");
        let bytes = docx_with(&body, false);
        let opened = Document::open(&bytes, &FontDb::new(), &Options::base()).unwrap();
        let report = opened.value.fidelity();

        assert_eq!(report.level, FidelityLevel::Degraded);
        assert_eq!(report.fonts[0].match_kind, FontMatchKind::Missing);
        assert_eq!(
            report.fonts[0].asked.as_ref().map(Name::as_str),
            Some("MyBrandFont")
        );
    }

    #[test]
    fn sorts_fonts_worst_first_and_aggregates_omissions() {
        let mut warnings = Warnings::new();
        warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
            asked: Name::new("Arial"),
            used: Some(Name::new("Arimo CF")),
            version: Some(Name::new("7.06.1")),
            layout: SubstituteLayout::Exact,
        }));
        warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
            asked: Name::new("BrandSans"),
            used: Some(Name::new("Carlito CF")),
            version: Some(Name::new("1.103")),
            layout: SubstituteLayout::Fallback,
        }));
        warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
            asked: Name::new("Georgia"),
            used: Some(Name::new("Gelasio")),
            version: None,
            layout: SubstituteLayout::Widths,
        }));
        warnings.push(Warning::Docx(f_office_docx::Warning::TextNotDrawn {
            asked: Some(Name::new("AbsentFont")),
            tried: vec![Name::new("AbsentFont")],
        }));
        warnings.push(Warning::Docx(f_office_docx::Warning::DrawingSkipped {
            drawing: Drawing::Chart,
            part: Name::new("word/document.xml"),
            reason: Reason::Unsupported,
        }));
        warnings.push(Warning::Docx(f_office_docx::Warning::ArtBorderNotDrawn {
            style: "apples",
            size: 12,
        }));

        let matched = vec![
            MatchedFont {
                asked: Name::new("Carlito"),
                used: Some(Name::new("Carlito")),
                version: Some(Name::new("1.103")),
            },
            // Redundant native entry for a family that also has a substitution is deduplicated.
            MatchedFont {
                asked: Name::new("Arial"),
                used: Some(Name::new("Arial")),
                version: None,
            },
        ];

        let report = FidelityReport::from_parts(&matched, &warnings);
        assert_eq!(report.level, FidelityLevel::Degraded);
        let kinds: Vec<FontMatchKind> = report.fonts.iter().map(|f| f.match_kind).collect();
        assert_eq!(
            kinds,
            vec![
                FontMatchKind::Missing,
                FontMatchKind::Fallback,
                FontMatchKind::Widths,
                FontMatchKind::ExactStandIn,
                FontMatchKind::Native,
            ]
        );
        assert_eq!(
            report.fonts[0],
            FontStatus {
                asked: Some(Name::new("AbsentFont")),
                used: None,
                version: None,
                match_kind: FontMatchKind::Missing,
            }
        );
        assert_eq!(
            report.omissions,
            vec![
                Omission {
                    kind: OmissionKind::ChartSkipped,
                    count: 1,
                    degraded: true,
                },
                Omission {
                    kind: OmissionKind::ArtBorderNotDrawn,
                    count: 1,
                    degraded: false,
                },
            ]
        );
    }
}