PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: keep the source operators of rows a text edit doesn't reach (#1754)
komo1iddin8955ed8379ff
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex 5c555814a..d1ee5c656 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -3544,3 +3544,99 @@ fn page_marks_and_added_content_preserve_fractional_user_unit_matrices() {}}}++#[test]+fn rows_the_edit_does_not_reach_keep_their_source_operators() {+ // Word gaps in TJ, as justified text from a layout program has; the text state alone+ // can't reproduce them, so a rewritten row would lose them.+ let rows = [+ "[(justified) -400 ( text) -400 ( uses) -400 ( wide) -400 ( gaps)] TJ",+ "[(between) -400 ( every) -400 ( single) -400 ( word) -400 ( here)] TJ",+ "(last line.) Tj",+ ];+ let content = format!("BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm {} T* {} T* {} ET", rows[0], rows[1], rows[2]);+ let row_texts = |doc: &Document| -> Vec<(String, [f64; 2])> {+ text::text_lines(doc, 0).unwrap().into_iter().map(|l| (l.text.clone(), l.baseline())).collect()+ };+ let source = row_texts(&text_page(&content));+ assert_eq!(source.len(), 3);+ for (row, from, to) in [(2, "last line.", "last line!"), (0, "justified", "justify"), (1, "single", "lone")] {+ let mut doc = text_page(&content);+ let block = text::text_blocks(&doc, 0).unwrap().into_iter().position(|b| b.text.contains("justified")).unwrap();+ let draft = text::text_blocks(&doc, 0).unwrap()[block].editor_text.replacen(from, to, 1);+ text::rewrite_block(&mut doc, 0, block, Some(&draft), &text::BlockStyle::default()).unwrap();+ let doc = reopen(&doc);+ let bytes = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();+ let after = row_texts(&doc);+ assert_eq!(after.len(), 3, "{to}: {after:?}");+ for (i, ((text, at), (old, was))) in after.iter().zip(&source).enumerate() {+ assert!((at[0] - was[0]).abs() < 0.01 && (at[1] - was[1]).abs() < 0.01, "{to}: row {i} stays at {was:?}, not {at:?}");+ if i == row {+ assert_eq!(*text, old.replacen(from, to, 1), "{to}: the edited row");+ assert!(!bytes.contains(rows[i]), "{to}: the edited row is rewritten");+ } else {+ assert_eq!(text, old, "{to}: row {i}");+ assert_eq!(bytes.matches(rows[i]).count(), 1, "{to}: row {i} keeps its own operator, kerning included:\n{bytes}");+ }+ }+ }+ // Colouring a selection in the last row leaves the rows above it as they were.+ let mut doc = text_page(&content);+ let block = text::text_blocks(&doc, 0).unwrap().into_iter().position(|b| b.text.contains("justified")).unwrap();+ let draft = text::text_blocks(&doc, 0).unwrap()[block].editor_text.clone();+ let at = draft.find("line").unwrap();+ let range = text::RangeStyle {+ range: at..at + 4,+ family: None,+ resource: None,+ size: None,+ color: Some([1.0, 0.0, 0.0]),+ underline: None,+ char_spacing: None,+ scale: None,+ };+ text::rewrite_block(&mut doc, 0, block, Some(&draft), &text::BlockStyle { ranges: vec![range], ..Default::default() }).unwrap();+ let bytes = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();+ assert!(rows[..2].iter().all(|row| bytes.matches(row).count() == 1) && !bytes.contains(rows[2]), "{bytes}");+ assert!(bytes.contains("1 0 0 rg"), "{bytes}");+ // The coloured word is its own run now, so only the rows above compare whole.+ assert_eq!(row_texts(&reopen(&doc))[..2], source[..2]);+}++#[test]+fn kept_rows_stay_in_place_when_rows_wrap_or_move_with_quote_operators() {+ let lines_of = |doc: &Document| -> Vec<(String, [f64; 2])> {+ text::text_lines(doc, 0).unwrap().into_iter().map(|l| (l.text.clone(), l.baseline())).collect()+ };+ let edit = |content: &str, from: &str, to: &str| {+ let mut doc = text_page(content);+ let block = text::text_blocks(&doc, 0).unwrap().into_iter().position(|b| b.editor_text.contains(from)).unwrap();+ let draft = text::text_blocks(&doc, 0).unwrap()[block].editor_text.replacen(from, to, 1);+ text::rewrite_block(&mut doc, 0, block, Some(&draft), &text::BlockStyle::default()).unwrap();+ reopen(&doc)+ };+ // `'` moves to the next line as it shows: a row after a rewritten `'` row can't stay as it is.+ for (quoted, from, to) in [+ ("BT /F1 12 Tf 14 TL 72 700 Td (first row here) Tj (second row here) ' (third row here) ' ET", "second", "2nd"),+ ("BT /F1 12 Tf 14 TL 72 700 Td (first row here) Tj (second row here) ' (third row here) ' ET", "third", "3rd"),+ // Here the first row's own `'` makes the step down that the rows after it build on.+ ("BT /F1 12 Tf 14 TL 72 714 Td (first row here) ' (second row here) ' (third row here) ' ET", "first", "1st"),+ ] {+ let source = lines_of(&text_page(quoted));+ let after = lines_of(&edit(quoted, from, to));+ assert_eq!(after.len(), 3, "{to}: {after:?}");+ for ((text, at), (old, was)) in after.iter().zip(&source) {+ assert_eq!(*text, old.replacen(from, to, 1));+ assert!((at[0] - was[0]).abs() < 0.01 && (at[1] - was[1]).abs() < 0.01, "{to}: {text} stays at {was:?}, not {at:?}");+ }+ }+ // A row that grows past the paragraph's width wraps and pushes the rows below it down;+ // those are rewritten in their new places, never left behind as well.+ let rows = "BT /F1 12 Tf 14.4 TL 72 700 Td (one two three four) Tj T* (five six seven eight) Tj T* (nine ten eleven twelve) Tj ET";+ let doc = edit(rows, "two", "two and a great many more words");+ let text: String = lines_of(&doc).into_iter().map(|(t, _)| t + " ").collect();+ for word in ["one", "five", "nine", "twelve"] {+ assert_eq!(text.matches(word).count(), 1, "{word} appears once: {text}");+ }+ assert!(lines_of(&doc).len() > 3, "the edited row wrapped: {text}");+}diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rsindex 0213d9040..614349681 100644--- a/crates/edit/src/text_regions.rs+++ b/crates/edit/src/text_regions.rs@@ -192,6 +192,46 @@ fn shape_source(Err(EditError::Invalid("complex text needs the complete source TrueType/OpenType face; load that font before editing".into()))}+/// For each output row (a range of the draft's characters), whether it is exactly the source row+/// at the same position: the same characters, none of them inserted or changed by the edit.+fn untouched_rows(block: &TextBlock, draft: &str, rows: &[std::ops::Range<usize>]) -> Vec<bool> {+ let old: Vec<char> = block.editor_text.chars().collect();+ let new: Vec<char> = draft.chars().collect();+ let prefix = old.iter().zip(&new).take_while(|(a, b)| a == b).count();+ let suffix = old.iter().rev().zip(new.iter().rev()).take(old.len().min(new.len()).saturating_sub(prefix)).take_while(|(a, b)| a == b).count();+ // The source character a draft character is, if the edit left it alone.+ let origin = |i: usize| {+ if i < prefix {+ Some(i)+ } else if i >= new.len().saturating_sub(suffix) {+ (old.len() + i).checked_sub(new.len())+ } else {+ None+ }+ };+ let mut source_rows = Vec::new();+ let mut start = 0;+ for (i, ch) in old.iter().enumerate() {+ if *ch == '\n' {+ source_rows.push(start..i);+ start = i + 1;+ }+ }+ source_rows.push(start..old.len());+ // A line break inside a source run would pair editor rows with the wrong visual rows.+ if source_rows.len() != block.rows.len() {+ return vec![false; rows.len()];+ }+ rows.iter()+ .enumerate()+ .map(|(r, range)| {+ source_rows.get(r).is_some_and(|source| {+ !range.is_empty() && range.len() == source.len() && range.clone().zip(source.clone()).all(|(i, j)| origin(i) == Some(j))+ })+ })+ .collect()+}+/// Rewrite visual rows while keeping the source style on each surviving character. Resource/// names may differ between Unicode subsets of the same face; encoding searches those subsets.pub(super) fn rewrite_styled_block(@@ -227,6 +267,7 @@ pub(super) fn rewrite_styled_block({return Err(EditError::Invalid("text style ranges must be disjoint UTF-8 boundaries with finite formatting (at most 1024 ranges)".into()));}+ let source_count = lines.len();let mut styled_lines = lines.to_vec();let mut styled_spans = Vec::new();let mut underlines = HashMap::new();@@ -488,6 +529,9 @@ pub(super) fn rewrite_styled_block(Ok(width)};let mut rows: Vec<Vec<(char, usize, String)>> = Vec::new();+ // Each row's characters, as indexes into the draft's characters (`chars` holds all of them).+ let mut row_ranges = Vec::new();+ let mut row_start = 0;let mut row = Vec::new();let mut row_width = 0.0;// Wrap at word boundaries, retaining explicit source row breaks and whitespace.@@ -495,9 +539,11 @@ pub(super) fn rewrite_styled_block(while at < chars.len() {let Some(item) = chars.get(at) else { break };if item.0 == '\n' {+ row_ranges.push(row_start..row_start + row.len());rows.push(std::mem::take(&mut row));row_width = 0.0;at += 1;+ row_start = at;continue;}let mut end = at + 1;@@ -512,17 +558,47 @@ pub(super) fn rewrite_styled_block(while row.last().is_some_and(|c: &(char, usize, String)| c.0.is_whitespace()) {row.pop();}+ row_ranges.push(row_start..row_start + row.len());rows.push(std::mem::take(&mut row));row_width = 0.0;+ row_start = at;}row.extend_from_slice(word);row_width += w;at = end;}if !row.is_empty() {+ row_ranges.push(row_start..row_start + row.len());rows.push(row);}- for row in &rows {+ 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;+ // A row the edit doesn't reach keeps its source operators, so its kerning, TJ word gaps and+ // glyph widths stay exactly as they were instead of being rebuilt from the text state.+ let plain = BlockStyle { ranges: Vec::new(), ..style.clone() } == BlockStyle::default();+ let mut kept = if plain {+ untouched_rows(block, draft, &row_ranges).into_iter().zip(&rows).map(|(same, row)| same && row.iter().all(|c| c.1 < source_count)).collect()+ } else {+ vec![false; rows.len()]+ };+ let kept_lines: std::collections::HashSet<usize> =+ kept.iter().enumerate().filter(|(_, k)| **k).filter_map(|(r, _)| block.rows.get(r)).flatten().copied().collect();+ let rewritten: Vec<&TextLine> = block.lines.iter().filter(|i| !kept_lines.contains(i)).filter_map(|i| lines.get(*i)).collect();+ // The rewrite goes where the first rewritten row was drawn, so it must share the paragraph's+ // space. A dropped `'` or `"` also moved to the next line, which a kept row relies on.+ let lead = rewritten.first().copied().filter(|lead| {+ lead.origin.ctm.iter().zip(first.origin.ctm).all(|(a, b)| (a - b).abs() < 1e-9)+ && !rewritten.iter().flat_map(|l| &l.ops).any(|i| ops.get(*i).is_some_and(|op| op.is("'") || op.is("\"")))+ });+ let (members, lead) = match lead {+ Some(lead) if !kept_lines.is_empty() => (rewritten, lead),+ _ => {+ kept.iter_mut().for_each(|k| *k = false);+ (block.lines.iter().filter_map(|i| lines.get(*i)).collect(), first)+ }+ };+ for (row, _) in rows.iter().zip(&kept).filter(|(_, k)| !**k) {let text: String = row.iter().map(|v| v.0).collect();if pdfcraft_fonts::source_shaping::required(&text) && row.first().is_some_and(|first| row.iter().any(|v| v.1 != first.1 || v.2 != first.2)) {return Err(EditError::Invalid(@@ -534,7 +610,7 @@ pub(super) fn rewrite_styled_block(let measured: Vec<_> = rows.iter().map(|r| measure(r)).collect::<Result<_, _>>()?;let mut shaped_runs = HashMap::new();let mut segment_advances = HashMap::new();- for (row_index, row) in rows.iter().enumerate() {+ for (row_index, row) in rows.iter().enumerate().filter(|(r, _)| !kept.get(*r).copied().unwrap_or(false)) {let mut at = 0;while let Some(item) = row.get(at) {let mut end = at + 1;@@ -589,6 +665,11 @@ pub(super) fn rewrite_styled_block(baseline = anchor.origin.baseline;}let anchor = anchor.unwrap_or(first);+ if kept.get(row_index).copied().unwrap_or(false) {+ // Kept rows only occur without spacing or size changes, so this is the step below.+ baseline -= source_leading;+ continue;+ }let w = measured.get(row_index).copied().unwrap_or(0.0);let align = style.align.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });let original_rect = block.rows.get(row_index).and_then(|row| row_rect(row, lines)).unwrap_or(block.rect);@@ -692,14 +773,10 @@ pub(super) fn rewrite_styled_block(};}block_ops.push(Op::new("Q", vec![]));- 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 members: Vec<_> = block.lines.iter().filter_map(|i| lines.get(*i)).collect();let mut drop = coincident_ops(lines, &members);drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));- let o = &first.origin;- let start = first.ops.first().copied().unwrap_or(o.bt_op);+ let o = &lead.origin;+ let start = lead.ops.first().copied().unwrap_or(o.bt_op);let split = ops.get(o.bt_op..start).unwrap_or_default()diff --git a/docs/editing-existing-text.md b/docs/editing-existing-text.mdindex 3e71c8c72..07104d79e 100644--- a/docs/editing-existing-text.md+++ b/docs/editing-existing-text.md@@ -4,6 +4,11 @@ Click a text region in **Edit a PDF → Edit text and images**. One editor contasource rows and mixed styles. Embedded TrueType and OpenType/CFF faces are used in memory;source font programs, colour, size and baseline anchors stay intact. A textless previewprevents a second copy underneath. The frame shows the live extent as text grows or shrinks.+Rows a text edit doesn't reach keep their original operators, so their kerning, `TJ` word+gaps and glyph widths stay exactly as they were. Only rows whose characters changed, or that+moved because an earlier row wrapped, are rewritten, and formatting a selection rewrites+only the rows it covers. Changing the whole paragraph's formatting, width or position rewrites+every row.A subset font contains only some of the original face's glyphs. A new character cannot bereconstructed from a glyph the PDF does not contain. **Load font…** imports an openly licensed,