PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Clear image leftovers (#1151)
Jules Kreuer039706c4371d
diff --git a/ROADMAP.md b/ROADMAP.mdindex 309d4dccd..baedd7fbb 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -444,5 +444,6 @@ Newest first: the date, what moved, and the new overall estimate.| 2026-10-10 | major | Restructured to the progress-docs standard (stage, two numbers, dimensions, features, languages, upcoming, log); full re-measure; assessment, gaps and milestones moved to `docs/`; log sorted newest first and a stray merged entry dated || 2026-10-07 | minor | 806 tracked features, 51.0% shipped, effort-weighted ≈ 30–35%, 600–1,100 h || 2026-10-05 | major | Honest assessment and "Where we're lacking" added |+| 2026-10-12 | minor | M8: image redaction removes alternate images and unsupported masks only on affected images. Estimates unchanged. |- **2026-10-12 (M8):** Redaction cleans indirect and form structure references, preserving surviving form tags.diff --git a/crates/redact/README.md b/crates/redact/README.mdindex 4a569eaa1..8ff86e960 100644--- a/crates/redact/README.md+++ b/crates/redact/README.md@@ -20,7 +20,8 @@ clear_marks(&mut doc, None)?; // remove marks without app- **images**: fully covered → removed; partly covered → a copy with the covered pixels cleared(8/16-bit and 1/2/4-bit images, image masks; Flate/LZW/RL/A85/AHx). Codecs PdfCraft can'tre-encode (DCT, JPX, JBIG2, CCITT) are removed whole (fail-closed); inline images under an- area are removed;+ area are removed. Images with separate `/SMask` or `/Mask` data are removed whole;+ cleared copies drop `/Alternates` so alternate pixels cannot survive;- **vectors**: covered paths are removed; partly covered paths and shadings are clipped sonothing paints inside the areas;- **form XObjects**: rewritten recursively into new objects (pages sharing the original keep it);diff --git a/crates/redact/src/image.rs b/crates/redact/src/image.rsindex 4d61fd6c6..043a77db9 100644--- a/crates/redact/src/image.rs+++ b/crates/redact/src/image.rs@@ -41,6 +41,10 @@ pub(crate) fn clear(doc: &Document, s: &Stream, ctm: &Matrix, rects: &[[f64; 4]]}fn decode_and_clear(doc: &Document, s: &Stream, ctm: &Matrix, rects: &[[f64; 4]]) -> Option<Option<Stream>> {+ // Separate masks can retain the original image data.+ if s.dict.contains(b"SMask") || s.dict.contains(b"Mask") {+ return None;+ }let supported = |n: &[u8]| {matches!(n,@@ -114,5 +118,6 @@ fn decode_and_clear(doc: &Document, s: &Stream, ctm: &Matrix, rects: &[[f64; 4]]let mut dict = s.dict.clone();dict.remove(b"Length");dict.remove(b"DecodeParms");+ dict.remove(b"Alternates");Some(Some(Stream::flate(dict, &data)))}diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rsindex 09723b763..dd319846f 100644--- a/crates/redact/src/tests.rs+++ b/crates/redact/src/tests.rs@@ -920,3 +920,50 @@ fn redacting_every_inheriting_page_retires_the_parent_resources() {assert_eq!(under(&mut saved, page, &[[0.0, 190.0, 300.0, 220.0]]), 0);}}++#[test]+fn image_alternatives_and_masks_cannot_keep_redacted_pixels() {+ for extra in ["/Alternates [<< /Image 8 0 R >>]", "/SMask 8 0 R", "/Mask 8 0 R", "/Mask [0 0]"] {+ let mut doc = one_page(+ b"q 0 0 300 300 re W n 8 0 0 10 10 10 cm /Im Do Q",+ "/XObject << /Im 7 0 R >>",+ vec![+ stream(+ &format!("/Type /XObject /Subtype /Image /Width 8 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8 {extra}"),+ b"LEAK_TOPPUBLIC__",+ ),+ stream("/Type /XObject /Subtype /Image /Width 8 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"LEAK_ALT"),+ ],+ );+ mark(&mut doc, 0, &[[10.0, 15.0, 18.0, 20.0]], "");+ let report = apply(&mut doc, None).unwrap();+ assert_no_secret(&doc, b"LEAK_");+ assert_eq!((report.images_cleared, report.images_removed), if extra.starts_with("/Alternates") { (1, 0) } else { (0, 1) });+ }+}++#[test]+fn masks_and_alternates_outside_redaction_stay() {+ let mut doc = one_page(+ b"q 8 0 0 10 10 10 cm /Im Do Q",+ "/XObject << /Im 7 0 R >>",+ vec![+ stream(+ "/Type /XObject /Subtype /Image /Width 8 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 8 0 R /Alternates [<< /Image 8 0 R >>]",+ b"PUBLIC_TOPBOTTOM",+ ),+ stream("/Type /XObject /Subtype /Image /Width 8 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"PUBLIC__"),+ ],+ );+ mark(&mut doc, 0, &[[100.0, 100.0, 120.0, 120.0]], "");+ let report = apply(&mut doc, None).unwrap();+ assert_eq!((report.images_removed, report.images_cleared), (0, 0));+ let saved = reopen(&doc);+ let page = pdfcraft_model::pages(&saved).swap_remove(0);+ let resources = saved.resolve(page.dict.get(b"Resources").unwrap());+ let xobjects = saved.resolve(resources.as_dict().unwrap().get(b"XObject").unwrap());+ let image = saved.resolve(xobjects.as_dict().unwrap().get(b"Im").unwrap());+ let Object::Stream(image) = &*image else { panic!() };+ assert!(image.dict.contains(b"SMask") && image.dict.contains(b"Alternates"));+ assert_eq!(image.decoded().unwrap(), b"PUBLIC_TOPBOTTOM");+}diff --git a/docs/roadmap.md b/docs/roadmap.mdindex 95e9142ef..9b9a39b62 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -108,7 +108,7 @@ total matches the parity estimate.| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Tab and Shift-Tab wrapping to the same field or another widget of that field refresh the newly opened editor from the accepted value before Save. Synthetic UI regressions cover both directions, same-frame Save, validation refusal and undo/redo. || M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Missing: editing existing text and images in place (the longest pole), image/PDF watermarks || M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize.<br>Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Vertical-writing text is still refused, and the error no longer claims the text was under the mark (#1340). Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding |-| M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize.<br>Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Redaction retires inherited resource dictionaries, so a parent `/Pages` can't keep a removed XObject reachable; unredacted pages are left untouched. Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding |+| M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize.<br>Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Redaction retires inherited resource dictionaries, so a parent `/Pages` can't keep a removed XObject reachable; unredacted pages are left untouched. Image redaction removes alternate images and unsupported masks only on affected images. Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding || M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.<br>Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 || M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).<br>Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import || M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA |@@ -197,4 +197,5 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st| 2026-10-10 | minor | M3 records the System appearance completion after #881; estimates unchanged || 2026-10-10 | minor | Re-judged convert and share with the cross-app gate rule (only a workflow that can't be completed at all blocks): partial, not blocking → stage alpha || 2026-10-10 | minor | Added the alpha gate (six core workflows; convert and share fails → pre-alpha, 40–70 h to alpha) and rank 0 in the upcoming milestones |+| 2026-10-12 | minor | M8: image redaction removes alternate images and unsupported masks only on affected images. Estimates unchanged. || 2026-10-10 | major | Created from ROADMAP.md §Milestones, §Critical path, §Risks and §Where we're lacking. Merged the duplicated M1, M2, M3 and M14 rows, re-measured Done and Remaining, added Current focus and the ranked upcoming milestones |