R7.4: an unembedded font is no damage (#5)

The warning watch skips MuPDF's non-embedded font notice and its
repeat counts. Text and search reads are watched too: damage they meet
is kept on the document, told by the next draw or picture check, and
fails image and text exports until then.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-16 13:44:17 -04:00
1 parent 969cb67c96
commit 6b676e06e6
9 files changed
+191 -9

No files matched your search

+14 -1
View File
@@ -56,10 +56,21 @@ typedef struct
void *user;
} passing;
/* MuPDF draws an unembedded font with another. */
static const char notice[] = "non-embedded font using identity encoding:";
/* 1 while the last warning was that notice. */
static int substituted;
static void keep_warning(void *user, const char *message)
{
passing *p = user;
if (strlen(warned) + strlen(message) + 2 < sizeof warned)
/* An unembedded font drawn by another is no damage. */
if (!strncmp(message, notice, sizeof notice - 1))
substituted = 1;
else if (strncmp(message, "... repeated ", 13))
substituted = 0;
if (!substituted && strlen(warned) + strlen(message) + 2 < sizeof warned)
{
fz_strlcat(warned, message, sizeof warned);
fz_strlcat(warned, "\n", sizeof warned);
@@ -74,6 +85,8 @@ static int watched;
/* Collects MuPDF's warnings until `ely_watch_end`. */
void ely_watch_begin(fz_context *ctx)
{
/* A pending repeat is of MuPDF's last warning. */
substituted = !strncmp(ctx->warn.message, notice, sizeof notice - 1);
watching.next = fz_warning_callback(ctx, &watching.user);
warned[0] = 0;
watched = 1;
@@ -31,6 +31,8 @@ struct Doc {
/// What MuPDF warned at open; kept as the repair report.
warnings: String,
repair: Option<String>,
/// Damage a read met that no draw has told yet.
found: bool,
/// The repaired copy standing in; removed on close.
copy: Option<std::path::PathBuf>,
/// MuPDF's steps: an edit's id, or none for a save.
@@ -359,7 +361,7 @@ impl Worker {
let id = self.next;
self.next += 1;
let warnings = output::open_warnings();
let doc = Doc { open, password: String::new(), owner, warnings, repair: None, copy: None, steps: Vec::new(), at: 0 };
let doc = Doc { open, password: String::new(), owner, warnings, repair: None, found: false, copy: None, steps: Vec::new(), at: 0 };
self.docs.insert(id, doc);
if !locked && let Err(error) = self.repair(id) {
self.forget(id)?;
@@ -405,13 +407,12 @@ impl Worker {
self.drawn(id, page, (scale, rotate), tile, dark)
}
tag::TEXT => {
let doc = self.doc(ask.u64()?)?;
self.mupdf.text(doc, ask.u64()? as usize)
let (id, page) = (ask.u64()?, ask.u64()? as usize);
self.read(id, |mupdf, doc| mupdf.text(doc, page))
}
tag::SEARCH => {
let doc = self.doc(ask.u64()?)?;
let page = ask.u64()? as usize;
self.mupdf.search(doc, page, &ask.str()?)
let (id, page, needle) = (ask.u64()?, ask.u64()? as usize, ask.str()?);
self.read(id, |mupdf, doc| mupdf.search(doc, page, &needle))
}
tag::OUTLINE => self.mupdf.outline(self.doc(ask.u64()?)?),
tag::HELLO => Ok(Pack::new().str(ely_pdf_engine::proto::BUILD).bytes()),
@@ -82,6 +82,24 @@ impl crate::Worker {
Ok(())
}
/// A text read; damage it meets waits for a draw.
pub(crate) fn read(&mut self, id: u64, read: impl FnOnce(&Mupdf, &Open) -> io::Result<Vec<u8>>) -> io::Result<Vec<u8>> {
let doc = self.doc(id)?;
unsafe { ely_watch_begin(self.mupdf.ctx) };
let answer = read(&self.mupdf, doc);
if unsafe { ely_watch_end(self.mupdf.ctx) } != 0 {
self.note_damage(id)?;
self.docs.get_mut(&id).expect("just read").found = true;
}
answer
}
/// Takes damage a read found; the caller tells it.
fn found(&mut self, id: u64) -> io::Result<bool> {
let doc = self.docs.get_mut(&id).ok_or_else(|| io::Error::other(format!("no document {id}")))?;
Ok(std::mem::take(&mut doc.found))
}
/// A tile, and whether drawing it met damage.
pub(crate) fn drawn(&mut self, id: u64, page: usize, view: (f32, i32), tile: [i32; 4], dark: bool) -> io::Result<Vec<u8>> {
unsafe { ely_watch_begin(self.mupdf.ctx) };
@@ -90,7 +108,9 @@ impl crate::Worker {
if warned {
self.note_damage(id)?;
}
Ok(Pack::new().u64(u64::from(warned)).blob(&pixels?).bytes())
let pixels = pixels?;
let damaged = warned | self.found(id)?;
Ok(Pack::new().u64(u64::from(damaged)).blob(&pixels).bytes())
}
/// Every picture decoded before an overwrite; true if any failed.
@@ -99,6 +119,7 @@ impl crate::Worker {
if failed {
self.note_damage(id)?;
}
let failed = failed | self.found(id)?;
Ok(Pack::new().u64(u64::from(failed)).bytes())
}
@@ -153,6 +174,12 @@ impl crate::Worker {
pub(crate) fn output(&mut self, kind: u8, id: u64, ask: &mut Unpack) -> io::Result<Vec<u8>> {
let has = self.allowed(id)?;
let doc = self.record(id)?;
// What a read found is no whole export.
if matches!(kind, tag::EXPORT_IMAGE | tag::EXPORT_TEXT) && doc.found {
refuse(may::COPY, has)?;
let report = doc.repair.as_deref().expect("noted with the damage");
return Err(io::Error::other(format!("the document did not read whole: {report}")));
}
match kind {
tag::EXPORT_IMAGE => {
refuse(may::COPY, has)?;
+129
View File
@@ -148,6 +148,7 @@ fn a_broken_stream_under_a_sound_table_is_damage_and_fails_exports() {
let report = worker.repair_report(doc).expect("asks").expect("damage is reported");
assert!(!report.trim().is_empty());
assert!(worker.export_text(doc, &dir.path().join("doc.txt")).is_err(), "partial text is no export");
assert!(worker.export_image(doc, 0, 72.0, &dir.path().join("page.png")).is_err(), "nor a partial page");
worker.rotate_pages(doc, &[0], 90).expect("edits the copy");
doc = worker.now(doc).expect("the state");
worker.save(doc, &dir.path().join("fixed.pdf")).expect("saves the copy");
@@ -186,3 +187,131 @@ fn a_broken_picture_shows_when_drawn_or_checked() {
assert!(other.check_pictures(again).expect("checks"), "the check finds it undrawn");
assert_eq!(std::fs::read(&path).expect("reads"), bytes);
}
/// As many Chinese files name their fonts.
const SIMSUN: &str = "<< /Type /Font /Subtype /Type0 /BaseFont /SimSun /Encoding /Identity-H /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /SimSun /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 2 >> /FontDescriptor << /Type /FontDescriptor /FontName /SimSun /Flags 6 /FontBBox [0 -141 996 855] /ItalicAngle 0 /Ascent 859 /Descent -141 /CapHeight 859 /StemV 91 >> >>] >>";
/// Two runs, each in its own unembedded font.
const TWO_RUNS: &str = "BT /F1 24 Tf 72 700 Td <00410042> Tj /F2 24 Tf <0043> Tj ET";
#[test]
fn an_unembedded_font_is_no_damage() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("doc.pdf");
// Two fonts, one notice: a repeat is no damage either.
let fonts = " /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >>";
let bytes = one_page("", fonts, TWO_RUNS, &[SIMSUN.to_string(), SIMSUN.to_string()]);
std::fs::write(&path, &bytes).expect("writes");
// Each on a fresh worker: no font loaded before.
let (mut worker, doc) = opened(&path);
worker.export_text(doc, &dir.path().join("doc.txt")).expect("the text exports");
let (mut worker, doc) = opened(&path);
worker.export_image(doc, 0, 72.0, &dir.path().join("page.png")).expect("the page exports");
let (mut worker, doc) = opened(&path);
// Read unwatched first: its repeat is pending.
worker.text(doc, 0).expect("reads");
let tile = worker.render(doc, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws");
assert!(!tile.damaged, "a substituted font draws whole");
assert_eq!(worker.repair_report(doc).expect("asks"), None);
}
#[test]
fn unreadable_content_still_draws_as_damage() {
let dir = tempfile::tempdir().expect("a temp dir");
// Text with no font; a stray bracket.
for content in ["BT 72 700 Td (Missing text) Tj ET", "BT ] ET"] {
let path = dir.path().join("doc.pdf");
std::fs::write(&path, one_page("", "", content, &[])).expect("writes");
let (mut worker, doc) = opened(&path);
let tile = worker.render(doc, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws");
assert!(tile.damaged, "{content} draws as damage");
}
}
/// Two pictures whose zlib checksums are wrong.
fn broken_pictures(dir: &Path) -> std::path::PathBuf {
let hex = format!("{}>", "ff0000".repeat(16));
// One stored deflate block, its checksum wrong.
let mut zlib = vec![0x78, 0x01, 0x01];
zlib.extend_from_slice(&(hex.len() as u16).to_le_bytes());
zlib.extend_from_slice(&(!(hex.len() as u16)).to_le_bytes());
zlib.extend_from_slice(hex.as_bytes());
zlib.extend_from_slice(&[0, 0, 0, 0]);
let slot = "#".repeat(zlib.len());
let image = format!("<< /Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter [/FlateDecode /ASCIIHexDecode] /Length {} >>
stream
{slot}
endstream", zlib.len());
let names = " /Resources << /XObject << /Im1 5 0 R /Im2 6 0 R >> >>";
let mut bytes = one_page("", names, "q 100 0 0 100 72 600 cm /Im1 Do Q q 100 0 0 100 72 400 cm /Im2 Do Q", &[image.clone(), image]);
for _ in 0..2 {
let at = bytes.windows(slot.len()).position(|w| w == slot.as_bytes()).expect("the slot");
bytes[at..at + zlib.len()].copy_from_slice(&zlib);
}
let path = dir.join("doc.pdf");
std::fs::write(&path, &bytes).expect("writes");
path
}
/// A picture whose colour key mask is invalid.
fn masked() -> String {
let hex = format!("{}>", "ff0000".repeat(16));
format!("<< /Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Mask [null null null null null null] /Filter /ASCIIHexDecode /Length {} >>
stream
{hex}
endstream", hex.len())
}
/// The bad mask, alone or drawn beside two font notices.
fn bad_mask(dir: &Path, fonts: Option<bool>) -> std::path::PathBuf {
let picture = "q 100 0 0 100 72 600 cm /Im1 Do Q";
let (resources, content, objects) = match fonts {
None => (String::new(), picture.to_string(), vec![masked()]),
Some(first) => (
" /Font << /F1 6 0 R /F2 7 0 R >>".to_string(),
if first { format!("{picture} {TWO_RUNS}") } else { format!("{TWO_RUNS} {picture}") },
vec![masked(), SIMSUN.to_string(), SIMSUN.to_string()],
),
};
let names = format!(" /Resources << /XObject << /Im1 5 0 R >>{resources} >>");
let path = dir.join(format!("mask-{fonts:?}.pdf"));
std::fs::write(&path, one_page("", &names, &content, &objects)).expect("writes");
path
}
#[test]
fn a_broken_picture_under_two_filters_fails_exports() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = broken_pictures(dir.path());
let (mut worker, doc) = opened(&path);
assert!(worker.export_text(doc, &dir.path().join("doc.txt")).is_err(), "its text read whole");
let (mut worker, doc) = opened(&path);
assert!(worker.export_image(doc, 0, 72.0, &dir.path().join("page.png")).is_err(), "its page read whole");
let (mut worker, doc) = opened(&path);
let tile = worker.render(doc, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws");
assert!(tile.damaged, "the picture draws as damage");
}
#[test]
fn a_broken_picture_read_before_is_still_damage() {
let dir = tempfile::tempdir().expect("a temp dir");
let files = [broken_pictures(dir.path()), bad_mask(dir.path(), None), bad_mask(dir.path(), Some(true)), bad_mask(dir.path(), Some(false))];
// Reading caches the pictures; their repeat waits.
let read: [fn(&mut Worker, Doc); 2] = [|w, d| drop(w.text(d, 0).expect("reads")), |w, d| drop(w.search(d, 0, "x").expect("searches"))];
for (path, first) in files.iter().flat_map(|p| read.map(|r| (p, r))) {
let (mut worker, doc) = opened(&path);
first(&mut worker, doc);
let tile = worker.render(doc, 0, (1.0, 0), [0, 0, 612, 792], false).expect("draws");
assert!(tile.damaged, "the picture draws as damage");
assert!(worker.repair_report(doc).expect("asks").is_some());
let (mut worker, doc) = opened(&path);
first(&mut worker, doc);
assert!(worker.export_image(doc, 0, 72.0, &dir.path().join("page.png")).is_err(), "its page read whole");
let (mut worker, doc) = opened(&path);
first(&mut worker, doc);
assert!(worker.export_text(doc, &dir.path().join("doc.txt")).is_err(), "its text read whole");
let (mut worker, doc) = opened(&path);
first(&mut worker, doc);
assert!(worker.check_pictures(doc).expect("checks"), "the check finds it");
}
}