use std::fmt;
use serde::Serialize;
use crate::GlyphSpace;
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
Info,
Note,
Warning,
}
impl Severity {
fn prefix(self) -> &'static str {
match self {
Severity::Info => "",
Severity::Note => "note: ",
Severity::Warning => "warning: ",
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Diagnostic {
GeometryAssumed { space: GlyphSpace },
PageAnnotCounts {
page: usize,
in_annots: usize,
parsed: usize,
inline: usize,
},
UnparsedAnnots { dropped: usize, total: usize },
AnnotsUnreadable { page: usize, error: String },
NoMediaBox { page: usize, annotations: usize },
TextUnextractable { page: usize, error: String },
UnmatchedQuads {
page: usize,
unmatched: usize,
total: usize,
rotation: i32,
},
EncodingSniffed { count: usize },
UndefinedPdfDocBytes { count: usize },
DeclarationOutsideText { page: usize, text: String },
DeclarationCoversNoText { page: usize, text: String },
DeclarationUnanchored { page: usize, text: String },
DeclarationUnrepaired {
page: usize,
text: String,
found: usize,
wanted: usize,
x: f32,
},
ScopesLeftOpen { page: usize, count: usize },
}
impl Diagnostic {
pub fn severity(&self) -> Severity {
match self {
Diagnostic::PageAnnotCounts { .. } => Severity::Info,
Diagnostic::EncodingSniffed { .. } | Diagnostic::UndefinedPdfDocBytes { .. } => {
Severity::Note
}
Diagnostic::GeometryAssumed { .. }
| Diagnostic::UnparsedAnnots { .. }
| Diagnostic::AnnotsUnreadable { .. }
| Diagnostic::NoMediaBox { .. }
| Diagnostic::TextUnextractable { .. }
| Diagnostic::UnmatchedQuads { .. }
| Diagnostic::DeclarationOutsideText { .. }
| Diagnostic::DeclarationCoversNoText { .. }
| Diagnostic::DeclarationUnanchored { .. }
| Diagnostic::DeclarationUnrepaired { .. }
| Diagnostic::ScopesLeftOpen { .. } => Severity::Warning,
}
}
pub(crate) fn is_annotation_scope(&self) -> bool {
matches!(
self,
Diagnostic::UnmatchedQuads { .. } | Diagnostic::DeclarationUnrepaired { .. }
)
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Diagnostic::GeometryAssumed { space } => write!(
f,
"too little text to measure the glyph coordinate convention; \
assumed {space:?}. Set --geometry explicitly."
),
Diagnostic::PageAnnotCounts {
page,
in_annots,
parsed,
inline,
} => {
write!(f, "page {page:>3}: {in_annots} in /Annots, {parsed} parsed")?;
if *inline > 0 {
write!(f, ", {inline} inline dicts (dropped by pdf_oxide)")?;
}
Ok(())
}
Diagnostic::UnparsedAnnots { dropped, total } => write!(
f,
"{dropped} of {total} annotations in /Annots were not parsed \
(rerun with --stats)"
),
Diagnostic::AnnotsUnreadable { page, error } => {
write!(
f,
"page {page}: /Annots could not be read ({error}); page skipped"
)
}
Diagnostic::NoMediaBox { page, annotations } => write!(
f,
"page {page}: no /MediaBox, and none inherited; {annotations} \
annotation(s) here cannot be placed and are skipped"
),
Diagnostic::TextUnextractable { page, error } => write!(
f,
"page {page}: text could not be extracted ({error}); markup here \
is reported with its comment but no covered text"
),
Diagnostic::UnmatchedQuads {
page,
unmatched,
total,
rotation,
} => {
write!(
f,
"page {page}: {unmatched}/{total} quads matched no glyphs"
)?;
if rotation % 360 != 0 {
write!(f, "; page carries /Rotate {rotation}")?;
}
write!(f, " (try --min-overlap or --geometry)")
}
Diagnostic::EncodingSniffed { count } => write!(
f,
"{count} string(s) carried no byte order mark and were read as \
UTF-8 rather than PDFDocEncoding"
),
Diagnostic::UndefinedPdfDocBytes { count } => write!(
f,
"{count} byte(s) fell on PDFDocEncoding slots the spec leaves \
undefined (0x7F, 0x9F, 0xAD) and were read as Latin-1"
),
Diagnostic::DeclarationOutsideText { page, text } => write!(
f,
"page {page}: declaration {text:?} opens outside BT/ET; text suppressed"
),
Diagnostic::DeclarationCoversNoText { page, text } => write!(
f,
"page {page}: declaration {text:?} covers no shown text; text suppressed"
),
Diagnostic::DeclarationUnanchored { page, text } => write!(
f,
"page {page}: declaration {text:?} covers no shown text; nothing to \
place it against"
),
Diagnostic::DeclarationUnrepaired {
page,
text,
found,
wanted,
x,
} => write!(
f,
"page {page}: declaration {text:?}: found {found} of {wanted} \
replacement characters at x={x:.2}; text suppressed"
),
Diagnostic::ScopesLeftOpen { page, count } => {
write!(f, "page {page}: {count} marked-content scope(s) left open")
}
}
}
}
#[derive(Default, Debug)]
pub struct Diagnostics {
items: Vec<Diagnostic>,
}
impl Diagnostics {
pub(crate) fn push(&mut self, d: Diagnostic) {
self.items.push(d);
}
pub(crate) fn contains(&self, d: &Diagnostic) -> bool {
self.items.contains(d)
}
pub fn warnings(&self) -> usize {
self.items
.iter()
.filter(|d| d.severity() == Severity::Warning)
.count()
}
pub fn render(&self) -> String {
let mut out = String::new();
for d in &self.items {
out.push_str(d.severity().prefix());
out.push_str(&d.to_string());
out.push('\n');
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reproduces_the_messages_it_replaced() {
assert_eq!(
Diagnostic::GeometryAssumed {
space: GlyphSpace::BottomUp
}
.to_string(),
"too little text to measure the glyph coordinate convention; \
assumed BottomUp. Set --geometry explicitly."
);
assert_eq!(
Diagnostic::UnparsedAnnots {
dropped: 3,
total: 20
}
.to_string(),
"3 of 20 annotations in /Annots were not parsed (rerun with --stats)"
);
assert_eq!(
Diagnostic::EncodingSniffed { count: 2 }.to_string(),
"2 string(s) carried no byte order mark and were read as UTF-8 \
rather than PDFDocEncoding"
);
assert_eq!(
Diagnostic::UndefinedPdfDocBytes { count: 1 }.to_string(),
"1 byte(s) fell on PDFDocEncoding slots the spec leaves undefined \
(0x7F, 0x9F, 0xAD) and were read as Latin-1"
);
}
#[test]
fn stats_lines_keep_their_alignment_and_gain_no_prefix() {
let d = Diagnostic::PageAnnotCounts {
page: 7,
in_annots: 5,
parsed: 4,
inline: 0,
};
assert_eq!(d.to_string(), "page 7: 5 in /Annots, 4 parsed");
assert_eq!(d.severity(), Severity::Info);
assert_eq!(d.severity().prefix(), "");
}
#[test]
fn inline_dictionaries_are_mentioned_only_when_present() {
assert_eq!(
Diagnostic::PageAnnotCounts {
page: 1,
in_annots: 5,
parsed: 4,
inline: 1,
}
.to_string(),
"page 1: 5 in /Annots, 4 parsed, 1 inline dicts (dropped by pdf_oxide)"
);
}
#[test]
fn rotation_is_named_only_when_the_page_carries_one() {
let plain = Diagnostic::UnmatchedQuads {
page: 2,
unmatched: 1,
total: 4,
rotation: 0,
};
assert_eq!(
plain.to_string(),
"page 2: 1/4 quads matched no glyphs (try --min-overlap or --geometry)"
);
let rotated = Diagnostic::UnmatchedQuads {
page: 3,
unmatched: 11,
total: 11,
rotation: 90,
};
assert_eq!(
rotated.to_string(),
"page 3: 11/11 quads matched no glyphs; page carries /Rotate 90 \
(try --min-overlap or --geometry)"
);
}
#[test]
fn a_full_turn_is_not_a_rotation() {
for r in [360, -360] {
let d = Diagnostic::UnmatchedQuads {
page: 1,
unmatched: 1,
total: 1,
rotation: r,
};
assert!(!d.to_string().contains("/Rotate"), "{r} leaked");
}
}
#[test]
fn a_negative_rotation_is_reported_as_written() {
assert!(
Diagnostic::UnmatchedQuads {
page: 1,
unmatched: 1,
total: 1,
rotation: -90,
}
.to_string()
.contains("/Rotate -90")
);
}
#[test]
fn only_warnings_count_toward_strict() {
let mut d = Diagnostics::default();
d.push(Diagnostic::PageAnnotCounts {
page: 1,
in_annots: 1,
parsed: 1,
inline: 0,
});
d.push(Diagnostic::EncodingSniffed { count: 1 });
assert_eq!(d.warnings(), 0);
d.push(Diagnostic::NoMediaBox {
page: 2,
annotations: 3,
});
assert_eq!(d.warnings(), 1);
}
#[test]
fn severity_is_ordered_so_strict_can_be_a_threshold() {
assert!(Severity::Warning > Severity::Note);
assert!(Severity::Note > Severity::Info);
}
#[test]
fn nothing_to_say_renders_to_nothing() {
assert_eq!(Diagnostics::default().render(), "");
}
#[test]
fn renders_in_insertion_order_with_prefixes() {
let mut d = Diagnostics::default();
d.push(Diagnostic::PageAnnotCounts {
page: 1,
in_annots: 2,
parsed: 1,
inline: 0,
});
d.push(Diagnostic::UnmatchedQuads {
page: 1,
unmatched: 1,
total: 2,
rotation: 0,
});
d.push(Diagnostic::EncodingSniffed { count: 1 });
assert_eq!(
d.render(),
"page 1: 2 in /Annots, 1 parsed\n\
warning: page 1: 1/2 quads matched no glyphs (try --min-overlap or --geometry)\n\
note: 1 string(s) carried no byte order mark and were read as UTF-8 \
rather than PDFDocEncoding\n"
);
}
#[test]
fn the_actual_text_messages_survived_being_typed() {
assert_eq!(
Diagnostic::DeclarationOutsideText {
page: 2,
text: "Figure 3".to_string(),
}
.to_string(),
"page 2: declaration \"Figure 3\" opens outside BT/ET; text suppressed"
);
assert_eq!(
Diagnostic::DeclarationCoversNoText {
page: 1,
text: "A".to_string(),
}
.to_string(),
"page 1: declaration \"A\" covers no shown text; text suppressed"
);
assert_eq!(
Diagnostic::ScopesLeftOpen { page: 4, count: 2 }.to_string(),
"page 4: 2 marked-content scope(s) left open"
);
}
#[test]
fn an_unrepaired_declaration_names_the_text_it_withheld() {
let d = Diagnostic::DeclarationUnrepaired {
page: 1,
text: "\u{2122}".to_string(),
found: 1,
wanted: 3,
x: 72.5,
};
assert_eq!(
d.to_string(),
"page 1: declaration \"™\": found 1 of 3 replacement characters \
at x=72.50; text suppressed"
);
assert_eq!(d.severity(), Severity::Warning);
}
#[test]
fn the_two_item_level_facts_ride_on_the_record() {
assert!(
Diagnostic::UnmatchedQuads {
page: 1,
unmatched: 1,
total: 2,
rotation: 0,
}
.is_annotation_scope()
);
assert!(
Diagnostic::DeclarationUnrepaired {
page: 1,
text: "x".to_string(),
found: 0,
wanted: 1,
x: 0.0,
}
.is_annotation_scope()
);
for d in [
Diagnostic::GeometryAssumed {
space: GlyphSpace::BottomUp,
},
Diagnostic::EncodingSniffed { count: 1 },
Diagnostic::ScopesLeftOpen { page: 1, count: 1 },
Diagnostic::DeclarationUnanchored {
page: 1,
text: "x".to_string(),
},
] {
assert!(!d.is_annotation_scope(), "{d:?} claimed annotation scope");
}
}
#[test]
fn serialises_internally_tagged_in_snake_case() {
let json = serde_json::to_string(&Diagnostic::UnmatchedQuads {
page: 3,
unmatched: 2,
total: 5,
rotation: 90,
})
.unwrap();
assert_eq!(
json,
r#"{"kind":"unmatched_quads","page":3,"unmatched":2,"total":5,"rotation":90}"#
);
}
#[test]
fn the_wire_form_carries_no_rendered_message() {
let json = serde_json::to_string(&Diagnostic::DeclarationUnrepaired {
page: 1,
text: "\u{2122}".to_string(),
found: 1,
wanted: 3,
x: 72.5,
})
.unwrap();
assert!(!json.contains("suppressed"), "{json}");
assert!(
json.contains(r#""kind":"declaration_unrepaired""#),
"{json}"
);
}
#[test]
fn contains_lets_a_document_level_warning_be_raised_once() {
let mut d = Diagnostics::default();
let assumed = Diagnostic::GeometryAssumed {
space: GlyphSpace::BottomUp,
};
assert!(!d.contains(&assumed));
d.push(assumed.clone());
assert!(d.contains(&assumed));
assert!(!d.contains(&Diagnostic::GeometryAssumed {
space: GlyphSpace::TopDownTop
}));
}
}