Skip to content

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

Merge storytold/pdfcraft main (picks up the zbus advisory ignores)

skylar taylor-barrick4938bbf272bc
diff --cc crates/edit/src/tests.rs
index e224565d4,88e3d7806..546f1ed4d
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@@ -4981,36 -4251,225 +4982,259 @@@ fn japanese_paragraphs_wrap_between_cha
}
}
+#[test]
+fn test_image_move_does_not_emit_whiteout() {
+ let mut doc = image_page();
+ let imgs = images::page_images(&doc, 0).unwrap();
+ assert_eq!(imgs.len(), 1);
+ let original_rect = imgs[0].rect;
+
+ // Move the image to a new location
+ let target_rect = [original_rect[0] + 50.0, original_rect[1] + 100.0, original_rect[2] + 50.0, original_rect[3] + 100.0];
+ let t = images::rect_to_rect(original_rect, target_rect);
+ images::change_image(&mut doc, 0, 0, &images::ImageChange::Transform(t)).unwrap();
+ let doc = reopen(&doc);
+
+ // Inspect the resulting PDF content stream
+ let bytes = page_content_bytes(&doc, 0);
+ let content = String::from_utf8_lossy(&bytes);
+
+ // Assert that no white fill operators were added
+ assert!(!content.contains("1 1 1 rg"), "must not emit white fill rgb: {content}");
+ assert!(!content.contains("1 g"), "must not emit white fill gray: {content}");
+ assert!(!content.contains("re\nf") && !content.contains("re f"), "must not emit whiteout rect fill: {content}");
+
+ // Assert that the image's cm was cleanly updated to the new position
+ let moved_imgs = images::page_images(&doc, 0).unwrap();
+ assert_eq!(moved_imgs.len(), 1);
+ assert!(close(moved_imgs[0].rect, target_rect), "rect matches target: {:?}", moved_imgs[0].rect);
+ assert!(
+ content.contains(&format!("{} {} cm", moved_imgs[0].matrix[4] as i64, moved_imgs[0].matrix[5] as i64))
+ || content.contains("cm\n /Im0 Do")
+ || content.contains("cm /Im0 Do"),
+ "cm cleanly updated: {content}"
+ );
+}
++
+ /// Small graphics-state oracle for synthetic streams: every tracked state change must
+ /// have been restored when a probe XObject would draw. No external assets are involved.
+ fn probe_states(doc: &Document) -> Vec<std::collections::BTreeMap<Vec<u8>, Vec<Object>>> {
+ let bytes = streams(doc, 0);
+ let joined = pdfcraft_content::Pieces::join(&bytes);
+ let mut state = std::collections::BTreeMap::new();
+ let mut stack = Vec::new();
+ let mut probes = Vec::new();
+ for op in joined.parse().ops {
+ match op.op.as_slice() {
+ b"q" => stack.push(state.clone()),
+ b"Q" => state = stack.pop().expect("balanced graphics state"),
+ b"cm" | b"W" | b"W*" | b"Tz" | b"Tc" | b"Tw" | b"Tr" | b"cs" => {
+ state.insert(op.op, op.operands);
+ }
+ b"Do" if op.name(0) == Some(b"PCProbe") => probes.push(state.clone()),
+ _ => {}
+ }
+ }
+ probes
+ }
+
+ fn isolation_fixture(parts: &[(&str, &str)]) -> Document {
+ let mut doc = fixture();
+ let page = page_list(&doc).remove(0);
+ let list = parts
+ .iter()
+ .map(|(tag, bytes)| {
+ Object::Ref(doc.add(Object::Stream(Stream::from_raw(if tag.is_empty() { Dict::new() } else { tagged(tag) }, bytes.as_bytes().to_vec()))))
+ })
+ .collect();
+ doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list))).unwrap();
+ doc
+ }
+
+ #[test]
+ fn new_marks_isolate_state_appended_after_old_wrappers() {
+ for dirt in ["0.5 0 0 0.5 0 0 cm", "0 0 200 200 re W n", "50 Tz", "5 Tc 20 Tw", "3 Tr", "/Pattern cs"] {
+ for tag in ["", "OCR", "Wrap"] {
+ let mut doc = isolation_fixture(&[
+ ("Wrap", "q %PdfCraft\n"),
+ ("", "2 0 0 2 0 0 cm"),
+ ("Wrap", "Q %PdfCraft\n"),
+ ("Added", "q /PCProbe Do Q"),
+ (tag, dirt),
+ ]);
+ let before = probe_states(&doc);
+ stamp(&mut doc, 0, "Probe", b"q /PCProbe Do Q\n".to_vec()).unwrap();
+ let after = probe_states(&reopen(&doc));
+ assert_eq!(&after[..before.len()], &before, "existing content must not change");
+ assert!(after.last().unwrap().is_empty(), "tag={tag}, dirt={dirt}: {after:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn new_marks_isolate_dirty_tagged_only_pages() {
+ let mut doc = isolation_fixture(&[("OCR", "50 Tz 5 Tc 20 Tw")]);
+ stamp(&mut doc, 0, "Probe", b"q /PCProbe Do Q\n".to_vec()).unwrap();
+ assert!(probe_states(&doc).last().unwrap().is_empty());
+ }
+
+ #[test]
+ fn new_marks_do_not_accumulate_wrappers_for_self_contained_marks() {
+ let mut doc = isolation_fixture(&[("", "2 0 0 2 0 0 cm")]);
+ for _ in 0..10 {
+ stamp(&mut doc, 0, "Probe", b"q /PCProbe Do Q\n".to_vec()).unwrap();
+ }
+ assert_eq!(streams(&doc, 0).len(), 13);
+ assert!(probe_states(&doc).iter().all(|s| s.is_empty()));
+ }
+
+ #[test]
+ fn new_marks_close_wrapper_after_an_unterminated_comment() {
+ let mut doc = isolation_fixture(&[("", "50 Tz % no final newline")]);
+ stamp(&mut doc, 0, "Probe", b"q /PCProbe Do Q\n".to_vec()).unwrap();
+ // Check literal concatenation too: a separator must exist in the saved stream itself,
+ // not just in the inspection parser, or the comment can swallow the closing Q.
+ let bytes = streams(&doc, 0).concat();
+ let parsed = pdfcraft_content::parse(bytes.as_bytes());
+ assert_eq!(parsed.ops.iter().filter(|op| op.is("Q")).count(), 2);
+ assert!(probe_states(&doc).last().unwrap().is_empty());
+ }
+
+ #[test]
+ fn new_marks_wrap_unbalanced_graphics_state_whole_without_changing_it() {
+ // Content that can't be isolated precisely is wrapped whole, as before #3084, instead of
+ // refusing: redaction stamps its boxes after removing the text, so it can't back out.
+ for (data, probe_clean) in [("q 50 Tz", true), ("50 Tz q", true), ("q q Q", true), ("Q 50 Tz", false), ("q Q Q 50 Tz", false)] {
+ let mut doc = isolation_fixture(&[("Wrap", data)]);
+ let page = page_list(&doc).remove(0);
+ place_tagged(&mut doc, &page, "Probe", b"q /PCProbe Do Q".to_vec(), false).unwrap();
+ let after = streams(&doc, 0);
+ assert_eq!(after.len(), 4, "{data}: {after:?}");
+ assert_eq!((after[0].as_str(), after[1].as_str()), ("q %PdfCraft\n", data), "{data}");
+ // A `q` the content leaves open is closed after it, so the mark starts clean. A stray
+ // `Q` pops the wrapper itself: nothing placed after it can undo that.
+ let probe = probe_states_lenient(&doc);
+ assert_eq!(probe.last().unwrap().is_empty(), probe_clean, "{data}: {after:?}");
+ }
+ }
+
+ /// [`probe_states`] for unbalanced content: a `Q` with nothing saved leaves the state as is,
+ /// as renderers do.
+ fn probe_states_lenient(doc: &Document) -> Vec<std::collections::BTreeMap<Vec<u8>, Vec<Object>>> {
+ let joined = pdfcraft_content::Pieces::join(&streams(doc, 0));
+ let mut state = std::collections::BTreeMap::new();
+ let mut stack = Vec::new();
+ let mut probes = Vec::new();
+ for op in joined.parse().ops {
+ match op.op.as_slice() {
+ b"q" => stack.push(state.clone()),
+ b"Q" => state = stack.pop().unwrap_or(state),
+ b"cm" | b"W" | b"W*" | b"Tz" | b"Tc" | b"Tw" | b"Tr" | b"cs" => {
+ state.insert(op.op, op.operands);
+ }
+ b"Do" if op.name(0) == Some(b"PCProbe") => probes.push(state.clone()),
+ _ => {}
+ }
+ }
+ probes
+ }
+
+ #[test]
+ fn new_marks_preserve_cross_stream_operands_and_q_pairs() {
+ let mut doc = isolation_fixture(&[("", "q 2 0 0 2"), ("", "0 0 cm Q 50"), ("", "Tz")]);
+ stamp(&mut doc, 0, "Probe", b"q /PCProbe Do Q\n".to_vec()).unwrap();
+ assert!(probe_states(&doc).last().unwrap().is_empty());
+ }
+
+ #[test]
+ fn removing_marks_keeps_wrappers_needed_by_later_external_content() {
+ let mut doc = isolation_fixture(&[
+ ("Wrap", "q %PdfCraft\n"),
+ ("", "2 0 0 2 0 0 cm"),
+ ("Wrap", "Q %PdfCraft\n"),
+ ("HeaderFooter", "q /PCProbe Do Q"),
+ ("", "/PCProbe Do"),
+ ]);
+ remove_marks(&mut doc, &[0], MarkKind::HeaderFooter).unwrap();
+ assert_eq!(probe_states(&doc).len(), 1);
+ assert!(probe_states(&doc)[0].is_empty(), "the external content still needs the original reset");
+ }
+
+ #[test]
+ fn new_marks_wrap_unfinished_text_paths_and_operands_whole() {
+ for data in ["BT", "ET", "BT BT ET", "0 0 10 10 re", "q 0 0 m Q", "50"] {
+ let mut doc = isolation_fixture(&[("Background", "q Q"), ("", data)]);
+ let page = page_list(&doc).remove(0);
+ place_tagged(&mut doc, &page, "Probe", b"q /PCProbe Do Q".to_vec(), false).unwrap();
+ // The behind-mark stays outside the wrapper and the content itself is untouched.
+ assert_eq!(streams(&doc, 0), ["q Q", "q %PdfCraft\n", data, "\nQ %PdfCraft\n", "q /PCProbe Do Q"], "{data}");
+ }
+ }
+
+ #[test]
+ fn new_marks_do_not_reveal_cross_stream_comments() {
+ let mut doc = isolation_fixture(&[("", "q 50 Tz % comment continues"), ("", "Q 20 Tc\nQ 5 Tw")]);
+ stamp(&mut doc, 0, "Probe", b"q /PCProbe Do Q\n".to_vec()).unwrap();
+ assert!(probe_states(&doc).last().unwrap().is_empty());
+ let joined = pdfcraft_content::Pieces::join(&streams(&doc, 0));
+ assert!(!joined.parse().ops.iter().any(|op| op.is("Tc")), "commented content must remain inert");
+ }
+
+ #[test]
+ fn new_marks_follow_clean_streams_ending_in_comments() {
+ let mut doc = isolation_fixture(&[("Added", "q 50 Tz Q % no newline")]);
+ stamp(&mut doc, 0, "Probe", b"q /PCProbe Do Q\n".to_vec()).unwrap();
+ assert_eq!(probe_states(&doc).len(), 1, "the new mark must not be swallowed by a comment");
+ assert!(probe_states(&doc)[0].is_empty());
+ }
+
+ #[test]
+ fn removing_marks_does_not_strip_arbitrary_wrap_tagged_content() {
+ let mut doc = isolation_fixture(&[("Wrap", "q /PCProbe Do Q"), ("HeaderFooter", "q Q")]);
+ assert_eq!(remove_marks(&mut doc, &[0], MarkKind::HeaderFooter).unwrap(), 1);
+ assert_eq!(probe_states(&doc).len(), 1);
+ }
+
+ #[test]
+ fn removing_marks_strips_nested_trailing_wrapper_pairs() {
+ let mut doc = isolation_fixture(&[
+ ("Wrap", "q %PdfCraft\n"),
+ ("Wrap", "q %PdfCraft\n"),
+ ("", "2 0 0 2 0 0 cm"),
+ ("Wrap", "Q %PdfCraft\n"),
+ ("Wrap", "Q %PdfCraft\n"),
+ ("HeaderFooter", "q Q"),
+ ]);
+ assert_eq!(remove_marks(&mut doc, &[0], MarkKind::HeaderFooter).unwrap(), 1);
+ assert_eq!(streams(&doc, 0), ["2 0 0 2 0 0 cm"]);
+ }
+
+ #[test]
+ fn updating_marks_on_unreadable_content_does_not_nest_wrappers() {
+ for data in ["q 50 Tz", "Q 50 Tz", "BT"] {
+ let mut doc = isolation_fixture(&[("", data)]);
+ let page = page_list(&doc).remove(0);
+ for _ in 0..3 {
+ place_tagged(&mut doc, &page, MarkKind::HeaderFooter.tag(), b"q /PCProbe Do Q".to_vec(), false).unwrap();
+ assert_eq!(streams(&doc, 0).len(), 4, "{data}: {:?}", streams(&doc, 0));
+ assert_eq!(remove_marks(&mut doc, &[0], MarkKind::HeaderFooter).unwrap(), 1);
+ assert_eq!(streams(&doc, 0), [data], "{data}: the original list comes back");
+ }
+ }
+ }
+
+ #[test]
+ fn removing_marks_strips_wrappers_that_closed_open_state() {
+ let mut doc = isolation_fixture(&[("", "q 2 0 0 2 0 0 cm")]);
+ stamp(&mut doc, 0, "Probe", b"q /PCProbe Do Q\n".to_vec()).unwrap();
+ assert!(probe_states(&doc).last().unwrap().is_empty());
+ // Now balanced, the page reads cleanly: the close (with its extra `Q`) still pairs.
+ let page = page_list(&doc).remove(0);
+ place_tagged(&mut doc, &page, MarkKind::Watermark.tag(), b"q /PCProbe Do Q\n".to_vec(), false).unwrap();
+ assert_eq!(streams(&doc, 0).len(), 5, "no second wrapper: {:?}", streams(&doc, 0));
+ let mut doc = isolation_fixture(&[("", "q 2 0 0 2 0 0 cm")]);
+ let page = page_list(&doc).remove(0);
+ place_tagged(&mut doc, &page, MarkKind::Watermark.tag(), b"q /PCProbe Do Q\n".to_vec(), false).unwrap();
+ assert_eq!(remove_marks(&mut doc, &[0], MarkKind::Watermark).unwrap(), 1);
+ assert_eq!(streams(&doc, 0), ["q 2 0 0 2 0 0 cm"]);
+ }