PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(edit): merge main into paragraph background repair
jonathanwxh-cell958914e72bad
diff --cc crates/edit/src/tests.rsindex 1a0940617,88e3d7806..d4ced87a6--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@@ -4250,102 -4251,225 +4251,325 @@@ fn japanese_paragraphs_wrap_between_cha}}+#[test]+fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() {+ // Each row has its own background box drawn immediately before its BT..ET, as cards and+ // highlighted headings exported from LibreOffice or browsers do (#2377).+ let card = "0 0.45 0.25 rg 60 696 240 16 re f BT /F1 10 Tf 1 1 1 rg 64 700 Td (SEMINARIO ONLINE) Tj ET \+ 0 0.45 0.25 rg 60 668 240 24 re f BT /F1 16 Tf 1 1 1 rg 64 674 Td (Dalla teoria alla pratica:) Tj ET \+ 0 0.45 0.25 rg 60 632 240 32 re f BT /F1 24 Tf 1 1 1 rg 64 640 Td (gestire con metodo) Tj ET \+ 0 0.45 0.25 rg 60 596 240 32 re f BT /F1 24 Tf 1 1 1 rg 64 604 Td (un progetto complesso) Tj ET";+ let shown_at = |ops: &[pdfcraft_content::Op], needle: &str| {+ ops.iter()+ .position(|op| {+ matches!(op.op.as_slice(), b"Tj" | b"TJ")+ && op.operands.iter().any(|o| matches!(o, Object::String(s) if String::from_utf8_lossy(&s.bytes).contains(needle)))+ })+ .unwrap()+ };++ // 1. Editing the title rows emits all rewritten rows after all four background fills.+ let mut doc = text_page(card);+ assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 1);+ let edited = "SEMINARIO ONLINE\nDalla teoria alla pratica:\ngestire con criterio\nun progetto nuovo";+ text::rewrite_block(&mut doc, 0, 0, Some(edited), &text::BlockStyle::default()).unwrap();+ let doc = reopen(&doc);+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].editor_text, edited);+ let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;+ let fills: Vec<usize> = ops.iter().enumerate().filter_map(|(i, op)| op.is("f").then_some(i)).collect();+ assert_eq!(fills.len(), 4);+ assert!(+ shown_at(&ops, "criterio") > fills[3] && shown_at(&ops, "nuovo") > fills[3],+ "rewritten title rows must be drawn after their row background fills (fills at {fills:?}): {ops:?}"+ );++ // 2. Partial edit with a kept suffix row: rewritten rows 0..=2 are drawn after fills[0..=2]+ // and still before kept row 3, preserving reading order.+ let mut doc = text_page(card);+ let partial = "WORKSHOP ONLINE\nDalla teoria alla pratica:\ngestire con criterio\nun progetto complesso";+ text::rewrite_block(&mut doc, 0, 0, Some(partial), &text::BlockStyle::default()).unwrap();+ let doc = reopen(&doc);+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].editor_text, partial);+ let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;+ let fills: Vec<usize> = ops.iter().enumerate().filter_map(|(i, op)| op.is("f").then_some(i)).collect();+ assert!(+ shown_at(&ops, "WORKSHOP") > fills[2]+ && shown_at(&ops, "pratica:") > fills[2]+ && shown_at(&ops, "criterio") > fills[2]+ && shown_at(&ops, "criterio") < shown_at(&ops, "complesso")+ && shown_at(&ops, "complesso") > fills[3],+ "rewritten prefix rows must follow their fills and precede the kept final row"+ );++ // 3. Editing row 2 so that it wraps pushes row 3 down; all rewritten rows must follow fills[3].+ let mut doc = text_page(card);+ let wrapped_edit = "SEMINARIO ONLINE\nDalla teoria alla pratica:\ngestire con criterio e metodo approfondito\nun progetto complesso";+ text::rewrite_block(&mut doc, 0, 0, Some(wrapped_edit), &text::BlockStyle::default()).unwrap();+ let doc = reopen(&doc);+ let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;+ let last_fill = ops.iter().rposition(|op| op.is("f")).unwrap();+ assert!(+ shown_at(&ops, "approfondito") > last_fill && shown_at(&ops, "complesso") > last_fill,+ "wrapped rows and pushed-down suffix row must follow all row background fills"+ );++ // 4. Single-style paragraph path across a CTM change between rows, with movement, underline,+ // and a trailing unrelated line sharing the second row's BT..ET.+ let cross_ctm = "0.9 0.9 0.2 rg 60 696 240 18 re f BT /F1 12 Tf 0 0 0 rg 64 700 Td (First highlighted row) Tj ET \+ q 1 0 0 1 10 12 cm 0.9 0.9 0.2 rg 50 668 240 18 re f \+ BT /F1 12 Tf 0 0 0 rg 54 672 Td (Second highlighted row) Tj 246 -40 Td (Side footer) Tj ET Q";+ let mut doc = text_page(cross_ctm);+ let para = text::text_blocks(&doc, 0).unwrap().into_iter().position(|b| b.text.starts_with("First highlighted")).unwrap();+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[para].rows.len(), 2);+ text::rewrite_block(+ &mut doc,+ 0,+ para,+ Some("Updated first highlighted row and updated second highlighted row"),+ &text::BlockStyle { offset: Some([6.0, -4.0]), underline: Some(true), ..Default::default() },+ )+ .unwrap();+ let doc = reopen(&doc);+ let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;+ let last_fill = ops.iter().rposition(|op| op.is("f")).unwrap();+ assert!(+ shown_at(&ops, "Updated first") > last_fill && shown_at(&ops, "Side footer") > shown_at(&ops, "Updated first"),+ "cross-CTM single-style rewrite must follow both background fills and precede the shared BT's trailing line"+ );+ let lines = text::text_lines(&doc, 0).unwrap();+ let updated_first = lines.iter().find(|l| l.text.starts_with("Updated first")).unwrap();+ let side_footer = lines.iter().find(|l| l.text == "Side footer").unwrap();+ assert!(+ (updated_first.baseline()[0] - 70.0).abs() < 0.01 && (updated_first.baseline()[1] - 696.0).abs() < 0.01,+ "offset baseline in user space across CTM: {:?}",+ updated_first.baseline()+ );+ assert!(+ (side_footer.baseline()[0] - 310.0).abs() < 0.01 && (side_footer.baseline()[1] - 644.0).abs() < 0.01,+ "trailing line in shared BT keeps its tlm across CTM: {:?}",+ side_footer.baseline()+ );+}+++ /// 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"]);+ }