PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge PR #3289: Lay out vertical (Identity-V) text as columns in the edit layer
aiongg41ec3f370e45
diff --cc crates/edit/src/tests.rsindex 494c7bf06,9291d31dd..d880f2bb9--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@@ -5261,220 -4976,143 +5261,361 @@@ 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");+}+++ /// A page of three vertical (`Identity-V`) columns at 20 pt: `ABCDEF` at x = 500, the same+ /// text 30 pt to its left, and `ABCD` far away. Synthetic font: no font program is needed.+ fn vertical_columns_page() -> Document {+ vertical_page(+ "BT /V1 20 Tf 500 720 Td <004100420043004400450046> Tj ET\nBT /V1 20 Tf 470 720 Td <004100420043004400450046> Tj ET\nBT /V1 20 Tf 300 720 Td <0041004200430044> Tj ET",+ )+ }++ /// A page drawing `content` with the vertical font `/V1` (as in [`vertical_columns_page`]) and+ /// Helvetica `/F1`.+ fn vertical_page(content: &str) -> Document {+ let mut doc = text_page(content);+ let mut font = Dict::from_iter([+ (b"Type".to_vec(), Object::name("Font")),+ (b"Subtype".to_vec(), Object::name("Type0")),+ (b"BaseFont".to_vec(), Object::name("SyntheticCID")),+ (b"Encoding".to_vec(), Object::name("Identity-V")),+ ]);+ let unicode = doc.add(Object::Stream(Stream::flate(+ Dict::new(),+ b"1 begincodespacerange <0000> <ffff> endcodespacerange 6 beginbfchar <0041> <0041> <0042> <0042> <0043> <0043> <0044> <0044> <0045> <0045> <0046> <0046> endbfchar",+ )));+ font.set(b"ToUnicode".to_vec(), Object::Ref(unicode));+ font.set(+ b"DescendantFonts".to_vec(),+ Object::Array(vec![Object::Dict(Dict::from_iter([+ (b"Subtype".to_vec(), Object::name("CIDFontType2")),+ (b"DW".to_vec(), Object::Int(1000)),+ ]))]),+ );+ let p = pdfcraft_model::pages(&doc)[0].obj;+ let helvetica = Dict::from_iter([+ (b"Type".to_vec(), Object::name("Font")),+ (b"Subtype".to_vec(), Object::name("Type1")),+ (b"BaseFont".to_vec(), Object::name("Helvetica")),+ (b"Encoding".to_vec(), Object::name("WinAnsiEncoding")),+ ]);+ let fonts = Dict::from_iter([(b"V1".to_vec(), Object::Dict(font)), (b"F1".to_vec(), Object::Dict(helvetica))]);+ let resources = Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))]);+ doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(resources))).unwrap();+ doc+ }++ #[test]+ fn vertical_text_lines_are_columns_and_editing_one_keeps_its_neighbour() {+ let doc = vertical_columns_page();+ let lines = text::text_lines(&doc, 0).unwrap();+ let first = lines.iter().find(|l| l.baseline()[0] == 500.0).unwrap();+ let r = first.rect;+ // Six glyphs, each 20 pt wide and advancing 20 pt down, centred on x = 500.+ assert!((r[0] - 490.0).abs() < 0.5 && (r[2] - 510.0).abs() < 0.5, "{r:?}");+ assert!((r[1] - 600.0).abs() < 0.5 && (r[3] - 720.0).abs() < 0.5, "{r:?}");+ for edit in [0, 1] {+ let mut doc = vertical_columns_page();+ let lines = text::text_lines(&doc, 0).unwrap();+ if edit == 0 {+ let line = lines.iter().position(|l| l.baseline()[0] == 500.0).unwrap();+ text::replace_line(&mut doc, 0, line, "ABCDEA").unwrap();+ } else {+ let blocks = text::text_blocks(&doc, 0).unwrap();+ let block = blocks.iter().position(|b| b.lines.iter().any(|&i| lines[i].baseline()[0] == 500.0)).unwrap();+ assert_eq!(blocks[block].lines.len(), 1, "{blocks:?}");+ text::replace_block(&mut doc, 0, block, "ABCDEA").unwrap();+ }+ let after = text::text_lines(&doc, 0).unwrap();+ let texts: Vec<(f64, &str)> = after.iter().map(|l| (l.baseline()[0], l.text.as_str())).collect();+ assert!(texts.contains(&(500.0, "ABCDEA")), "{texts:?}");+ assert!(texts.contains(&(470.0, "ABCDEF")), "{texts:?}");+ assert!(texts.contains(&(300.0, "ABCD")), "{texts:?}");+ }+ }++ /// Gives `/V1` an embedded CMap that uses itself: which way its glyphs advance can't be known.+ fn make_cmap_cyclic(doc: &mut Document) {+ let cmap = doc.add(Object::Null);+ doc.set(+ cmap,+ Object::Stream(Stream::flate(+ Dict::from_iter([(b"UseCMap".to_vec(), Object::Ref(cmap))]),+ b"1 begincodespacerange <0000> <ffff> endcodespacerange",+ )),+ );+ let p = pdfcraft_model::pages(doc)[0].obj;+ doc.update_dict(p, |d| {+ if let Some(Object::Dict(res)) = d.get_mut(b"Resources")+ && let Some(Object::Dict(fonts)) = res.get_mut(b"Font")+ && let Some(Object::Dict(font)) = fonts.get_mut(b"V1")+ {+ font.set(b"Encoding".to_vec(), Object::Ref(cmap));+ }+ })+ .unwrap();+ }++ #[test]+ fn text_whose_cmap_writing_mode_cannot_be_read_is_not_edited() {+ let mut doc = vertical_columns_page();+ make_cmap_cyclic(&mut doc);+ let error = text::replace_line(&mut doc, 0, 0, "ABCDEA").unwrap_err();+ assert!(error.to_string().contains("cyclic"), "{error}");+ }++ #[test]+ fn a_cyclic_cmap_falls_back_to_horizontal_and_only_refuses_its_own_lines() {+ let mut doc = vertical_page("BT /V1 20 Tf 100 700 Td <00410042> Tj ET\nBT /F1 12 Tf 100 600 Td (Plain) Tj ET");+ make_cmap_cyclic(&mut doc);+ // The page is still listed: the broken font's text as horizontal, the rest untouched.+ let lines = text::text_lines(&doc, 0).unwrap();+ let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();+ assert_eq!(texts, ["AB", "Plain"], "{texts:?}");+ assert!(lines[0].rect[2] - lines[0].rect[0] > 30.0 && lines[0].rect[3] - lines[0].rect[1] < 30.0, "{:?}", lines[0].rect);+ assert_eq!(text::reading_blocks(&doc, 0).unwrap().len(), 2);+ assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 2);+ // Only the line in the broken font is refused.+ let error = text::replace_line(&mut doc.clone(), 0, 0, "BA").unwrap_err();+ assert!(error.to_string().contains("cyclic"), "{error}");+ let block = text::text_blocks(&doc, 0).unwrap().iter().position(|b| b.text == "AB").unwrap();+ let error = text::replace_block(&mut doc.clone(), 0, block, "BA").unwrap_err();+ assert!(error.to_string().contains("cyclic"), "{error}");+ text::replace_line(&mut doc, 0, 1, "Changed").unwrap();+ let texts: Vec<String> = text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect();+ assert_eq!(texts, ["AB", "Changed"]);+ }++ #[test]+ fn vertical_text_drawn_one_glyph_per_tj_is_one_line() {+ // One text object, a `Tj` per glyph; and a column with a text object per glyph.+ let doc = vertical_page(+ "BT /V1 20 Tf 500 720 Td <0041> Tj <0042> Tj <0043> Tj ET\n\+ BT /V1 20 Tf 1 0 0 1 470 720 Tm <0041> Tj ET\nBT /V1 20 Tf 1 0 0 1 470 700 Tm <0042> Tj ET\nBT /V1 20 Tf 1 0 0 1 470 680 Tm <0043> Tj ET",+ );+ let lines = text::text_lines(&doc, 0).unwrap();+ let columns: Vec<(f64, &str)> = lines.iter().map(|l| (l.baseline()[0], l.text.as_str())).collect();+ assert_eq!(columns, [(500.0, "ABC"), (470.0, "ABC")], "{columns:?}");+ for line in &lines {+ let r = line.rect;+ assert!((r[1] - 660.0).abs() < 0.5 && (r[3] - 720.0).abs() < 0.5, "{r:?}");+ }+ assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 2);+ }diff --cc crates/edit/src/text.rsindex 6cda909b5,2c8b0627d..13b828db6--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@@ -73,10 -68,9 +73,13 @@@ pub struct TextLine/// Some of the line's text is `/ActualText`, which is already in logical order: visual-order/// Indic recovery would scramble it.actual_text: bool,+ /// Whether any of the line's runs draws in a clipping mode (`4 Tr` to `7 Tr`). The join below+ /// does not require one rendering mode, so a line that starts as ink can continue as a mask;+ /// [`refuse_clipping_text`] reads this rather than the origin's mode alone.+ clips: bool,+ /// Why the line can't be edited: its font's writing mode (its CMap's `WMode`) couldn't be read,+ /// so which way its glyphs advance is unknown. The line is listed as horizontal text.+ unreadable_mode: Option<String>,}impl TextLine {@@@ -597,8 -527,12 +605,14 @@@ struct Tsleading: f64,rise: f64,render_mode: i64,+ /// The transparency parameters the `gs` operators have set so far (see [`Paint`]).+ gs: Gs,+ /// The font's vertical advance per unit of font size (`/DW2`'s w1, normally −1) when its+ /// CMap writes vertically (`WMode 1`, §9.7.4.3): each glyph then moves the pen down, not right.+ vertical: Option<f64>,+ /// Why the font's writing mode couldn't be read (a broken or cyclic CMap). Its text is then+ /// listed as horizontal, but the lines in it are refused for editing.+ unreadable: Option<Rc<str>>,}fn content_streams(doc: &Document, page: &Dict) -> Vec<(Object, Vec<u8>)> {@@@ -880,9 -748,10 +903,11 @@@ impl Carryleading: 0.0,rise: 0.0,render_mode: 0,+ gs: Gs::default(),+ vertical: None,+ unreadable: None,};- Carry { ts, stack: Vec::new(), marked: Vec::new() }+ Carry { ts, stack: Vec::new(), marked: Vec::new(), layers: Vec::new() }}}@@@ -892,15 -765,13 +921,15 @@@ type Invocation = (usize, Vec<u8>, Ts)fn interpret(doc: &Document,ops: &[Op],- fonts_res: &Dict,+ resources: &Dict,- cache: &mut HashMap<Vec<u8>, (Rc<Metrics>, Option<String>)>,+ cache: &mut HashMap<Vec<u8>, CachedFont>,carry: &mut Carry,mut invoked: Option<&mut Vec<Invocation>>,// `Some(properties)`: read `/ActualText`, looking named property lists up in `properties`.logical_text: Option<&Dict>,- ) -> Vec<Shown> {+ ) -> Result<Vec<Shown>, EditError> {+ 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());@@@ -1093,14 -977,26 +1148,26 @@@}other => {if let Some(n) = other.as_f64() {+ if vertical.is_some() {+ // Down by n/1000 em, not scaled by `Tz`.+ let dy = -n / 1000.0 * ts.size;+ if -dy > ts.size * 0.2 && !text.ends_with(' ') {+ text.push(' ');+ }+ if dy.abs() > ts.size.abs() * 0.2 {+ in_word = false;+ }+ y_text += dy;+ continue;+ }let dx = -n / 1000.0 * ts.size * ts.scale;// A large gap inside TJ reads as a space.- if dx > ts.size * 0.2 && !text.ends_with(' ') {+ if dx - tracking > (ts.size * ts.scale).abs() * 0.2 && !text.ends_with(' ') {text.push(' ');}- // Kerning keeps a word together; a jump either way of more- // than 0.2 em ends it (whatever the sign of the size or `Tz`).- if dx.abs() > (ts.size * ts.scale).abs() * 0.2 {+ // Tracking and kerning keep a word together; a larger jump+ // ends it (whatever the sign of the size or `Tz`).+ if dx - tracking > (ts.size * ts.scale).abs() * 0.2 || dx < -(ts.size * ts.scale).abs() * 0.2 {in_word = false;}x_text += dx;@@@ -1146,9 -1048,17 +1219,18 @@@op: i,extra_ops: Vec::new(),glyph_count,- advance: x_text,+ // Vertical text: the TJ adjustment that undoes the run is n = -1000 y / size; the+ // preview divides by size × `Tz`, so `Tz` is put back here.+ advance: if vertical.is_some() { y_text * ts.scale } else { x_text },+ tracking: 0.0,- tm: Matrix([tm.0[0], tm.0[1], tm.0[2], tm.0[3], tm.0[4] - x_text * tm.0[0], tm.0[5] - x_text * tm.0[1]]),+ tm: Matrix([+ tm.0[0],+ tm.0[1],+ tm.0[2],+ tm.0[3],+ tm.0[4] - x_text * tm.0[0] - y_text * tm.0[2],+ tm.0[5] - x_text * tm.0[1] - y_text * tm.0[3],+ ]),state: ts.clone(),tlm,bt_op: at_bt.0,@@@ -1182,9 -1091,7 +1264,9 @@@carry.ts = ts;carry.stack = stack;carry.marked = marked;+ carry.layers = layers;+ positioned_tracking(&mut out);- out+ Ok(out)}/// The lines of text on a page (0-based), in content order.@@@ -1199,7 -1107,7 +1281,7 @@@ pub fn text_lines(doc: &Document, pagelet pieces = Pieces::join(&content_streams(doc, &p.dict).into_iter().map(|(_, d)| d).collect::<Vec<_>>());let ops = pieces.parse().ops;let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default();- let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, Some(&properties));- 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@@@ -1243,7 -1151,9 +1325,10 @@@l.decodable &= s.decodable;l.visual_order |= s.visual_order;l.actual_text |= s.actual_text;+ l.clips |= s.state.render_mode >= 4;+ if l.unreadable_mode.is_none() {+ l.unreadable_mode = s.state.unreadable.as_deref().map(str::to_owned);+ }// Spaces may use a separate subset font; they do not change the visible style.} else {lines.push(TextLine {@@@ -1262,10 -1172,9 +1347,11 @@@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,+ unreadable_mode: s.state.unreadable.as_deref().map(str::to_owned),ops: std::iter::once(s.op).chain(s.extra_ops.iter().copied()).collect(),origin: Origin {tm: s.tm.0,@@@ -1337,7 -1245,9 +1423,10 @@@ fn add_shown(lines: &mut Vec<TextLine>l.decodable &= s.decodable;l.visual_order |= s.visual_order;l.actual_text |= s.actual_text;+ l.clips |= s.state.render_mode >= 4;+ if l.unreadable_mode.is_none() {+ l.unreadable_mode = s.state.unreadable.as_deref().map(str::to_owned);+ }} else {lines.push(TextLine {text: s.text.clone(),@@@ -1355,10 -1265,9 +1444,11 @@@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,+ unreadable_mode: s.state.unreadable.as_deref().map(str::to_owned),ops: std::iter::once(s.op).chain(s.extra_ops.iter().copied()).collect(),origin: Origin {tm: s.tm.0,@@@ -1464,14 -1351,15 +1554,14 @@@ fn reading_lines(doc: &Document, page:lines: Vec<TextLine>,next_stream: usize,path: Vec<pdfcraft_cos::ObjRef>,- visits: usize,+ budget: FormBudget,}/// `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) {+ fn walk(w: &mut Walk, ops: &[Op], resources: &Dict, carry: &mut Carry, stream: &dyn Fn(usize) -> usize) -> Result<(), EditError> {- 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 properties = resources.get(b"Properties").and_then(|o| w.doc.dict(o)).unwrap_or_default();- let shown = interpret(w.doc, ops, resources, &mut cache, carry, Some(&mut invoked), Some(&properties));- 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();@@@ -1489,14 -1377,15 +1579,15 @@@add_shown(&mut w.lines, &mut last, s, si);}for (_, name, ts) in forms {- enter(w, resources, &name, ts);+ enter(w, resources, &name, ts)?;}+ Ok(())}- 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.budget) else { return };+ fn enter(w: &mut Walk, resources: &Dict, name: &[u8], ts: Ts) -> Result<(), EditError> {- let Some(form) = form_call(w.doc, resources, name, ts.ctm, &w.path, &mut w.visits) else { return Ok(()) };++ let Some(form) = form_call(w.doc, resources, name, ts.ctm, &w.path, &mut w.budget) else { return Ok(()) };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 {@@@ -1979,12 -1836,7 +2071,13 @@@ pub(crate) fn replace_line_with_limit(dlet text = text.replace(['\n', '\r'], " ");let lines = text_lines(doc, page)?;let target = lines.get(line).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no line {}", page + 1, line + 1)))?;+ target.ensure_editable()?;+ // Copies of the line drawn on the same baseline go with it, so the replacement is all that+ // shows. Which operators go is settled here, before any font is generated, so that a refusal+ // leaves the document untouched.+ let mut drops = coincident_ops(&lines, &[&target]);+ drops.extend(target.ops.iter().copied());+ refuse_clipping_text(&lines, &drops)?;let p = page_dict(doc, page)?;let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();@@@ -2195,7 -2000,8 +2289,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, &res, &mut HashMap::new(), &mut Carry::new(), None, None);- 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, None)?;let mut patches = HashMap::new();for s in shown.into_iter().filter(|s| drops.contains(&s.op)) {if s.state.render_mode >= 4 {@@@ -2368,11 -2157,8 +2462,12 @@@ fn rewrite_block_fromlet blocks = group_blocks(&lines);let b = blocks.get(block).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no paragraph {}", page + 1, block + 1)))?;let members: Vec<&TextLine> = b.lines.iter().map(|i| &lines[*i]).collect();+ // One clipping run is enough: rewriting the paragraph would drop its mask with the rest.+ let mut dropped = coincident_ops(&lines, &members);+ dropped.extend(members.iter().flat_map(|l| l.ops.iter().copied()));+ refuse_clipping_text(&lines, &dropped)?;let first = members.first().copied().ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;+ members.iter().try_for_each(|line| line.ensure_editable())?;let p = page_dict(doc, page)?;let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();@@@ -2873,7 -2678,7 +2987,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, &res, &mut HashMap::new(), &mut Carry::new(), None, None);- 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, 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.