1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub enum FidelityLevel {
13 #[default]
16 Exact,
17 Approximate,
20 Degraded,
22}
23
24impl FidelityLevel {
25 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub enum FontMatchKind {
42 Missing,
44 Fallback,
47 Widths,
49 OtherVersion,
51 ExactStandIn,
53 Native,
55}
56
57impl FontMatchKind {
58 #[must_use]
60 pub const fn as_str(self) -> &'static str {
61 match self {
62 Self::Missing => "missing",
63 Self::Fallback => "fallback",
64 Self::Widths => "widths",
65 Self::OtherVersion => "other-version",
66 Self::ExactStandIn => "exact-stand-in",
67 Self::Native => "native",
68 }
69 }
70}
71
72#[derive(Clone, Debug, PartialEq, Eq, Hash)]
74pub struct FontStatus {
75 pub asked: Option<Name>,
77 pub used: Option<Name>,
79 pub version: Option<Name>,
81 pub match_kind: FontMatchKind,
83}
84
85#[derive(Clone, Debug, PartialEq, Eq, Hash)]
87pub struct MissingGlyphGroup {
88 pub font: Option<Name>,
90 pub block: UnicodeBlock,
92 pub count: u32,
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
98pub enum OmissionKind {
99 ChartSkipped,
101 PictureSkipped,
103 SmartArtSkipped,
105 ShapeSkipped,
107 PartSkipped,
109 NoteMissing,
111 ScriptNotShaped,
113 FontFileNotRead,
115 ArtBorderNotDrawn,
117 WrapApproximated,
119 FeatureApproximated,
121 InkNotMeasured,
123 DocumentLimitOrInvalid,
125 DrawingDetailSkipped,
127}
128
129impl OmissionKind {
130 #[must_use]
132 pub const fn as_str(self) -> &'static str {
133 match self {
134 Self::ChartSkipped => "chart-skipped",
135 Self::PictureSkipped => "picture-skipped",
136 Self::SmartArtSkipped => "smartart-skipped",
137 Self::ShapeSkipped => "shape-skipped",
138 Self::PartSkipped => "part-skipped",
139 Self::NoteMissing => "note-missing",
140 Self::ScriptNotShaped => "script-not-shaped",
141 Self::FontFileNotRead => "font-file-not-read",
142 Self::ArtBorderNotDrawn => "art-border-not-drawn",
143 Self::WrapApproximated => "wrap-approximated",
144 Self::FeatureApproximated => "feature-approximated",
145 Self::InkNotMeasured => "ink-not-measured",
146 Self::DocumentLimitOrInvalid => "document-limit-or-invalid",
147 Self::DrawingDetailSkipped => "drawing-detail-skipped",
148 }
149 }
150
151 #[must_use]
153 pub const fn label(self) -> &'static str {
154 match self {
155 Self::ChartSkipped => "Skipped charts",
156 Self::PictureSkipped => "Skipped pictures",
157 Self::SmartArtSkipped => "Skipped SmartArt diagrams",
158 Self::ShapeSkipped => "Skipped shapes",
159 Self::PartSkipped => "Skipped document parts",
160 Self::NoteMissing => "Missing footnote or endnote targets",
161 Self::ScriptNotShaped => "Unshaped complex-script runs",
162 Self::FontFileNotRead => "Unreadable font files",
163 Self::ArtBorderNotDrawn => "Omitted art page borders",
164 Self::WrapApproximated => "Approximated wrap polygons",
165 Self::FeatureApproximated => "Approximated styles or features",
166 Self::InkNotMeasured => "Unmeasured glyph ink bounds",
167 Self::DocumentLimitOrInvalid => "Malformed values or document limits",
168 Self::DrawingDetailSkipped => "Approximated vector or DrawingML details",
169 }
170 }
171
172 #[must_use]
175 pub const fn is_degraded(self) -> bool {
176 matches!(
177 self,
178 Self::ChartSkipped
179 | Self::PictureSkipped
180 | Self::SmartArtSkipped
181 | Self::ShapeSkipped
182 | Self::PartSkipped
183 | Self::NoteMissing
184 | Self::ScriptNotShaped
185 | Self::FontFileNotRead
186 )
187 }
188}
189
190#[derive(Clone, Debug, PartialEq, Eq, Hash)]
192pub struct Omission {
193 pub kind: OmissionKind,
195 pub count: u32,
197 pub degraded: bool,
199}
200
201#[derive(Clone, Debug, Default, PartialEq, Eq)]
203pub struct FidelityReport {
204 pub level: FidelityLevel,
206 pub fonts: Vec<FontStatus>,
208 pub missing_glyphs: Vec<MissingGlyphGroup>,
210 pub omissions: Vec<Omission>,
212}
213
214impl FidelityReport {
215 #[must_use]
217 pub(crate) fn from_parts(matched_fonts: &[MatchedFont], warnings: &Warnings) -> Self {
218 let mut fonts = Vec::new();
219 let mut seen_fonts: BTreeSet<(Option<String>, Option<String>, FontMatchKind)> =
220 BTreeSet::new();
221 let mut non_native_asked: BTreeSet<String> = BTreeSet::new();
222 let mut missing_glyph_counts: BTreeMap<(Option<Name>, UnicodeBlock), u32> = BTreeMap::new();
223 let mut omission_counts: BTreeMap<OmissionKind, u32> = BTreeMap::new();
224
225 for (warning, count) in warnings.iter() {
226 classify_warning(
227 warning,
228 count,
229 &mut fonts,
230 &mut seen_fonts,
231 &mut non_native_asked,
232 &mut missing_glyph_counts,
233 &mut omission_counts,
234 );
235 }
236
237 for matched in matched_fonts {
238 let key_asked = matched.asked.as_str().to_ascii_lowercase();
239 if non_native_asked.contains(&key_asked) {
240 continue;
241 }
242 push_font(
243 FontStatus {
244 asked: Some(matched.asked.clone()),
245 used: matched.used.clone(),
246 version: matched.version.clone(),
247 match_kind: FontMatchKind::Native,
248 },
249 &mut fonts,
250 &mut seen_fonts,
251 );
252 }
253
254 fonts.sort_by(|a, b| {
255 a.match_kind
256 .cmp(&b.match_kind)
257 .then_with(|| lower_opt(a.asked.as_ref()).cmp(&lower_opt(b.asked.as_ref())))
258 .then_with(|| lower_opt(a.used.as_ref()).cmp(&lower_opt(b.used.as_ref())))
259 });
260
261 let mut missing_glyphs: Vec<MissingGlyphGroup> = missing_glyph_counts
262 .into_iter()
263 .map(|((font, block), count)| MissingGlyphGroup { font, block, count })
264 .collect();
265 missing_glyphs.sort_by(|a, b| {
266 b.count
267 .cmp(&a.count)
268 .then_with(|| lower_opt(a.font.as_ref()).cmp(&lower_opt(b.font.as_ref())))
269 .then_with(|| a.block.cmp(&b.block))
270 });
271
272 let mut omissions: Vec<Omission> = omission_counts
273 .into_iter()
274 .map(|(kind, count)| Omission {
275 kind,
276 count,
277 degraded: kind.is_degraded(),
278 })
279 .collect();
280 omissions.sort_by(|a, b| {
281 b.degraded
282 .cmp(&a.degraded)
283 .then_with(|| a.kind.cmp(&b.kind))
284 });
285
286 let level = compute_level(&fonts, &missing_glyphs, &omissions);
287 Self {
288 level,
289 fonts,
290 missing_glyphs,
291 omissions,
292 }
293 }
294}
295
296fn lower_opt(name: Option<&Name>) -> String {
297 name.map_or_default(|n| n.as_str().to_ascii_lowercase())
298}
299
300fn push_font(
301 status: FontStatus,
302 out: &mut Vec<FontStatus>,
303 seen: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
304) {
305 let key = (
306 status
307 .asked
308 .as_ref()
309 .map(|n| n.as_str().to_ascii_lowercase()),
310 status
311 .used
312 .as_ref()
313 .map(|n| n.as_str().to_ascii_lowercase()),
314 status.match_kind,
315 );
316 if seen.insert(key) {
317 out.push(status);
318 }
319}
320
321fn add_omission(omissions: &mut BTreeMap<OmissionKind, u32>, kind: OmissionKind, count: u32) {
322 omissions
323 .entry(kind)
324 .and_modify(|existing| *existing = existing.saturating_add(count))
325 .or_insert(count);
326}
327
328fn classify_warning(
329 warning: &Warning,
330 count: u32,
331 fonts: &mut Vec<FontStatus>,
332 seen_fonts: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
333 non_native_asked: &mut BTreeSet<String>,
334 missing_glyphs: &mut BTreeMap<(Option<Name>, UnicodeBlock), u32>,
335 omissions: &mut BTreeMap<OmissionKind, u32>,
336) {
337 match warning {
338 Warning::Docx(docx) => classify_docx_warning(
339 docx,
340 count,
341 fonts,
342 seen_fonts,
343 non_native_asked,
344 missing_glyphs,
345 omissions,
346 ),
347 Warning::Pdf(_) => add_omission(omissions, OmissionKind::DrawingDetailSkipped, count),
348 Warning::PictureNotWrittenAgain { .. } => {
349 add_omission(omissions, OmissionKind::FeatureApproximated, count);
350 }
351 Warning::SignatureBroken | Warning::NoteKept => {}
352 }
353}
354
355fn classify_docx_warning(
356 warning: &DocxWarning,
357 count: u32,
358 fonts: &mut Vec<FontStatus>,
359 seen_fonts: &mut BTreeSet<(Option<String>, Option<String>, FontMatchKind)>,
360 non_native_asked: &mut BTreeSet<String>,
361 missing_glyphs: &mut BTreeMap<(Option<Name>, UnicodeBlock), u32>,
362 omissions: &mut BTreeMap<OmissionKind, u32>,
363) {
364 match warning {
365 DocxWarning::FontSubstituted {
366 asked,
367 used,
368 version,
369 layout,
370 } => {
371 let match_kind = match layout {
372 SubstituteLayout::Exact => FontMatchKind::ExactStandIn,
373 SubstituteLayout::OtherVersion { .. } => FontMatchKind::OtherVersion,
374 SubstituteLayout::Fallback => FontMatchKind::Fallback,
375 _ => FontMatchKind::Widths,
376 };
377 non_native_asked.insert(asked.as_str().to_ascii_lowercase());
378 push_font(
379 FontStatus {
380 asked: Some(asked.clone()),
381 used: used.clone(),
382 version: version.clone(),
383 match_kind,
384 },
385 fonts,
386 seen_fonts,
387 );
388 }
389 DocxWarning::TextNotDrawn { asked, .. } | DocxWarning::FontNotFound { asked, .. } => {
390 if let Some(name) = asked {
391 non_native_asked.insert(name.as_str().to_ascii_lowercase());
392 }
393 push_font(
394 FontStatus {
395 asked: asked.clone(),
396 used: None,
397 version: None,
398 match_kind: FontMatchKind::Missing,
399 },
400 fonts,
401 seen_fonts,
402 );
403 }
404 DocxWarning::GlyphMissing {
405 font,
406 block,
407 count: glyph_count,
408 } => {
409 let total = glyph_count.saturating_mul(count);
410 missing_glyphs
411 .entry((font.clone(), *block))
412 .and_modify(|existing| *existing = existing.saturating_add(total))
413 .or_insert(total);
414 }
415 DocxWarning::DrawingSkipped { drawing, .. } => {
416 let kind = match drawing {
417 Drawing::Chart => OmissionKind::ChartSkipped,
418 Drawing::Picture => OmissionKind::PictureSkipped,
419 Drawing::SmartArt => OmissionKind::SmartArtSkipped,
420 _ => OmissionKind::ShapeSkipped,
421 };
422 add_omission(omissions, kind, count);
423 }
424 other => {
425 if let Some(kind) = omission_kind_of(other) {
426 add_omission(omissions, kind, count);
427 }
428 }
429 }
430}
431
432fn omission_kind_of(warning: &DocxWarning) -> Option<OmissionKind> {
433 Some(match warning {
434 DocxWarning::PartSkipped { .. } | DocxWarning::RelationshipsSkipped { .. } => {
435 OmissionKind::PartSkipped
436 }
437 DocxWarning::NoteMissing { .. } => OmissionKind::NoteMissing,
438 DocxWarning::ScriptNotShaped { .. } => OmissionKind::ScriptNotShaped,
439 DocxWarning::FontFileNotRead { .. } => OmissionKind::FontFileNotRead,
440 DocxWarning::ArtBorderNotDrawn { .. } => OmissionKind::ArtBorderNotDrawn,
441 DocxWarning::WrapPolygonSkipped { .. } => OmissionKind::WrapApproximated,
442 DocxWarning::ValueNotSupported { .. } | DocxWarning::FeatureNotSupported { .. } => {
443 OmissionKind::FeatureApproximated
444 }
445 DocxWarning::InkNotMeasured { .. } => OmissionKind::InkNotMeasured,
446 DocxWarning::InvalidValue { .. }
447 | DocxWarning::NoteIdRepeated { .. }
448 | DocxWarning::UndeclaredPrefix { .. }
449 | DocxWarning::LimitReached { .. } => OmissionKind::DocumentLimitOrInvalid,
450 DocxWarning::Metafile { .. } | DocxWarning::DrawingMl { .. } => {
451 OmissionKind::DrawingDetailSkipped
452 }
453 _ => return None,
454 })
455}
456
457fn compute_level(
458 fonts: &[FontStatus],
459 missing_glyphs: &[MissingGlyphGroup],
460 omissions: &[Omission],
461) -> FidelityLevel {
462 let degraded = !missing_glyphs.is_empty()
463 || fonts
464 .iter()
465 .any(|font| font.match_kind == FontMatchKind::Missing)
466 || omissions.iter().any(|omission| omission.degraded);
467 if degraded {
468 return FidelityLevel::Degraded;
469 }
470 let approximate = !omissions.is_empty()
471 || fonts.iter().any(|font| {
472 matches!(
473 font.match_kind,
474 FontMatchKind::Fallback | FontMatchKind::Widths | FontMatchKind::OtherVersion
475 )
476 });
477 if approximate {
478 FidelityLevel::Approximate
479 } else {
480 FidelityLevel::Exact
481 }
482}
483
484#[cfg(test)]
485mod tests {
486 use f_office_docx::testing::{self, WordParts as _};
487 use f_office_docx::{Drawing, MatchedFont, Reason, SubstituteLayout, UnicodeBlock};
488 use f_office_warnings::Name;
489
490 use super::{
491 FidelityLevel, FidelityReport, FontMatchKind, FontStatus, MissingGlyphGroup, Omission,
492 OmissionKind,
493 };
494 use crate::test_fonts::{CARLITO_RUN, carlito};
495 use crate::{Document, FontDb, Options, Warning, Warnings};
496
497 fn docx_with(body: &str, theme: bool) -> Vec<u8> {
498 let mut pkg = testing::docx(body).plain_styles();
499 if theme {
500 pkg = pkg
501 .relationship(testing::DOCUMENT, "th", "theme", "theme/theme1.xml")
502 .part(
503 "word/theme/theme1.xml",
504 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>"#,
505 );
506 }
507 pkg.zip().unwrap()
508 }
509
510 #[test]
511 fn custom_uninstalled_font_falling_back_to_carlito_is_fallback_not_exact() {
512 let rpr = r#"<w:rPr><w:rFonts w:ascii="MyBrandFont" w:hAnsi="MyBrandFont"/></w:rPr>"#;
513 let body =
514 format!("<w:p><w:pPr>{rpr}</w:pPr><w:r>{rpr}<w:t>Hello custom font</w:t></w:r></w:p>");
515 let bytes = docx_with(&body, true);
516 let fonts = carlito();
517 let opened = Document::open(&bytes, &fonts, &Options::base()).unwrap();
518 let report = opened.value.fidelity();
519
520 assert_eq!(report.level, FidelityLevel::Approximate, "{report:?}");
521 let custom = report
522 .fonts
523 .iter()
524 .find(|font| font.asked.as_ref().map(Name::as_str) == Some("MyBrandFont"))
525 .expect("MyBrandFont must appear in fidelity report");
526 assert_eq!(custom.match_kind, FontMatchKind::Fallback);
527 assert_ne!(custom.match_kind, FontMatchKind::ExactStandIn);
528 assert_eq!(custom.used.as_ref().map(Name::as_str), Some("Carlito"));
529 }
530
531 #[test]
532 fn native_font_reports_exact_and_native_match_kind() {
533 let body = format!(
534 "<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:t>Native Carlito text</w:t></w:r></w:p>"
535 );
536 let bytes = docx_with(&body, false);
537 let fonts = carlito();
538 let mut options = Options::base();
539 options
540 .configuration
541 .fonts
542 .installed
543 .insert("Carlito".to_owned(), true);
544 let opened = Document::open(&bytes, &fonts, &options).unwrap();
545 let report = opened.value.fidelity();
546
547 assert_eq!(report.level, FidelityLevel::Exact, "{report:?}");
548 assert_eq!(report.missing_glyphs, []);
549 assert_eq!(report.omissions, []);
550 assert!(report.fonts.iter().any(|font| {
551 font.asked.as_ref().map(Name::as_str) == Some("Carlito")
552 && font.used.as_ref().map(Name::as_str) == Some("Carlito")
553 && font.match_kind == FontMatchKind::Native
554 }));
555 }
556
557 #[test]
558 fn missing_notdef_glyphs_report_degraded_without_leaking_text() {
559 let secret_cjk = "漢字";
560 let body = format!(
561 "<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:t>Hello {secret_cjk}</w:t></w:r></w:p>"
562 );
563 let bytes = docx_with(&body, false);
564 let fonts = carlito();
565 let mut options = Options::base();
566 options
567 .configuration
568 .fonts
569 .installed
570 .insert("Carlito".to_owned(), true);
571 let opened = Document::open(&bytes, &fonts, &options).unwrap();
572
573 let glyph_warnings: Vec<_> = opened
575 .warnings
576 .iter()
577 .filter_map(|(warning, _)| match warning {
578 Warning::Docx(f_office_docx::Warning::GlyphMissing { font, block, count }) => {
579 assert!(!warning.to_string().contains(secret_cjk));
580 Some((font.clone(), *block, *count))
581 }
582 _ => None,
583 })
584 .collect();
585 assert_eq!(
586 glyph_warnings,
587 vec![(Some(Name::new("Carlito")), UnicodeBlock::Cjk, 2)]
588 );
589
590 let report = opened.value.fidelity();
591 assert_eq!(report.level, FidelityLevel::Degraded);
592 assert_eq!(
593 report.missing_glyphs,
594 vec![MissingGlyphGroup {
595 font: Some(Name::new("Carlito")),
596 block: UnicodeBlock::Cjk,
597 count: 2,
598 }]
599 );
600 }
601
602 #[test]
603 fn missing_font_with_empty_font_db_reports_degraded_missing() {
604 let rpr = r#"<w:rPr><w:rFonts w:ascii="MyBrandFont" w:hAnsi="MyBrandFont"/></w:rPr>"#;
605 let body =
606 format!("<w:p><w:pPr>{rpr}</w:pPr><w:r>{rpr}<w:t>No fonts loaded</w:t></w:r></w:p>");
607 let bytes = docx_with(&body, false);
608 let opened = Document::open(&bytes, &FontDb::new(), &Options::base()).unwrap();
609 let report = opened.value.fidelity();
610
611 assert_eq!(report.level, FidelityLevel::Degraded);
612 assert_eq!(report.fonts[0].match_kind, FontMatchKind::Missing);
613 assert_eq!(
614 report.fonts[0].asked.as_ref().map(Name::as_str),
615 Some("MyBrandFont")
616 );
617 }
618
619 #[test]
620 fn sorts_fonts_worst_first_and_aggregates_omissions() {
621 let mut warnings = Warnings::new();
622 warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
623 asked: Name::new("Arial"),
624 used: Some(Name::new("Arimo CF")),
625 version: Some(Name::new("7.06.1")),
626 layout: SubstituteLayout::Exact,
627 }));
628 warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
629 asked: Name::new("BrandSans"),
630 used: Some(Name::new("Carlito CF")),
631 version: Some(Name::new("1.103")),
632 layout: SubstituteLayout::Fallback,
633 }));
634 warnings.push(Warning::Docx(f_office_docx::Warning::FontSubstituted {
635 asked: Name::new("Georgia"),
636 used: Some(Name::new("Gelasio")),
637 version: None,
638 layout: SubstituteLayout::Widths,
639 }));
640 warnings.push(Warning::Docx(f_office_docx::Warning::TextNotDrawn {
641 asked: Some(Name::new("AbsentFont")),
642 tried: vec![Name::new("AbsentFont")],
643 }));
644 warnings.push(Warning::Docx(f_office_docx::Warning::DrawingSkipped {
645 drawing: Drawing::Chart,
646 part: Name::new("word/document.xml"),
647 reason: Reason::Unsupported,
648 }));
649 warnings.push(Warning::Docx(f_office_docx::Warning::ArtBorderNotDrawn {
650 style: "apples",
651 size: 12,
652 }));
653
654 let matched = vec![
655 MatchedFont {
656 asked: Name::new("Carlito"),
657 used: Some(Name::new("Carlito")),
658 version: Some(Name::new("1.103")),
659 },
660 MatchedFont {
662 asked: Name::new("Arial"),
663 used: Some(Name::new("Arial")),
664 version: None,
665 },
666 ];
667
668 let report = FidelityReport::from_parts(&matched, &warnings);
669 assert_eq!(report.level, FidelityLevel::Degraded);
670 let kinds: Vec<FontMatchKind> = report.fonts.iter().map(|f| f.match_kind).collect();
671 assert_eq!(
672 kinds,
673 vec![
674 FontMatchKind::Missing,
675 FontMatchKind::Fallback,
676 FontMatchKind::Widths,
677 FontMatchKind::ExactStandIn,
678 FontMatchKind::Native,
679 ]
680 );
681 assert_eq!(
682 report.fonts[0],
683 FontStatus {
684 asked: Some(Name::new("AbsentFont")),
685 used: None,
686 version: None,
687 match_kind: FontMatchKind::Missing,
688 }
689 );
690 assert_eq!(
691 report.omissions,
692 vec![
693 Omission {
694 kind: OmissionKind::ChartSkipped,
695 count: 1,
696 degraded: true,
697 },
698 Omission {
699 kind: OmissionKind::ArtBorderNotDrawn,
700 count: 1,
701 degraded: false,
702 },
703 ]
704 );
705 }
706}