PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: Edit text: click a line of existing text and retype it in place, reusing its font when it can show the text, else Helvetica; text_lines / text_edit tools
Brandon Thomasfb6208b089bf
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsindex e2d65c832..f9bc39a55 100644--- a/crates/automation/src/lib.rs+++ b/crates/automation/src/lib.rs@@ -275,6 +275,43 @@ impl Automation {"doc_optimize" => self.doc_optimize(&a)?,"doc_initial_view" => self.doc_initial_view(&a)?,"doc_revisions" => self.doc_revisions(&a)?,+ "text_lines" => {+ let page = self.page(&a)?;+ let doc = self.doc(&a)?;+ let info = &doc.info.pages[page];+ let r = |x: f32| (x as f64 * 100.0).round() / 100.0;+ let lines: Vec<Value> = doc+ .text_lines(page)+ .iter()+ .enumerate()+ .map(|(i, l)| {+ let (u, v) = (info.user_to_view(l.rect[0] as f32, l.rect[1] as f32), info.user_to_view(l.rect[2] as f32, l.rect[3] as f32));+ json!({+ "line": i + 1,+ "text": l.text,+ "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))],+ "font": l.base_font,+ "size": (l.size * 100.0).round() / 100.0,+ })+ })+ .collect();+ json!({ "page": page + 1, "count": lines.len(), "lines": lines })+ }+ "text_edit" => {+ let page = self.page(&a)?;+ let n = self.doc(&a)?.text_lines(page).len();+ let line = a.int("line")?;+ if line < 1 || line as usize > n {+ return Err(ToolError::InvalidArgs(format!("line {line} is out of range: page {} has {n} lines", page + 1)));+ }+ let text = a.str("text")?.to_owned();+ let mut out = self.apply(&a, Edit::EditTextLine { page, line: line as usize - 1, text })?;+ let after = self.doc(&a)?.text_lines(page);+ if let Some(l) = after.get(line as usize - 1) {+ out["line"] = json!({ "text": l.text, "font": l.base_font });+ }+ out+ }"doc_audit_space" => {let rows: Vec<Value> = self.doc(&a)?diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex e284939ea..4b806f690 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -812,6 +812,16 @@ pub fn tools() -> Vec<ToolDef> {.ro().cmd("optimize.advanced").with(schema(json!({ "doc": doc() }), &["doc"])),+ t("text_lines", "List text lines", "The lines of existing text on a page (Edit a PDF ▸ Edit text): number, text, box (top-left-origin points), font and size. Use the number with text_edit.")+ .ro()+ .cmd("edit.edit_text")+ .with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])),+ t("text_edit", "Edit a line of text", "Replace the text of one line (from text_lines) in place, keeping its position, size and colour. Its own font is reused when it can show every character; otherwise the line is set in Helvetica (the result shows the font used). Text that no available font can show is refused. Undoable.")+ .cmd("edit.edit_text")+ .with(schema(+ json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "line": { "type": "integer", "minimum": 1 }, "text": { "type": "string" } }),+ &["doc", "page", "line", "text"],+ )),t("doc_revisions", "List revisions", "List the document's saved revisions (oldest first): each incremental update is one. Returns revision number, where it ends in the file and its size, and which signatures sign exactly that revision.").with(schema(json!({ "doc": doc() }), &["doc"])),t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rsindex dcaada256..6f135b31d 100644--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@ -635,6 +635,20 @@ trailer << /Root 1 0 R >>assert!(matches!(a.call("accessibility_set_alt", &json!({ "doc": fd, "figure": 6, "alt": "x" })), Err(ToolError::Failed(_))));}+#[test]+fn editing_existing_text_through_tools() {+ let dir = workdir("edit-text");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ let lines = ok(&mut a, "text_lines", json!({ "doc": doc, "page": 2 }));+ assert_eq!((lines["count"].as_u64(), lines["lines"][0]["text"].as_str()), (Some(1), Some("Page 2")));+ let r = ok(&mut a, "text_edit", json!({ "doc": doc, "page": 2, "line": 1, "text": "Section two" }));+ assert_eq!(r["line"]["text"], "Section two");+ assert_eq!(page_text(&mut a, doc)[1], "Section two");+ assert!(matches!(a.call("text_edit", &json!({ "doc": doc, "page": 2, "line": 9, "text": "x" })), Err(ToolError::InvalidArgs(_))));+ assert_eq!(ok(&mut a, "edit_undo", json!({ "doc": doc }))["undone"], "Edit text");+}+#[test]fn auditing_space_through_tools() {let dir = workdir("audit");diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rsindex 62f88304c..27efbc49c 100644--- a/crates/edit/src/lib.rs+++ b/crates/edit/src/lib.rs@@ -587,6 +587,8 @@ pub fn marks_present(doc: &Document) -> Vec<MarkKind> {mod flatten;pub use flatten::flatten;+pub mod text;+pub use text::{LineEdit, TextLine, replace_line, text_lines};pub mod added;pub use added::{Added, AddedImage, AddedText, Align, Content, Family, add_content, delete_content, list_added, update_content};diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex 51673332f..656db84e7 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -226,3 +226,65 @@ fn added_text_and_images_are_page_content_that_stays_editable() {// Page marks ignore added items.assert!(marks_present(&doc).is_empty());}++/// One page with Helvetica (WinAnsi) and a subset font that has only the glyphs it uses.+fn text_page(content: &str) -> Document {+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> >>".into(),+ format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ // Subset: glyphs for a (97) and b (98) only.+ "<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Arial /FirstChar 97 /LastChar 99 /Widths [500 520 0] /Encoding /WinAnsiEncoding >>"+ .into(),+ ];+ 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()+}++#[test]+fn text_lines_are_found_and_replaced_in_place() {+ let mut doc =+ text_page("BT /F1 12 Tf 72 700 Td (Hello) Tj 40 0 Td [(wor) -20 (ld)] TJ 0 -20 Td (Second line) Tj ET BT /F2 10 Tf 72 600 Td (ab) Tj ET");+ let lines = text::text_lines(&doc, 0).unwrap();+ let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();+ assert_eq!(texts, ["Hello world", "Second line", "ab"]);+ assert!((lines[0].rect[0] - 72.0).abs() < 0.01 && lines[0].rect[1] < 700.0 && lines[0].rect[3] > 700.0, "{:?}", lines[0].rect);+ assert!((lines[0].size - 12.0).abs() < 1e-9 && lines[0].base_font == "Helvetica");+ let second = lines[1].rect;+ // Same font: reused; the next line stays where it was.+ let r = text::replace_line(&mut doc, 0, 0, "Goodbye, café").unwrap();+ assert_eq!(r.substituted, None);+ let doc = reopen(&doc);+ let lines = text::text_lines(&doc, 0).unwrap();+ assert_eq!(lines[0].text, "Goodbye, café");+ assert_eq!(lines[1].text, "Second line");+ assert_eq!(lines[1].rect, second);+}++#[test]+fn missing_glyphs_substitute_helvetica_and_impossible_text_is_refused() {+ let mut doc = text_page("BT /F2 10 Tf 72 600 Td (ab) Tj ET");+ // "c" has no glyph in the subset: Helvetica takes over for this line.+ let r = text::replace_line(&mut doc, 0, 0, "abc").unwrap();+ assert_eq!(r.substituted.as_deref(), Some("Helvetica"));+ let doc2 = reopen(&doc);+ let lines = text::text_lines(&doc2, 0).unwrap();+ assert_eq!((lines[0].text.as_str(), lines[0].base_font.as_str()), ("abc", "Helvetica"));+ // Neither font can show Greek.+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello) Tj ET");+ assert!(text::replace_line(&mut doc, 0, 0, "Ωmega").is_err());+ assert!(text::replace_line(&mut doc, 0, 5, "x").is_err(), "no such line");+}diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rsnew file mode 100644index 000000000..257ad84b1--- /dev/null+++ b/crates/edit/src/text.rs@@ -0,0 +1,367 @@+//! Edit a PDF ▸ Edit text: the text lines already on a page, and replacing a line's text in place.+//!+//! A *line* is a run of text-showing operators inside one `BT … ET` on the same baseline, read+//! from one content stream. Replacing it rewrites only that stream (as a new object, since content+//! streams may be shared): the first operator of the line shows the new text, the others are+//! dropped, and every positioning operator stays, so the lines after it keep their places+//! (`Td`, `T*` and friends move from the line matrix, which showing text doesn't change).+//!+//! The new text uses the line's own font when every character has a code and a glyph in it;+//! otherwise it is set in Helvetica (WinAnsi), and the result says the font was substituted.+//! Reflowing a paragraph to a new width is not done here (see `edit.text-reflow`).++use std::collections::HashMap;+use std::rc::Rc;++use printcraft_content::{Matrix, Op, parse, serialize_ops};+use printcraft_cos::{Dict, Document, Object, PdfString, Stream};+use printcraft_fonts::pdf::Metrics;++use crate::EditError;++/// One line of existing text.+#[derive(Clone, Debug, PartialEq)]+pub struct TextLine {+ /// The line's text as shown.+ pub text: String,+ /// Its box in user space.+ pub rect: [f64; 4],+ /// The font's resource name and `/BaseFont`, and its size in text space.+ pub font: String,+ pub base_font: String,+ pub size: f64,+ /// Whether new text in this font can only be shown by substituting another font (no+ /// Unicode mapping for the line, so nothing could be reused).+ pub decodable: bool,+ stream: usize,+ ops: Vec<usize>,+}++/// What replacing a line did.+#[derive(Clone, Debug, PartialEq)]+pub struct LineEdit {+ /// `Some(font)` when the line's font couldn't show the new text and Helvetica was used.+ pub substituted: Option<String>,+}++#[derive(Clone)]+struct Ts {+ ctm: Matrix,+ font: Option<(Vec<u8>, Rc<Metrics>)>,+ size: f64,+ char_spacing: f64,+ word_spacing: f64,+ scale: f64,+ leading: f64,+ rise: f64,+}++fn content_streams(doc: &Document, page: &Dict) -> Vec<(Object, Vec<u8>)> {+ let list: Vec<Object> = match page.get(b"Contents") {+ None => Vec::new(),+ Some(c) => match &*doc.resolve(c) {+ Object::Array(a) => a.clone(),+ _ => vec![c.clone()],+ },+ };+ list.into_iter()+ .map(|o| {+ let data = match &*doc.resolve(&o) {+ Object::Stream(s) => s.decoded().unwrap_or_default(),+ _ => Vec::new(),+ };+ (o, data)+ })+ .collect()+}++fn page_dict(doc: &Document, page: usize) -> Result<printcraft_model::Page, EditError> {+ printcraft_model::pages(doc).into_iter().nth(page).ok_or(EditError::NoSuchPage(page))+}++/// The text-showing operators of one stream with their text, font, box and baseline.+struct Shown {+ op: usize,+ text: String,+ rect: [f64; 4],+ baseline: f64,+ start_x: f64,+ end_x: f64,+ bt: usize,+ font: Vec<u8>,+ base_font: String,+ size: f64,+ decodable: bool,+}++fn interpret(doc: &Document, ops: &[Op], fonts_res: &Dict, cache: &mut HashMap<Vec<u8>, Rc<Metrics>>) -> Vec<Shown> {+ let mut out = Vec::new();+ let mut ts = Ts { ctm: Matrix::IDENTITY, font: None, size: 0.0, char_spacing: 0.0, word_spacing: 0.0, scale: 1.0, leading: 0.0, rise: 0.0 };+ let mut stack: Vec<Ts> = Vec::new();+ let (mut tm, mut tlm) = (Matrix::IDENTITY, Matrix::IDENTITY);+ let mut bt = 0usize;+ for (i, op) in ops.iter().enumerate() {+ match op.op.as_slice() {+ b"q" => stack.push(ts.clone()),+ b"Q" => {+ if let Some(s) = stack.pop() {+ ts = s;+ }+ }+ b"cm" => {+ if let Some(m) = op.nums::<6>() {+ ts.ctm = Matrix(m).then(&ts.ctm);+ }+ }+ b"BT" => {+ tm = Matrix::IDENTITY;+ tlm = Matrix::IDENTITY;+ bt += 1;+ }+ b"Tf" => {+ ts.size = op.num(1).unwrap_or(ts.size);+ if let Some(name) = op.name(0) {+ let m = cache.entry(name.to_vec()).or_insert_with(|| {+ Rc::new(+ fonts_res+ .get(name)+ .and_then(|f| doc.resolve(f).as_dict().cloned())+ .map(|d| Metrics::from_dict(doc, &d))+ .unwrap_or_else(Metrics::fallback),+ )+ });+ ts.font = Some((name.to_vec(), m.clone()));+ }+ }+ b"Tc" => ts.char_spacing = op.num(0).unwrap_or(0.0),+ b"Tw" => ts.word_spacing = op.num(0).unwrap_or(0.0),+ b"Tz" => ts.scale = op.num(0).unwrap_or(100.0) / 100.0,+ b"TL" => ts.leading = op.num(0).unwrap_or(0.0),+ b"Ts" => ts.rise = op.num(0).unwrap_or(0.0),+ b"Td" | b"TD" => {+ if let Some([x, y]) = op.nums::<2>() {+ if op.is("TD") {+ ts.leading = -y;+ }+ tlm = Matrix([1.0, 0.0, 0.0, 1.0, x, y]).then(&tlm);+ tm = tlm;+ }+ }+ b"Tm" => {+ if let Some(m) = op.nums::<6>() {+ tlm = Matrix(m);+ tm = tlm;+ }+ }+ b"T*" => {+ tlm = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, -ts.leading]).then(&tlm);+ tm = tlm;+ }+ b"Tj" | b"TJ" | b"'" | b"\"" => {+ if matches!(op.op.as_slice(), b"'" | b"\"") {+ if op.is("\"") {+ ts.word_spacing = op.num(0).unwrap_or(ts.word_spacing);+ ts.char_spacing = op.num(1).unwrap_or(ts.char_spacing);+ }+ tlm = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, -ts.leading]).then(&tlm);+ tm = tlm;+ }+ let Some((name, m)) = ts.font.clone() else { continue };+ // Pieces: strings, and TJ number adjustments.+ let pieces: Vec<Object> = match op.op.as_slice() {+ b"TJ" => op.operands.first().and_then(Object::as_array).cloned().unwrap_or_default(),+ _ => op.operands.last().cloned().into_iter().collect(),+ };+ let trm0 = tm.then(&ts.ctm);+ let start = trm0.apply(0.0, ts.rise);+ let mut text = String::new();+ let mut decodable = true;+ let mut x_text = 0.0;+ for p in &pieces {+ match p {+ Object::String(s) => {+ for (code, len) in m.codes(&s.bytes) {+ match m.text_of(code) {+ Some(t) => text.push_str(t),+ None => decodable = false,+ }+ let w = m.width(code) * ts.size + ts.char_spacing + if m.is_space(code, len) { ts.word_spacing } else { 0.0 };+ x_text += w * ts.scale;+ }+ }+ other => {+ if let Some(n) = other.as_f64() {+ 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(' ') {+ text.push(' ');+ }+ x_text += dx;+ }+ }+ }+ }+ tm = Matrix([1.0, 0.0, 0.0, 1.0, x_text, 0.0]).then(&tm);+ let end = tm.then(&ts.ctm).apply(0.0, ts.rise);+ // The box: from descent to ascent along the run.+ let corners = [+ trm0.apply(0.0, ts.rise + m.descent * ts.size),+ trm0.apply(x_text, ts.rise + m.descent * ts.size),+ trm0.apply(0.0, ts.rise + m.ascent * ts.size),+ trm0.apply(x_text, ts.rise + m.ascent * ts.size),+ ];+ let rect = corners+ .iter()+ .fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p.0), b[1].min(p.1), b[2].max(p.0), b[3].max(p.1)]);+ let size_user = (trm0.0[2].powi(2) + trm0.0[3].powi(2)).sqrt() * ts.size;+ out.push(Shown {+ op: i,+ text,+ rect,+ baseline: start.1,+ start_x: start.0,+ end_x: end.0,+ bt,+ font: name,+ base_font: m.base_font.clone(),+ size: if size_user > 0.0 { size_user } else { ts.size },+ decodable,+ });+ }+ _ => {}+ }+ }+ out+}++/// The lines of text on a page (0-based), in content order.+pub fn text_lines(doc: &Document, page: usize) -> Result<Vec<TextLine>, EditError> {+ let p = page_dict(doc, page)?;+ let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();+ let fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();+ let mut cache = HashMap::new();+ let mut lines: Vec<TextLine> = Vec::new();+ for (si, (_, data)) in content_streams(doc, &p.dict).into_iter().enumerate() {+ let ops = parse(&data).ops;+ let shown = interpret(doc, &ops, &fonts_res, &mut cache);+ let mut last: Option<(usize, f64, f64, f64)> = None; // (bt, baseline, end_x, size)+ for s in shown {+ let joins = last.is_some_and(|(bt, base, end, size)| {+ bt == s.bt && (s.baseline - base).abs() < size * 0.3 && s.start_x > end - size && s.start_x - end < size * 3.0+ });+ if joins && let Some(l) = lines.last_mut() {+ let gap = s.start_x - last.map_or(s.start_x, |x| x.2);+ if gap > l.size * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ') {+ l.text.push(' ');+ }+ l.text.push_str(&s.text);+ l.rect = [l.rect[0].min(s.rect[0]), l.rect[1].min(s.rect[1]), l.rect[2].max(s.rect[2]), l.rect[3].max(s.rect[3])];+ l.ops.push(s.op);+ l.decodable &= s.decodable;+ } else {+ lines.push(TextLine {+ text: s.text.clone(),+ rect: s.rect,+ font: String::from_utf8_lossy(&s.font).into_owned(),+ base_font: s.base_font.clone(),+ size: s.size,+ decodable: s.decodable,+ stream: si,+ ops: vec![s.op],+ });+ }+ last = Some((s.bt, s.baseline, s.end_x, s.size.max(1.0)));+ }+ }+ // Lines of only spaces aren't editable text.+ lines.retain(|l| !l.text.trim().is_empty());+ Ok(lines)+}++/// The substitute font's resource name.+const SUBSTITUTE: &[u8] = b"PCEdHelv";++/// Replace the text of line `line` (an index into [`text_lines`]) on `page` with `text`.+pub fn replace_line(doc: &mut Document, page: usize, line: usize, text: &str) -> Result<LineEdit, EditError> {+ let 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)))?;+ 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();+ let streams = content_streams(doc, &p.dict);+ let (stream_obj, data) = streams.get(target.stream).cloned().ok_or_else(|| EditError::Invalid("the page's content changed".into()))?;+ let mut ops = parse(&data).ops;+ let first = target.ops[0];+ // The line's own font, when it can show every character.+ let font = fonts_res.get(target.font.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned()).map(|d| Metrics::from_dict(doc, &d));+ let reused = font.as_ref().and_then(|m| m.encode(&text));+ let mut substituted = None;+ let mut replacement: Vec<Op> = Vec::new();+ // ' and " also move to the next line; keep that.+ match ops[first].op.as_slice() {+ b"'" => replacement.push(Op::new("T*", vec![])),+ b"\"" => {+ replacement.push(Op::new("Tw", vec![ops[first].operands.first().cloned().unwrap_or(Object::Int(0))]));+ replacement.push(Op::new("Tc", vec![ops[first].operands.get(1).cloned().unwrap_or(Object::Int(0))]));+ replacement.push(Op::new("T*", vec![]));+ }+ _ => {}+ }+ match reused {+ Some(bytes) => replacement.push(Op::new("Tj", vec![Object::String(PdfString::literal(bytes))])),+ None => {+ let win = printcraft_fonts::win_ansi(&text);+ // WinAnsi turns what it can't show into '?'; refuse rather than print the wrong thing.+ let back: String = win.iter().map(|b| char::from_u32(u32::from(*b)).unwrap_or('?')).collect();+ if text.chars().zip(back.chars()).any(|(a, b)| b == '?' && a != '?') {+ return Err(EditError::Invalid(format!("\"{text}\" has characters neither {} nor Helvetica can show", target.base_font)));+ }+ // The size in text space: the current Tf's size.+ let size = font_size_before(&ops, first).unwrap_or(target.size);+ replacement.push(Op::new("Tf", vec![Object::name(std::str::from_utf8(SUBSTITUTE).expect("ascii")), printcraft_content::num(size)]));+ replacement.push(Op::new("Tj", vec![Object::String(PdfString::literal(win))]));+ replacement.push(Op::new("Tf", vec![Object::name(&target.font), printcraft_content::num(size)]));+ substituted = Some("Helvetica".to_string());+ let mut f = Dict::new();+ f.set(b"Type".to_vec(), Object::name("Font"));+ f.set(b"Subtype".to_vec(), Object::name("Type1"));+ f.set(b"BaseFont".to_vec(), Object::name("Helvetica"));+ f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));+ fonts_res.set(SUBSTITUTE.to_vec(), Object::Dict(f));+ }+ }+ // Rebuild: the line's first operator becomes the replacement, its others go.+ let drop: std::collections::HashSet<usize> = target.ops[1..].iter().copied().collect();+ let mut new_ops = Vec::with_capacity(ops.len() + replacement.len());+ for (i, op) in ops.drain(..).enumerate() {+ if i == first {+ new_ops.append(&mut replacement);+ } else if !drop.contains(&i) {+ new_ops.push(op);+ }+ }+ let mut dict = match &*doc.resolve(&stream_obj) {+ Object::Stream(s) => s.dict.clone(),+ _ => Dict::new(),+ };+ dict.remove(b"Length");+ let new = doc.add(Object::Stream(Stream::flate(dict, &serialize_ops(&new_ops))));+ let contents: Vec<Object> = streams.iter().enumerate().map(|(i, (o, _))| if i == target.stream { Object::Ref(new) } else { o.clone() }).collect();+ let page_ref = p.obj;+ if substituted.is_some() {+ res.set(b"Font".to_vec(), Object::Dict(fonts_res));+ }+ doc.update_dict(page_ref, |d| {+ d.set(b"Contents".to_vec(), if contents.len() == 1 { contents[0].clone() } else { Object::Array(contents) });+ if substituted.is_some() {+ d.set(b"Resources".to_vec(), Object::Dict(res));+ }+ })?;+ Ok(LineEdit { substituted })+}++/// The size of the last `Tf` before operator `at`.+fn font_size_before(ops: &[Op], at: usize) -> Option<f64> {+ ops[..at].iter().rev().find(|o| o.is("Tf")).and_then(|o| o.num(1))+}diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rsindex de02b8645..dd479935c 100644--- a/crates/engine/src/catalog.rs+++ b/crates/engine/src/catalog.rs@@ -122,6 +122,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ToolSection {title: "Add content",items: &[+ item("Edit text", "text-cursor-input", "edit.edit_text", Ready),item("Text", "type", "edit.text", Ready),item("Image", "image-plus", "edit.image", Ready),item("Header and footer", "heading", "edit.header_footer", Ready),diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 91a8e8ce4..ebe5489cb 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -207,6 +207,7 @@ pub const COMMANDS: &[CommandSpec] = &[c("form.tab_order.column", "Tab order: by columns", None, None, HasFields, "columns-3"),c("form.tab_order.structure", "Tab order: by document structure", None, None, HasFields, "list"),c("edit.text", "Add text", None, None, Modification, "type"),+ c("edit.edit_text", "Edit text", None, None, Modification, "text-cursor-input"),c("edit.link", "Add or edit links", None, None, Modification, "link-2"),c("edit.links_from_urls", "Create links from URLs", None, None, Modification, "link-2"),c("edit.remove_links", "Remove all links", None, None, Modification, "trash-2"),diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex f26a6ac2c..3305c12b0 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -31,6 +31,7 @@ pub use printcraft_forms::{};pub use printcraft_a11y as a11y;+pub use printcraft_edit::TextLine;pub use printcraft_fonts::{ScriptOutline, script_outline};/// Fill & Sign: `text` in the script font as a typed signature, its left edge at `at` (user@@ -182,6 +183,16 @@ impl Document {self.editor.as_ref().map(|e| optimize::audit_space(&e.cos, self.bytes.len() as u64)).unwrap_or_default()}+ /// A counter that changes with every edit (for caches of derived data).+ pub fn edit_generation(&self) -> u64 {+ self.generation+ }++ /// Edit a PDF ▸ Edit text: the lines of existing text on `page` (0-based).+ pub fn text_lines(&self, page: usize) -> Vec<printcraft_edit::TextLine> {+ self.editor.as_ref().and_then(|e| printcraft_edit::text_lines(&e.cos, page).ok()).unwrap_or_default()+ }+/// Add alternate text: the figures, in document order.pub fn figures(&self) -> Vec<a11y::Figure> {self.editor.as_ref().map(|e| a11y::figures(&e.cos)).unwrap_or_default()@@ -729,6 +740,13 @@ pub enum Edit {MarkDecorative {figure: u32,},+ /// Edit a PDF ▸ Edit text: replace the text of line `line` (from `Document::text_lines`) on+ /// `page`, in its own font when it can show it, else in Helvetica.+ EditTextLine {+ page: usize,+ line: usize,+ text: String,+ },/// Order tabs manually: move a field one place earlier or later on its page.MoveInTabOrder {name: String,@@ -895,6 +913,7 @@ impl Edit {Edit::SetInitialView(_) => "Change initial view".into(),Edit::SetAltText { .. } => "Set alternate text".into(),Edit::MarkDecorative { .. } => "Mark figure as decorative".into(),+ Edit::EditTextLine { .. } => "Edit text".into(),Edit::AddHeaderFooter { replace: false, .. } => "Add header & footer".into(),Edit::AddHeaderFooter { .. } => "Update header & footer".into(),Edit::AddWatermark { replace: false, .. } => "Add watermark".into(),@@ -1054,6 +1073,7 @@ fn check_permission(edit: &Edit, p: &printcraft_cos::Permissions) -> Result<(),| Edit::SetInitialView(_)| Edit::SetAltText { .. }| Edit::MarkDecorative { .. }+ | Edit::EditTextLine { .. }| Edit::Flatten { .. } => {if p.modify() {Ok(())@@ -1234,6 +1254,9 @@ fn run_edit(doc: &mut printcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -let r = printcraft_cos::ObjRef::new(*figure, doc.generation(*figure));a11y::set_alt(doc, r, alt.as_deref()).map_err(|e| EditError::Accessibility(e.to_string()))?;}+ Edit::EditTextLine { page, line, text } => {+ printcraft_edit::replace_line(doc, *page, *line, text)?;+ }Edit::MarkDecorative { figure } => {let r = printcraft_cos::ObjRef::new(*figure, doc.generation(*figure));a11y::mark_decorative(doc, r).map_err(|e| EditError::Accessibility(e.to_string()))?;diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 446814e07..386c72cf8 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -137,6 +137,10 @@ pub struct DocView {select_anchor: Option<usize>,/// An edit requested by the view (organize toolbar, keys), applied by the app this frame.pub pending_edit: Option<Edit>,+ /// Edit text: the lines per page (with the document generation they were read at), and the+ /// line being edited.+ pub(crate) edit_lines: HashMap<usize, (u64, Vec<printcraft_engine::TextLine>)>,+ pub line_editor: Option<crate::edit_text_ui::LineEditor>,/// Commenting state: selected comment, gestures, composer.pub comments: crate::comments::CommentView,/// Form filling state: the focused field.@@ -236,6 +240,8 @@ impl DocView {selected: BTreeSet::new(),select_anchor: None,pending_edit: None,+ edit_lines: HashMap::new(),+ line_editor: None,pending_action: None,comments: Default::default(),forms: Default::default(),@@ -959,6 +965,7 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {| QuickTool::Fill(_)| QuickTool::Field(_)| QuickTool::AddText+ | QuickTool::EditText| QuickTool::Stamp(_)| QuickTool::CustomStamp(_)| QuickTool::Link@@ -1216,8 +1223,20 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {content_done |= o.done;o.consumed || tool == QuickTool::AddText};+ let on_edit_text = tool == QuickTool::EditText && can_modify && {+ let generation = doc.edit_generation();+ let lines = match view.edit_lines.get(&i) {+ Some((g, l)) if *g == generation => l.clone(),+ _ => {+ let l = doc.text_lines(i);+ view.edit_lines.insert(i, (generation, l.clone()));+ l+ }+ };+ crate::edit_text_ui::page_input(ui, &resp, &xf, i, info, &lines, view)+ };let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(ui, &resp, &xf, i, info, &doc_links, view);- let consumed = on_link || on_content || boxing || on_field || comments::page_input(ui, &resp, &pcx, view);+ let consumed = on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, &resp, &pcx, view);// Text layer: find matches, selection, I-beam and drag-to-select.let to_screen = |g: [f32; 4]| xf.view_rect(g);@@ -1482,6 +1501,9 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {view.pending_edit = Some(e);}+ if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view) {+ view.pending_edit = Some(e);+ }if let Some(e) = crate::forms_ui::overlay(ui.ctx(), view, info, &form, today) {view.pending_edit = Some(e);}diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rsindex 3eb283ed8..1193993b2 100644--- a/crates/ui-egui/src/commands.rs+++ b/crates/ui-egui/src/commands.rs@@ -223,6 +223,10 @@ impl PrintCraftApp {"export.image" => self.dialog = Some(Dialog::Export(crate::export_ui::ExportKind::Image)),"export.text" => self.dialog = Some(Dialog::Export(crate::export_ui::ExportKind::Text)),"a11y.check" => self.start_accessibility_check(),+ "edit.edit_text" => {+ self.quick_tool = crate::QuickTool::EditText;+ self.notify("Click a line of text to edit it");+ }"edit.advanced_search" => {if let Some(i) = self.active {let f = self.views[i].find.get_or_insert_with(Default::default);diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 3704e5c4a..d1c89518c 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -540,6 +540,7 @@ impl Host for crate::PrintCraftApp {crate::QuickTool::Crop => "crop".to_string(),crate::QuickTool::Redact => "redact".to_string(),crate::QuickTool::AddText => "add-text".to_string(),+ crate::QuickTool::EditText => "edit-text".to_string(),crate::QuickTool::Link => "link".to_string(),crate::QuickTool::SignArea { certify: false } => "sign".to_string(),crate::QuickTool::SignArea { certify: true } => "certify".to_string(),diff --git a/crates/ui-egui/src/edit_text_ui.rs b/crates/ui-egui/src/edit_text_ui.rsnew file mode 100644index 000000000..eadeb5f65--- /dev/null+++ b/crates/ui-egui/src/edit_text_ui.rs@@ -0,0 +1,96 @@+//! Edit a PDF ▸ Edit text: boxes around the lines of existing text; click one to edit it in place+//! (Enter or clicking away applies, Esc cancels).++use egui::{Color32, CornerRadius, Pos2, Rect, Stroke};+use printcraft_engine::Edit;+use printcraft_render::DocInfo;++use crate::canvas::{DocView, PageXform};++const ACCENT: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);++/// A line being edited.+#[derive(Clone, Debug, PartialEq)]+pub struct LineEditor {+ pub page: usize,+ pub line: usize,+ pub text: String,+ original: String,+ rect: Rect,+ size: f32,+ focus: bool,+}++/// Lines and their screen boxes for a page; hover outlines, click opens the editor. Returns+/// `true` when the pointer was used.+pub(crate) fn page_input(+ ui: &egui::Ui,+ resp: &egui::Response,+ xf: &PageXform,+ page: usize,+ info: &DocInfo,+ lines: &[printcraft_engine::TextLine],+ view: &mut DocView,+) -> bool {+ let boxes: Vec<Rect> = lines.iter().map(|l| xf.user_rect(info, page, l.rect.map(|v| v as f32)).expand(2.0)).collect();+ let painter = ui.painter();+ for b in &boxes {+ painter.rect_stroke(*b, CornerRadius::same(2), Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);+ }+ let Some(p) = ui.input(|i| i.pointer.hover_pos()).filter(|p| xf.rect.contains(*p)) else { return false };+ let Some(hit) = boxes.iter().position(|b| b.contains(p)) else { return false };+ painter.rect_stroke(boxes[hit], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);+ ui.ctx().set_cursor_icon(egui::CursorIcon::Text);+ if resp.clicked() {+ let l = &lines[hit];+ let scale = boxes[hit].height() / ((l.rect[3] - l.rect[1]).max(1.0) as f32 + 4.0);+ view.line_editor = Some(LineEditor {+ page,+ line: hit,+ text: l.text.clone(),+ original: l.text.clone(),+ rect: boxes[hit],+ size: (l.size as f32 * scale).clamp(8.0, 72.0),+ focus: true,+ });+ }+ true+}++/// The inline editor; returns the edit once the text is applied.+pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView) -> Option<Edit> {+ let ed = view.line_editor.as_mut()?;+ let mut done = None;+ egui::Area::new(egui::Id::new("edit-text-line")).order(egui::Order::Foreground).fixed_pos(Pos2::new(ed.rect.left(), ed.rect.top())).show(+ ctx,+ |ui| {+ egui::Frame::NONE.fill(Color32::WHITE).stroke(Stroke::new(1.5, ACCENT)).inner_margin(egui::Margin::symmetric(2, 0)).show(ui, |ui| {+ let r = ui.add(+ egui::TextEdit::singleline(&mut ed.text)+ .id(egui::Id::new("edit-text-line-input"))+ .font(egui::FontId::proportional(ed.size))+ .text_color(Color32::BLACK)+ .frame(egui::Frame::NONE)+ .desired_width(ed.rect.width().max(120.0)),+ );+ if ed.focus {+ r.request_focus();+ ed.focus = false;+ }+ let esc = ui.input(|i| i.key_pressed(egui::Key::Escape));+ if esc {+ done = Some(false);+ } else if r.lost_focus() {+ done = Some(true);+ }+ });+ },+ );+ match done {+ Some(apply) => {+ let ed = view.line_editor.take()?;+ (apply && ed.text != ed.original).then_some(Edit::EditTextLine { page: ed.page, line: ed.line, text: ed.text })+ }+ None => None,+ }+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 0aa5aacf5..bfca01585 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -34,6 +34,7 @@ pub use link_ui::LinkDraft;pub use optimize_ui::{OptimizeDraft, OptimizeTab};pub use sign_ui::{DigitalIdEntry, SignDraft, SignStep};mod dialogs;+mod edit_text_ui;mod editing;mod files;pub mod fill_sign;@@ -112,6 +113,8 @@ pub enum QuickTool {Redact,/// Edit a PDF ▸ Add content ▸ Text.AddText,+ /// Edit a PDF ▸ Edit text: click a line of existing text to edit it.+ EditText,/// Add a stamp: click to place this stamp.Stamp(printcraft_engine::StampKind),/// A custom stamp from the library (its index).@@ -937,6 +940,7 @@ impl PrintCraftApp {"crop" => QuickTool::Crop,"redact" => QuickTool::Redact,"add-text" => QuickTool::AddText,+ "edit-text" => QuickTool::EditText,"link" => QuickTool::Link,"sign" => QuickTool::SignArea { certify: false },"marquee-zoom" => QuickTool::MarqueeZoom,diff --git a/crates/ui-egui/tests/editing.rs b/crates/ui-egui/tests/editing.rsindex eabe5a278..6823a52e7 100644--- a/crates/ui-egui/tests/editing.rs+++ b/crates/ui-egui/tests/editing.rs@@ -591,3 +591,30 @@ fn copying_cutting_and_pasting_pages() {h.state_mut().execute("page.cut");assert_eq!(page_texts(h.state()).len(), 5);}++#[test]+fn editing_existing_text_in_place() {+ let mut h = harness(1, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ // The line "Page 1" sits at (20, 150) on a 200 × 300 page, 24 pt.+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let at = egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height());+ h.hover_at(at);+ h.run_steps(1);+ h.drag_at(at);+ h.run_steps(1);+ h.drop_at(at);+ h.run_steps(3);+ let ed = h.state().views[0].line_editor.clone().expect("the line opens for editing");+ assert_eq!((ed.page, ed.line, ed.text.as_str()), (0, 0, "Page 1"));+ h.state_mut().views[0].line_editor.as_mut().unwrap().text = "Chapter One".into();+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(4);+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ assert_eq!(doc.can_undo(), Some("Edit text"));+ assert_eq!(doc.text_lines(0)[0].text, "Chapter One");+ assert_eq!(texts_of(s, 0), ["Chapter One"], "the page shows it");+}diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 9087c783e..dc69b96e6 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -1779,11 +1779,11 @@ title = "Edit existing text in place"area = "C"tier = "P0"milestone = "M7"-status = "planned"-commands = []-tools = []-evidence = []-notes = ""+status = "partial"+commands = ["edit.edit_text"]+tools = ["text_lines", "text_edit"]+evidence = ["crates/edit/src/tests.rs::text_lines_are_found_and_replaced_in_place", "crates/ui-egui/tests/editing.rs::editing_existing_text_in_place", "crates/automation/tests/automation.rs::editing_existing_text_through_tools"]+notes = "line by line: click a line of existing text and retype it in place (position, size and colour kept; later lines untouched); paragraph boxes and multi-line reflow are next"[[feature]]id = "edit.text-reflow"@@ -1815,11 +1815,11 @@ title = "Reuse embedded fonts or substitute with a warning"area = "C"tier = "P0"milestone = "M7"-status = "planned"-commands = []-tools = []-evidence = []-notes = ""+status = "shipped"+commands = ["edit.edit_text"]+tools = ["text_edit"]+evidence = ["crates/edit/src/tests.rs::missing_glyphs_substitute_helvetica_and_impossible_text_is_refused", "crates/fonts/src/pdf.rs::subset_fonts_only_encode_the_glyphs_they_have", "crates/fonts/src/pdf.rs::composite_fonts_use_to_unicode"]+notes = "the line's font is reused when every character has a code and a glyph (ToUnicode, encodings, Differences; subset glyph checks); otherwise Helvetica (WinAnsi) is used and reported; text no font can show is refused"[[feature]]id = "edit.text-format-font"