PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge PR #3310: Keep text rows in other layers, gs states or Tz out of a paragraph
aionggf58254b57f2e
diff --cc crates/edit/src/tests.rsindex 3168dddca,42a054eaa..494c7bf06--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@@ -5261,114 -4800,108 +5261,220 @@@ fn flattening_comments_keeps_annotationassert_eq!(left(&reopen(&doc)), without_widget, "flattening fields touches no annotation that isn't a widget");}+/// A page whose text is a clipping mask (`mode` Tr) with a fill painted through it.+fn clipping_text_page(mode: i64) -> Document {+ text_page(&format!("q\nBT {mode} Tr /F1 48 Tf 40 60 Td (MASK) Tj ET\n1 0 0 rg 0 0 300 150 re f\nQ\n"))+}++/// Rewriting text that is a clipping path destroyed the artwork it masked: the glyphs went, the+/// mask with them, and the fill behind flooded its own rectangle, in a file that still opened+/// without a warning (#3429). Photoshop exports draw every text object this way. The rewrite is+/// refused instead, as `clear_block` already refuses a preview.+#[test]+fn rewriting_clipping_path_text_is_refused_for_every_clipping_mode() {+ for mode in [4, 5, 6, 7] {+ let before = text::text_lines(&clipping_text_page(mode), 0).unwrap();+ assert_eq!(before.len(), 1, "mode {mode}: the mask is one line");++ let mut doc = clipping_text_page(mode);+ let line = text::replace_line(&mut doc, 0, 0, "EDITED");+ assert!(matches!(&line, Err(EditError::Invalid(m)) if m.contains("clipping path")), "mode {mode}: {line:?}");++ let mut doc = clipping_text_page(mode);+ let block = text::rewrite_block(&mut doc, 0, 0, Some("EDITED"), &BlockStyle::default());+ assert!(matches!(&block, Err(EditError::Invalid(m)) if m.contains("clipping path")), "mode {mode}: {block:?}");++ // Refused means untouched: the mask is still there to shape what is painted through it.+ let after = text::text_lines(&doc, 0).unwrap();+ assert_eq!(after.len(), 1, "mode {mode}");+ assert_eq!(after[0].text, "MASK", "mode {mode}");+ }+}++/// The modes that paint ink are still editable: only 4 to 7 add to the clip path.+#[test]+fn painting_modes_are_still_rewritten() {+ for mode in [0, 1, 2] {+ let mut doc = clipping_text_page(mode);+ assert!(text::replace_line(&mut doc, 0, 0, "EDITED").is_ok(), "mode {mode}");+ assert_eq!(text::text_lines(&doc, 0).unwrap()[0].text, "EDITED", "mode {mode}");+ }+}++/// A line's runs need not share a rendering mode: nothing in the join requires it, so a line that+/// starts as ink can continue as a mask. The refusal reads the whole line, not the mode its first+/// run set -- otherwise the rewrite passed the guard and took the mask away with the ink.+#[test]+fn a_line_that_starts_as_ink_and_continues_as_a_mask_is_refused() {+ let content = "q\nBT /F1 48 Tf 40 60 Td 0 Tr (TITLE) Tj 7 Tr (MASK) Tj ET\n1 0 0 rg 0 0 300 150 re f\nQ\n";+ let before = text::text_lines(&text_page(content), 0).unwrap();+ assert_eq!(before.len(), 1, "the two runs are one line: {:?}", before.iter().map(|l| &l.text).collect::<Vec<_>>());+ assert_eq!(before[0].text, "TITLEMASK", "and the mask is the second half of it");++ let mut doc = text_page(content);+ let line = text::replace_line(&mut doc, 0, 0, "EDITED");+ assert!(matches!(&line, Err(EditError::Invalid(m)) if m.contains("clipping path")), "{line:?}");+ let block = text::rewrite_block(&mut doc, 0, 0, Some("EDITED"), &BlockStyle::default());+ assert!(matches!(&block, Err(EditError::Invalid(m)) if m.contains("clipping path")), "{block:?}");+ assert_eq!(text::text_lines(&doc, 0).unwrap()[0].text, "TITLEMASK", "refused means untouched");+}++/// Another drawing of the line on the same baseline goes with it, so that the replacement is all+/// that shows -- and that copy can be the mask while the line being replaced is ink. Dropping it+/// destroys the artwork as surely as rewriting the mask itself, so this is refused too.+#[test]+fn a_clipping_copy_on_the_same_baseline_is_refused() {+ let content = "q\nBT 0 Tr /F1 48 Tf 40 60 Td (MASK) Tj ET\nBT 7 Tr /F1 48 Tf 40 60 Td (MASK) Tj ET\n1 0 0 rg 0 0 300 150 re f\nQ\n";+ let before = text::text_lines(&text_page(content), 0).unwrap();+ assert_eq!(before.len(), 2, "two drawings of the same line");++ let mut doc = text_page(content);+ let line = text::replace_line(&mut doc, 0, 0, "EDITED");+ assert!(matches!(&line, Err(EditError::Invalid(m)) if m.contains("clipping path")), "{line:?}");+ let block = text::rewrite_block(&mut doc, 0, 0, Some("EDITED"), &BlockStyle::default());+ assert!(matches!(&block, Err(EditError::Invalid(m)) if m.contains("clipping path")), "{block:?}");+ assert_eq!(text::text_lines(&doc, 0).unwrap().len(), 2, "refused means untouched");+}++/// #2512: a session's drafts are laid out from the document as it was opened, never from each+/// other, and its commit writes what a one-shot rewrite writes, whatever was laid out before.+#[test]+fn a_text_session_commits_what_a_rewrite_writes_whatever_it_laid_out_before() {+ let page = "BT /F1 12 Tf 14 TL 72 700 Td (The first row of a paragraph) Tj T* (and its second row here.) Tj ET";+ let bold = BlockStyle { bold: Some(true), ..Default::default() };+ let drafts: [(&str, &BlockStyle); 4] = [+ ("The first row of a paragraph\nand its second row here, with more words to wrap it onto a third row", &BlockStyle::default()),+ ("Short", &bold),+ ("The first row\nsecond", &BlockStyle::default()),+ ("The first row of a paragraph\nand its second row here.", &bold),+ ];+ let doc = text_page(page);+ let session = text::TextSession::open(&doc, 0, 0).unwrap();+ assert_eq!(session.source().editor_text, "The first row of a paragraph\nand its second row here.");+ for (text, style) in drafts {+ let fresh = text::text_edit_layout(&text_page(page), 0, 0, text, style).unwrap();+ assert_eq!(session.layout(text, style).unwrap(), fresh, "{text:?} is laid out from the opened page");+ }+ let (text, style) = drafts[0];+ let mut by_session = doc.clone();+ session.commit(&mut by_session, Some(text), style).unwrap();+ let mut by_rewrite = text_page(page);+ text::rewrite_block(&mut by_rewrite, 0, 0, Some(text), style).unwrap();+ assert_eq!(+ pdfcraft_cos::write_full(&by_session, &SaveOptions::default()).unwrap(),+ pdfcraft_cos::write_full(&by_rewrite, &SaveOptions::default()).unwrap(),+ "the commit writes what a rewrite writes"+ );+ // A document changed since the session opened isn't written to.+ let before = pdfcraft_cos::write_full(&by_session, &SaveOptions::default()).unwrap();+ let refused = session.commit(&mut by_session, Some("Again"), &BlockStyle::default());+ assert!(matches!(&refused, Err(EditError::Invalid(m)) if m.contains("changed while it was being edited")), "{refused:?}");+ assert_eq!(pdfcraft_cos::write_full(&by_session, &SaveOptions::default()).unwrap(), before);+ assert!(session.is_current(&doc) && !session.is_current(&by_session));+}+++ /// A one-page document whose resources have `/GS0` (30 % opacity) and `/L1`, a layer that is OFF.+ fn row_state_page(content: &str) -> Document {+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R] /D << /OFF [5 0 R] /Order [5 0 R] >> >> >>".into(),+ "<< /Type /Pages /Kids [6 0 R] /Count 1 >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ "<< /Type /ExtGState /ca 0.3 /CA 0.3 >>".into(),+ "<< /Type /OCG /Name (Hidden layer) >>".into(),+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 7 0 R /Resources << /Font << /F1 3 0 R >> /ExtGState << /GS0 4 0 R /GS1 << /Type /ExtGState /ca 0.3 /CA 0.3 /BM /Normal >> /GS2 << /Type /ExtGState /ca 1 /CA 1 >> >> /Properties << /L1 5 0 R >> >> >>".into(),+ format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),+ ];+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offs = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offs.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ let x = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offs {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes());+ Document::open(Arc::new(out)).unwrap()+ }++ /// Each shown string on page 0 with the state it is drawn in: inside a `/OC` marked-content+ /// sequence, after `/GS0 gs`, and its horizontal scale (percent).+ fn shown_states(doc: &Document) -> Vec<(String, bool, bool, f64)> {+ let joined = streams(doc, 0).join("\n");+ let (mut oc, mut marks) = (0usize, Vec::new());+ let (mut gs, mut tz, mut stack) = (false, 100.0, Vec::new());+ let mut out = Vec::new();+ for op in pdfcraft_content::parse(joined.as_bytes()).ops {+ match op.op.as_slice() {+ b"BDC" | b"BMC" => {+ let layer = op.name(0) == Some(b"OC".as_slice());+ oc += usize::from(layer);+ marks.push(layer);+ }+ b"EMC" => oc -= usize::from(marks.pop().unwrap()),+ b"q" => stack.push((gs, tz)),+ b"Q" => (gs, tz) = stack.pop().unwrap(),+ b"gs" => gs |= op.name(0) == Some(b"GS0".as_slice()),+ b"Tz" => tz = op.num(0).unwrap(),+ b"Tj" | b"'" => {+ let Some(Object::String(s)) = op.operands.last() else { continue };+ if !s.bytes.is_empty() {+ out.push((String::from_utf8_lossy(&s.bytes).into_owned(), oc > 0, gs, tz));+ }+ }+ _ => {}+ }+ }+ out+ }++ /// #3115: a row drawn in a hidden layer, at 30 % opacity or at 80 % horizontal scale keeps that+ /// state when another row of the same paragraph is edited; the edited row doesn't take it on.+ #[test]+ fn editing_a_row_keeps_the_layer_opacity_and_scale_of_the_rows_around_it() {+ let row1 = "BT /F1 12 Tf 72 700 Td (Hello world, this is the first line) Tj ET\n";+ let row2 = "BT /F1 12 Tf 72 686 Td (and the second) Tj ET";+ let pages = [+ (format!("{row1}/OC /L1 BDC {row2} EMC"), (true, false, 100.0)),+ (format!("{row1}q /GS0 gs {row2} Q"), (false, true, 100.0)),+ ("BT /F1 12 Tf 72 700 Td (Hello world, this is the first line) Tj 80 Tz 0 -14 Td (and the second) Tj ET".to_string(), (false, false, 80.0)),+ (format!("{row1}{row2}"), (false, false, 100.0)),+ ];+ for (n, (content, (oc, gs, tz))) in pages.iter().enumerate() {+ let mut doc = row_state_page(content);+ let blocks = text::text_blocks(&doc, 0).unwrap();+ let block = blocks.iter().position(|b| b.text.starts_with("Hello")).unwrap();+ let text = blocks[block].text.replacen("Hello", "Jello", 1);+ text::replace_block(&mut doc, 0, block, &text).unwrap();+ let shown = shown_states(&reopen(&doc));+ let find = |needle: &str| shown.iter().filter(|s| s.0.contains(needle)).cloned().collect::<Vec<_>>();+ let first = find("Jello");+ assert_eq!(first.len(), 1, "page {}: {shown:?}", n + 1);+ assert_eq!((first[0].1, first[0].2, first[0].3), (false, false, 100.0), "page {}: the edited row keeps its own state: {shown:?}", n + 1);+ let second = find("and the second");+ assert_eq!(second.len(), 1, "page {}: {shown:?}", n + 1);+ assert_eq!((second[0].1, second[0].2, second[0].3), (*oc, *gs, *tz), "page {}: the other row keeps its state: {shown:?}", n + 1);+ }+ // The control: rows in the same state are still one paragraph.+ let blocks = text::text_blocks(&row_state_page(&pages[3].0), 0).unwrap();+ assert_eq!(blocks.len(), 1);+ assert_eq!(blocks[0].text, "Hello world, this is the first line and the second");+ }++ /// What keeps rows apart is the graphics state they are drawn in, not the `gs` operators+ /// before them: a repeated `gs` without q/Q, or another name with the same settings, is still one+ /// paragraph, and a `gs` that changes the opacity or puts it back is not.+ #[test]+ fn rows_under_repeated_or_equal_gs_states_stay_one_paragraph() {+ let row1 = "BT /F1 12 Tf 72 700 Td (Hello world, this is the first line) Tj ET\n";+ let row2 = "BT /F1 12 Tf 72 686 Td (and the second) Tj ET";+ let paragraphs = |content: String| text::text_blocks(&row_state_page(&content), 0).unwrap().len();+ assert_eq!(paragraphs(format!("/GS0 gs {row1}/GS0 gs {row2}")), 1, "the same name twice");+ assert_eq!(paragraphs(format!("/GS0 gs {row1}/GS0 gs /GS0 gs {row2}")), 1, "the same name three times");+ assert_eq!(paragraphs(format!("/GS0 gs {row1}/GS1 gs {row2}")), 1, "two names, the same settings");+ assert_eq!(paragraphs(format!("/GS2 gs {row1}{row2}")), 1, "settings that are the defaults");+ assert_eq!(paragraphs(format!("{row1}/GS0 gs {row2}")), 2, "another opacity");+ assert_eq!(paragraphs(format!("/GS0 gs {row1}/GS2 gs {row2}")), 2, "the opacity put back");+ }diff --cc crates/edit/src/text.rsindex f8cd15fc6,cf3eb74f8..6cda909b5--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@@ -828,9 -808,10 +896,11 @@@ fn interpretcache: &mut HashMap<Vec<u8>, (Rc<Metrics>, Option<String>)>,carry: &mut Carry,mut invoked: Option<&mut Vec<Invocation>>,- logical_text: bool,+ // `Some(properties)`: read `/ActualText`, looking named property lists up in `properties`.+ logical_text: Option<&Dict>,) -> Vec<Shown> {+ let fonts_res = resources.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();+ let states = resources.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();let mut out: Vec<Shown> = Vec::new();let mut ts = carry.ts.clone();let mut at_bt = (0usize, ts.clone());@@@ -846,12 -828,10 +917,15 @@@// artifacts and inner spans, which inherit their enclosing region.let region = matches!(op.name(0), Some(b"P" | b"H" | b"H1" | b"H2" | b"H3" | b"H4" | b"H5" | b"H6" | b"LI" | b"TD" | b"TH"));marked.push(if region { Some(i) } else { marked.last().copied().flatten() });+ // A layer named in the resources is told apart by its name, an inline one by where it opens.+ let layer = op.is("BDC") && op.name(0) == Some(b"OC".as_slice());+ layers.push(layer.then(|| op.operands.get(1).and_then(Object::as_name).map_or_else(|| format!("@{i}").into_bytes(), <[u8]>::to_vec)));- let logical = op.operands.get(1).and_then(Object::as_dict).and_then(|d| d.get(b"ActualText")).and_then(|s| match s {+ // The property list is inline or named in the resources' /Properties (§14.6.2).+ let list = logical_text.and_then(|properties| match op.operands.get(1) {+ Some(Object::Name(n)) => properties.get(n).and_then(|o| doc.dict(o)),+ other => other.and_then(Object::as_dict).cloned(),+ });+ let logical = list.as_ref().and_then(|d| d.get(b"ActualText")).and_then(|s| match s {Object::String(s) if s.bytes.len() <= 4_000_000 => Some(s.to_text()),_ => None,});@@@ -1100,7 -1085,7 +1182,8 @@@carry.ts = ts;carry.stack = stack;carry.marked = marked;+ carry.layers = layers;+ positioned_tracking(&mut out);out}@@@ -1116,8 -1100,7 +1198,8 @@@ pub fn text_lines(doc: &Document, page// joined, so an operator whose operands end one piece still has them.let pieces = Pieces::join(&content_streams(doc, &p.dict).into_iter().map(|(_, d)| d).collect::<Vec<_>>());let ops = pieces.parse().ops;- let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, true);+ let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default();- let shown = interpret(doc, &ops, &fonts_res, &mut cache, &mut carry, None, Some(&properties));++ let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, Some(&properties));let mut last: Option<(usize, Pen)> = None; // the stream piece and where its last run endedfor mut s in shown {// A single RTL glyph's ActualText (e.g. lam-alef) is an inline ligature, not a@@@ -1135,9 -1118,9 +1217,9 @@@let bt = pen.bt;let (near, gap) = pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 });piece == si- && lines.last().is_some_and(|l| l.scope == s.scope && l.logical_order == s.logical_order)+ && lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.logical_order == s.logical_order)&& (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s)))- && (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, s.face.as_deref())))+ && (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, &s.base_font, s.face.as_deref())))&& (s.text.trim().is_empty()|| lines.last().is_some_and(|l| {(s.size - l.size).abs() < 0.01 && s.bold == l.bold && s.italic == l.italic && fill_color(&s.state.fill) == l.color@@@ -1180,9 -1162,9 +1262,10 @@@face: s.face.clone(),stream: si,scope: s.scope,+ paint: s.paint.clone(),logical_order: s.logical_order,actual_text: s.actual_text,+ clips: s.state.render_mode >= 4,ops: std::iter::once(s.op).chain(s.extra_ops.iter().copied()).collect(),origin: Origin {tm: s.tm.0,@@@ -1230,9 -1213,9 +1314,9 @@@ fn compatible_word(line: &TextLine, shofn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream: usize) {let joins = last.is_some_and(|pen| {let bt = pen.bt;- lines.last().is_some_and(|l| l.scope == s.scope && l.logical_order == s.logical_order)+ lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.logical_order == s.logical_order)&& (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s)))- && (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, s.face.as_deref())))+ && (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, &s.base_font, s.face.as_deref())))&& (s.text.trim().is_empty()|| lines.last().is_some_and(|l| {(s.size - l.size).abs() < 0.01 && s.bold == l.bold && s.italic == l.italic && fill_color(&s.state.fill) == l.color@@@ -1271,9 -1253,9 +1355,10 @@@face: s.face.clone(),stream,scope: s.scope,+ paint: s.paint.clone(),logical_order: s.logical_order,actual_text: s.actual_text,+ clips: s.state.render_mode >= 4,ops: std::iter::once(s.op).chain(s.extra_ops.iter().copied()).collect(),origin: Origin {tm: s.tm.0,@@@ -1383,11 -1343,9 +1468,10 @@@ fn reading_lines(doc: &Document, page:}/// `stream` gives the stream number of the operator at an index of `ops`.fn walk(w: &mut Walk, ops: &[Op], resources: &Dict, carry: &mut Carry, stream: &dyn Fn(usize) -> usize) {- let fonts_res = resources.get(b"Font").map(|f| w.doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();let mut cache = HashMap::new();let mut invoked = Vec::new();- let shown = interpret(w.doc, ops, resources, &mut cache, carry, Some(&mut invoked), true);+ let properties = resources.get(b"Properties").and_then(|o| w.doc.dict(o)).unwrap_or_default();- let shown = interpret(w.doc, ops, &fonts_res, &mut cache, carry, Some(&mut invoked), Some(&properties));++ let shown = interpret(w.doc, ops, resources, &mut cache, carry, Some(&mut invoked), Some(&properties));let mut last = None;let mut last_stream = None;let mut forms = invoked.into_iter().peekable();@@@ -1409,10 -1367,10 +1493,10 @@@}}fn enter(w: &mut Walk, resources: &Dict, name: &[u8], ts: Ts) {- let Some(form) = form_call(w.doc, resources, name, ts.ctm, &w.path, &mut w.visits) else { return };+ let Some(form) = form_call(w.doc, resources, name, ts.ctm, &w.path, &mut w.budget) else { return };let ops = parse(&form.data).ops;// The form starts with the graphics state at its `Do`, its own matrix applied.- let mut carry = Carry { ts: Ts { ctm: form.ctm, ..ts }, stack: Vec::new(), marked: Vec::new() };+ let mut carry = Carry { ts: Ts { ctm: form.ctm, ..ts }, stack: Vec::new(), marked: Vec::new(), layers: Vec::new() };let stream = w.next_stream;w.next_stream = w.next_stream.saturating_add(1);if let Some(r) = form.obj {@@@ -2111,8 -1974,7 +2195,7 @@@ pub fn clear_block(doc: &mut Document,let streams = content_streams(doc, &p.dict);let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());let ops = pieces.parse().ops;- let shown = interpret(doc, &ops, &fonts, &mut HashMap::new(), &mut Carry::new(), None, None);- let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, false);++ let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None);let mut patches = HashMap::new();for s in shown.into_iter().filter(|s| drops.contains(&s.op)) {if s.state.render_mode >= 4 {@@@ -2790,7 -2631,7 +2873,7 @@@ pub(crate) fn translate_blocks(doc: &mulet fonts = res.get(b"Font").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());let ops = pieces.parse().ops;- let shown = interpret(doc, &ops, &fonts, &mut HashMap::new(), &mut Carry::new(), None, None);- let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, false);++ let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None);let mut patches = HashMap::new();// Keep full precision: a tiny rounded text-space change can be magnified by a CTM,// and restoring rise/spacing must not alter following unselected text.