Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M12: isolate decorative edits of shared content streams

jonathanwxh-celle3d095f632a0
diff --git a/ROADMAP.md b/ROADMAP.md
index bad75fc3b..a72dc5f82 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -171,6 +171,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
## Progress log
+- **2026-10-19 (M12, #3217):** Decorative marking replaces changed content-stream occurrences with fresh objects, preserving other uses of shared streams and leaving untouched entries byte-identical. Regressions cover repeated references, another page sharing a stream, unique references, and full/incremental save-and-reopen. Estimates unchanged.
+
- **2026-10-18 (M6, #2892):** Push-button normal labels are editable per widget through Options and form_set_props, independently of field names; rendering, undo/redo and incremental/full save/reopen are covered. Estimates unchanged.
- **2026-10-18 (M7, #3212):** Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, with original content preserved.
diff --git a/crates/a11y/src/alt.rs b/crates/a11y/src/alt.rs
index 486ce9af1..e4755ab38 100644
--- a/crates/a11y/src/alt.rs
+++ b/crates/a11y/src/alt.rs
@@ -357,14 +357,9 @@ fn artifact_marked_content(doc: &mut Document, page: &pdfcraft_model::Page, ids:
dict.remove(b"Filter");
dict.remove(b"DecodeParms");
let stream = Object::Stream(Stream::flate(dict, &new));
- let stored = match entry {
- Object::Ref(r) => {
- doc.set(r, stream);
- Object::Ref(r)
- }
- _ => Object::Ref(doc.add(stream)),
- };
- next.push(stored);
+ // Splicing depends on this occurrence's neighbours. The original stream may also
+ // appear elsewhere in this array or on another page, where it must stay unchanged.
+ next.push(Object::Ref(doc.add(stream)));
}
if changed {
let contents = match next.as_slice() {
diff --git a/crates/a11y/tests/cross_stream.rs b/crates/a11y/tests/cross_stream.rs
index 309491436..ad613a293 100644
--- a/crates/a11y/tests/cross_stream.rs
+++ b/crates/a11y/tests/cross_stream.rs
@@ -1,6 +1,6 @@
use pdfcraft_a11y::{Options, Rule, Status, autotag_text, check, figures, mark_decorative, mark_tag_artifact, tag_content, tags};
use pdfcraft_content::{Op, Pieces};
-use pdfcraft_cos::{Document, ObjRef, Object};
+use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full, write_incremental};
const FONT: &str = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>";
const HIDDEN_AND_AFTER: &str = "BT /F1 12 Tf 72 520 Td (Hidden) Tj ET\nBT /F1 12 Tf 72 500 Td (After) Tj ET";
@@ -97,6 +97,93 @@ fn shown_strings(ops: &[Op]) -> Vec<String> {
ops.iter().filter(|op| op.is("Tj")).filter_map(|op| op.operands.first()?.as_string().map(|s| s.to_text())).collect()
}
+#[test]
+fn mark_decorative_leaves_the_other_stream_untouched() {
+ let mut doc = tagged_figure_two_streams("0 0 1 rg 300 600 100 50 re f", "BT /F1 12 Tf 72 500 Td (After) Tj ET");
+ let before = doc.get(ObjRef::new(11, 0)).clone();
+ mark_decorative(&mut doc, ObjRef::new(8, 0)).expect("mark decorative succeeds");
+ assert!(figures(&doc).is_empty());
+ assert_eq!(*doc.get(ObjRef::new(11, 0)), *before, "the second stream holds no figure and keeps its object");
+ let page = doc.get(ObjRef::new(3, 0));
+ let contents = page.as_dict().unwrap().get(b"Contents").unwrap().as_array().unwrap();
+ assert_eq!(contents[1].as_ref(), Some(ObjRef::new(11, 0)), "the untouched stream must not be replaced by a re-encoded copy");
+}
+
+/// A and B supply different operands to R's BDC. Reusing R must not let the first
+/// occurrence's splice remove the unselected second occurrence's BDC.
+fn split_marked_content(shared: bool) -> Document {
+ let mut doc = tagged_figure_two_streams("", "");
+ doc.set(ObjRef::new(10, 0), Object::Stream(Stream::flate(Dict::new(), b"/Figure << /MCID 0 >>")));
+ let body = Object::Stream(Stream::flate(Dict::new(), b"BDC 0 0 10 10 re f EMC"));
+ doc.set(ObjRef::new(11, 0), body.clone());
+ let b = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/Span << /MCID 1 >>")));
+ let second = if shared { ObjRef::new(11, 0) } else { doc.add(body) };
+ doc.update_dict(ObjRef::new(3, 0), |p| {
+ p.set(
+ b"Contents".to_vec(),
+ Object::Array(vec![Object::Ref(ObjRef::new(10, 0)), Object::Ref(ObjRef::new(11, 0)), Object::Ref(b), Object::Ref(second)]),
+ );
+ })
+ .unwrap();
+ Document::open(std::sync::Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap()
+}
+
+fn assert_selected_occurrence_only(shared: bool) {
+ let mut doc = split_marked_content(shared);
+ let (before, skipped) = joined_ops(&doc);
+ assert_eq!(skipped, 0);
+ assert_eq!(before.iter().filter(|op| op.is("BDC")).count(), 2);
+ let figure = figures(&doc)[0].obj;
+ mark_decorative(&mut doc, figure).unwrap();
+ for bytes in [write_full(&doc, &SaveOptions::default()).unwrap(), write_incremental(&doc, &SaveOptions::default()).unwrap()] {
+ let reopened = Document::open(std::sync::Arc::new(bytes)).unwrap();
+ let (ops, skipped) = joined_ops(&reopened);
+ assert_eq!(skipped, 0);
+ assert_eq!(ops.iter().filter(|op| op.is("BMC") && op.name(0) == Some(b"Artifact")).count(), 1);
+ let unselected: Vec<_> = ops.iter().filter(|op| op.is("BDC")).collect();
+ assert_eq!(unselected.len(), 1, "unselected Span must retain its BDC after save/reopen");
+ assert_eq!(unselected[0].name(0), Some(b"Span".as_slice()));
+ assert_eq!(unselected[0].operands[1].as_dict().unwrap().get(b"MCID").and_then(Object::as_int), Some(1));
+ assert_eq!(ops.iter().filter(|op| op.is("re")).count(), 2);
+ assert_eq!(ops.iter().filter(|op| op.is("EMC")).count(), 2);
+ assert!(figures(&reopened).is_empty());
+ }
+}
+
+#[test]
+fn mark_decorative_isolates_shared_stream_occurrences_after_save() {
+ assert_selected_occurrence_only(true);
+}
+
+#[test]
+fn mark_decorative_preserves_unique_stream_occurrences_after_save() {
+ assert_selected_occurrence_only(false);
+}
+
+#[test]
+fn mark_decorative_leaves_another_page_using_the_stream_untouched() {
+ let mut doc = tagged_figure_two_streams("", "BT /F1 12 Tf 72 500 Td (After) Tj ET");
+ let page = doc.get(ObjRef::new(3, 0)).as_dict().unwrap().clone();
+ let other_page = doc.add(Object::Dict(page));
+ doc.update_dict(ObjRef::new(2, 0), |p| {
+ p.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(3, 0)), Object::Ref(other_page)]));
+ p.set(b"Count".to_vec(), Object::Int(2));
+ })
+ .unwrap();
+ let before = doc.get(ObjRef::new(10, 0)).clone();
+ mark_decorative(&mut doc, ObjRef::new(8, 0)).unwrap();
+ for bytes in [write_full(&doc, &SaveOptions::default()).unwrap(), write_incremental(&doc, &SaveOptions::default()).unwrap()] {
+ let reopened = Document::open(std::sync::Arc::new(bytes)).unwrap();
+ let pages = pdfcraft_model::pages(&reopened);
+ assert_eq!(pages.len(), 2);
+ let contents = pages[1].dict.get(b"Contents").unwrap().as_array().unwrap();
+ assert_eq!(*reopened.resolve(&contents[0]), *before, "the other page's shared figure stream must stay intact");
+ let (ops, skipped) = joined_ops(&reopened);
+ assert_eq!(skipped, 0);
+ assert!(ops.iter().any(|op| op.is("BMC") && op.name(0) == Some(b"Artifact")));
+ }
+}
+
#[test]
fn autotag_keeps_text_commented_out_across_stream_boundary_hidden() {
let mut doc = untagged_two_streams("BT /F1 12 Tf 72 540 Td (Visible) Tj ET\n% a note at the end of the first stream", HIDDEN_AND_AFTER);
diff --git a/docs/roadmap.md b/docs/roadmap.md
index e1fdce650..8ff987fca 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -146,7 +146,7 @@ total matches the parity estimate.
| 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, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. 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). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. 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 |
-| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA |
+| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only changed stream occurrences and preserves other uses of shared streams through full/incremental saves (#1324, #3217). An XFA radio item whose value contains a space is written back unchanged (#1319). Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA |
| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers<br>Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. |
| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645). |
| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers<br>Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. |