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};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FidelityLevel {
#[default]
Exact,
Approximate,
Degraded,
}
impl FidelityLevel {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Exact => "exact",
Self::Approximate => "approximate",
Self::Degraded => "degraded",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FontMatchKind {
Missing,
Fallback,
Widths,
OtherVersion,
MetricStandIn,
ExactStandIn,
Native,
}
impl FontMatchKind {
#[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::MetricStandIn => "metric-stand-in",
Self::ExactStandIn => "exact-stand-in",
Self::Native => "native",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FontStatus {
pub asked: Option<Name>,
pub used: Option<Name>,
pub version: Option<Name>,
pub match_kind: FontMatchKind,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MissingGlyphGroup {
pub font: Option<Name>,
pub block: UnicodeBlock,
pub count: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OmissionKind {
ChartSkipped,
PictureSkipped,
SmartArtSkipped,
ShapeSkipped,
PartSkipped,
NoteMissing,
ScriptNotShaped,
FontFileNotRead,
ArtBorderNotDrawn,
WrapApproximated,
FeatureApproximated,
InkNotMeasured,
DocumentLimitOrInvalid,
DrawingDetailSkipped,
}
impl OmissionKind {
#[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",
}
}
#[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",
}
}
#[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
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Omission {
pub kind: OmissionKind,
pub count: u32,
pub degraded: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FidelityReport {
pub level: FidelityLevel,
pub fonts: Vec<FontStatus>,
pub missing_glyphs: Vec<MissingGlyphGroup>,
pub omissions: Vec<Omission>,
}
impl FidelityReport {
#[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::Metrics => FontMatchKind::MetricStandIn,
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();
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")),
},
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,
},
]
);
}
#[test]
fn verified_metric_stand_ins_are_exact_while_unverified_widths_are_approximate() {
let mut exact_warnings = Warnings::new();
exact_warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
asked: Name::new("Aptos"),
used: Some(Name::new("Intos CF")),
version: Some(Name::new("2.01.1")),
layout: SubstituteLayout::Metrics,
}));
exact_warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
asked: Name::new("Calibri"),
used: Some(Name::new("Celeborn CF")),
version: Some(Name::new("6.27.1")),
layout: SubstituteLayout::Metrics,
}));
let exact_report = FidelityReport::from_parts(&[], &exact_warnings);
assert_eq!(exact_report.level, FidelityLevel::Exact);
assert_eq!(exact_report.fonts.len(), 2);
assert!(
exact_report
.fonts
.iter()
.all(|f| f.match_kind == FontMatchKind::MetricStandIn)
);
let mut approx_warnings = Warnings::new();
approx_warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
asked: Name::new("Calibri"),
used: Some(Name::new("Carlito")),
version: Some(Name::new("1.104")),
layout: SubstituteLayout::Widths,
}));
let approx_report = FidelityReport::from_parts(&[], &approx_warnings);
assert_eq!(approx_report.level, FidelityLevel::Approximate);
assert_eq!(approx_report.fonts[0].match_kind, FontMatchKind::Widths);
}
}