Skip to content

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

fix(edit): isolate added marks from unfinished marked content (#3279)

Ahmad Mu38999b3e906a
diff --git a/ROADMAP.md b/ROADMAP.md
index 79c8fdfa1..bad75fc3b 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -172,6 +172,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
## Progress log
- **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.
- **2026-10-15 (M7, Edit text caret):** In a text region that mixes sizes (a 24 pt title over 12 pt lines), the inline editor's caret on a small row was as tall as the region's first size and reached into the row below: egui draws the caret at least one row of the text field's font tall, and that font had the paragraph's first size. The field's font is now half the region's smallest size, so each row's own height decides. Kittest regression; checked in the app on a real document. Estimates unchanged.
- **2026-10-16 (M3, #2781):** The Pages panel follows the current page, as Acrobat's page thumbnails do: going to a page whose thumbnail is out of sight (scrolling, Page Down, Go to page, a bookmark) scrolls the panel just enough to show it. A thumbnail already in view, or clicked, leaves the panel where it is, and a page change while the user scrolls the panel or drags thumbnails does not move it. Estimates unchanged.
- **2026-10-16 (M12, #1645):** CLI info, text and render use the engine's dynamic XFA layout rather than placeholder pages. Synthetic two-page and encrypted-form regressions cover counts, text, pixels, copy permissions and unchanged input bytes. Estimates unchanged.
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs
index cef8f3c9d..fcf2f1997 100644
--- a/crates/edit/src/lib.rs
+++ b/crates/edit/src/lib.rs
@@ -8,7 +8,8 @@
//! `/PCMark` entry (also in the stream dictionary) names the kind of mark, which is how Update and
//! Remove find them again without decompressing page content. When
//! anything is drawn on top, the page's original content is wrapped in `q … Q` (two tiny streams)
-//! so its graphics state can't leak into the mark.
+//! so its graphics state cannot reach the mark. The closing stream also ends known unfinished
+//! marked-content sequences before the new mark.
//!
//! Text uses standard Helvetica (WinAnsi) added to the page resources as `/PCHelv`.
@@ -332,12 +333,16 @@ const WRAP_OPEN: &[u8] = b"q %PdfCraft\n";
const WRAP_CLOSE: &[u8] = b"\nQ %PdfCraft\n";
const OLD_WRAP_CLOSE: &[u8] = b"Q %PdfCraft\n";
-/// Whether `bytes` are a wrapper's close: [`WRAP_CLOSE`] after a `Q` for each `q` the wrapped
-/// content left open, or [`OLD_WRAP_CLOSE`].
+/// Whether `bytes` are a wrapper's close: canonical `EMC` closures, then the existing
+/// graphics closures. Legacy closes without the leading newline remain valid on their own.
fn is_wrap_close(bytes: &[u8]) -> bool {
let mut rest = bytes;
+ while let Some(shorter) = rest.strip_prefix(b"\nEMC".as_slice()) {
+ rest = shorter;
+ }
+ let legacy = rest.len() == bytes.len();
loop {
- if rest == WRAP_CLOSE || rest == OLD_WRAP_CLOSE {
+ if rest == WRAP_CLOSE || (legacy && rest == OLD_WRAP_CLOSE) {
return true;
}
match rest.strip_prefix(b"\nQ".as_slice()) {
@@ -387,11 +392,13 @@ enum Isolation {
/// `suffix`: the stream from which the content leaves graphics state set (or a comment open)
/// that a mark on top must not inherit, so it needs a wrapper from there to the end.
/// `wrappers`: PdfCraft wrapper pairs (open, close) as stream indexes.
- Clean { suffix: Option<usize>, wrappers: Vec<(usize, usize)> },
+ /// `marked`: unfinished marked-content sequences to close before a new mark.
+ Clean { suffix: Option<usize>, wrappers: Vec<(usize, usize)>, marked: usize },
/// The content could not be read that precisely (it doesn't decode, is too large, or has
/// stray bytes, unbalanced `q`/`Q` or an unfinished text object or path). `unclosed` is
- /// the count of `q` left open at the end, when known.
- Unknown { unclosed: usize },
+ /// the count of `q` left open at the end, when known. `marked` counts known unfinished
+ /// marked-content sequences independently of graphics malformation, or zero when unknown.
+ Unknown { unclosed: usize, marked: usize },
}
const ISOLATION_MAX_STREAMS: usize = 100_000;
@@ -400,7 +407,7 @@ const ISOLATION_MAX_OPS: usize = 1_000_000;
const ISOLATION_MAX_DEPTH: usize = 10_000;
fn isolation(doc: &Document, list: &[Object]) -> Isolation {
- let unknown = Isolation::Unknown { unclosed: 0 };
+ let unknown = Isolation::Unknown { unclosed: 0, marked: 0 };
if list.len() > ISOLATION_MAX_STREAMS {
return unknown;
}
@@ -422,14 +429,17 @@ fn isolation(doc: &Document, list: &[Object]) -> Isolation {
let edges = pieces.comment_edges(&parsed);
let (mut text_open, mut path_open, mut dirty, mut malformed) = (false, false, false, false);
let mut stack: Vec<usize> = Vec::new();
+ let (mut marked, mut marked_known) = (0usize, true);
let mut split = 0;
let mut previous_last = None;
let mut wrappers = Vec::new();
for op in &parsed.ops {
let (first, last) = pieces.pieces_of(op);
- // A wrapper can only go in before a whole stream, at the top level, between operators,
- // and where no comment runs into the stream (it would swallow the wrapper's `q`).
+ // A wrapper can only go in before a whole stream, outside graphics and marked-content
+ // scopes, between operators, where no comment would swallow the wrapper's `q`.
if stack.is_empty()
+ && marked_known
+ && marked == 0
&& !text_open
&& !path_open
&& !dirty
@@ -439,6 +449,26 @@ fn isolation(doc: &Document, list: &[Object]) -> Isolation {
split = first;
}
previous_last = Some(last);
+ // Match the reader's tolerant operands: BMC uses the last name, BDC the last
+ // name/object pair, and EMC ignores surplus operands. Invalid begins are ignored.
+ let begin_marked = match op.op.as_slice() {
+ b"BMC" => op.operands.last().is_some_and(|o| matches!(o, Object::Name(_))),
+ b"BDC" => op.operands.len().checked_sub(2).and_then(|i| op.operands.get(i)).is_some_and(|o| matches!(o, Object::Name(_))),
+ _ => false,
+ };
+ if marked_known {
+ if begin_marked {
+ if marked < ISOLATION_MAX_DEPTH {
+ marked += 1;
+ } else {
+ // Once the budget is exceeded, later EMCs cannot restore a known depth.
+ marked_known = false;
+ marked = 0;
+ }
+ } else if op.is("EMC") {
+ marked = marked.saturating_sub(1);
+ }
+ }
match op.op.as_slice() {
b"BT" if !text_open => text_open = true,
b"ET" if text_open => text_open = false,
@@ -468,11 +498,11 @@ fn isolation(doc: &Document, list: &[Object]) -> Isolation {
_ => {}
}
}
- if malformed || text_open || path_open || !stack.is_empty() {
- return Isolation::Unknown { unclosed: if malformed { 0 } else { stack.len() } };
+ if malformed || text_open || path_open || !stack.is_empty() || !marked_known {
+ return Isolation::Unknown { unclosed: if malformed { 0 } else { stack.len() }, marked };
}
let comment_open = edges.last().is_some_and(|edge| edge.1);
- Isolation::Clean { suffix: (dirty || comment_open).then_some(split), wrappers }
+ Isolation::Clean { suffix: (dirty || comment_open || marked != 0).then_some(split), wrappers, marked }
}
/// Put a mark's content on a page: behind (prepended) or on top (appended, after wrapping the
@@ -484,21 +514,22 @@ fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, conten
/// Put content on a page, tagged `tag` (see [`place`]). On top, whatever graphics state the
/// content before leaves set (a `cm`, a clip, text state…) must not reach the mark, including
/// content appended after an earlier PdfCraft wrapper by another tool (#3084): the stretch of
-/// content that leaves state set is wrapped in q/Q, once.
+/// content that leaves state set is wrapped in q/Q, once. Any known unfinished marked-content
+/// sequences are closed at the end too, so hidden optional content cannot hide the new mark.
fn place_tagged(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
let mut list = contents(doc, page)?;
let wrap = if behind {
None
} else {
match isolation(doc, &list) {
- Isolation::Clean { suffix, .. } => suffix.map(|split| (split, 0)),
+ Isolation::Clean { suffix, marked, .. } => suffix.map(|split| (split, 0, marked)),
// Content that can't be read precisely is wrapped whole, as before: after the
// behind-marks at the start. A `q` it leaves open is closed at its end, where
// closing it changes nothing already drawn.
- Isolation::Unknown { unclosed } => {
+ Isolation::Unknown { unclosed, marked } => {
let behind_kinds = [MarkKind::Background.tag(), MarkKind::Watermark.tag()];
let split = list.iter().position(|o| !stream_tag(doc, o).is_some_and(|t| behind_kinds.contains(&t.as_str()))).unwrap_or(list.len());
- (split < list.len()).then_some((split, unclosed))
+ (split < list.len()).then_some((split, unclosed, marked))
}
}
};
@@ -506,8 +537,9 @@ fn place_tagged(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, cont
if behind {
list.insert(0, mark);
} else {
- if let Some((split, unclosed)) = wrap {
- let mut close_bytes = b"\nQ".repeat(unclosed);
+ if let Some((split, unclosed, marked)) = wrap {
+ let mut close_bytes = b"\nEMC".repeat(marked);
+ close_bytes.extend_from_slice(&b"\nQ".repeat(unclosed));
close_bytes.extend_from_slice(WRAP_CLOSE);
let open = Object::Ref(doc.add(Object::Stream(Stream::from_raw(tagged("Wrap"), WRAP_OPEN.to_vec()))));
let close = Object::Ref(doc.add(Object::Stream(Stream::from_raw(tagged("Wrap"), close_bytes))));
@@ -836,5 +868,7 @@ pub use added::{
update_content,
};
+#[cfg(test)]
+mod marked_isolation_tests;
#[cfg(test)]
mod tests;
diff --git a/crates/edit/src/marked_isolation_tests.rs b/crates/edit/src/marked_isolation_tests.rs
new file mode 100644
index 000000000..6da832229
--- /dev/null
+++ b/crates/edit/src/marked_isolation_tests.rs
@@ -0,0 +1,122 @@
+use super::*;
+
+fn fixture(parts: &[&[u8]]) -> Document {
+ let mut doc = Document::new_empty();
+ let pages = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();
+ let streams = parts.iter().map(|data| Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), data.to_vec()))))).collect();
+ let mut page = Dict::new();
+ page.set(b"Type".to_vec(), Object::name("Page"));
+ page.set(b"Parent".to_vec(), Object::Ref(pages));
+ page.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 600.into(), 800.into()]));
+ page.set(b"Contents".to_vec(), Object::Array(streams));
+ let page = doc.add(page);
+ doc.update_dict(pages, |d| {
+ d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)]));
+ d.set(b"Count".to_vec(), Object::Int(1));
+ })
+ .unwrap();
+ doc
+}
+
+fn placed(parts: &[&[u8]]) -> (Document, Vec<Object>) {
+ let mut doc = fixture(parts);
+ stamp(&mut doc, 0, "Probe", b"q Q\n".to_vec()).unwrap();
+ let page = page_list(&doc).remove(0);
+ let list = contents(&mut doc, &page).unwrap();
+ (doc, list)
+}
+
+fn close(parts: &[&[u8]]) -> Vec<u8> {
+ let (doc, list) = placed(parts);
+ let object = &list[list.len() - 2];
+ assert_eq!(stream_tag(&doc, object).as_deref(), Some("Wrap"));
+ let bytes = stream_bytes(&doc, object).unwrap();
+ assert_eq!(wrapper_role(&doc, object), Some(false));
+ bytes
+}
+
+#[test]
+fn closes_only_marked_operators_not_strings_names_comments_or_image_samples() {
+ for tail in
+ [b"/Span << /Text (BMC BDC EMC) >> DP".as_slice(), b"/BMC /EMC DP", b"% BMC BDC EMC", b"BI /W 11 /H 1 /BPC 8 /CS /G ID BMC BDC EMC EI\n"]
+ {
+ let mut input = b"/OC /L1 BDC\n".to_vec();
+ input.extend_from_slice(tail);
+ assert_eq!(close(&[&input]), b"\nEMC\nQ %PdfCraft\n", "{tail:?}");
+ }
+}
+
+#[test]
+fn safe_suffix_stays_outside_marked_content_across_balanced_graphics() {
+ let (doc, list) = placed(&[b"q /OC /L1 BDC Q", b"50 Tz"]);
+ assert_eq!(stream_bytes(&doc, &list[0]).unwrap(), WRAP_OPEN);
+ assert_eq!(stream_bytes(&doc, &list[1]).unwrap(), b"q /OC /L1 BDC Q");
+ assert_eq!(stream_bytes(&doc, &list[list.len() - 2]).unwrap(), b"\nEMC\nQ %PdfCraft\n");
+ assert_eq!(close(&[b"q /OC /L1 BDC Q"]), b"\nEMC\nQ %PdfCraft\n");
+}
+
+#[test]
+fn known_marked_depth_survives_unknown_graphics_and_tolerant_operands() {
+ for (input, expected) in [
+ (b"/OC /L1 BDC q".as_slice(), b"\nEMC\nQ\nQ %PdfCraft\n".as_slice()),
+ (b"Q /OC /L1 BDC", b"\nEMC\nQ %PdfCraft\n"),
+ (b"/OC /L1 BDC BT", b"\nEMC\nQ %PdfCraft\n"),
+ (b"/OC /L1 BDC 0 0 m", b"\nEMC\nQ %PdfCraft\n"),
+ (b"/OC /L1 BDC 123 BMC /Artifact BDC", b"\nEMC\nQ %PdfCraft\n"),
+ (b"EMC 123 /OC /L1 BDC 123 /Artifact BMC", b"\nEMC\nEMC\nQ %PdfCraft\n"),
+ (b"/OC /L1 BDC 123 EMC", b"\nQ %PdfCraft\n"),
+ (b"/Span 123 BDC", b"\nEMC\nQ %PdfCraft\n"),
+ ] {
+ assert_eq!(close(&[input]), expected, "{input:?}");
+ }
+}
+
+#[test]
+fn closes_cross_stream_begins_without_closing_balanced_sequences_twice() {
+ assert_eq!(close(&[b"/OC", b"/L1 BDC"]), b"\nEMC\nQ %PdfCraft\n");
+ assert_eq!(close(&[b"/OC /L1 BDC", b"EMC"]), WRAP_CLOSE);
+ assert_eq!(close(&[b"/OC /L1 BDC % EMC", b"EMC\n"]), b"\nEMC\nQ %PdfCraft\n");
+}
+
+#[test]
+fn recognizes_only_canonical_new_closes_and_retains_legacy_closes() {
+ for bytes in [WRAP_CLOSE, OLD_WRAP_CLOSE, b"\nQ\nQ %PdfCraft\n", b"\nEMC\nQ %PdfCraft\n", b"\nEMC\nEMC\nQ\nQ %PdfCraft\n"] {
+ assert!(is_wrap_close(bytes), "{bytes:?}");
+ }
+ for bytes in [
+ b"\nEMCQ %PdfCraft\n".as_slice(),
+ b"\nEMC\nQQ %PdfCraft\n",
+ b"\nQ\nEMC\nQ %PdfCraft\n",
+ b"EMC\nQ %PdfCraft\n",
+ b"\nEMC 1 w\nQ %PdfCraft\n",
+ b"\nEMC\nQ %PdfCraft\nq Q",
+ ] {
+ assert!(!is_wrap_close(bytes), "{bytes:?}");
+ }
+}
+
+#[test]
+fn depth_budget_bounds_emitted_closures_and_overflow_stays_unknown() {
+ let maximum = b"/Artifact BMC\n".repeat(ISOLATION_MAX_DEPTH);
+ let mut expected = b"\nEMC".repeat(ISOLATION_MAX_DEPTH);
+ expected.extend_from_slice(WRAP_CLOSE);
+ assert_eq!(close(&[&maximum]), expected);
+ let mut combined = maximum.clone();
+ combined.extend_from_slice(&b"q\n".repeat(ISOLATION_MAX_DEPTH));
+ let mut expected = b"\nEMC".repeat(ISOLATION_MAX_DEPTH);
+ expected.extend_from_slice(&b"\nQ".repeat(ISOLATION_MAX_DEPTH));
+ expected.extend_from_slice(WRAP_CLOSE);
+ assert_eq!(close(&[&combined]), expected);
+ assert!(expected.len() < 64 * 1024, "maximum generated close remains recognizable for removal");
+ let mut doc = fixture(&[&combined]);
+ let page = page_list(&doc).remove(0);
+ let original = contents(&mut doc, &page).unwrap();
+ place_tagged(&mut doc, &page, MarkKind::HeaderFooter.tag(), b"q Q\n".to_vec(), false).unwrap();
+ assert_eq!(remove_marks(&mut doc, &[0], MarkKind::HeaderFooter).unwrap(), 1);
+ assert_eq!(contents(&mut doc, &page).unwrap(), original, "maximum combined close can be removed without nesting wrappers");
+ for suffix in [b"/Artifact BMC\n".as_slice(), b"/Artifact BMC\nEMC\n", b"/Artifact BMC\nEMC\nEMC\n"] {
+ let mut over = maximum.clone();
+ over.extend_from_slice(suffix);
+ assert_eq!(close(&[&over]), WRAP_CLOSE, "overflow cannot resume speculative depth tracking after EMC");
+ }
+}
diff --git a/crates/engine/tests/marked_content_isolation.rs b/crates/engine/tests/marked_content_isolation.rs
new file mode 100644
index 000000000..32a42d517
--- /dev/null
+++ b/crates/engine/tests/marked_content_isolation.rs
@@ -0,0 +1,274 @@
+//! Contributor-original pages. Added marks must not inherit an unfinished hidden layer.
+use std::sync::Arc;
+
+use pdfcraft_cos::{Dict, Document, Object, SaveOptions, Stream, write_incremental};
+use pdfcraft_engine::{AddedText, Edit, HeaderFooter, Session, Watermark};
+use pdfcraft_render::{PageRenderer, RenderRequest, RequestKind};
+
+const VISIBLE: &str = "BT /F1 18 Tf 72 700 Td (Visible text) Tj ET\n";
+const HIDDEN: &str = "BT /F1 18 Tf 72 600 Td (Hidden note) Tj ET\n";
+
+fn fixture(parts: &[String]) -> Arc<Vec<u8>> {
+ let mut doc = Document::new_empty();
+ let pages = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();
+ let mut font = Dict::new();
+ font.set(b"Type".to_vec(), Object::name("Font"));
+ font.set(b"Subtype".to_vec(), Object::name("Type1"));
+ font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
+ let mut fonts = Dict::new();
+ fonts.set(b"F1".to_vec(), Object::Ref(doc.add(font)));
+ let mut group = Dict::new();
+ group.set(b"Type".to_vec(), Object::name("OCG"));
+ group.set(b"Name".to_vec(), Object::String(pdfcraft_cos::PdfString::text("Hidden layer")));
+ let group = doc.add(group);
+ let mut properties = Dict::new();
+ properties.set(b"L1".to_vec(), Object::Ref(group));
+ let mut resources = Dict::new();
+ resources.set(b"Font".to_vec(), Object::Dict(fonts));
+ resources.set(b"Properties".to_vec(), Object::Dict(properties));
+ let mut config = Dict::new();
+ config.set(b"OFF".to_vec(), Object::Array(vec![Object::Ref(group)]));
+ let mut oc = Dict::new();
+ oc.set(b"OCGs".to_vec(), Object::Array(vec![Object::Ref(group)]));
+ oc.set(b"D".to_vec(), Object::Dict(config));
+ doc.update_dict(doc.root().unwrap(), |d| d.set(b"OCProperties".to_vec(), Object::Dict(oc))).unwrap();
+ let streams = parts.iter().map(|s| Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), s.as_bytes().to_vec()))))).collect();
+ let mut page = Dict::new();
+ page.set(b"Type".to_vec(), Object::name("Page"));
+ page.set(b"Parent".to_vec(), Object::Ref(pages));
+ page.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));
+ page.set(b"Resources".to_vec(), Object::Dict(resources));
+ page.set(b"Contents".to_vec(), Object::Array(streams));
+ let page = doc.add(page);
+ doc.update_dict(pages, |d| {
+ d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)]));
+ d.set(b"Count".to_vec(), Object::Int(1));
+ })
+ .unwrap();
+ Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())
+}
+
+fn render(bytes: Arc<Vec<u8>>) -> (Vec<u8>, String) {
+ let mut renderer = PageRenderer::new(bytes, Default::default());
+ let pixels = renderer.render(RenderRequest { page: 0, scale: 1.0, ..Default::default() });
+ assert!(pixels.error.is_none(), "{:?}", pixels.error);
+ let text = renderer.render(RenderRequest { page: 0, kind: RequestKind::Text, ..Default::default() });
+ assert!(text.error.is_none(), "{:?}", text.error);
+ let text = text.text.unwrap();
+ (pixels.rgba.to_vec(), text.text_of(0..text.glyphs.len()))
+}
+
+fn edit(kind: &str) -> Edit {
+ match kind {
+ "HEADER" | "000001" => {
+ let mut settings = HeaderFooter::default();
+ if kind == "HEADER" {
+ settings.text[1] = "HEADER".into();
+ } else {
+ settings.text[5] = "<<Bates Number#6#1##>>".into();
+ }
+ Edit::AddHeaderFooter { pages: vec![0], settings, replace: true }
+ }
+ "WATERMARK" => Edit::AddWatermark {
+ pages: vec![0],
+ settings: Watermark { text: kind.into(), opacity: 1.0, rotation: 0.0, font_size: 18.0, ..Default::default() },
+ replace: true,
+ file: None,
+ },
+ "ADDED" => Edit::AddText { page: 0, text: AddedText { text: kind.into(), rect: [72.0, 300.0, 250.0, 330.0], ..Default::default() } },
+ _ => panic!("unknown mark"),
+ }
+}
+
+fn add_and_save(input: Arc<Vec<u8>>, kind: &str) -> Arc<Vec<u8>> {
+ let mut session = Session::new();
+ let id = session.open("fixture.pdf", None, input.clone(), None).unwrap();
+ session.apply(id, edit(kind)).unwrap();
+ let saved = session.save_bytes(id).unwrap();
+ assert!(saved.starts_with(&input), "incremental save preserves the original file bytes");
+ assert_original_streams(&input, &saved);
+ let mut reopened = Session::new();
+ let id = reopened.open("saved.pdf", None, saved.clone(), None).unwrap();
+ assert_eq!(reopened.save_bytes(id).unwrap().as_slice(), saved.as_slice());
+ saved
+}
+
+#[test]
+fn all_four_mark_paths_remain_visible_after_saved_unfinished_marked_content() {
+ let mut failures = Vec::new();
+ for (case, opening, hidden) in [("hidden", "/OC /L1 BDC\n", true), ("artifact", "/Artifact BMC\n", false), ("balanced", "/OC /L1 BDC\n", true)] {
+ let closed = fixture(&[format!("{VISIBLE}{opening}{HIDDEN}EMC\n")]);
+ let input = if case == "balanced" { closed.clone() } else { fixture(&[format!("{VISIBLE}{opening}{HIDDEN}")]) };
+ let original = render(input.clone());
+ assert!(original.1.contains("Visible text"));
+ assert_eq!(original.1.contains("Hidden note"), !hidden);
+ for kind in ["HEADER", "000001", "WATERMARK", "ADDED"] {
+ let saved = add_and_save(input.clone(), kind);
+
+ let actual = render(saved);
+ let expected_bytes = add_and_save(closed.clone(), kind);
+
+ let expected = render(expected_bytes);
+ let mut wanted = vec!["Visible text", kind];
+ if !hidden {
+ wanted.push("Hidden note");
+ }
+ wanted.sort_unstable();
+ let pass = actual.0 == expected.0 && actual.1 == expected.1 && lines(&actual.1) == wanted;
+ eprintln!("{case}/{kind}: visible={} closed-control-pixels={}", actual.1.contains(kind), actual.0 == expected.0);
+ if !pass {
+ failures.push(format!("{case}/{kind}: {:?}", actual.1));
+ }
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
+
+fn stream_list(doc: &Document) -> Vec<Object> {
+ let page = pdfcraft_model::pages(doc).remove(0);
+ let contents = doc.resolve(page.dict.get(b"Contents").unwrap());
+ match &*contents {
+ Object::Array(items) => items.clone(),
+ _ => vec![page.dict.get(b"Contents").unwrap().clone()],
+ }
+}
+
+fn assert_original_streams(before: &Arc<Vec<u8>>, after: &Arc<Vec<u8>>) {
+ let original = Document::open(before.clone()).unwrap();
+ let saved = Document::open(after.clone()).unwrap();
+ let saved_list = stream_list(&saved);
+ for reference in stream_list(&original) {
+ assert!(saved_list.contains(&reference), "the original stream stays on the page");
+ assert_eq!(original.resolve(&reference), saved.resolve(&reference), "original encoded stream object remains unchanged");
+ }
+}
+
+fn lines(text: &str) -> Vec<&str> {
+ let mut lines: Vec<_> = text.lines().filter(|line| !line.is_empty()).collect();
+ lines.sort_unstable();
+ lines
+}
+
+#[test]
+fn nested_stream_edges_and_malformed_graphics_keep_hidden_content_hidden() {
+ let cases: Vec<(&str, Vec<String>, usize)> = vec![
+ ("nested", vec![format!("{VISIBLE}/OC /L1 BDC /Artifact BMC {HIDDEN}")], 2),
+ ("split operands", vec![format!("{VISIBLE}/OC"), format!("/L1 BDC {HIDDEN}")], 1),
+ ("split close", vec![format!("{VISIBLE}/OC /L1 BDC {HIDDEN}"), "EMC\n".into()], 0),
+ ("trailing comment", vec![format!("{VISIBLE}/OC /L1 BDC {HIDDEN}% EMC")], 1),
+ ("cross-stream comment", vec![format!("{VISIBLE}/OC /L1 BDC {HIDDEN}% EMC"), "EMC BMC\n".into()], 1),
+ ("unclosed graphics", vec![format!("{VISIBLE}/OC /L1 BDC {HIDDEN}q")], 1),
+ ("balanced graphics open marked", vec![format!("q {VISIBLE}/OC /L1 BDC {HIDDEN}Q")], 1),
+ ("malformed graphics", vec![format!("Q {VISIBLE}/OC /L1 BDC {HIDDEN}")], 1),
+ ("invalid begins", vec![format!("{VISIBLE}/OC /L1 BDC {HIDDEN}123 BMC /Artifact BDC")], 1),
+ ("extra begins", vec![format!("{VISIBLE}123 /OC /L1 BDC {HIDDEN}123 /Artifact BMC")], 2),
+ ("extra close", vec![format!("{VISIBLE}/OC /L1 BDC {HIDDEN}123 EMC")], 0),
+ ("underflow", vec![format!("EMC {VISIBLE}/OC /L1 BDC {HIDDEN}")], 1),
+ ("operator strings", vec![format!("{VISIBLE}/OC /L1 BDC {HIDDEN}/Note <</Text (BMC BDC EMC)>> DP")], 1),
+ ("inline samples", vec![format!("{VISIBLE}/OC /L1 BDC {HIDDEN}BI /W 11 /H 1 /BPC 8 /CS /G ID BMC BDC EMC EI\n")], 1),
+ ];
+ for (case, parts, close_count) in cases {
+ let input = fixture(&parts);
+ let mut closed = parts.clone();
+ closed.push(format!("\n{}", "EMC\n".repeat(close_count)));
+ let actual = render(add_and_save(input, "HEADER"));
+ let expected = render(add_and_save(fixture(&closed), "HEADER"));
+ assert_eq!(lines(&actual.1), lines("Visible text\nHEADER"), "{case}");
+ assert!(actual.0 == expected.0, "{case}: pixels equal the explicitly closed control");
+ }
+}
+
+#[test]
+fn replacing_and_removing_marks_restores_the_original_stream_list() {
+ let input = fixture(&[format!("{VISIBLE}/OC /L1 BDC {HIDDEN}")]);
+ let original = Document::open(input.clone()).unwrap();
+ for kind in ["HEADER", "000001", "WATERMARK"] {
+ let mut session = Session::new();
+ let mut id = session.open("fixture.pdf", None, input.clone(), None).unwrap();
+ for _ in 0..3 {
+ session.apply(id, edit(kind)).unwrap();
+ let saved = session.save_bytes(id).unwrap();
+ let page = Document::open(saved.clone()).unwrap();
+ assert_eq!(stream_list(&page).len(), 4, "{kind}: updating does not add wrappers");
+ assert_original_streams(&input, &saved);
+ assert_eq!(lines(&render(saved.clone()).1), lines(&format!("Visible text\n{kind}")));
+ session = Session::new();
+ id = session.open("saved.pdf", None, saved, None).unwrap();
+ }
+ let mark_kind = if kind == "WATERMARK" { pdfcraft_edit::MarkKind::Watermark } else { pdfcraft_edit::MarkKind::HeaderFooter };
+ session.apply(id, Edit::RemoveMarks { kind: mark_kind }).unwrap();
+ let saved = session.save_bytes(id).unwrap();
+ let page = Document::open(saved.clone()).unwrap();
+ assert_eq!(stream_list(&page), stream_list(&original), "{kind}: removal restores original references");
+ assert_original_streams(&input, &saved);
+ assert!(render(saved) == render(input.clone()), "{kind}: removal restores original pixels and text");
+ session.undo(id).unwrap();
+ assert_eq!(lines(&render(session.save_bytes(id).unwrap()).1), lines(&format!("Visible text\n{kind}")));
+ session.redo(id).unwrap();
+ assert!(render(session.save_bytes(id).unwrap()) == render(input.clone()), "redo removal restores the original rendering");
+ }
+}
+
+#[test]
+fn added_update_delete_and_readd_preserve_existing_wrapper_behavior() {
+ let input = fixture(&[format!("{VISIBLE}/OC /L1 BDC {HIDDEN}")]);
+ let mut session = Session::new();
+ let mut id = session.open("fixture.pdf", None, input.clone(), None).unwrap();
+ for _ in 0..3 {
+ session.apply(id, edit("ADDED")).unwrap();
+ assert_eq!(session.get(id).unwrap().added().len(), 1);
+ let text = AddedText { text: "UPDATED".into(), rect: [72.0, 300.0, 250.0, 330.0], ..Default::default() };
+ session.apply(id, Edit::UpdateContent { page: 0, index: 0, content: pdfcraft_edit::Content::Text(text) }).unwrap();
+ let saved = session.save_bytes(id).unwrap();
+ assert_eq!(lines(&render(saved.clone()).1), lines("Visible text\nUPDATED"));
+ assert_eq!(stream_list(&Document::open(saved.clone()).unwrap()).len(), 4);
+ assert_original_streams(&input, &saved);
+ session = Session::new();
+ id = session.open("saved.pdf", None, saved, None).unwrap();
+ session.apply(id, Edit::DeleteContent { page: 0, index: 0 }).unwrap();
+ let saved = session.save_bytes(id).unwrap();
+ assert_eq!(stream_list(&Document::open(saved.clone()).unwrap()).len(), 3, "Added deletion retains the established wrappers");
+ assert!(render(saved.clone()) == render(input.clone()), "deleting Added restores the original rendering");
+ assert_original_streams(&input, &saved);
+ session = Session::new();
+ id = session.open("saved.pdf", None, saved, None).unwrap();
+ }
+}
+
+#[test]
+fn an_existing_behind_watermark_does_not_inherit_or_reveal_hidden_content() {
+ let input = fixture(&[format!("{VISIBLE}/OC /L1 BDC {HIDDEN}")]);
+ let mut session = Session::new();
+ let id = session.open("fixture.pdf", None, input.clone(), None).unwrap();
+ session
+ .apply(
+ id,
+ Edit::AddWatermark {
+ pages: vec![0],
+ settings: Watermark { text: "BEHIND".into(), behind: true, font_size: 18.0, opacity: 1.0, rotation: 0.0, ..Default::default() },
+ replace: false,
+ file: None,
+ },
+ )
+ .unwrap();
+ session.apply(id, edit("HEADER")).unwrap();
+ let saved = session.save_bytes(id).unwrap();
+ assert_eq!(lines(&render(saved.clone()).1), lines("Visible text\nBEHIND\nHEADER"));
+ assert_original_streams(&input, &saved);
+}
+
+#[test]
+fn new_mark_closes_hidden_content_appended_after_an_old_wrapper() {
+ let bytes = fixture(&["q %PdfCraft\n".into(), VISIBLE.into(), "Q %PdfCraft\n".into(), format!("/OC /L1 BDC {HIDDEN}")]);
+ let mut doc = Document::open(bytes).unwrap();
+ let list = stream_list(&doc);
+ for index in [0, 2] {
+ let reference = list[index].as_ref().unwrap();
+ let Object::Stream(mut stream) = doc.get(reference).as_ref().clone() else { panic!("stream") };
+ stream.dict.set(b"PCMark".to_vec(), Object::name("Wrap"));
+ doc.set(reference, Object::Stream(stream));
+ }
+ let input = Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap());
+ let saved = add_and_save(input, "HEADER");
+ assert_eq!(lines(&render(saved).1), lines("Visible text\nHEADER"));
+}
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 61793f629..e1fdce650 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -138,7 +138,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; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV delimiters without changing field identities.<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: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
| 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). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks |
| 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). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. #1316: replacing a line or paragraph keeps a neighbouring line whose glyph box overlaps when the baselines differ; a second copy on the same baseline is still replaced. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks |
-| 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), watermark print/screen visibility and repeat |
+| 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). #3212: Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, without revealing hidden content. Missing: editing existing text and images in place (the longest pole), watermark print/screen visibility and repeat |
| 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; XFDF values retain text across XML comments and processing instructions.<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: Existing simple field-font encodings and Differences are respected when generating appearances; an unencodable value uses a separate Helvetica appearance font without changing the source font. Synthetic reopen regressions cover punctuation, subset fallback and multiline text. Exact font metrics/layout and broader Unicode fallback remain incomplete. |
| 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; XFDF values retain text across XML comments and processing instructions.<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 |