Skip to main content

f_office/
fidelity.rs

1//! Typed rendering fidelity summary derived in one place from layout font records and warnings.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use f_office_docx::{Drawing, MatchedFont, SubstituteLayout, UnicodeBlock, Warning as DocxWarning};
6use f_office_warnings::Name;
7
8use crate::{Warning, Warnings};
9
10/// Overall rendering fidelity of a laid-out document.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub enum FidelityLevel {
13    /// Every used font matched natively or with an exact metric stand-in, with zero missing
14    /// glyphs, skipped content, or visual approximations.
15    #[default]
16    Exact,
17    /// All text and drawings rendered, but at least one font used a fallback or approximate
18    /// metrics, or a visual property was approximated (line breaks or appearance may differ).
19    Approximate,
20    /// Some text, glyphs, drawings, or document parts could not be rendered faithfully.
21    Degraded,
22}
23
24impl FidelityLevel {
25    /// Stable lowercase identifier for serialization across borders.
26    #[must_use]
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::Exact => "exact",
30            Self::Approximate => "approximate",
31            Self::Degraded => "degraded",
32        }
33    }
34}
35
36/// How a font family requested by the document was resolved for rendering.
37///
38/// Ordered from highest severity (`Missing`) to lowest (`Native`) so sorting puts actionable
39/// font issues first.
40#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub enum FontMatchKind {
42    /// No usable face was available (text or font marks were omitted).
43    Missing,
44    /// Fell back to another family because neither the requested family nor a metric stand-in
45    /// was available.
46    Fallback,
47    /// Substituted with an unverified or approximate width-compatible font whose line breaks may
48    /// still differ.
49    Widths,
50    /// Substituted with a metric stand-in made for a different version of the requested family.
51    OtherVersion,
52    /// Substituted with a verified metric-compatible stand-in whose advance widths and line
53    /// metrics match the requested family and target version.
54    MetricStandIn,
55    /// Substituted with an exact layout stand-in for the requested family and target version.
56    ExactStandIn,
57    /// Rendered with the requested family's own native face.
58    Native,
59}
60
61impl FontMatchKind {
62    /// Stable kebab-case identifier for serialization across borders.
63    #[must_use]
64    pub const fn as_str(self) -> &'static str {
65        match self {
66            Self::Missing => "missing",
67            Self::Fallback => "fallback",
68            Self::Widths => "widths",
69            Self::OtherVersion => "other-version",
70            Self::MetricStandIn => "metric-stand-in",
71            Self::ExactStandIn => "exact-stand-in",
72            Self::Native => "native",
73        }
74    }
75}
76
77/// Resolution details for one font family requested by the document.
78#[derive(Clone, Debug, PartialEq, Eq, Hash)]
79pub struct FontStatus {
80    /// The family requested by the document (`None` when text named no font).
81    pub asked: Option<Name>,
82    /// The family that rendered the text (`None` when missing or unknown).
83    pub used: Option<Name>,
84    /// The resolved face version, when known.
85    pub version: Option<Name>,
86    /// How the rendered face relates to the requested family.
87    pub match_kind: FontMatchKind,
88}
89
90/// Missing (`.notdef`) characters grouped by font and coarse Unicode block, with zero raw text.
91#[derive(Clone, Debug, PartialEq, Eq, Hash)]
92pub struct MissingGlyphGroup {
93    /// The font family that rendered `.notdef`, or `None` when unknown.
94    pub font: Option<Name>,
95    /// Coarse Unicode script or block of the missing characters.
96    pub block: UnicodeBlock,
97    /// Number of `.notdef` glyphs in this font and block.
98    pub count: u32,
99}
100
101/// Category of non-font rendering omission or approximation.
102#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
103pub enum OmissionKind {
104    /// A chart could not be drawn.
105    ChartSkipped,
106    /// A picture could not be drawn.
107    PictureSkipped,
108    /// A SmartArt diagram could not be drawn.
109    SmartArtSkipped,
110    /// A shape could not be drawn.
111    ShapeSkipped,
112    /// A document part or its relationships could not be read.
113    PartSkipped,
114    /// A footnote or endnote reference pointed to a missing note.
115    NoteMissing,
116    /// Complex-script text could not be shaped and fell back to character mapping.
117    ScriptNotShaped,
118    /// A font file failed to load.
119    FontFileNotRead,
120    /// An art page border was omitted because its artwork was not provided.
121    ArtBorderNotDrawn,
122    /// A tight or through wrap polygon fell back to box wrapping.
123    WrapApproximated,
124    /// A style, effect, or feature value was approximated.
125    FeatureApproximated,
126    /// A glyph outline could not be measured for ink bounds.
127    InkNotMeasured,
128    /// A document limit or malformed value triggered a fallback reading.
129    DocumentLimitOrInvalid,
130    /// A metafile or DrawingML detail was approximated or skipped.
131    DrawingDetailSkipped,
132}
133
134impl OmissionKind {
135    /// Stable kebab-case identifier for serialization across borders.
136    #[must_use]
137    pub const fn as_str(self) -> &'static str {
138        match self {
139            Self::ChartSkipped => "chart-skipped",
140            Self::PictureSkipped => "picture-skipped",
141            Self::SmartArtSkipped => "smartart-skipped",
142            Self::ShapeSkipped => "shape-skipped",
143            Self::PartSkipped => "part-skipped",
144            Self::NoteMissing => "note-missing",
145            Self::ScriptNotShaped => "script-not-shaped",
146            Self::FontFileNotRead => "font-file-not-read",
147            Self::ArtBorderNotDrawn => "art-border-not-drawn",
148            Self::WrapApproximated => "wrap-approximated",
149            Self::FeatureApproximated => "feature-approximated",
150            Self::InkNotMeasured => "ink-not-measured",
151            Self::DocumentLimitOrInvalid => "document-limit-or-invalid",
152            Self::DrawingDetailSkipped => "drawing-detail-skipped",
153        }
154    }
155
156    /// Human-readable plural label for UI display.
157    #[must_use]
158    pub const fn label(self) -> &'static str {
159        match self {
160            Self::ChartSkipped => "Skipped charts",
161            Self::PictureSkipped => "Skipped pictures",
162            Self::SmartArtSkipped => "Skipped SmartArt diagrams",
163            Self::ShapeSkipped => "Skipped shapes",
164            Self::PartSkipped => "Skipped document parts",
165            Self::NoteMissing => "Missing footnote or endnote targets",
166            Self::ScriptNotShaped => "Unshaped complex-script runs",
167            Self::FontFileNotRead => "Unreadable font files",
168            Self::ArtBorderNotDrawn => "Omitted art page borders",
169            Self::WrapApproximated => "Approximated wrap polygons",
170            Self::FeatureApproximated => "Approximated styles or features",
171            Self::InkNotMeasured => "Unmeasured glyph ink bounds",
172            Self::DocumentLimitOrInvalid => "Malformed values or document limits",
173            Self::DrawingDetailSkipped => "Approximated vector or DrawingML details",
174        }
175    }
176
177    /// Whether this omission represents missing or unrendered content (`Degraded`) rather than
178    /// an approximation (`Approximate`).
179    #[must_use]
180    pub const fn is_degraded(self) -> bool {
181        matches!(
182            self,
183            Self::ChartSkipped
184                | Self::PictureSkipped
185                | Self::SmartArtSkipped
186                | Self::ShapeSkipped
187                | Self::PartSkipped
188                | Self::NoteMissing
189                | Self::ScriptNotShaped
190                | Self::FontFileNotRead
191        )
192    }
193}
194
195/// Counted summary of one category of rendering omission or approximation.
196#[derive(Clone, Debug, PartialEq, Eq, Hash)]
197pub struct Omission {
198    /// Category of omission or approximation.
199    pub kind: OmissionKind,
200    /// Total occurrences across the document.
201    pub count: u32,
202    /// Whether this omission causes `FidelityLevel::Degraded`.
203    pub degraded: bool,
204}
205
206/// Complete typed rendering fidelity report for a laid-out document.
207#[derive(Clone, Debug, Default, PartialEq, Eq)]
208pub struct FidelityReport {
209    /// Overall fidelity tier (`Exact`, `Approximate`, or `Degraded`).
210    pub level: FidelityLevel,
211    /// Every font requested by the document, sorted worst-first (`Missing` -> `Native`).
212    pub fonts: Vec<FontStatus>,
213    /// Rendered `.notdef` characters grouped by font and Unicode block.
214    pub missing_glyphs: Vec<MissingGlyphGroup>,
215    /// Counted non-font omissions and approximations.
216    pub omissions: Vec<Omission>,
217}
218
219impl FidelityReport {
220    /// Derives one typed fidelity report from native font matches and accumulated warnings.
221    #[must_use]
222    pub(crate) fn from_parts(matched_fonts: &[MatchedFont], warnings: &Warnings) -> Self {
223        let mut fonts = Vec::new();
224        let mut seen_fonts: BTreeSet<(Option<String>, Option<String>, FontMatchKind)> =
225            BTreeSet::new();
226        let mut non_native_asked: BTreeSet<String> = BTreeSet::new();
227        let mut missing_glyph_counts: BTreeMap<(Option<Name>, UnicodeBlock), u32> = BTreeMap::new();
228        let mut omission_counts: BTreeMap<OmissionKind, u32> = BTreeMap::new();
229
230        for (warning, count) in warnings.iter() {
231            classify_warning(
232                warning,
233                count,
234                &mut fonts,
235                &mut seen_fonts,
236                &mut non_native_asked,
237                &mut missing_glyph_counts,
238                &mut omission_counts,
239            );
240        }
241
242        for matched in matched_fonts {
243            let key_asked = matched.asked.as_str().to_ascii_lowercase();
244            if non_native_asked.contains(&key_asked) {
245                continue;
246            }
247            push_font(
248                FontStatus {
249                    asked: Some(matched.asked.clone()),
250                    used: matched.used.clone(),
251                    version: matched.version.clone(),
252                    match_kind: FontMatchKind::Native,
253                },
254                &mut fonts,
255                &mut seen_fonts,
256            );
257        }
258
259        fonts.sort_by(|a, b| {
260            a.match_kind
261                .cmp(&b.match_kind)
262                .then_with(|| lower_opt(a.asked.as_ref()).cmp(&lower_opt(b.asked.as_ref())))
263                .then_with(|| lower_opt(a.used.as_ref()).cmp(&lower_opt(b.used.as_ref())))
264        });
265
266        let mut missing_glyphs: Vec<MissingGlyphGroup> = missing_glyph_counts
267            .into_iter()
268            .map(|((font, block), count)| MissingGlyphGroup { font, block, count })
269            .collect();
270        missing_glyphs.sort_by(|a, b| {
271            b.count
272                .cmp(&a.count)
273                .then_with(|| lower_opt(a.font.as_ref()).cmp(&lower_opt(b.font.as_ref())))
274                .then_with(|| a.block.cmp(&b.block))
275        });
276
277        let mut omissions: Vec<Omission> = omission_counts
278            .into_iter()
279            .map(|(kind, count)| Omission {
280                kind,
281                count,
282                degraded: kind.is_degraded(),
283            })
284            .collect();
285        omissions.sort_by(|a, b| {
286            b.degraded
287                .cmp(&a.degraded)
288                .then_with(|| a.kind.cmp(&b.kind))
289        });
290
291        let level = compute_level(&fonts, &missing_glyphs, &omissions);
292        Self {
293            level,
294            fonts,
295            missing_glyphs,
296            omissions,
297        }
298    }
299}
300
301fn lower_opt(name: Option<&Name>) -> String {
302    name.map_or_default(|n| n.as_str().to_ascii_lowercase())
303}
304
305fn push_font(
306    status: FontStatus,
307    out: &mut Vec<FontStatus>,
308    seen: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
309) {
310    let key = (
311        status
312            .asked
313            .as_ref()
314            .map(|n| n.as_str().to_ascii_lowercase()),
315        status
316            .used
317            .as_ref()
318            .map(|n| n.as_str().to_ascii_lowercase()),
319        status.match_kind,
320    );
321    if seen.insert(key) {
322        out.push(status);
323    }
324}
325
326fn add_omission(omissions: &mut BTreeMap<OmissionKind, u32>, kind: OmissionKind, count: u32) {
327    omissions
328        .entry(kind)
329        .and_modify(|existing| *existing = existing.saturating_add(count))
330        .or_insert(count);
331}
332
333fn classify_warning(
334    warning: &Warning,
335    count: u32,
336    fonts: &mut Vec<FontStatus>,
337    seen_fonts: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
338    non_native_asked: &mut BTreeSet<String>,
339    missing_glyphs: &mut BTreeMap<(Option<Name>, UnicodeBlock), u32>,
340    omissions: &mut BTreeMap<OmissionKind, u32>,
341) {
342    match warning {
343        Warning::Docx(docx) => classify_docx_warning(
344            docx,
345            count,
346            fonts,
347            seen_fonts,
348            non_native_asked,
349            missing_glyphs,
350            omissions,
351        ),
352        Warning::Pdf(_) => add_omission(omissions, OmissionKind::DrawingDetailSkipped, count),
353        Warning::PictureNotWrittenAgain { .. } => {
354            add_omission(omissions, OmissionKind::FeatureApproximated, count);
355        }
356        Warning::SignatureBroken | Warning::NoteKept => {}
357    }
358}
359
360fn classify_docx_warning(
361    warning: &DocxWarning,
362    count: u32,
363    fonts: &mut Vec<FontStatus>,
364    seen_fonts: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
365    non_native_asked: &mut BTreeSet<String>,
366    missing_glyphs: &mut BTreeMap<(Option<Name>, UnicodeBlock), u32>,
367    omissions: &mut BTreeMap<OmissionKind, u32>,
368) {
369    match warning {
370        DocxWarning::FontSubstituted {
371            asked,
372            used,
373            version,
374            layout,
375        } => {
376            let match_kind = match layout {
377                SubstituteLayout::Exact => FontMatchKind::ExactStandIn,
378                SubstituteLayout::Metrics => FontMatchKind::MetricStandIn,
379                SubstituteLayout::OtherVersion { .. } => FontMatchKind::OtherVersion,
380                SubstituteLayout::Fallback => FontMatchKind::Fallback,
381                _ => FontMatchKind::Widths,
382            };
383            non_native_asked.insert(asked.as_str().to_ascii_lowercase());
384            push_font(
385                FontStatus {
386                    asked: Some(asked.clone()),
387                    used: used.clone(),
388                    version: version.clone(),
389                    match_kind,
390                },
391                fonts,
392                seen_fonts,
393            );
394        }
395        DocxWarning::TextNotDrawn { asked, .. } | DocxWarning::FontNotFound { asked, .. } => {
396            if let Some(name) = asked {
397                non_native_asked.insert(name.as_str().to_ascii_lowercase());
398            }
399            push_font(
400                FontStatus {
401                    asked: asked.clone(),
402                    used: None,
403                    version: None,
404                    match_kind: FontMatchKind::Missing,
405                },
406                fonts,
407                seen_fonts,
408            );
409        }
410        DocxWarning::GlyphMissing {
411            font,
412            block,
413            count: glyph_count,
414        } => {
415            let total = glyph_count.saturating_mul(count);
416            missing_glyphs
417                .entry((font.clone(), *block))
418                .and_modify(|existing| *existing = existing.saturating_add(total))
419                .or_insert(total);
420        }
421        DocxWarning::DrawingSkipped { drawing, .. } => {
422            let kind = match drawing {
423                Drawing::Chart => OmissionKind::ChartSkipped,
424                Drawing::Picture => OmissionKind::PictureSkipped,
425                Drawing::SmartArt => OmissionKind::SmartArtSkipped,
426                _ => OmissionKind::ShapeSkipped,
427            };
428            add_omission(omissions, kind, count);
429        }
430        other => {
431            if let Some(kind) = omission_kind_of(other) {
432                add_omission(omissions, kind, count);
433            }
434        }
435    }
436}
437
438fn omission_kind_of(warning: &DocxWarning) -> Option<OmissionKind> {
439    Some(match warning {
440        DocxWarning::PartSkipped { .. } | DocxWarning::RelationshipsSkipped { .. } => {
441            OmissionKind::PartSkipped
442        }
443        DocxWarning::NoteMissing { .. } => OmissionKind::NoteMissing,
444        DocxWarning::ScriptNotShaped { .. } => OmissionKind::ScriptNotShaped,
445        DocxWarning::FontFileNotRead { .. } => OmissionKind::FontFileNotRead,
446        DocxWarning::ArtBorderNotDrawn { .. } => OmissionKind::ArtBorderNotDrawn,
447        DocxWarning::WrapPolygonSkipped { .. } => OmissionKind::WrapApproximated,
448        DocxWarning::ValueNotSupported { .. } | DocxWarning::FeatureNotSupported { .. } => {
449            OmissionKind::FeatureApproximated
450        }
451        DocxWarning::InkNotMeasured { .. } => OmissionKind::InkNotMeasured,
452        DocxWarning::InvalidValue { .. }
453        | DocxWarning::NoteIdRepeated { .. }
454        | DocxWarning::UndeclaredPrefix { .. }
455        | DocxWarning::LimitReached { .. } => OmissionKind::DocumentLimitOrInvalid,
456        DocxWarning::Metafile { .. } | DocxWarning::DrawingMl { .. } => {
457            OmissionKind::DrawingDetailSkipped
458        }
459        _ => return None,
460    })
461}
462
463fn compute_level(
464    fonts: &[FontStatus],
465    missing_glyphs: &[MissingGlyphGroup],
466    omissions: &[Omission],
467) -> FidelityLevel {
468    let degraded = !missing_glyphs.is_empty()
469        || fonts
470            .iter()
471            .any(|font| font.match_kind == FontMatchKind::Missing)
472        || omissions.iter().any(|omission| omission.degraded);
473    if degraded {
474        return FidelityLevel::Degraded;
475    }
476    let approximate = !omissions.is_empty()
477        || fonts.iter().any(|font| {
478            matches!(
479                font.match_kind,
480                FontMatchKind::Fallback | FontMatchKind::Widths | FontMatchKind::OtherVersion
481            )
482        });
483    if approximate {
484        FidelityLevel::Approximate
485    } else {
486        FidelityLevel::Exact
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use f_office_docx::testing::{self, WordParts as _};
493    use f_office_docx::{Drawing, MatchedFont, Reason, SubstituteLayout, UnicodeBlock};
494    use f_office_warnings::Name;
495
496    use super::{
497        FidelityLevel, FidelityReport, FontMatchKind, FontStatus, MissingGlyphGroup, Omission,
498        OmissionKind,
499    };
500    use crate::test_fonts::{CARLITO_RUN, carlito};
501    use crate::{Document, FontDb, Options, Warning, Warnings};
502
503    fn docx_with(body: &str, theme: bool) -> Vec<u8> {
504        let mut pkg = testing::docx(body).plain_styles();
505        if theme {
506            pkg = pkg
507                .relationship(testing::DOCUMENT, "th", "theme", "theme/theme1.xml")
508                .part(
509                    "word/theme/theme1.xml",
510                    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>"#,
511                );
512        }
513        pkg.zip().unwrap()
514    }
515
516    #[test]
517    fn custom_uninstalled_font_falling_back_to_carlito_is_fallback_not_exact() {
518        let rpr = r#"<w:rPr><w:rFonts w:ascii="MyBrandFont" w:hAnsi="MyBrandFont"/></w:rPr>"#;
519        let body =
520            format!("<w:p><w:pPr>{rpr}</w:pPr><w:r>{rpr}<w:t>Hello custom font</w:t></w:r></w:p>");
521        let bytes = docx_with(&body, true);
522        let fonts = carlito();
523        let opened = Document::open(&bytes, &fonts, &Options::base()).unwrap();
524        let report = opened.value.fidelity();
525
526        assert_eq!(report.level, FidelityLevel::Approximate, "{report:?}");
527        let custom = report
528            .fonts
529            .iter()
530            .find(|font| font.asked.as_ref().map(Name::as_str) == Some("MyBrandFont"))
531            .expect("MyBrandFont must appear in fidelity report");
532        assert_eq!(custom.match_kind, FontMatchKind::Fallback);
533        assert_ne!(custom.match_kind, FontMatchKind::ExactStandIn);
534        assert_eq!(custom.used.as_ref().map(Name::as_str), Some("Carlito"));
535    }
536
537    #[test]
538    fn native_font_reports_exact_and_native_match_kind() {
539        let body = format!(
540            "<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:t>Native Carlito text</w:t></w:r></w:p>"
541        );
542        let bytes = docx_with(&body, false);
543        let fonts = carlito();
544        let mut options = Options::base();
545        options
546            .configuration
547            .fonts
548            .installed
549            .insert("Carlito".to_owned(), true);
550        let opened = Document::open(&bytes, &fonts, &options).unwrap();
551        let report = opened.value.fidelity();
552
553        assert_eq!(report.level, FidelityLevel::Exact, "{report:?}");
554        assert_eq!(report.missing_glyphs, []);
555        assert_eq!(report.omissions, []);
556        assert!(report.fonts.iter().any(|font| {
557            font.asked.as_ref().map(Name::as_str) == Some("Carlito")
558                && font.used.as_ref().map(Name::as_str) == Some("Carlito")
559                && font.match_kind == FontMatchKind::Native
560        }));
561    }
562
563    #[test]
564    fn missing_notdef_glyphs_report_degraded_without_leaking_text() {
565        let secret_cjk = "漢字";
566        let body = format!(
567            "<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:t>Hello {secret_cjk}</w:t></w:r></w:p>"
568        );
569        let bytes = docx_with(&body, false);
570        let fonts = carlito();
571        let mut options = Options::base();
572        options
573            .configuration
574            .fonts
575            .installed
576            .insert("Carlito".to_owned(), true);
577        let opened = Document::open(&bytes, &fonts, &options).unwrap();
578
579        // Warning::GlyphMissing must never contain raw document text.
580        let glyph_warnings: Vec<_> = opened
581            .warnings
582            .iter()
583            .filter_map(|(warning, _)| match warning {
584                Warning::Docx(f_office_docx::Warning::GlyphMissing { font, block, count }) => {
585                    assert!(!warning.to_string().contains(secret_cjk));
586                    Some((font.clone(), *block, *count))
587                }
588                _ => None,
589            })
590            .collect();
591        assert_eq!(
592            glyph_warnings,
593            vec![(Some(Name::new("Carlito")), UnicodeBlock::Cjk, 2)]
594        );
595
596        let report = opened.value.fidelity();
597        assert_eq!(report.level, FidelityLevel::Degraded);
598        assert_eq!(
599            report.missing_glyphs,
600            vec![MissingGlyphGroup {
601                font: Some(Name::new("Carlito")),
602                block: UnicodeBlock::Cjk,
603                count: 2,
604            }]
605        );
606    }
607
608    #[test]
609    fn missing_font_with_empty_font_db_reports_degraded_missing() {
610        let rpr = r#"<w:rPr><w:rFonts w:ascii="MyBrandFont" w:hAnsi="MyBrandFont"/></w:rPr>"#;
611        let body =
612            format!("<w:p><w:pPr>{rpr}</w:pPr><w:r>{rpr}<w:t>No fonts loaded</w:t></w:r></w:p>");
613        let bytes = docx_with(&body, false);
614        let opened = Document::open(&bytes, &FontDb::new(), &Options::base()).unwrap();
615        let report = opened.value.fidelity();
616
617        assert_eq!(report.level, FidelityLevel::Degraded);
618        assert_eq!(report.fonts[0].match_kind, FontMatchKind::Missing);
619        assert_eq!(
620            report.fonts[0].asked.as_ref().map(Name::as_str),
621            Some("MyBrandFont")
622        );
623    }
624
625    #[test]
626    fn sorts_fonts_worst_first_and_aggregates_omissions() {
627        let mut warnings = Warnings::new();
628        warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
629            asked: Name::new("Arial"),
630            used: Some(Name::new("Arimo CF")),
631            version: Some(Name::new("7.06.1")),
632            layout: SubstituteLayout::Exact,
633        }));
634        warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
635            asked: Name::new("BrandSans"),
636            used: Some(Name::new("Carlito CF")),
637            version: Some(Name::new("1.103")),
638            layout: SubstituteLayout::Fallback,
639        }));
640        warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
641            asked: Name::new("Georgia"),
642            used: Some(Name::new("Gelasio")),
643            version: None,
644            layout: SubstituteLayout::Widths,
645        }));
646        warnings.push(Warning::Docx(f_office_docx::Warning::TextNotDrawn {
647            asked: Some(Name::new("AbsentFont")),
648            tried: vec![Name::new("AbsentFont")],
649        }));
650        warnings.push(Warning::Docx(f_office_docx::Warning::DrawingSkipped {
651            drawing: Drawing::Chart,
652            part: Name::new("word/document.xml"),
653            reason: Reason::Unsupported,
654        }));
655        warnings.push(Warning::Docx(f_office_docx::Warning::ArtBorderNotDrawn {
656            style: "apples",
657            size: 12,
658        }));
659
660        let matched = vec![
661            MatchedFont {
662                asked: Name::new("Carlito"),
663                used: Some(Name::new("Carlito")),
664                version: Some(Name::new("1.103")),
665            },
666            // Redundant native entry for a family that also has a substitution is deduplicated.
667            MatchedFont {
668                asked: Name::new("Arial"),
669                used: Some(Name::new("Arial")),
670                version: None,
671            },
672        ];
673
674        let report = FidelityReport::from_parts(&matched, &warnings);
675        assert_eq!(report.level, FidelityLevel::Degraded);
676        let kinds: Vec<FontMatchKind> = report.fonts.iter().map(|f| f.match_kind).collect();
677        assert_eq!(
678            kinds,
679            vec![
680                FontMatchKind::Missing,
681                FontMatchKind::Fallback,
682                FontMatchKind::Widths,
683                FontMatchKind::ExactStandIn,
684                FontMatchKind::Native,
685            ]
686        );
687        assert_eq!(
688            report.fonts[0],
689            FontStatus {
690                asked: Some(Name::new("AbsentFont")),
691                used: None,
692                version: None,
693                match_kind: FontMatchKind::Missing,
694            }
695        );
696        assert_eq!(
697            report.omissions,
698            vec![
699                Omission {
700                    kind: OmissionKind::ChartSkipped,
701                    count: 1,
702                    degraded: true,
703                },
704                Omission {
705                    kind: OmissionKind::ArtBorderNotDrawn,
706                    count: 1,
707                    degraded: false,
708                },
709            ]
710        );
711    }
712
713    #[test]
714    fn verified_metric_stand_ins_are_exact_while_unverified_widths_are_approximate() {
715        let mut exact_warnings = Warnings::new();
716        exact_warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
717            asked: Name::new("Aptos"),
718            used: Some(Name::new("Intos CF")),
719            version: Some(Name::new("2.01.1")),
720            layout: SubstituteLayout::Metrics,
721        }));
722        exact_warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
723            asked: Name::new("Calibri"),
724            used: Some(Name::new("Celeborn CF")),
725            version: Some(Name::new("6.27.1")),
726            layout: SubstituteLayout::Metrics,
727        }));
728        let exact_report = FidelityReport::from_parts(&[], &exact_warnings);
729        assert_eq!(exact_report.level, FidelityLevel::Exact);
730        assert_eq!(exact_report.fonts.len(), 2);
731        assert!(
732            exact_report
733                .fonts
734                .iter()
735                .all(|f| f.match_kind == FontMatchKind::MetricStandIn)
736        );
737
738        let mut approx_warnings = Warnings::new();
739        approx_warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
740            asked: Name::new("Calibri"),
741            used: Some(Name::new("Carlito")),
742            version: Some(Name::new("1.104")),
743            layout: SubstituteLayout::Widths,
744        }));
745        let approx_report = FidelityReport::from_parts(&[], &approx_warnings);
746        assert_eq!(approx_report.level, FidelityLevel::Approximate);
747        assert_eq!(approx_report.fonts[0].match_kind, FontMatchKind::Widths);
748    }
749}