From df751f252e0eb33b51c58581d7c1f3ed5d3919bb Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 16 Oct 2026 02:20:09 +0200 Subject: [PATCH 01/65] Contributors: add my name for the About window --- contributors/people.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index da3cfc6a77..3d6bb7fa47 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -145,3 +145,8 @@ sync_github_name = false [people.Silvertree2010] display_name = "Netter" sync_github_name = false + +[people.marcoarnulfo] +real_name = "Marco Arnulfo" +display_name = "Marco Arnulfo" +sync_github_name = false From 8f900c8dcb6b59f2611741a010c0fe48a27b9dd0 Mon Sep 17 00:00:00 2001 From: rangoDJ Date: Thu, 15 Oct 2026 22:30:22 -0400 Subject: [PATCH 02/65] fix(automation,edit): clean AcroForm leftovers on flatten and reject invalid opacity (#2670) When flattening form fields, /AcroForm /CO was left pointing to removed calculated fields, and /SigFlags remained set even when all signature fields were flattened or no signature fields remained. Prune removed field references from /CO (removing /CO if empty) and remove /SigFlags when no signature fields survive in the field tree. Also validate opacity in automation tools (comment_add, comment_edit, doc_watermark, doc_background) so out-of-range values return an invalid arguments error rather than clamping negative opacity to 0. --- crates/automation/src/comments.rs | 8 +++- crates/automation/src/lib.rs | 16 ++++++- crates/automation/tests/automation.rs | 12 ++++++ crates/edit/src/flatten.rs | 60 +++++++++++++++++++++++---- crates/edit/src/tests.rs | 46 ++++++++++++++++++++ 5 files changed, 131 insertions(+), 11 deletions(-) diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs index 302688f729..ea1d6d0d0a 100644 --- a/crates/automation/src/comments.rs +++ b/crates/automation/src/comments.rs @@ -397,7 +397,10 @@ impl Automation { } style.fill = a.color("fill")?; if let Some(o) = a.opt_num("opacity")? { - style.opacity = o.clamp(0.0, 1.0); + if !(0.0..=1.0).contains(&o) { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + style.opacity = o; } if let Some(w) = a.opt_num("width")? { style.width = w.max(0.0); @@ -612,6 +615,9 @@ impl Automation { edits.push(Edit::SetAnnotationContents { page, index, text: text.to_string() }); } let (color, opacity, width) = (a.color("color")?, a.opt_num("opacity")?, a.opt_num("width")?); + if let Some(o) = opacity.filter(|&o| !(0.0..=1.0).contains(&o)) { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } if color.is_some() || opacity.is_some() || width.is_some() { edits.push(Edit::StyleAnnotation { page, index, color, opacity, width, endings: None }); } diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 88856305b2..29409424c2 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -1214,7 +1214,13 @@ impl Automation { scale: a.opt_num("scale")?.unwrap_or(d.scale).clamp(0.01, 1.0), font_size: a.opt_num("font_size")?.unwrap_or(0.0), color: color("color", d.color)?, - opacity: a.opt_num("opacity")?.unwrap_or(d.opacity), + opacity: match a.opt_num("opacity")? { + Some(o) if !(0.0..=1.0).contains(&o) => { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + Some(o) => o, + None => d.opacity, + }, rotation: a.opt_num("rotation")?.unwrap_or(d.rotation), behind: a.opt_bool("behind")?.unwrap_or(false), offset: [ @@ -1228,7 +1234,13 @@ impl Automation { pages, settings: Background { color: color("color", [1.0; 3])?, - opacity: a.opt_num("opacity")?.unwrap_or(1.0), + opacity: match a.opt_num("opacity")? { + Some(o) if !(0.0..=1.0).contains(&o) => { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + Some(o) => o, + None => 1.0, + }, scale: a.opt_num("scale")?.unwrap_or(1.0).clamp(0.01, 1.0), ..Background::default() }, diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs index 1e662d8f38..6890e3c775 100644 --- a/crates/automation/tests/automation.rs +++ b/crates/automation/tests/automation.rs @@ -1785,6 +1785,17 @@ fn comments_through_tools() { Err(ToolError::InvalidArgs(_)) )); assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": 1, "index": 1 })), Err(ToolError::InvalidArgs(_)))); + // #2670: opacity must be between 0 and 1. + assert!(matches!( + a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "opacity": -3 })), + Err(ToolError::InvalidArgs(_)) + )); + assert!(matches!( + a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "opacity": 1.5 })), + Err(ToolError::InvalidArgs(_)) + )); + assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "opacity": 2.0 })), Err(ToolError::InvalidArgs(_)))); // Comments survive a save and reopen. ok(&mut a, "doc_save", json!({ "doc": doc, "path": "commented.pdf" })); @@ -2153,6 +2164,7 @@ fn watermarks_move_from_the_page_centre_through_tools() { // Huge offsets are clamped, and a value that isn't a number is refused. ok(&mut a, "doc_watermark", json!({ "doc": doc, "pages": [1], "text": "DRAFT", "offset_y": 1e300, "replace": true })); assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "offset_x": "left" })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); } #[test] diff --git a/crates/edit/src/flatten.rs b/crates/edit/src/flatten.rs index 8202c18d83..dc2afb9b8c 100644 --- a/crates/edit/src/flatten.rs +++ b/crates/edit/src/flatten.rs @@ -297,27 +297,71 @@ fn prune_fields(doc: &mut Document, widgets: &HashSet, on_page: Option<& let af_ref = af.as_ref(); let mut af_dict = doc.resolve(&af).as_dict().cloned().unwrap_or_default(); let fields = af_dict.get(b"Fields").map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()).unwrap_or_default(); - // Returns whether the node survives. - fn keep(doc: &mut Document, r: ObjRef, widgets: &HashSet, on_page: Option<&HashSet>, depth: usize) -> bool { - if widgets.contains(&r) || depth > 64 { + struct FormPrune<'a> { + widgets: &'a HashSet, + on_page: Option<&'a HashSet>, + surviving_nodes: HashSet, + has_signatures: bool, + } + let mut state = FormPrune { widgets, on_page, surviving_nodes: HashSet::new(), has_signatures: false }; + // Returns whether the node survives, and collects surviving node refs and signature presence. + fn check_node(doc: &mut Document, r: ObjRef, inherited_ft: Option<&[u8]>, state: &mut FormPrune<'_>, depth: usize) -> bool { + if state.widgets.contains(&r) || depth > 64 { return depth > 64; } let Some(d) = doc.get(r).as_dict().cloned() else { return true }; + let own_ft = d.get(b"FT").map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(|n| n.to_vec())); + let ft = own_ft.as_deref().or(inherited_ft); + let is_sig = ft == Some(b"Sig"); let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) else { - return on_page.is_none_or(|p| p.contains(&r)); + let survives = state.on_page.is_none_or(|p| p.contains(&r)); + if survives { + state.surviving_nodes.insert(r); + if is_sig { + state.has_signatures = true; + } + } + return survives; }; - let survivors: Vec = - kids.iter().filter(|k| k.as_ref().is_none_or(|kr| keep(doc, kr, widgets, on_page, depth + 1))).cloned().collect(); + let survivors: Vec = kids.iter().filter(|k| k.as_ref().is_none_or(|kr| check_node(doc, kr, ft, state, depth + 1))).cloned().collect(); if survivors.len() != kids.len() { let _ = doc.update_dict(r, |d| d.set(b"Kids".to_vec(), Object::Array(survivors.clone()))); } - !survivors.is_empty() + let survives = !survivors.is_empty(); + if survives { + state.surviving_nodes.insert(r); + if is_sig { + state.has_signatures = true; + } + } + survives } - let survivors: Vec = fields.iter().filter(|f| f.as_ref().is_none_or(|r| keep(doc, r, widgets, on_page, 0))).cloned().collect(); + let survivors: Vec = fields.iter().filter(|f| f.as_ref().is_none_or(|r| check_node(doc, r, None, &mut state, 0))).cloned().collect(); if survivors.len() == fields.len() && widgets.is_empty() { return Ok(()); // only looked for fields on no page, and there were none } af_dict.set(b"Fields".to_vec(), Object::Array(survivors)); + if let Some(co_obj) = af_dict.get(b"CO").cloned() { + let co_array = doc.resolve(&co_obj).as_array().cloned().unwrap_or_default(); + let co_survivors: Vec = + co_array.into_iter().filter(|item| item.as_ref().is_some_and(|r| state.surviving_nodes.contains(&r))).collect(); + if co_survivors.is_empty() { + af_dict.remove(b"CO"); + if let Some(r) = co_obj.as_ref() { + doc.free(r); + } + } else if let Some(r) = co_obj.as_ref() { + doc.set(r, Object::Array(co_survivors)); + } else { + af_dict.set(b"CO".to_vec(), Object::Array(co_survivors)); + } + } + if !state.has_signatures { + let removed = af_dict.remove(b"SigFlags"); + if let Some(r) = removed.and_then(|o| o.as_ref()) { + doc.free(r); + } + } match af_ref { Some(r) => doc.set(r, Object::Dict(af_dict)), None => doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af_dict)))?, diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index b542142df8..e4c3a2f602 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -311,6 +311,52 @@ fn flattening_fields_drops_the_ones_on_no_page() { assert_eq!(left, [pdfcraft_cos::ObjRef::new(7, 0)], "only the hidden field on the page stays"); } +/// #2670: flattening form fields drops removed fields from `/AcroForm /CO` (calculation order) +/// and removes `/CO` once empty, and drops `/SigFlags` once no signature fields remain. +#[test] +fn flattening_fields_cleans_calculation_order_and_sigflags() { + let page = stream("", " "); + // Test 1: both fields flattened -> /Fields becomes empty, /CO and /SigFlags are removed. + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO [5 0 R] /SigFlags 1 >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig) /Rect [10 50 150 80] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 2); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + let fields = doc.resolve(af_dict.get(b"Fields").unwrap()); + assert_eq!(fields.as_array().unwrap().len(), 0, "no fields remain"); + assert!(!af_dict.contains(b"CO"), "empty calculation order was removed"); + assert!(!af_dict.contains(b"SigFlags"), "SigFlags was removed with no signature fields"); + + // Test 2: one field flattened, one surviving field -> /CO retains surviving field, SigFlags kept. + let mut doc2 = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO [5 0 R 6 0 R] /SigFlags 1 >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc1) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig_undrawable) /Rect [10 50 150 80] /F 4 >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream", + ]); + assert_eq!(flatten(&mut doc2, &[0], false, true).unwrap(), 1, "only calc1 with appearance is drawn"); + let doc2 = reopen(&doc2); + let root2 = doc2.root().unwrap(); + let af2 = doc2.resolve(doc2.get(root2).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict2 = af2.as_dict().unwrap(); + let co2 = doc2.resolve(af_dict2.get(b"CO").unwrap()); + let co_refs: Vec = co2.as_array().unwrap().iter().filter_map(|f| f.as_ref()).collect(); + assert_eq!(co_refs, [pdfcraft_cos::ObjRef::new(6, 0)], "only surviving field remains in /CO"); + assert!(af_dict2.contains(b"SigFlags"), "SigFlags kept because signature field survived"); +} + /// #1794: a form field whose widget has no usable appearance (none stored, or none for its /// selected state) has nothing to draw. Flattening used to remove it anyway, losing its value /// with no ink in its place. It stays, in the page and in the form, like a comment that can't be From ed93f17174d32c898fec1d43a746a8f9710364b7 Mon Sep 17 00:00:00 2001 From: rangoDJ Date: Fri, 16 Oct 2026 12:29:51 -0400 Subject: [PATCH 03/65] test(automation): assert invalid opacity rejection on doc_background (#2670) --- crates/automation/tests/automation.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs index 6890e3c775..a0c250269a 100644 --- a/crates/automation/tests/automation.rs +++ b/crates/automation/tests/automation.rs @@ -2165,6 +2165,7 @@ fn watermarks_move_from_the_page_centre_through_tools() { ok(&mut a, "doc_watermark", json!({ "doc": doc, "pages": [1], "text": "DRAFT", "offset_y": 1e300, "replace": true })); assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "offset_x": "left" })), Err(ToolError::InvalidArgs(_)))); assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("doc_background", &json!({ "doc": doc, "color": "yellow", "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); } #[test] From 641380989c478fffa11b32c72f2692a76e7028b0 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:49:17 +0200 Subject: [PATCH 04/65] Drop a glyph redrawn at the same place by a later pass, not only within 4 glyphs (#3173) --- crates/render/src/text.rs | 48 ++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 5054859961..b1af213e16 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -1043,6 +1043,11 @@ fn union_find(parent: &mut [usize], mut r: usize) -> usize { r } +/// A 64-bit FNV-1a hash of one glyph text. +fn text_hash(text: &str) -> u64 { + text.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)) +} + /// A 64-bit fingerprint of a run's glyph texts. Each text is hashed with its length, so ["ab", "c"] and /// ["a", "bc"] differ. Equal fingerprints are only candidates: `redraws` decides. fn fingerprint(glyphs: &[&TextGlyph], run: Run) -> u64 { @@ -1421,17 +1426,27 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec, Vec, Vec) { // also overlaps most of its own width: a narrow letter in condensed text (80 Tz and below) sits // closer than a fifth of its height to its double, as the second "l" of "Alle" (#1467). let mut keep = vec![true; glyphs.len()]; - for i in 1..glyphs.len() { + // The twin is usually among the last few glyphs. A page drawn once per column clip redraws a glyph on the clip edge + // thousands of glyphs later, so `latest` also leads from the text and grid cell (a fifth of a line) of each kept glyph + // to the latest kept glyph there, and the cell and its neighbours are checked too (#3173). + let mut latest: HashMap<(u64, i32, i32), usize> = HashMap::new(); + for i in 0..glyphs.len() { let g = &glyphs[i]; let h = (g.rect[3] - g.rect[1]).max(0.1); let w = g.rect[2] - g.rect[0]; let dx = if w > 0.05 * h { (h * 0.2).min(w * 0.5) } else { h * 0.2 }; - for j in (i.saturating_sub(4)..i).rev() { + let same = |j: usize| { let p = &glyphs[j]; - if keep[j] && p.text == g.text && (p.rect[0] - g.rect[0]).abs() < dx && (p.rect[1] - g.rect[1]).abs() < h * 0.2 { - keep[i] = false; - break; - } + keep[j] && p.text == g.text && (p.rect[0] - g.rect[0]).abs() < dx && (p.rect[1] - g.rect[1]).abs() < h * 0.2 + }; + let (fp, cx, cy_) = (text_hash(&g.text), (g.rect[0] / (0.2 * h)).floor() as i32, (g.rect[1] / (0.2 * h)).floor() as i32); + let key = |ox: i32, oy: i32| (fp, cx.saturating_add(ox), cy_.saturating_add(oy)); + let twin = (i.saturating_sub(4)..i).rev().any(&same) + || (-1..=1i32).any(|ox| (-1..=1i32).any(|oy| latest.get(&key(ox, oy)).is_some_and(|&j| same(j)))); + if twin { + keep[i] = false; + } else { + latest.insert((fp, cx, cy_), i); } } let kept: Vec = (0..glyphs.len()).filter(|i| keep[*i]).collect(); @@ -2154,6 +2169,27 @@ mod tests { } } + /// #3173: a page drawn once per column clip draws a glyph on the clip edge in both passes, far apart in drawing order. + #[test] + fn a_glyph_redrawn_by_the_other_column_pass_is_dropped() { + let mut v = Vec::new(); + word(&mut v, "WO", 10.0, 10.0, 6.0); + v.push(g("R", 22.0, 10.0, 28.0)); + word(&mut v, "illu", 10.0, 30.0, 6.0); + v.push(g("s", 34.0, 30.0, 40.0)); + // The other pass: lots of other text, then the same glyphs at (almost) the same place and the rest of each word. + for k in 0..50 { + word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0); + } + v.push(g("R", 22.0, 10.0, 28.0)); + word(&mut v, "LD", 28.0, 10.0, 6.0); + v.push(g("s", 33.99, 30.0, 39.99)); + word(&mut v, "trated", 40.0, 30.0, 6.0); + let text = layout(v).plain_text(); + assert!(text.lines().any(|l| l == "WORLD"), "{text}"); + assert!(text.lines().any(|l| l == "illustrated"), "{text}"); + } + #[test] fn two_columns_read_left_then_right_even_if_drawn_interleaved() { let mut v = Vec::new(); From 78ab758c9d144e47ed668a024ea26bdf79ea5f32 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:30:48 +0200 Subject: [PATCH 05/65] Keep earlier redraw matches when dropping repeated glyphs (#3173) --- crates/render/src/text.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index b1af213e16..c1f8e034e6 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -1426,9 +1426,16 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec, Vec, Vec) { // also overlaps most of its own width: a narrow letter in condensed text (80 Tz and below) sits // closer than a fifth of its height to its double, as the second "l" of "Alle" (#1467). let mut keep = vec![true; glyphs.len()]; - // The twin is usually among the last few glyphs. A page drawn once per column clip redraws a glyph on the clip edge - // thousands of glyphs later, so `latest` also leads from the text and grid cell (a fifth of a line) of each kept glyph - // to the latest kept glyph there, and the cell and its neighbours are checked too (#3173). + // The twin is usually among the last few glyphs. A page drawn once per column clip also redraws the glyph on the clip + // edge thousands of glyphs later: the last glyph of one run is the first of another (#3173). So a glyph that starts a + // run is also checked against the latest kept glyph of its text and grid cell (a fifth of a line) and its neighbours, + // if that one ends a run. A glyph inside a run stays for the redraw check on whole runs below, which keeps a run + // that only starts like an earlier one. + let follows = |p: usize, q: usize| { + let (a, b) = (&glyphs[p].rect, &glyphs[q].rect); + let ph = (a[3] - a[1]).max(0.1).min((b[3] - b[1]).max(0.1)); + ((a[1] + a[3]) / 2.0 - (b[1] + b[3]) / 2.0).abs() < ph * 0.5 && b[0] - a[2] < ph * 3.0 && b[0] > a[0] - ph * 2.0 + }; let mut latest: HashMap<(u64, i32, i32), usize> = HashMap::new(); for i in 0..glyphs.len() { let g = &glyphs[i]; @@ -1441,8 +1448,10 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec, Vec, Vec) { }; let (fp, cx, cy_) = (text_hash(&g.text), (g.rect[0] / (0.2 * h)).floor() as i32, (g.rect[1] / (0.2 * h)).floor() as i32); let key = |ox: i32, oy: i32| (fp, cx.saturating_add(ox), cy_.saturating_add(oy)); - let twin = (i.saturating_sub(4)..i).rev().any(&same) - || (-1..=1i32).any(|ox| (-1..=1i32).any(|oy| latest.get(&key(ox, oy)).is_some_and(|&j| same(j)))); + let ends_run = |j: usize| j + 1 >= glyphs.len() || !follows(j, j + 1); + let starts_run = i == 0 || !follows(i - 1, i); + let far = |ox: i32, oy: i32| latest.get(&key(ox, oy)).is_some_and(|&j| same(j) && ends_run(j)); + let twin = (i.saturating_sub(4)..i).rev().any(&same) || (starts_run && (-1..=1i32).any(|ox| (-1..=1i32).any(|oy| far(ox, oy)))); if twin { keep[i] = false; } else { From 37d123751828bd08016162b8c656e881e3be18db Mon Sep 17 00:00:00 2001 From: oracola91 <118899664+oracola91@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:01:35 +0300 Subject: [PATCH 06/65] fix(packaging): ship the licences and NOTICE in the AppImage and PdfCraft.app The AppImage step moved usr/share/doc out of the AppDir, so the AppImage carried none of the licence files the .deb, .rpm and .tar.gz ship from the same staged tree. PdfCraft.app copied only the craft-fonts licences; it now uses copy_docs, as the CLI zip does, before signing. Part of #2175. --- packaging/linux/package.sh | 1 - packaging/macos/package.sh | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 7513d3c3d6..61b4d8ef41 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -127,7 +127,6 @@ fi if has appimage; then APPDIR="$WORK/PdfCraft.AppDir" cp -R "$STAGE" "$APPDIR" - mv "$APPDIR/usr/share/doc" "$WORK/doc-unused" ln -s usr/bin/pdfcraft "$APPDIR/AppRun" cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index 267a87280b..6b748e5fed 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -106,7 +106,7 @@ cp "$ROOT/assets/app-icon/pdfcraft.icns" "$APP/Contents/Resources/PdfCraft.icns" # The standard About panel (PdfCraft menu > About PdfCraft) shows Credits.rtf under the version: # the website and Discord links the in-app About dialog has (#1287). cp "$HERE/Credits.rtf" "$APP/Contents/Resources/Credits.rtf" -copy_font_licences "$APP/Contents/Resources" +copy_docs "$APP/Contents/Resources" # OCR models: the app finds them at Contents/MacOS/../Resources/models. Before signing, so the # bundle's seal covers them. stage_models "$APP/Contents/Resources/models" From bac18cb2eb4c5f031a41d45f7535278241d3a230 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:33:24 -0400 Subject: [PATCH 07/65] M12: a negative XFA text indent hangs the first line A negative textIndent was clamped to 0, so a hanging indent was lost and every line started at the left margin. The first line now starts left of the others by the indent, never left of the box: with no left margin the other lines move in to make room, as other viewers lay DA Form 31's '10a. ACCRUED / LEAVE / (CR BAL)' out. --- crates/xfa/src/tests.rs | 42 +++++++++++++++++++++++++++++++++++++++++ crates/xfa/src/text.rs | 14 ++++++++++---- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 03eb2c67ad..245b988927 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -139,6 +139,48 @@ fn layout_places_captions_fields_and_sizes_containers_to_their_content() { ); } +/// The left edges of the lines of a draw `w` points wide holding `text` in Arial 8 pt, with +/// `para` attributes, from the content area's left edge (0.5in). +fn line_starts(text: &str, w: f64, para: &str) -> Vec { + let xdp = format!( + r##""## + ); + let form = layout_xml(&xdp).unwrap(); + let mut lines: Vec<(i64, f64)> = Vec::new(); + for item in &form.pages[0].items { + let Item::Text(s) = item else { continue }; + let key = (s.baseline * 100.0).round() as i64; + match lines.iter_mut().find(|(b, _)| *b == key) { + Some((_, x)) => *x = x.min(s.x), + None => lines.push((key, s.x)), + } + } + lines.sort_by_key(|(b, _)| *b); + lines.into_iter().map(|(_, x)| x - 36.0).collect() +} + +#[test] +fn a_negative_text_indent_hangs_the_first_line_and_indents_the_rest() { + let text = "11. SERVICE MEMBER BALANCE (TOTAL)"; + // No left margin: the first line starts at the box's edge and the others 18pt in. + let starts = line_starts(text, 58.0, r#"textIndent="-18pt""#); + assert!(starts.len() >= 3, "{starts:?}"); + assert!(starts[0].abs() < 1e-6, "first line at the edge: {starts:?}"); + assert!(starts[1..].iter().all(|x| (x - 18.0).abs() < 1e-6), "the rest hang 18pt in: {starts:?}"); + // With a left margin wider than the hang, the first line starts at the margin less the hang. + let starts = line_starts(text, 90.0, r#"marginLeft="30pt" textIndent="-18pt""#); + assert!(starts.len() >= 2, "{starts:?}"); + assert!((starts[0] - 12.0).abs() < 1e-6 && starts[1..].iter().all(|x| (x - 30.0).abs() < 1e-6), "{starts:?}"); + // A positive indent still moves only the first line in. + let starts = line_starts(text, 58.0, r#"textIndent="10pt""#); + assert!((starts[0] - 10.0).abs() < 1e-6 && starts[1..].iter().all(|x| x.abs() < 1e-6), "{starts:?}"); +} + #[test] fn tables_break_across_pages_and_repeat_their_header_row() { let form = layout_xml(&template(40)).unwrap(); diff --git a/crates/xfa/src/text.rs b/crates/xfa/src/text.rs index 6db0777c06..1b0a0b5492 100644 --- a/crates/xfa/src/text.rs +++ b/crates/xfa/src/text.rs @@ -188,14 +188,20 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn size: f64, first: bool, } - let avail = (rect.w - para.margin_left - para.margin_right).max(1.0); + // A negative textIndent is a hanging indent: the first line starts left of the others. It + // never starts left of the box, so the others move in to make room, as other viewers lay + // such labels out. + let margin_left = para.margin_left.max(-para.text_indent); + // Where the first line starts, from the others. + let first_indent = para.text_indent.max(-margin_left); + let avail = (rect.w - margin_left - para.margin_right).max(1.0); let mut lines: Vec<(Line, Option)> = Vec::new(); let mut total = 0.0; for (pi, p) in rich.paragraphs.iter().enumerate() { let ws = words(&p.runs, base, embed); let mut line = Line { words: Vec::new(), width: 0.0, size: base.size, first: true }; let mut first_in_para = true; - let indent = |first: bool| if first { para.text_indent.max(0.0) } else { 0.0 }; + let indent = |first: bool| if first { first_indent } else { 0.0 }; for w in ws { let fits = line.width + w.width <= avail - indent(line.first) || line.words.is_empty() && w.width <= avail - indent(line.first); if !fits && !line.words.is_empty() { @@ -247,11 +253,11 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn let mut spans = Vec::new(); let mut y = start_y + para.space_above; for ((line, align), lh) in lines.into_iter().zip(heights) { - let indent = if line.first { para.text_indent.max(0.0) } else { 0.0 }; + let indent = if line.first { first_indent } else { 0.0 }; // Trailing spaces don't count for alignment. let trailing = line.words.last().map_or(0.0, |w| if w.text.ends_with(' ') { w.face.width(" ") } else { 0.0 }); let used = (line.width - trailing).max(0.0); - let mut x = rect.x + para.margin_left + indent; + let mut x = rect.x + margin_left + indent; x += match align.unwrap_or(para.h_align) { HAlign::Left | HAlign::Justify => 0.0, HAlign::Center => ((avail - indent - used) / 2.0).max(0.0), From 00dbcc6036c54d7a65e6129957e8766d930b42b5 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:00:11 -0400 Subject: [PATCH 08/65] M12: a hanging indent wider than its box keeps the text inside it A hang wider than the box moved the other lines past its right edge, and gave the first line room beyond it, so right-aligned text was drawn outside the box. The hang is now bounded by the box. --- crates/xfa/src/tests.rs | 18 ++++++++++++++++++ crates/xfa/src/text.rs | 5 +++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 245b988927..6b103e3715 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -181,6 +181,24 @@ fn a_negative_text_indent_hangs_the_first_line_and_indents_the_rest() { assert!((starts[0] - 10.0).abs() < 1e-6 && starts[1..].iter().all(|x| x.abs() < 1e-6), "{starts:?}"); } +#[test] +fn a_hang_wider_than_the_box_keeps_every_line_inside_it() { + // A 58pt box hanging its first line by 100pt, right-aligned: every line still starts and + // ends inside the box. + let xdp = r##""##; + let form = layout_xml(xdp).unwrap(); + for item in &form.pages[0].items { + let Item::Text(s) = item else { continue }; + let right = s.x + s.face.width(s.text.trim_end()); + assert!(s.x >= 36.0 - 1e-6 && right <= 36.0 + 58.0 + 1e-6, "{:?} runs from {} to {right}", s.text, s.x); + } +} + #[test] fn tables_break_across_pages_and_repeat_their_header_row() { let form = layout_xml(&template(40)).unwrap(); diff --git a/crates/xfa/src/text.rs b/crates/xfa/src/text.rs index 1b0a0b5492..d9a7f5dff6 100644 --- a/crates/xfa/src/text.rs +++ b/crates/xfa/src/text.rs @@ -190,8 +190,9 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn } // A negative textIndent is a hanging indent: the first line starts left of the others. It // never starts left of the box, so the others move in to make room, as other viewers lay - // such labels out. - let margin_left = para.margin_left.max(-para.text_indent); + // such labels out; never past the box's right edge, however wide the hang. + let hang = (-para.text_indent).min((rect.w - para.margin_right - 1.0).max(0.0)); + let margin_left = para.margin_left.max(hang); // Where the first line starts, from the others. let first_indent = para.text_indent.max(-margin_left); let avail = (rect.w - margin_left - para.margin_right).max(1.0); From 08f5fa2734182fe5d35d7ecb9f6c8eb6ba88d8eb Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Wed, 21 Oct 2026 20:47:44 +0800 Subject: [PATCH 09/65] fix(edit): substitute a visible font when editing glyphless OCR text --- Cargo.lock | 20 ++-- crates/edit/src/tests.rs | 116 +++++++++++++++++++ crates/edit/src/text_regions.rs | 9 +- crates/fonts/src/pdf.rs | 198 +++++++++++++++++++++++++++++++- 4 files changed, 326 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2399531ef4..2e8133dbb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1887,7 +1887,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -4934,7 +4934,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -5484,7 +5484,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -5554,7 +5554,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -5565,9 +5565,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -6431,7 +6431,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -7306,9 +7306,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" dependencies = [ "rustls-pki-types", ] @@ -7514,7 +7514,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 879ebc6c66..2302864527 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -5218,3 +5218,119 @@ fn a_clipping_copy_on_the_same_baseline_is_refused() { 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"); } + +/// #3803: Tesseract and PDFium write invisible (`3 Tr`) OCR layers in a `/Glyphless` CIDFontType2 +/// whose `/ToUnicode` and `/W` cover Latin text while `/CIDToGIDMap` maps every CID to GID 1 (a +/// solid rectangle). Rewriting such text as visible (`0 Tr`) must substitute a real font rather +/// than drawing the replacement in `/Glyphless` rectangles. +#[test] +fn editing_glyphless_ocr_text_substitutes_a_visible_font() { + let mut one_glyph_ttf = include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec(); + let count = u16::from_be_bytes(one_glyph_ttf[4..6].try_into().unwrap()) as usize; + let loca_rec = (0..count).map(|i| 12 + i * 16).find(|i| &one_glyph_ttf[*i..*i + 4] == b"loca").unwrap(); + let loca_off = u32::from_be_bytes(one_glyph_ttf[loca_rec + 8..loca_rec + 12].try_into().unwrap()) as usize; + let loca_len = u32::from_be_bytes(one_glyph_ttf[loca_rec + 12..loca_rec + 16].try_into().unwrap()) as usize; + one_glyph_ttf[loca_off..loca_off + 8].fill(0); + for chunk in one_glyph_ttf[loca_off + 8..loca_off + loca_len].as_chunks_mut::<4>().0 { + *chunk = 4u32.to_be_bytes(); + } + + let make_page = |content: &str, base: &str| { + let mut doc = text_page(content); + let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf))); + let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 1].repeat(256)))); + let cmap = b"1 begincodespacerange <0000> endcodespacerange 1 beginbfrange <0000> <00FF> <0000> endbfrange"; + let unicode = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap))); + let descriptor = Dict::from_iter([ + (b"Type".to_vec(), Object::name("FontDescriptor")), + (b"FontName".to_vec(), Object::name(base)), + (b"Flags".to_vec(), Object::Int(5)), + (b"FontBBox".to_vec(), Object::Array([0, -207, 500, 718].map(Object::Int).to_vec())), + (b"Ascent".to_vec(), Object::Int(718)), + (b"Descent".to_vec(), Object::Int(-207)), + (b"FontFile2".to_vec(), Object::Ref(program)), + ]); + let cid_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("CIDFontType2")), + (b"BaseFont".to_vec(), Object::name(base)), + (b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid)), + (b"DW".to_vec(), Object::Int(500)), + (b"W".to_vec(), Object::Array(vec![Object::Int(32), Object::Array(vec![Object::Int(285)])])), + (b"FontDescriptor".to_vec(), Object::Dict(descriptor)), + ]); + let font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type0")), + (b"BaseFont".to_vec(), Object::name(base)), + (b"Encoding".to_vec(), Object::name("Identity-H")), + (b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(cid_font)])), + (b"ToUnicode".to_vec(), Object::Ref(unicode)), + ]); + let p = pdfcraft_model::pages(&doc)[0].obj; + let fonts = Dict::from_iter([(b"F0".to_vec(), Object::Dict(font))]); + doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + doc + }; + + // Single-line OCR paragraph (rewrite_block_from path) and replace_line path. + let single = "BT 3 Tr 0.055 Tw -0.581 Tc 100 Tz /F0 15.75 Tf 1 0 0 1 114.75 568.8 Tm \ + [<0044> -27 <0065> -23 <0020> -22 <006B> -29 <0069> -28 <006E> -27 <0064> -29 <0065> -23 <0072> -28 <0065> -23 <006E>] TJ ET"; + for base in ["Glyphless", "CustomOCR"] { + let mut doc = make_page(single, base); + assert!(text::text_editor_fonts(&doc, 0).unwrap().is_empty(), "{base} must not be loaded into the inline editor"); + let before = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(before.len(), 1); + assert_eq!(before[0].text, "De kinderen"); + assert!(before[0].invisible); + + let edit = text::replace_block(&mut doc, 0, 0, "De Kinderen").unwrap(); + assert_eq!(edit.substituted.as_deref(), Some("Helvetica"), "{base} must substitute Helvetica instead of drawing in /F0"); + let after = text::text_blocks(&reopen(&doc), 0).unwrap(); + assert_eq!(after.len(), 1); + assert_eq!(after[0].text, "De Kinderen"); + assert!(!after[0].invisible, "the edited OCR paragraph is now visible"); + assert_eq!(after[0].base_font, "Helvetica"); + + let mut line_doc = make_page(single, base); + let line_edit = text::replace_line(&mut line_doc, 0, 0, "De Kinderen").unwrap(); + assert_eq!(line_edit.substituted.as_deref(), Some("Helvetica"), "{base} replace_line must also substitute"); + assert_eq!(text::text_lines(&reopen(&line_doc), 0).unwrap()[0].base_font, "Helvetica"); + } + + // Multi-run OCR phrase on one row with slightly different OCR font sizes (rewrite_styled_block + // path): both runs switch to the visible substitute font and keep calibrated widths without + // stretching spaces to 200%. + let multi_run = "BT 3 Tr /F0 15.75 Tf 1 0 0 1 114.75 568.8 Tm <004400650020006B0069006E0064006500720065006E> Tj ET \ + BT 3 Tr /F0 15.5 Tf 1 0 0 1 205.0 568.8 Tm <006B0075006E006E0065006E> Tj ET"; + let mut doc = make_page(multi_run, "Glyphless"); + let before_lines = text::text_lines(&doc, 0).unwrap(); + let before = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(before.len(), 1); + assert_eq!(before[0].lines.len(), 2, "two runs on one OCR row"); + let edit = text::replace_block(&mut doc, 0, 0, "De kinderen Kunnen").unwrap(); + assert_eq!(edit.substituted.as_deref(), Some("Helvetica")); + let lines = text::text_lines(&reopen(&doc), 0).unwrap(); + assert_eq!(lines.iter().map(|l| l.text.trim()).collect::>(), ["De kinderen", "Kunnen"]); + for line in &lines { + assert_eq!(line.base_font, "Helvetica", "every run must use the visible substitute font: {line:?}"); + } + let old_w = before_lines[0].rect[2] - before_lines[0].rect[0]; + let new_w = lines[0].rect[2] - lines[0].rect[0]; + assert!((new_w - old_w).abs() < 5.0, "calibrated first run keeps its width ({old_w} -> {new_w}): {lines:?}"); + assert!(lines[1].rect[0] >= lines[0].rect[2] - 1.0, "calibrated first run does not stretch into the second: {lines:?}"); + let blocks = text::text_blocks(&reopen(&doc), 0).unwrap(); + assert!(!blocks[0].invisible, "the whole rewritten paragraph is visible"); + + // High WinAnsi characters on a glyphless OCR line also use the Helvetica substitute rather + // than /F0, and explicitly selecting the glyphless resource is refused. + let mut win_ansi_doc = make_page(single, "Glyphless"); + let win_edit = text::replace_block(&mut win_ansi_doc, 0, 0, "De kinderen € — café").unwrap(); + assert_eq!(win_edit.substituted.as_deref(), Some("Helvetica")); + assert_eq!(text::text_blocks(&reopen(&win_ansi_doc), 0).unwrap()[0].text, "De kinderen € — café"); + + let mut explicit = make_page(single, "Glyphless"); + let explicit_err = + text::rewrite_block(&mut explicit, 0, 0, Some("De Kinderen"), &BlockStyle { resource: Some("F0".into()), ..Default::default() }); + assert!(explicit_err.is_err(), "explicitly selecting a glyphless font resource must be refused"); +} diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rs index e08068d9f5..8f5199b17a 100644 --- a/crates/edit/src/text_regions.rs +++ b/crates/edit/src/text_regions.rs @@ -505,12 +505,17 @@ pub(super) fn rewrite_styled_block( }; let mut calibration = HashMap::new(); for (index, source) in lines.iter().enumerate() { - if let Some(m) = metrics.get(&source.font) { + let font_name = metrics + .get(&source.font) + .filter(|m| source_encodes(m, &source.text)) + .map(|_| &source.font) + .or_else(|| chars.iter().find(|c| c.1 == index && c.0 != '\n').map(|c| &c.2)); + if let Some((font_name, m)) = font_name.and_then(|name| metrics.get(name).filter(|m| source_encodes(m, &source.text)).map(|m| (name, m))) { let nominal = source_width( m, &source.text, source.origin.state.font.as_ref().map_or(1.0, |(_, s)| *s), - space_of(&source.font, m), + space_of(font_name, m), source.origin.state.char_spacing, source.origin.state.word_spacing, ) * source.origin.state.scale diff --git a/crates/fonts/src/pdf.rs b/crates/fonts/src/pdf.rs index 26685866b3..d1cd1fa026 100644 --- a/crates/fonts/src/pdf.rs +++ b/crates/fonts/src/pdf.rs @@ -67,6 +67,8 @@ pub struct Metrics { /// Subset CIDFontType2 only: one bit per CID (below 65 536) whose glyph has an outline in the /// embedded program. See [`cids_with_outlines`]. outlined_cids: Vec, + /// Whether this font is an OCR placeholder font with no real letterforms (e.g. `/Glyphless`). + glyphless: bool, } fn nums(doc: &Document, o: Option<&Object>) -> Vec { @@ -79,12 +81,64 @@ fn dict(doc: &Document, o: Option<&Object>) -> Option { o.and_then(|o| doc.resolve(o).as_dict().cloned()) } +/// Strip a six-letter uppercase `ABCDEF+` subset prefix, if present. +fn strip_subset_prefix(name: &str) -> &str { + name.split_once('+').filter(|(tag, _)| tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase())).map_or(name, |(_, rest)| rest) +} + +/// Whether `name` identifies an OCR placeholder font that carries widths and Unicode mappings +/// for invisible (`3 Tr`) text selection but no real letterforms. +fn glyphless_font_name(name: &str) -> bool { + let stem = strip_subset_prefix(name).to_ascii_lowercase(); + stem.starts_with("glyphless") || stem.starts_with("hiddenhorzocr") || stem.starts_with("hiddenvertocr") +} + +/// Whether `font` is an OCR placeholder font (such as Tesseract/PDFium `/Glyphless` or +/// `/GlyphlessFont`, Adobe `/HiddenHorzOCR`, or a dummy TrueType program whose non-zero codes +/// have no outlines or all map to a single placeholder rectangle). +fn is_glyphless(doc: &Document, font: &Dict) -> bool { + use skrifa::{MetadataProvider as _, raw::TableProvider as _}; + let descendant = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref()); + let descriptor = dict(doc, descendant.as_ref().unwrap_or(font).get(b"FontDescriptor")); + for name in [font.name(b"BaseFont"), descendant.as_ref().and_then(|d| d.name(b"BaseFont")), descriptor.as_ref().and_then(|d| d.name(b"FontName"))] + .into_iter() + .flatten() + { + if glyphless_font_name(&String::from_utf8_lossy(name)) { + return true; + } + } + let Some(descriptor) = descriptor else { return false }; + for key in [b"FontFile2".as_slice(), b"FontFile3".as_slice()] { + let Some(object) = descriptor.get(key) else { continue }; + let object = doc.resolve(object); + let Object::Stream(stream) = object.as_ref() else { continue }; + let Ok(bytes) = stream.decoded_within(16 << 20) else { continue }; + let Ok(face) = skrifa::FontRef::from_index(&bytes, 0) else { continue }; + let Ok(loca) = face.loca(None) else { continue }; + let mut outlined = + (1..loca.len().min(0x1_0000)).filter(|&gid| loca.get_raw(gid).zip(loca.get_raw(gid + 1)).is_some_and(|(start, end)| end > start)); + let Some(only_gid) = outlined.next() else { return true }; + if outlined.next().is_some() { + continue; + } + if let Some(Object::Stream(map)) = descendant.as_ref().and_then(|d| d.get(b"CIDToGIDMap")).map(|o| doc.resolve(o)).as_deref() + && let Ok(map) = map.decoded_within(1 << 17) + && map.as_chunks::<2>().0.iter().skip(1).filter(|gid| usize::from(u16::from_be_bytes(**gid)) == only_gid).take(2).count() > 1 + { + return true; + } + if face.charmap().mappings().filter(|(_, gid)| gid.to_u32() as usize == only_gid).take(3).count() > 2 { + return true; + } + } + false +} + /// Whether `base_font` (subset tag allowed) names a legacy Indic font family that is laid out in /// visual order (Kruti Dev, DevLys, Chanakya, Shusha, Shivaji, Walkman, Akruti, APS-DV, DV-TT…). fn legacy_indic_font(base_font: &str) -> bool { - let name = - base_font.split_once('+').filter(|(tag, _)| tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase())).map_or(base_font, |(_, n)| n); - let name = name.to_ascii_lowercase(); + let name = strip_subset_prefix(base_font).to_ascii_lowercase(); ["kruti", "devlys", "chanakya", "shusha", "shivaji", "walkman", "akruti"].iter().any(|n| name.contains(n)) || ["aps-", "dv-"].iter().any(|p| name.starts_with(p)) } @@ -93,6 +147,9 @@ fn legacy_indic_font(base_font: &str) -> bool { /// fallback. Type 1/Type 3 programs cannot be consumed by an sfnt text renderer. pub fn embedded_sfnt(doc: &Document, font: &Dict) -> Option> { use skrifa::{MetadataProvider as _, raw::TableProvider as _}; + if is_glyphless(doc, font) { + return None; + } let descendant = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref()); let descriptor = dict(doc, descendant.as_ref().unwrap_or(font).get(b"FontDescriptor"))?; for key in [b"FontFile2".as_slice(), b"FontFile3".as_slice()] { @@ -616,9 +673,11 @@ impl Metrics { code_len: 1, explicit_reverse: (32..127u8).map(|c| (char::from(c), u32::from(c))).collect(), outlined_cids: Vec::new(), + glyphless: false, } } + /// Builds font metrics, Unicode decoding/encoding maps, and glyph coverage from a PDF `/Font` dictionary. pub fn from_dict(doc: &Document, font: &Dict) -> Self { let mut m = Self::read_metrics(doc, font); let base = font @@ -636,7 +695,8 @@ impl Metrics { m.bold |= bold; m.italic |= italic; m.base_font = base; - if m.composite && m.subset { + m.glyphless = is_glyphless(doc, font); + if m.composite && m.subset && !m.glyphless { m.outlined_cids = cids_with_outlines(doc, font); } m.code_len = match &m.codes { @@ -645,7 +705,7 @@ impl Metrics { Codes::Ranges(r) => r.last().map_or(2, |x| x.0), }; m.unicode = unicode_map(doc, font, m.composite); - if m.std14.is_some() { + if m.std14.is_some() && !m.glyphless { embedded_widths(doc, font, &mut m); } let mut reverse = HashMap::new(); @@ -837,6 +897,9 @@ impl Metrics { /// Only asked for codes the font's Unicode mapping gives: a subset's `ToUnicode` lists the /// glyphs it kept, while its `/W` leaves out those of the default width (#1443). fn has_glyph(&self, code: u32) -> bool { + if self.glyphless { + return false; + } if self.composite { let cid = self.cid(code); // CID 0 is `.notdef` (an unmapped code lands there too), whatever ToUnicode says: Word @@ -868,6 +931,9 @@ impl Metrics { /// The bytes that show `text` in this font, or `None` if some character has no code or /// no glyph in it (the caller then substitutes another font). pub fn encode(&self, text: &str) -> Option> { + if self.glyphless { + return None; + } // The lowest code showing each wanted character. Explicit entries and the encoding are // checked one by one; each range is asked for the wanted characters it can show. let wanted: HashSet = text.chars().collect(); @@ -1264,6 +1330,128 @@ mod tests { assert!(embedded_sfnt(&doc, &Dict::new()).is_none()); } + /// #3803: OCR placeholder fonts (`/Glyphless`, `/GlyphlessFont`, `/HiddenHorzOCR`, or a + /// dummy TrueType program whose non-zero CIDs all share a single rectangle glyph) still decode + /// and measure the invisible OCR layer, but never encode replacement text or expose their + /// dummy program to the inline editor. + #[test] + fn glyphless_ocr_fonts_decode_and_measure_without_encoding_or_exposing_sfnt() { + use pdfcraft_cos::Stream; + // Build a 1-outline TrueType program (only GID 1 has an outline) from Inter-Regular.ttf. + let mut one_glyph_ttf = include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec(); + let count = u16::from_be_bytes(one_glyph_ttf[4..6].try_into().unwrap()) as usize; + let loca_rec = (0..count).map(|i| 12 + i * 16).find(|i| &one_glyph_ttf[*i..*i + 4] == b"loca").unwrap(); + let loca_off = u32::from_be_bytes(one_glyph_ttf[loca_rec + 8..loca_rec + 12].try_into().unwrap()) as usize; + let loca_len = u32::from_be_bytes(one_glyph_ttf[loca_rec + 12..loca_rec + 16].try_into().unwrap()) as usize; + let mut zero_glyph_ttf = one_glyph_ttf.clone(); + zero_glyph_ttf[loca_off..loca_off + loca_len].fill(0); + // Set loca[0] = 0, loca[1] = 0, and loca[2..] = 4 so only GID 1 has start < end. + one_glyph_ttf[loca_off..loca_off + 8].fill(0); + for chunk in one_glyph_ttf[loca_off + 8..loca_off + loca_len].as_chunks_mut::<4>().0 { + *chunk = 4u32.to_be_bytes(); + } + + for base in ["Glyphless", "GlyphlessFont", "ABCDEF+GlyphlessFont", "HiddenHorzOCR", "HiddenVertOCR", "CustomOCR"] { + let mut doc = Document::new_empty(); + let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf))); + let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 1].repeat(256)))); + let cmap = b"1 begincodespacerange <0000> endcodespacerange 1 beginbfrange <0000> <00FF> <0000> endbfrange"; + let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap))); + let mut descriptor = Dict::new(); + descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor")); + descriptor.set(b"FontName".to_vec(), Object::name(base)); + descriptor.set(b"FontFile2".to_vec(), Object::Ref(program)); + let mut desc = Dict::new(); + desc.set(b"Type".to_vec(), Object::name("Font")); + desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2")); + desc.set(b"BaseFont".to_vec(), Object::name(base)); + desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid)); + desc.set(b"DW".to_vec(), Object::Int(500)); + desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(32), Object::Array(vec![Object::Int(285)])])); + desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor)); + let f = font( + &mut doc, + vec![ + ("Subtype", Object::name("Type0")), + ("BaseFont", Object::name(base)), + ("Encoding", Object::name("Identity-H")), + ("DescendantFonts", Object::Array(vec![Object::Dict(desc)])), + ("ToUnicode", Object::Ref(tu)), + ], + ); + assert!(embedded_sfnt(&doc, &f).is_none(), "{base} must not be exposed as an editor sfnt"); + let m = Metrics::from_dict(&doc, &f); + assert_eq!(m.decode(b"\x00D\x00e\x00 \x00k"), "De k", "{base} still decodes OCR text"); + assert!((m.width(32) - 0.285).abs() < 1e-9 && (m.width(68) - 0.5).abs() < 1e-9, "{base} still measures OCR widths"); + assert_eq!(m.encode("De"), None, "{base} must not encode visible replacement text"); + assert_eq!(m.encode(" "), None, "{base} must not encode spaces"); + assert_eq!(m.encode(""), None, "{base} must not claim empty words"); + } + + // A TrueType program with zero outlined glyphs is also rejected even under an ordinary name. + let mut doc = Document::new_empty(); + let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf))); + let mut descriptor = Dict::new(); + descriptor.set(b"FontFile2".to_vec(), Object::Ref(program)); + let empty_font = font( + &mut doc, + vec![ + ("Subtype", Object::name("TrueType")), + ("BaseFont", Object::name("EmptyOutlines")), + ("Encoding", Object::name("WinAnsiEncoding")), + ("FontDescriptor", Object::Dict(descriptor)), + ], + ); + assert!(embedded_sfnt(&doc, &empty_font).is_none()); + assert_eq!(Metrics::from_dict(&doc, &empty_font).encode("A"), None); + + // Simple TrueType font whose cmap maps multiple distinct characters to the single outlined GID 1. + let mut shared_cmap_ttf = one_glyph_ttf.clone(); + append_editor_cmap(&mut shared_cmap_ttf, &std::collections::BTreeMap::from([(65, 1), (66, 1), (67, 1)])).unwrap(); + let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &shared_cmap_ttf))); + let mut descriptor = Dict::new(); + descriptor.set(b"FontFile2".to_vec(), Object::Ref(program)); + let shared_simple = font( + &mut doc, + vec![ + ("Subtype", Object::name("TrueType")), + ("BaseFont", Object::name("SimpleSharedGid")), + ("Encoding", Object::name("WinAnsiEncoding")), + ("FontDescriptor", Object::Dict(descriptor)), + ], + ); + assert!(embedded_sfnt(&doc, &shared_simple).is_none()); + assert_eq!(Metrics::from_dict(&doc, &shared_simple).encode("A"), None); + + // Control: a legitimate 1-glyph subset where only one CID and one character map to GID 1 stays usable. + let mut single_char_ttf = one_glyph_ttf; + append_editor_cmap(&mut single_char_ttf, &std::collections::BTreeMap::from([(65, 1)])).unwrap(); + let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &single_char_ttf))); + let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 0, 0, 1, 0, 0]))); + let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), b"1 beginbfchar <0001> <0041> endbfchar"))); + let mut descriptor = Dict::new(); + descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+SingleCharSubset")); + descriptor.set(b"FontFile2".to_vec(), Object::Ref(program)); + let mut desc = Dict::new(); + desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2")); + desc.set(b"BaseFont".to_vec(), Object::name("ABCDEF+SingleCharSubset")); + desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid)); + desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600)])])); + desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor)); + let valid_subset = font( + &mut doc, + vec![ + ("Subtype", Object::name("Type0")), + ("BaseFont", Object::name("ABCDEF+SingleCharSubset")), + ("Encoding", Object::name("Identity-H")), + ("DescendantFonts", Object::Array(vec![Object::Dict(desc)])), + ("ToUnicode", Object::Ref(tu)), + ], + ); + assert!(embedded_sfnt(&doc, &valid_subset).is_some(), "legitimate 1-glyph subset keeps its sfnt"); + assert_eq!(Metrics::from_dict(&doc, &valid_subset).encode("A").as_deref(), Some(&[0, 1][..])); + } + /// #2130: with no `/Widths`, an embedded program's advances win over a guess from the name /// ("Mono" would mean Courier, 600 units for every glyph). #[test] From 6da63a8a6b2abf4d489a32343452e724e736d67f Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Wed, 21 Oct 2026 21:15:24 +0800 Subject: [PATCH 10/65] fix(fonts): gate structural glyphless detection on CIDFontType2 OCR signature (#3803) --- crates/edit/src/tests.rs | 47 ++++++++++++++++++ crates/fonts/src/pdf.rs | 103 +++++++++++++++++++++------------------ 2 files changed, 102 insertions(+), 48 deletions(-) diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 2302864527..1f281893f4 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -5333,4 +5333,51 @@ fn editing_glyphless_ocr_text_substitutes_a_visible_font() { let explicit_err = text::rewrite_block(&mut explicit, 0, 0, Some("De Kinderen"), &BlockStyle { resource: Some("F0".into()), ..Default::default() }); assert!(explicit_err.is_err(), "explicitly selecting a glyphless font resource must be refused"); + + // Legitimate whitespace-only subsets and 1-glyph subsets with intentional CID aliases remain + // exposed to the inline editor and accepted when explicitly selected as a resource. + let mut zero_glyph_ttf = one_glyph_ttf.clone(); + zero_glyph_ttf[loca_off..loca_off + loca_len].fill(0); + let mut ws_doc = text_page("BT /F0 12 Tf 1 0 0 1 72 700 Tm <0001> Tj /WS 12 Tf ( ) Tj ET"); + let ws_prog = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf))); + let ws_desc = Dict::from_iter([(b"FontName".to_vec(), Object::name("ABCDEF+SpaceOnly")), (b"FontFile2".to_vec(), Object::Ref(ws_prog))]); + let ws_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("TrueType")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+SpaceOnly")), + (b"Encoding".to_vec(), Object::name("WinAnsiEncoding")), + (b"FirstChar".to_vec(), Object::Int(32)), + (b"LastChar".to_vec(), Object::Int(32)), + (b"Widths".to_vec(), Object::Array(vec![Object::Int(250)])), + (b"FontDescriptor".to_vec(), Object::Dict(ws_desc)), + ]); + let alias_prog = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf))); + let alias_map = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 0, 0, 1, 0, 1, 0, 1]))); + let alias_tu = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), b"2 beginbfchar <0001> <0041> <0002> <0061> endbfchar"))); + let alias_desc = Dict::from_iter([(b"FontName".to_vec(), Object::name("ABCDEF+AliasOne")), (b"FontFile2".to_vec(), Object::Ref(alias_prog))]); + let alias_cid = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("CIDFontType2")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+AliasOne")), + (b"CIDToGIDMap".to_vec(), Object::Ref(alias_map)), + (b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600), Object::Int(600)])])), + (b"FontDescriptor".to_vec(), Object::Dict(alias_desc)), + ]); + let alias_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type0")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+AliasOne")), + (b"Encoding".to_vec(), Object::name("Identity-H")), + (b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(alias_cid)])), + (b"ToUnicode".to_vec(), Object::Ref(alias_tu)), + ]); + let p = pdfcraft_model::pages(&ws_doc)[0].obj; + let fonts = Dict::from_iter([(b"F0".to_vec(), Object::Dict(alias_font)), (b"WS".to_vec(), Object::Dict(ws_font))]); + ws_doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + let editor_resources: Vec<_> = text::text_editor_fonts(&ws_doc, 0).unwrap().into_iter().map(|f| f.resource).collect(); + assert!(editor_resources.contains(&"F0".to_string()) && editor_resources.contains(&"WS".to_string()), "{editor_resources:?}"); + let mut ws_only = ws_doc.clone(); + text::rewrite_block(&mut ws_only, 0, 0, Some(" "), &BlockStyle { resource: Some("WS".into()), ..Default::default() }).unwrap(); + text::rewrite_block(&mut ws_doc, 0, 0, Some("Aa"), &BlockStyle { resource: Some("F0".into()), ..Default::default() }).unwrap(); + assert_eq!(text::text_blocks(&reopen(&ws_doc), 0).unwrap()[0].text, "Aa"); } diff --git a/crates/fonts/src/pdf.rs b/crates/fonts/src/pdf.rs index d1cd1fa026..0a4f383760 100644 --- a/crates/fonts/src/pdf.rs +++ b/crates/fonts/src/pdf.rs @@ -94,10 +94,10 @@ fn glyphless_font_name(name: &str) -> bool { } /// Whether `font` is an OCR placeholder font (such as Tesseract/PDFium `/Glyphless` or -/// `/GlyphlessFont`, Adobe `/HiddenHorzOCR`, or a dummy TrueType program whose non-zero codes -/// have no outlines or all map to a single placeholder rectangle). +/// `/GlyphlessFont`, Adobe `/HiddenHorzOCR`, or a `CIDFontType2` whose embedded TrueType program +/// has a single outlined glyph shared across the `/CIDToGIDMap` table). fn is_glyphless(doc: &Document, font: &Dict) -> bool { - use skrifa::{MetadataProvider as _, raw::TableProvider as _}; + use skrifa::raw::TableProvider as _; let descendant = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref()); let descriptor = dict(doc, descendant.as_ref().unwrap_or(font).get(b"FontDescriptor")); for name in [font.name(b"BaseFont"), descendant.as_ref().and_then(|d| d.name(b"BaseFont")), descriptor.as_ref().and_then(|d| d.name(b"FontName"))] @@ -108,31 +108,25 @@ fn is_glyphless(doc: &Document, font: &Dict) -> bool { return true; } } - let Some(descriptor) = descriptor else { return false }; - for key in [b"FontFile2".as_slice(), b"FontFile3".as_slice()] { - let Some(object) = descriptor.get(key) else { continue }; - let object = doc.resolve(object); - let Object::Stream(stream) = object.as_ref() else { continue }; - let Ok(bytes) = stream.decoded_within(16 << 20) else { continue }; - let Ok(face) = skrifa::FontRef::from_index(&bytes, 0) else { continue }; - let Ok(loca) = face.loca(None) else { continue }; - let mut outlined = - (1..loca.len().min(0x1_0000)).filter(|&gid| loca.get_raw(gid).zip(loca.get_raw(gid + 1)).is_some_and(|(start, end)| end > start)); - let Some(only_gid) = outlined.next() else { return true }; - if outlined.next().is_some() { - continue; - } - if let Some(Object::Stream(map)) = descendant.as_ref().and_then(|d| d.get(b"CIDToGIDMap")).map(|o| doc.resolve(o)).as_deref() - && let Ok(map) = map.decoded_within(1 << 17) - && map.as_chunks::<2>().0.iter().skip(1).filter(|gid| usize::from(u16::from_be_bytes(**gid)) == only_gid).take(2).count() > 1 - { - return true; - } - if face.charmap().mappings().filter(|(_, gid)| gid.to_u32() as usize == only_gid).take(3).count() > 2 { - return true; - } + let cid_to_gid = descendant.as_ref().and_then(|d| d.get(b"CIDToGIDMap")).map(|o| doc.resolve(o)); + let Some(Object::Stream(map)) = cid_to_gid.as_deref() else { return false }; + let Ok(map) = map.decoded_within(1 << 17) else { return false }; + let program = descriptor.as_ref().and_then(|d| d.get(b"FontFile2")).map(|o| doc.resolve(o)); + let Some(Object::Stream(stream)) = program.as_deref() else { return false }; + let Ok(bytes) = stream.decoded_within(16 << 20) else { return false }; + let Ok(face) = skrifa::FontRef::from_index(&bytes, 0) else { return false }; + let Ok(loca) = face.loca(None) else { return false }; + let mut outlined = + (1..loca.len().min(0x1_0000)).filter(|&gid| loca.get_raw(gid).zip(loca.get_raw(gid + 1)).is_some_and(|(start, end)| end > start)); + let Some(only_gid) = outlined.next() else { return false }; + if outlined.next().is_some() { + return false; } - false + let mut mapped = 0usize; + map.as_chunks::<2>().0.iter().skip(1).map(|gid| usize::from(u16::from_be_bytes(*gid))).filter(|&gid| gid != 0).all(|gid| { + mapped += 1; + gid == only_gid + }) && mapped >= 64 } /// Whether `base_font` (subset tag allowed) names a legacy Indic font family that is laid out in @@ -1354,7 +1348,6 @@ mod tests { for base in ["Glyphless", "GlyphlessFont", "ABCDEF+GlyphlessFont", "HiddenHorzOCR", "HiddenVertOCR", "CustomOCR"] { let mut doc = Document::new_empty(); let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf))); - let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 1].repeat(256)))); let cmap = b"1 begincodespacerange <0000> endcodespacerange 1 beginbfrange <0000> <00FF> <0000> endbfrange"; let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap))); let mut descriptor = Dict::new(); @@ -1365,7 +1358,10 @@ mod tests { desc.set(b"Type".to_vec(), Object::name("Font")); desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2")); desc.set(b"BaseFont".to_vec(), Object::name(base)); - desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid)); + if base == "CustomOCR" { + let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 1].repeat(256)))); + desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid)); + } desc.set(b"DW".to_vec(), Object::Int(500)); desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(32), Object::Array(vec![Object::Int(285)])])); desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor)); @@ -1388,47 +1384,58 @@ mod tests { assert_eq!(m.encode(""), None, "{base} must not claim empty words"); } - // A TrueType program with zero outlined glyphs is also rejected even under an ordinary name. + // Regression fixture 1: a valid whitespace-only subset (0 outlined glyphs in `loca` because + // space has no contours) remains exposed as an editor sfnt and encodes whitespace. let mut doc = Document::new_empty(); let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf))); let mut descriptor = Dict::new(); + descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+WhitespaceSubset")); descriptor.set(b"FontFile2".to_vec(), Object::Ref(program)); - let empty_font = font( + let whitespace_subset = font( &mut doc, vec![ ("Subtype", Object::name("TrueType")), - ("BaseFont", Object::name("EmptyOutlines")), + ("BaseFont", Object::name("ABCDEF+WhitespaceSubset")), ("Encoding", Object::name("WinAnsiEncoding")), + ("FirstChar", Object::Int(32)), + ("LastChar", Object::Int(32)), + ("Widths", Object::Array(vec![Object::Int(250)])), ("FontDescriptor", Object::Dict(descriptor)), ], ); - assert!(embedded_sfnt(&doc, &empty_font).is_none()); - assert_eq!(Metrics::from_dict(&doc, &empty_font).encode("A"), None); + assert!(embedded_sfnt(&doc, &whitespace_subset).is_some(), "whitespace-only subset keeps its sfnt"); + assert_eq!(Metrics::from_dict(&doc, &whitespace_subset).encode(" ").as_deref(), Some(&[32][..])); - // Simple TrueType font whose cmap maps multiple distinct characters to the single outlined GID 1. - let mut shared_cmap_ttf = one_glyph_ttf.clone(); - append_editor_cmap(&mut shared_cmap_ttf, &std::collections::BTreeMap::from([(65, 1), (66, 1), (67, 1)])).unwrap(); - let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &shared_cmap_ttf))); + // Regression fixture 2: a 1-glyph font with intentional cmap aliases (e.g. U+002D, U+2010, + // U+2011 hyphen variants sharing GID 1) remains exposed and encodes its characters. + let mut alias_cmap_ttf = one_glyph_ttf.clone(); + append_editor_cmap(&mut alias_cmap_ttf, &std::collections::BTreeMap::from([(0x002D, 1), (0x2010, 1), (0x2011, 1)])).unwrap(); + let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &alias_cmap_ttf))); let mut descriptor = Dict::new(); + descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+HyphenSubset")); descriptor.set(b"FontFile2".to_vec(), Object::Ref(program)); - let shared_simple = font( + let cmap_alias_font = font( &mut doc, vec![ ("Subtype", Object::name("TrueType")), - ("BaseFont", Object::name("SimpleSharedGid")), + ("BaseFont", Object::name("ABCDEF+HyphenSubset")), ("Encoding", Object::name("WinAnsiEncoding")), + ("FirstChar", Object::Int(45)), + ("LastChar", Object::Int(45)), + ("Widths", Object::Array(vec![Object::Int(333)])), ("FontDescriptor", Object::Dict(descriptor)), ], ); - assert!(embedded_sfnt(&doc, &shared_simple).is_none()); - assert_eq!(Metrics::from_dict(&doc, &shared_simple).encode("A"), None); + assert!(embedded_sfnt(&doc, &cmap_alias_font).is_some(), "intentional cmap alias subset keeps its sfnt"); + assert_eq!(Metrics::from_dict(&doc, &cmap_alias_font).encode("-").as_deref(), Some(&[45][..])); - // Control: a legitimate 1-glyph subset where only one CID and one character map to GID 1 stays usable. + // Regression fixture 3: a legitimate 1-glyph composite subset with intentional CIDToGIDMap + // aliases (CIDs 1..=3 all mapping to GID 1) stays usable and keeps its sfnt. let mut single_char_ttf = one_glyph_ttf; - append_editor_cmap(&mut single_char_ttf, &std::collections::BTreeMap::from([(65, 1)])).unwrap(); + append_editor_cmap(&mut single_char_ttf, &std::collections::BTreeMap::from([(65, 1), (0xFF21, 1)])).unwrap(); let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &single_char_ttf))); - let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 0, 0, 1, 0, 0]))); - let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), b"1 beginbfchar <0001> <0041> endbfchar"))); + let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 0, 0, 1, 0, 1, 0, 1]))); + let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), b"2 beginbfchar <0001> <0041> <0002> endbfchar"))); let mut descriptor = Dict::new(); descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+SingleCharSubset")); descriptor.set(b"FontFile2".to_vec(), Object::Ref(program)); @@ -1436,7 +1443,7 @@ mod tests { desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2")); desc.set(b"BaseFont".to_vec(), Object::name("ABCDEF+SingleCharSubset")); desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid)); - desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600)])])); + desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600), Object::Int(600)])])); desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor)); let valid_subset = font( &mut doc, @@ -1448,7 +1455,7 @@ mod tests { ("ToUnicode", Object::Ref(tu)), ], ); - assert!(embedded_sfnt(&doc, &valid_subset).is_some(), "legitimate 1-glyph subset keeps its sfnt"); + assert!(embedded_sfnt(&doc, &valid_subset).is_some(), "legitimate 1-glyph subset with CID aliases keeps its sfnt"); assert_eq!(Metrics::from_dict(&doc, &valid_subset).encode("A").as_deref(), Some(&[0, 1][..])); } From 95f9ef860ed39cec54caf8af96a5eaf3f9fd028d Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Thu, 22 Oct 2026 00:08:25 +0800 Subject: [PATCH 11/65] Validate CIDToGIDMap signature before decoding FontFile2 in is_glyphless (#3803) --- crates/fonts/src/pdf.rs | 40 +++++++++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/fonts/src/pdf.rs b/crates/fonts/src/pdf.rs index 0a4f383760..9995cbf935 100644 --- a/crates/fonts/src/pdf.rs +++ b/crates/fonts/src/pdf.rs @@ -111,6 +111,16 @@ fn is_glyphless(doc: &Document, font: &Dict) -> bool { let cid_to_gid = descendant.as_ref().and_then(|d| d.get(b"CIDToGIDMap")).map(|o| doc.resolve(o)); let Some(Object::Stream(map)) = cid_to_gid.as_deref() else { return false }; let Ok(map) = map.decoded_within(1 << 17) else { return false }; + let mut gids = map.as_chunks::<2>().0.iter().skip(1).map(|gid| usize::from(u16::from_be_bytes(*gid))).filter(|&gid| gid != 0); + let mapped_gid = gids.clone().next().unwrap_or(0); + let mut mapped = 0usize; + if !gids.all(|gid| { + mapped += 1; + gid == mapped_gid + }) || mapped < 64 + { + return false; + } let program = descriptor.as_ref().and_then(|d| d.get(b"FontFile2")).map(|o| doc.resolve(o)); let Some(Object::Stream(stream)) = program.as_deref() else { return false }; let Ok(bytes) = stream.decoded_within(16 << 20) else { return false }; @@ -118,15 +128,7 @@ fn is_glyphless(doc: &Document, font: &Dict) -> bool { let Ok(loca) = face.loca(None) else { return false }; let mut outlined = (1..loca.len().min(0x1_0000)).filter(|&gid| loca.get_raw(gid).zip(loca.get_raw(gid + 1)).is_some_and(|(start, end)| end > start)); - let Some(only_gid) = outlined.next() else { return false }; - if outlined.next().is_some() { - return false; - } - let mut mapped = 0usize; - map.as_chunks::<2>().0.iter().skip(1).map(|gid| usize::from(u16::from_be_bytes(*gid))).filter(|&gid| gid != 0).all(|gid| { - mapped += 1; - gid == only_gid - }) && mapped >= 64 + outlined.next() == Some(mapped_gid) && outlined.next().is_none() } /// Whether `base_font` (subset tag allowed) names a legacy Indic font family that is laid out in @@ -1457,6 +1459,26 @@ mod tests { ); assert!(embedded_sfnt(&doc, &valid_subset).is_some(), "legitimate 1-glyph subset with CID aliases keeps its sfnt"); assert_eq!(Metrics::from_dict(&doc, &valid_subset).encode("A").as_deref(), Some(&[0, 1][..])); + + // Distinct non-zero GIDs across >= 64 CIDs, or a single-GID map whose FontFile2 has 0 or + // multiple outlined glyphs (or a different outlined GID), are not classified as glyphless. + let mut multi_gid_map = [0u8, 1].repeat(65); + multi_gid_map.extend_from_slice(&[0, 2]); + let multi_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &multi_gid_map))); + let single_gid_64 = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0u8, 1].repeat(65)))); + let single_gid_2_64 = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0u8, 2].repeat(65)))); + let full_ttf = doc.add(Object::Stream(Stream::flate(Dict::new(), include_bytes!("../../../assets/fonts/Inter-Regular.ttf")))); + let zero_ttf = doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf))); + for (map_ref, prog_ref) in [(multi_gid, program), (single_gid_64, full_ttf), (single_gid_64, zero_ttf), (single_gid_2_64, program)] { + let mut fd = Dict::new(); + fd.set(b"FontFile2".to_vec(), Object::Ref(prog_ref)); + let mut desc = Dict::new(); + desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2")); + desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(map_ref)); + desc.set(b"FontDescriptor".to_vec(), Object::Dict(fd)); + let d = font(&mut doc, vec![("Subtype", Object::name("Type0")), ("DescendantFonts", Object::Array(vec![Object::Dict(desc)]))]); + assert!(!is_glyphless(&doc, &d)); + } } /// #2130: with no `/Widths`, an embedded program's advances win over a guess from the name From b898cc121364182b491353bd91685ad2bdfd938c Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Thu, 22 Oct 2026 07:52:57 +0800 Subject: [PATCH 12/65] fix(edit): preserve spacing across generated font subsets --- ROADMAP.md | 2 ++ crates/edit/src/tests.rs | 56 +++++++++++++++++++++++++++++++++ crates/edit/src/text_regions.rs | 33 +++++++++++++++---- docs/roadmap.md | 2 +- 4 files changed, 86 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b1283e7751..b5de6771d6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,7 @@ # PdfCraft roadmap +> **2026-10-21 · M7:** Coalesced same-face Type3 subsets retain measured TJ spacing during ordinary text edits; regression covers formatting-only edits, longer replacements, and unrelated-face metrics. The 197 edit-crate tests pass; no parity estimates changed. + **Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away > **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (M5, PR #1971: bounded nested FDF export excludes source page/page-tree dictionaries; refreshed against upstream 4db6ac4a; estimates unchanged) diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 1f281893f4..d2cb779949 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -5381,3 +5381,59 @@ fn editing_glyphless_ocr_text_substitutes_a_visible_font() { text::rewrite_block(&mut ws_doc, 0, 0, Some("Aa"), &BlockStyle { resource: Some("F0".into()), ..Default::default() }).unwrap(); assert_eq!(text::text_blocks(&reopen(&ws_doc), 0).unwrap()[0].text, "Aa"); } + +/// Same-face generated subsets share a source line; TJ adjustment must survive a style edit. +#[test] +fn split_subset_source_keeps_calibrated_advance() { + let mut doc = text_page("BT /A 12 Tf 72 700 Td [<01> -100] TJ /B 12 Tf <01> Tj ET BT /F1 13 Tf 1 0 0 1 85.2 700 Tm (X) Tj ET"); + let mut fonts = Dict::new(); + // AA sorts before B and encodes B too, but its unrelated face must not supply metrics. + for (name, unicode, face, width) in + [("A", "0041", "SyntheticSubset", 500), ("AA", "0042", "OtherFace", 900), ("B", "0042", "SyntheticSubset", 500)] + { + let cmap = format!("1 begincodespacerange <01> endcodespacerange 1 beginbfchar <01> <{unicode}> endbfchar"); + let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap.as_bytes()))); + let proc = doc.add(Object::Stream(Stream::flate(Dict::new(), b"500 0 d0 0 0 400 700 re f"))); + let font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type3")), + (b"Name".to_vec(), Object::name("PCJapanese")), + (b"BaseFont".to_vec(), Object::name(face)), + (b"FontBBox".to_vec(), Object::Array([0, 0, 500, 700].map(Object::Int).to_vec())), + (b"FontMatrix".to_vec(), Object::Array([0.001, 0.0, 0.0, 0.001, 0.0, 0.0].map(Object::Real).to_vec())), + (b"FirstChar".to_vec(), Object::Int(1)), + (b"LastChar".to_vec(), Object::Int(1)), + (b"Widths".to_vec(), Object::Array(vec![Object::Int(width)])), + ( + b"Encoding".to_vec(), + Object::Dict(Dict::from_iter([(b"Differences".to_vec(), Object::Array(vec![Object::Int(1), Object::name("g01")]))])), + ), + (b"CharProcs".to_vec(), Object::Dict(Dict::from_iter([(b"g01".to_vec(), Object::Ref(proc))]))), + (b"ToUnicode".to_vec(), Object::Ref(tu)), + ]); + fonts.set(name.as_bytes().to_vec(), Object::Dict(font)); + } + fonts.set( + b"F1".to_vec(), + Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type1")), + (b"BaseFont".to_vec(), Object::name("Helvetica")), + ])), + ); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + let before = text::text_lines(&doc, 0).unwrap(); + assert_eq!(before[0].text, "AB"); + let blocks = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(blocks.len(), 1, "{blocks:?}"); + assert_eq!(blocks[0].lines.len(), 2); + let original_width = before[0].rect[2] - before[0].rect[0]; + for (draft, factor) in [("ABX", 1.0), ("ABAX", 1.5)] { + let mut edited = doc.clone(); + text::rewrite_block(&mut edited, 0, 0, Some(draft), &BlockStyle { color: Some([0.0, 0.0, 1.0]), ..Default::default() }).unwrap(); + let after = text::text_lines(&reopen(&edited), 0).unwrap(); + let width = after[0].rect[2] - after[0].rect[0]; + assert!((width - original_width * factor).abs() < 0.01, "{draft}: original {original_width}, rewritten {width}; {after:?}"); + } +} diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rs index 8f5199b17a..f87f49f53f 100644 --- a/crates/edit/src/text_regions.rs +++ b/crates/edit/src/text_regions.rs @@ -510,16 +510,37 @@ pub(super) fn rewrite_styled_block( .filter(|m| source_encodes(m, &source.text)) .map(|_| &source.font) .or_else(|| chars.iter().find(|c| c.1 == index && c.0 != '\n').map(|c| &c.2)); - if let Some((font_name, m)) = font_name.and_then(|name| metrics.get(name).filter(|m| source_encodes(m, &source.text)).map(|m| (name, m))) { - let nominal = source_width( + let width_in = |name: &str, m: &Metrics, text: &str| { + source_width( m, - &source.text, + text, source.origin.state.font.as_ref().map_or(1.0, |(_, s)| *s), - space_of(font_name, m), + space_of(name, m), source.origin.state.char_spacing, source.origin.state.word_spacing, - ) * source.origin.state.scale - * across(source); + ) + }; + let nominal = font_name + .and_then(|name| metrics.get(name).filter(|m| source_encodes(m, &source.text)).map(|m| width_in(name, m, &source.text))) + .or_else(|| { + // Generated same-face subsets can form one source line even though no one + // subset encodes it all. Measure the ORIGINAL text, not the edited draft: + // adding characters must retain the source's spacing, not squeeze to its width. + // Shaped text has a separate authoritative advance below. + if source.face.is_none() || pdfcraft_fonts::source_shaping::required(&source.text) { + return None; + } + let face = pdfcraft_fonts::embedding::face_key(&source.base_font); + source.text.chars().try_fold(0.0, |width, ch| { + let text = ch.to_string(); + let (name, m) = metrics.get_key_value(&source.font).filter(|(_, m)| source_encodes(m, &text)).or_else(|| { + metrics.iter().find(|(_, m)| pdfcraft_fonts::embedding::face_key(&m.base_font) == face && source_encodes(m, &text)) + })?; + Some(width + width_in(name, m, &text)) + }) + }); + if let Some(nominal) = nominal { + let nominal = nominal * source.origin.state.scale * across(source); let changed_face = style.resource.is_some() || overrides.get(&index).is_some_and(|r| r.family.is_some() || r.resource.is_some()); let factor = if nominal > 0.0 && !changed_face { ((source.rect[2] - source.rect[0]) / nominal).clamp(0.5, 2.0) } else { 1.0 }; calibration.insert(index, factor); diff --git a/docs/roadmap.md b/docs/roadmap.md index 5d73511e9c..aef6e17fc7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -137,7 +137,7 @@ total matches the parity estimate. | M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references.
Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA
Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. | | M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Refreshed against upstream `99941daa` (2026-10-15).
Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA
Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. | | M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV delimiters without changing field identities.
Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA
Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. | -| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.
Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks | +| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.
Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks Same-face Type3 subset editing preserves measured TJ spacing (2026-10-21; `split_subset_source_keeps_calibrated_advance`); estimates unchanged. | | M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.
Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. #1316: replacing a line or paragraph keeps a neighbouring line whose glyph box overlaps when the baselines differ; a second copy on the same baseline is still replaced. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks | | M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). #3212: Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, without revealing hidden content. Tracked editable text distinguishes repeated glyph spacing from word gaps, with synthetic paragraph/object regressions. Missing: editing existing text and images in place (the longest pole), watermark print/screen visibility and repeat | | M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions.
Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA
Done since: Existing simple field-font encodings and Differences are respected when generating appearances; an unencodable value uses a separate Helvetica appearance font without changing the source font. Synthetic reopen regressions cover punctuation, subset fallback and multiline text. Exact font metrics/layout and broader Unicode fallback remain incomplete. | From 8273c88a99e393c0bfb1fa2beaec8e4f37a572be Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:11:10 -0400 Subject: [PATCH 13/65] M12: a label without a width measures its hanging indent as it is laid out --- crates/xfa/src/tests.rs | 12 ++++++++++++ crates/xfa/src/text.rs | 18 +++++++++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index cacf49375e..99a0b701d1 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -339,6 +339,18 @@ fn a_hang_wider_than_the_box_keeps_every_line_inside_it() { } } +/// A label without a width that hangs its first line is as wide as that line is laid out: the +/// hang takes back the left margin the first line doesn't use, so right-aligned text starts at +/// the label's x. +#[test] +fn a_label_without_a_width_measures_its_hanging_indent_as_it_is_laid_out() { + let items = positioned( + r#"11. BALANCE"#, + ); + let span = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).expect("the text"); + assert!((span.x - (36.0 + 72.0)).abs() < 0.05, "starts at its x: {}", span.x); +} + #[test] fn tables_break_across_pages_and_repeat_their_header_row() { let form = layout_xml(&template(40)).unwrap(); diff --git a/crates/xfa/src/text.rs b/crates/xfa/src/text.rs index f5223a39a6..8c060994a2 100644 --- a/crates/xfa/src/text.rs +++ b/crates/xfa/src/text.rs @@ -217,9 +217,7 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn // never starts left of the box, so the others move in to make room, as other viewers lay // such labels out; never past the box's right edge, however wide the hang. let hang = (-para.text_indent).min((rect.w - para.margin_right - 1.0).max(0.0)); - let margin_left = para.margin_left.max(hang); - // Where the first line starts, from the others. - let first_indent = para.text_indent.max(-margin_left); + let (margin_left, first_indent) = indents(para, hang); let avail = (rect.w - margin_left - para.margin_right).max(1.0); let mut lines: Vec<(Line, Option)> = Vec::new(); let mut total = 0.0; @@ -328,9 +326,19 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn /// The width `rich` takes with no line wrapped (its longest paragraph, with the paragraph's /// margins and first-line indent): how wide a box without an explicit width grows. pub fn natural_width(rich: &RichText, para: &Para, base: &Face, embed: &dyn Fn(&str) -> String) -> f64 { - let indent = para.text_indent.max(0.0); + // Unwrapped, every line is a paragraph's first line; the hang is as wide as asked, since the + // box will be as wide as this. + let (margin_left, first_indent) = indents(para, -para.text_indent); let widest = rich.paragraphs.iter().map(|p| words(&p.runs, base, embed).iter().map(|w| w.width).sum::()).fold(0.0, f64::max); - (para.margin_left + indent + widest + para.margin_right).max(0.0) + (margin_left + first_indent + widest + para.margin_right).max(0.0) +} + +/// The left margin of a paragraph's lines and where its first line starts from them, for a +/// hanging indent of `hang` (the negative textIndent, as far as the box allows): the first line +/// never starts left of the box, so the other lines move in to make room. +fn indents(para: &Para, hang: f64) -> (f64, f64) { + let margin_left = para.margin_left.max(hang); + (margin_left, para.text_indent.max(-margin_left)) } /// Height `rich` needs at `width` (for boxes without an explicit height). From 327c769c247d592cc639f268c70acb68cb10e9c6 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:11:51 -0400 Subject: [PATCH 14/65] M12: doc comments on the layout tests next to the hanging-indent change --- crates/xfa/src/tests.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 99a0b701d1..4b78aa3e56 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -221,6 +221,8 @@ fn the_xdp_template_wins_over_the_config_packets_template_element() { assert_eq!(tpl.root.common.name.as_deref(), Some("form")); } +/// The sample form lays out over two pages: captions, draws and page numbers are drawn, +/// hidden draws take no space, and each field gets its widget with its size, kind and SOM path. #[test] fn layout_places_captions_fields_and_sizes_containers_to_their_content() { let form = layout_xml(&template(1)).unwrap(); @@ -304,6 +306,8 @@ fn line_starts(text: &str, w: f64, para: &str) -> Vec { lines.into_iter().map(|(_, x)| x - 36.0).collect() } +/// A negative textIndent hangs the first line: it starts left of the others, never left of the +/// box, and the other lines move in by the hang. A positive indent still moves only the first line. #[test] fn a_negative_text_indent_hangs_the_first_line_and_indents_the_rest() { let text = "11. SERVICE MEMBER BALANCE (TOTAL)"; @@ -321,6 +325,7 @@ fn a_negative_text_indent_hangs_the_first_line_and_indents_the_rest() { assert!((starts[0] - 10.0).abs() < 1e-6 && starts[1..].iter().all(|x| x.abs() < 1e-6), "{starts:?}"); } +/// A hang wider than its box is bounded by it: every line still starts and ends inside the box. #[test] fn a_hang_wider_than_the_box_keeps_every_line_inside_it() { // A 58pt box hanging its first line by 100pt, right-aligned: every line still starts and @@ -351,6 +356,8 @@ fn a_label_without_a_width_measures_its_hanging_indent_as_it_is_laid_out() { assert!((span.x - (36.0 + 72.0)).abs() < 0.05, "starts at its x: {}", span.x); } +/// A long table breaks across pages between whole rows, repeats its header row at the top of +/// each page it continues on, and keeps every row (and field name) once. #[test] fn tables_break_across_pages_and_repeat_their_header_row() { let form = layout_xml(&template(40)).unwrap(); From af9c9d6073f7a4f6637656bcabb2240c2e646bac Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:25:36 -0400 Subject: [PATCH 15/65] M12: a hang leaves the lines after the first room for the widest glyph --- crates/xfa/src/tests.rs | 31 ++++++++++++++++++++----------- crates/xfa/src/text.rs | 24 ++++++++++++++++++++---- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 4b78aa3e56..e09e9495e5 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -325,22 +325,31 @@ fn a_negative_text_indent_hangs_the_first_line_and_indents_the_rest() { assert!((starts[0] - 10.0).abs() < 1e-6 && starts[1..].iter().all(|x| x.abs() < 1e-6), "{starts:?}"); } -/// A hang wider than its box is bounded by it: every line still starts and ends inside the box. +/// A hang wider than its box is bounded by it: every line still starts and ends inside the box, +/// and lines after the first keep room for the widest glyph when the text wraps. #[test] fn a_hang_wider_than_the_box_keeps_every_line_inside_it() { - // A 58pt box hanging its first line by 100pt, right-aligned: every line still starts and - // ends inside the box. - let xdp = r##""## + ); + let form = layout_xml(&xdp).unwrap(); + let mut lines = std::collections::BTreeSet::new(); + for item in &form.pages[0].items { + let Item::Text(s) = item else { continue }; + lines.insert((s.baseline * 100.0).round() as i64); + let right = s.x + s.face.width(s.text.trim_end()); + assert!(s.x >= 36.0 - 1e-6 && right <= 36.0 + 58.0 + 1e-6, "{text}: {:?} runs from {} to {right}", s.text, s.x); + } + if text.len() > 10 { + assert!(lines.len() > 1, "{text}: wraps onto more lines ({})", lines.len()); + } } } diff --git a/crates/xfa/src/text.rs b/crates/xfa/src/text.rs index 8c060994a2..ea3b35b6dd 100644 --- a/crates/xfa/src/text.rs +++ b/crates/xfa/src/text.rs @@ -213,16 +213,18 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn size: f64, first: bool, } + let paragraphs: Vec> = rich.paragraphs.iter().map(|p| words(&p.runs, base, embed)).collect(); // A negative textIndent is a hanging indent: the first line starts left of the others. It // never starts left of the box, so the others move in to make room, as other viewers lay - // such labels out; never past the box's right edge, however wide the hang. - let hang = (-para.text_indent).min((rect.w - para.margin_right - 1.0).max(0.0)); + // such labels out; never so far that a line after the first has no room for the widest + // glyph, however wide the hang. + let widest = paragraphs.iter().flatten().map(widest_glyph).fold(1.0, f64::max); + let hang = (-para.text_indent).min((rect.w - para.margin_right - widest).max(0.0)); let (margin_left, first_indent) = indents(para, hang); let avail = (rect.w - margin_left - para.margin_right).max(1.0); let mut lines: Vec<(Line, Option)> = Vec::new(); let mut total = 0.0; - for (pi, p) in rich.paragraphs.iter().enumerate() { - let ws = words(&p.runs, base, embed); + for (pi, (p, ws)) in rich.paragraphs.iter().zip(paragraphs).enumerate() { let mut line = Line { words: Vec::new(), width: 0.0, size: base.size, first: true }; let mut first_in_para = true; let indent = |first: bool| if first { first_indent } else { 0.0 }; @@ -333,6 +335,20 @@ pub fn natural_width(rich: &RichText, para: &Para, base: &Face, embed: &dyn Fn(& (margin_left + first_indent + widest + para.margin_right).max(0.0) } +/// The width of the widest glyph `w` draws (spaces draw nothing). +fn widest_glyph(w: &Word) -> f64 { + let mut glyph = String::new(); + w.text + .chars() + .filter(|c| *c != ' ') + .map(|c| { + glyph.clear(); + glyph.push(c); + w.face.width(&glyph) + }) + .fold(0.0, f64::max) +} + /// The left margin of a paragraph's lines and where its first line starts from them, for a /// hanging indent of `hang` (the negative textIndent, as far as the box allows): the first line /// never starts left of the box, so the other lines move in to make room. From 97354050b201c17873a86de35e332753bd6a6082 Mon Sep 17 00:00:00 2001 From: oracola91 <118899664+oracola91@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:43:30 +0300 Subject: [PATCH 16/65] clippy: keep rsa verification-only deny.toml ignores RUSTSEC-2023-0071 because pdfcraft-sign uses rsa only to verify signatures (ADR-0009). clippy.toml now disallows the rsa types that hold a private key and the two rsa::hazmat decrypt functions, so a private-key operation through rsa fails clippy instead of quietly breaking that assumption. --- clippy.toml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/clippy.toml b/clippy.toml index 7f2fd53057..5bf7f4d3f8 100644 --- a/clippy.toml +++ b/clippy.toml @@ -12,4 +12,20 @@ disallowed-methods = [ { path = "egui::Ui::radio", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, { path = "egui::Ui::radio_value", reason = "use radio_value from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, { path = "egui::RadioButton::new", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, + # The raw RSA private-key operations: see disallowed-types below. + { path = "rsa::hazmat::rsa_decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::hazmat::rsa_decrypt_and_check", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, +] + +# deny.toml ignores the Marvin advisory (RUSTSEC-2023-0071) because `rsa` is only used to verify +# signatures; RSA private-key operations use aws-lc-rs (ADR-0009). These are the `rsa` types +# that hold a private key, and above are the `rsa::hazmat` functions that take one, so a +# private-key operation through `rsa` fails clippy instead. +disallowed-types = [ + { path = "rsa::RsaPrivateKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pkcs1v15::SigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pkcs1v15::DecryptingKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pss::SigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pss::BlindedSigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::oaep::DecryptingKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, ] From f8e60b4cc337f5455fe79c0bf00a86065442ba3c Mon Sep 17 00:00:00 2001 From: oracola91 <118899664+oracola91@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:46:08 +0300 Subject: [PATCH 17/65] clippy: also ban the rsa private-key methods disallowed-types only fires where a type is named. A private key that reaches pdfcraft without its type being named, returned by another crate or behind a generic over rsa's traits, could still decrypt or sign. The RsaPrivateKey constructors and private-key methods, and the private-key methods of rsa's Decryptor, RandomizedDecryptor, PaddingScheme and SignatureScheme traits, are now disallowed methods. The generic signature and pkcs8 traits stay allowed: the ECDSA keys use them too. --- clippy.toml | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/clippy.toml b/clippy.toml index 5bf7f4d3f8..49a9f9fb3c 100644 --- a/clippy.toml +++ b/clippy.toml @@ -15,11 +15,30 @@ disallowed-methods = [ # The raw RSA private-key operations: see disallowed-types below. { path = "rsa::hazmat::rsa_decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, { path = "rsa::hazmat::rsa_decrypt_and_check", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + # The ways to make or use an `rsa` private key, so a key whose type is never named (one + # returned by another crate, or a generic over these traits) is caught too. The generic + # `signature` and `pkcs8` traits are left out: the ECDSA keys use them as well. + { path = "rsa::RsaPrivateKey::new", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_unchecked", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_with_exp", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_with_exp_unchecked", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_components", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_components_with_large_exponent", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_p_q", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_primes", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::decrypt_blinded", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::sign", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::sign_with_rng", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::Decryptor::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::RandomizedDecryptor::decrypt_with_rng", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::PaddingScheme::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::SignatureScheme::sign", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, ] # deny.toml ignores the Marvin advisory (RUSTSEC-2023-0071) because `rsa` is only used to verify # signatures; RSA private-key operations use aws-lc-rs (ADR-0009). These are the `rsa` types -# that hold a private key, and above are the `rsa::hazmat` functions that take one, so a +# that hold a private key, and above are the functions and methods that make or use one, so a # private-key operation through `rsa` fails clippy instead. disallowed-types = [ { path = "rsa::RsaPrivateKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, From 5dc7f536c6b70f4482a47c58701912ee9dbe336a Mon Sep 17 00:00:00 2001 From: cyfung1031 <44498510+cyfung1031@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:03:16 +0000 Subject: [PATCH 18/65] M0: keep independent CI gates running after failures Rebased onto main, where the CI phases moved from ci.yml steps into `cargo xtask ci` (run by the shared gate workflow) and tests already run with --no-fail-fast. - `cargo xtask ci` runs every step even after one fails, then reports each failing step and fails. - The FreeBSD workflow passes --no-fail-fast to cargo test. --- .github/workflows/freebsd.yml | 1 + xtask/src/gates.rs | 12 +++++++++--- xtask/src/main.rs | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index fba20b1cc7..cf46f01644 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -27,3 +27,4 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + cargo-test-extra-args: --no-fail-fast diff --git a/xtask/src/gates.rs b/xtask/src/gates.rs index 0212e165a5..073fceebe1 100644 --- a/xtask/src/gates.rs +++ b/xtask/src/gates.rs @@ -120,13 +120,19 @@ pub fn ci(_: &[String]) -> anyhow::Result<()> { ("deny", Box::new(|| deny(&[]))), ("parity", Box::new(|| crate::parity::run(&[]))), ]; - for (i, (name, f)) in steps.iter().enumerate() { + // Independent steps keep running after a failure, so one run reports every failing step. + let mut failed = Vec::new(); + for (name, f) in &steps { eprintln!("\n=== ci: {name} ==="); if let Err(e) = f() { - println!("\nCI: {} passed, FAILED at `{name}`: {e:#}", i); - bail!("ci failed at `{name}`"); + println!("\nCI: `{name}` FAILED: {e:#}"); + failed.push(*name); } } + if !failed.is_empty() { + println!("\nCI: {} of {} steps passed, FAILED: {}", steps.len() - failed.len(), steps.len(), failed.join(", ")); + bail!("ci failed at {}", failed.iter().map(|n| format!("`{n}`")).collect::>().join(", ")); + } println!("\nCI: all {} steps passed", steps.len()); Ok(()) } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 24ddd16d16..1328045437 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -23,7 +23,7 @@ const COMMANDS: &[(&str, &str, Command)] = &[ ("deny", "Dependency licences, bans, sources and advisories (deny.toml; needs cargo-deny)", gates::deny), ( "ci", - "fmt --check, clippy -D warnings, the CLI without default features, test, i18n-report, layers, wasm, assets, deny, parity (stops at first failure)", + "fmt --check, clippy -D warnings, the CLI without default features, test, i18n-report, layers, wasm, assets, deny, parity (runs every step, then reports each failure)", gates::ci, ), ("test", "Workspace tests: cargo nextest (cargo test when it is missing), then doctests", gates::test), From 5311ccafa659fc467510faf9d3a52d579d55f78b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 12:52:41 -0700 Subject: [PATCH 19/65] fix(automation): doc_open and form_fill report the errors of the form's scripts The errors of a form's scripts, including "The form's scripts were stopped: ..." and the message that a runaway script turned them off, stayed in the document's script output. doc_open returned only the document summary, and the warnings of the edit tools did not include them. An automation client was not told, and the next XFA button click through js_run returned the stale error as its own. doc_open now lists the errors of the scripts that ran on open in warnings, and form_fill and the other edit tools that go through apply add the errors of the scripts the edit ran to warnings. Session::take_js_errors takes only the errors and leaves the alerts, console lines and requests in the script output, as before. --- crates/automation/src/lib.rs | 16 +++++++++--- crates/automation/src/tools.rs | 4 +-- crates/automation/tests/it/automation.rs | 32 +++++++++++++++++++++++- crates/engine/src/js.rs | 7 ++++++ crates/engine/src/tests.rs | 14 +++++++++++ 5 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index e94354021f..abb7119c62 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -1061,8 +1061,14 @@ impl Automation { let bytes = read_input(&path)?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; + let errors = self.session.take_js_errors(id); let doc = self.session.get(id).ok_or_else(|| failed("the document vanished"))?; - Ok(summary(doc)) + let mut out = summary(doc); + // warnings lists the errors of the form's scripts that ran on open, including the messages that the scripts were stopped or turned off. + if !errors.is_empty() { + out["warnings"] = json!(errors); + } + Ok(out) } fn doc_close(&mut self, a: &Args) -> Result { @@ -1364,11 +1370,15 @@ impl Automation { fn apply(&mut self, a: &Args, edit: Edit) -> Result { let id = self.doc(a)?.id; self.session.apply(id, edit).map_err(failed)?; + let errors = self.session.take_js_errors(id); let doc = self.doc(a)?; let mut out = summary(doc); // Text the edit stored as typed but drew with `?` (its font can't draw it): said, not silent. - if !doc.edit_notices.is_empty() { - out["warnings"] = json!(doc.edit_notices.iter().map(ToString::to_string).collect::>()); + let mut warnings: Vec = doc.edit_notices.iter().map(ToString::to_string).collect(); + // The errors of the scripts the edit ran follow the notices, including the messages that a form's scripts were stopped or turned off. + warnings.extend(errors); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } Ok(out) } diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 1bfcc77984..c95966f20a 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -135,7 +135,7 @@ pub fn tools() -> Vec { t("attachment_delete", "Delete an attachment", "Remove the document-level attachment with this name (as doc_info lists it). Undoable.") .destructive() .with(schema(json!({"doc": doc(), "name": {"type": "string"}}), &["doc", "name"])), - t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited.") + t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited. `warnings` lists the errors of the form's scripts on open, including the messages that they were stopped or turned off.") .cmd("file.open") .with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])), t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])), @@ -361,7 +361,7 @@ pub fn tools() -> Vec { t( "form_fill", "Fill in form fields", - "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes, an array of strings for multi-select lists. Appearances are regenerated so every viewer shows the values. A value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.", + "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes, an array of strings for multi-select lists. Appearances are regenerated so every viewer shows the values. A value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value. `warnings` also lists the errors of the form's scripts that the change ran, including the messages that they were stopped or turned off.", ) .with(schema(json!({ "doc": doc(), "values": { "type": "object", "description": "Field name → value." } }), &["doc", "values"])), t("form_reset", "Clear form", "Reset fields to their default values: all of them, or only those listed. Undoable.") diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 9049299702..132b7480e3 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -7289,11 +7289,41 @@ fn doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off() { ); std::fs::write(dir.join("runaway.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap(); let mut a = auto(&dir); - let doc = ok(&mut a, "doc_open", json!({ "path": "runaway.pdf" }))["doc"].as_u64().unwrap(); + let opened = ok(&mut a, "doc_open", json!({ "path": "runaway.pdf" })); + let doc = opened["doc"].as_u64().unwrap(); + // doc_open's warnings also hold the message that the form's scripts are off. + let warnings = opened["warnings"].as_array().unwrap_or_else(|| panic!("{opened}")); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("the form's scripts are off"))), "{opened}"); assert_eq!(ok(&mut a, "doc_info", json!({ "doc": doc }))["xfa_scripts_off"], true); let _ = std::fs::remove_dir_all(dir); } +#[test] +fn doc_open_and_form_fill_report_the_errors_of_the_forms_scripts() { + let dir = workdir("xfa-script-errors"); + // The initialize script fails on open; the total's calculation fails once qty is 4. + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace("if (qty.rawValue === null) qty.rawValue = 2;", "qty.rawValue = 2; throw new Error('open failed');") + .replace( + "", + "", + ); + std::fs::write(dir.join("errors.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap(); + let mut a = auto(&dir); + let warns = |out: &Value, text: &str| out["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.contains(text)))); + let opened = ok(&mut a, "doc_open", json!({ "path": "errors.pdf" })); + let doc = opened["doc"].as_u64().unwrap(); + assert!(warns(&opened, "open failed"), "{opened}"); + // A button click after the open returns no error, because doc_open took the open's error. + let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello" })); + assert!(r["error"].is_null(), "{r}"); + assert_eq!(r["alerts"], json!(["Hello 2"]), "{r}"); + let filled = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "qty": "4" } })); + assert!(warns(&filled, "fill failed"), "{filled}"); + assert!(!warns(&filled, "open failed"), "{filled}"); + let _ = std::fs::remove_dir_all(dir); +} + /// doc_info describes a link's set-layer-visibility action by layer name, and each layer's /// visibility now and as the file opens. #[test] diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index 7f94971cc1..8540add18d 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -319,6 +319,13 @@ impl Session { } Ok(o) } + + /// The script errors not taken yet, out of what [`Session::take_js_output`] returns; the + /// alerts, console lines and requests stay for that call. Until that call, a document + /// script's error taken here is not repeated when the document scripts run again. + pub fn take_js_errors(&mut self, id: DocId) -> Vec { + self.docs.iter_mut().find(|d| d.id == id).map(|d| std::mem::take(&mut d.js_output.errors)).unwrap_or_default() + } } /// A page's words for form-field detection, in user space (underscore runs split from the diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index dc76159d14..a423d88d16 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4606,6 +4606,20 @@ fn active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts() { assert!(s.run_javascript(id, "", None).unwrap().alerts.is_empty()); } +#[test] +fn take_js_errors_leaves_the_alerts_for_take_js_output() { + let template = pdfcraft_xfa::fixtures::scripted_template() + .replace("if (qty.rawValue === null) qty.rawValue = 2;", "qty.rawValue = 2; xfa.host.messageBox('opened'); throw new Error('open failed');"); + let mut s = Session::new(); + let id = s.open("xfa.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap(); + let errors = s.take_js_errors(id); + assert!(errors.iter().any(|e| e.contains("open failed")), "{errors:?}"); + assert!(s.take_js_errors(id).is_empty()); + let out = s.take_js_output(id); + assert!(out.errors.is_empty(), "{out:?}"); + assert_eq!(out.alerts, ["opened"]); +} + #[test] fn active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts() { let template = r#"