From 094752889188720880a021699d23fe7bb1892bf7 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 11 Oct 2026 02:03:05 -0400 Subject: [PATCH 001/216] CI: run FreeBSD and Windows ARM64 checks nightly and on release, not per PR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit They ran on every push to main and on any PR touching Cargo.toml/Cargo.lock, which is nearly every PR. See craftrules release/playbook.md §2. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/freebsd.yml | 11 +++++++---- .github/workflows/windows-arm64.yml | 12 +++++------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index b852d863a7..2b7724ecf2 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -2,16 +2,19 @@ # (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter. name: FreeBSD +# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every push +# or dependency change: a drifted dependency still shows up within a day, and always before a +# release ships. PRs that change the FreeBSD packaging itself still run it. on: + schedule: + - cron: "27 3 * * *" push: - branches: [main] + branches: [release] pull_request: paths: - - Cargo.toml - - Cargo.lock - - "**/Cargo.toml" - .github/workflows/freebsd.yml - packaging/freebsd/** + - packaging/env.sh workflow_dispatch: concurrency: diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 2ddcf82a27..1f17aea032 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -3,19 +3,17 @@ # run the test suite natively on ARM64. name: Windows ARM64 +# Nightly on main and on pushes to `release` (dependency and runner-image drift shows up within a +# day, and always before a release ships), and on PRs that change the Windows packaging itself. on: + schedule: + - cron: "43 5 * * *" push: - branches: [main] + branches: [release] pull_request: paths: - - Cargo.toml - - Cargo.lock - - "**/Cargo.toml" - - "**/build.rs" - .github/workflows/windows-arm64.yml - packaging/windows/** - schedule: - - cron: "41 4 * * 1" # weekly, so drift in the runner images shows up workflow_dispatch: concurrency: From d812cf8a5ca46a27756aaae5a10240ca63dec0d9 Mon Sep 17 00:00:00 2001 From: Mara Johnson Date: Sun, 11 Oct 2026 12:55:33 -0400 Subject: [PATCH 002/216] Windows MSI: notify Explorer of the PDF association so PdfCraft shows under Open with (#1080) The MSI already registers PdfCraft.Document in .pdf\OpenWithProgids, Capabilities and RegisteredApplications, but Windows Installer never sends SHCNE_ASSOCCHANGED, so Explorer's cached Open with list can miss PdfCraft until sign-out. Send it after install and uninstall from an immediate, ignore-result custom action; test-msi.ps1 checks the action and its order. --- packaging/windows/pdfcraft.wxs | 13 +++++++++++++ packaging/windows/test-msi.ps1 | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/packaging/windows/pdfcraft.wxs b/packaging/windows/pdfcraft.wxs index e8bb53734d..015631bdd8 100644 --- a/packaging/windows/pdfcraft.wxs +++ b/packaging/windows/pdfcraft.wxs @@ -53,11 +53,24 @@ + + + + + + + diff --git a/packaging/windows/test-msi.ps1 b/packaging/windows/test-msi.ps1 index 0b6fa7781e..841c3c4dea 100644 --- a/packaging/windows/test-msi.ps1 +++ b/packaging/windows/test-msi.ps1 @@ -148,6 +148,15 @@ if ($pdfCheckbox[2] -notmatch 'Edit with PdfCraft') { throw "Welcome PDF context $pdfChecked = Read-Row 'SELECT `Value` FROM `CheckBox` WHERE `Property` = ''INSTALLPDFCONTEXTMENU''' 1 Assert-Equal $pdfChecked[0] '1' 'Welcome PDF context-menu value' Assert-NoRow 'SELECT `Registry` FROM `Registry` WHERE `Key` = ''Software\Classes\.pdf'' AND `Name` IS NULL' '.pdf default app' +# #1080: Explorer is told the associations changed (SHCNE_ASSOCCHANGED) after install/uninstall, +# without ever failing setup. 34 = exe in a directory; 64 = ignore its exit code. +$notify = Read-Row 'SELECT `Type`, `Source`, `Target` FROM `CustomAction` WHERE `Action` = ''NotifyAssociationsChanged''' 3 +Assert-Equal $notify[0] '98' 'Association notify action type' +Assert-Equal $notify[1] 'SystemFolder' 'Association notify directory' +if ($notify[2] -notmatch 'SHChangeNotify\(0x8000000,0,0,0\)' -or $notify[2].Length -gt 255) { throw "Association notify command: '$($notify[2])'" } +$after = Read-Row 'SELECT `Sequence` FROM `InstallExecuteSequence` WHERE `Action` = ''NotifyAssociationsChanged''' 1 +$finalize = Read-Row 'SELECT `Sequence` FROM `InstallExecuteSequence` WHERE `Action` = ''InstallFinalize''' 1 +if ([int] $after[0] -le [int] $finalize[0]) { throw 'Association notify must run after InstallFinalize' } # Negative sequences are Windows Installer's success/user-exit/failure paths. Only full UI # shows these dialogs: an unattended /qn or /qb install must never wait for a Finish click. From df751f252e0eb33b51c58581d7c1f3ed5d3919bb Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 16 Oct 2026 02:20:09 +0200 Subject: [PATCH 003/216] 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 004/216] 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 0fcb49aab536a18de34c1107a823cec57877d7b5 Mon Sep 17 00:00:00 2001 From: kavishkashehan726-sudo <260480244+kavishkashehan726-sudo@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:01:15 +0000 Subject: [PATCH 005/216] fix(engine): validate signed XFA forms as the file was read (#2759) Opening an XFA form appends PdfCraft's own revisions to the working file: the dynamic layout, the field values taken from the XFA data, and what the open scripts change. Signatures were then validated against that working file, so a certified (DocMDP P=2) form opened untouched was reported invalid, "altered since signed (pages added or removed, comments)", before the user had changed anything. This is the symptom the IRCC IMM forms show. Keep the file as read for a signed document whose opening appended revisions, and validate the signatures against it while the working state is still just the opened one: on open, on trust changes, after undo back to it, and after Revert. Once the user edits or saves, the file Save writes is judged as before, open-time revisions included, so the verdict never hides what saving will write. Part of storytold/pdfcraft#2759: the false "altered" on open. The trust lists and TSA trust it also asks for are separate problems. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AFWmxuUvJ4qW6tMcBHs1XJ --- crates/engine/src/lib.rs | 54 +++++++++++++++++++++++++------ crates/engine/src/tests.rs | 63 ++++++++++++++++++++++++++++++++++++ parity/acrobat-features.toml | 4 +-- 3 files changed, 109 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3432cd868e..79513a0108 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -315,6 +315,17 @@ struct Editor { appearances: AppearanceCache, /// The text blocks last computed for one page, reused while the document is unchanged. text_blocks: TextBlocksCache, + /// A signed file that opening appended revisions to (an XFA form's layout, the values from + /// its data, its open scripts): the file as it was read, which the signatures are validated + /// against until the user changes something or saves (#2759). + as_opened: Option, +} + +/// The file as read, before opening appended PdfCraft's own revisions to it. +#[derive(Clone)] +struct AsOpened { + cos: pdfcraft_cos::Document, + bytes: Arc>, } /// One page's text blocks ([`pdfcraft_edit::text_blocks`]) and the unmodified document state they @@ -3211,9 +3222,16 @@ fn xfa_values_from_datasets(doc: &mut pdfcraft_cos::Document) -> Result Vec { - pdfcraft_sign::pdf::list_cached(cos, bytes, trust, cache) +/// Validate the signature fields of the editor's working state (written as `bytes`). While that +/// state is still the file as opened plus only what opening appended, the file as read is +/// validated instead: PdfCraft's own open-time revisions are not changes made since signing. +fn signatures_of(editor: &Editor, bytes: &[u8], trust: &TrustStore, cache: &pdfcraft_sign::DigestCache) -> Vec { + match &editor.as_opened { + Some(o) if !editor.cos.is_modified() && Arc::ptr_eq(editor.cos.bytes(), &editor.saved) => { + pdfcraft_sign::pdf::list_cached(&o.cos, &o.bytes, trust, cache) + } + _ => pdfcraft_sign::pdf::list_cached(&editor.cos, bytes, trust, cache), + } } impl Session { @@ -3351,6 +3369,11 @@ impl Session { } Err(e) => return Err(e), }; + // The file as read, for its signatures: opening an XFA form may append revisions below. + let as_read = match (&info.xfa, &cos) { + (Some(_), Ok(Ok(c))) => Some(AsOpened { cos: c.clone(), bytes: bytes.clone() }), + _ => None, + }; // A dynamic XFA form is a shell around an XML template; lay the template out into real // pages and fields so the rest of the engine works on it. The original bytes stay: the // laid-out form is one appended revision. @@ -3491,7 +3514,8 @@ impl Session { }; // XFA notes survive the document being re-read after edits. let xfa_warnings: Vec = if info.xfa.is_some() { info.warnings.clone() } else { Vec::new() }; - let mut document = Self::build_document(&context.trust, name, path, bytes, info, cos, render_password, password, xfa); + let as_opened = as_read.filter(|o| !Arc::ptr_eq(&o.bytes, &bytes)); + let mut document = Self::build_document(&context.trust, name, path, bytes, info, cos, render_password, password, xfa, as_opened); // A script that ran away on open turns the form's scripts off for this document. document.xfa_template = if ran_away { None } else { xfa_template }; document.js_output.append(script_output); @@ -3515,6 +3539,7 @@ impl Session { render_password: Option, password: Option<&str>, xfa: Option, + as_opened: Option, ) -> Document { let config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() }; let (mut editor, read_only_reason) = match cos { @@ -3531,6 +3556,7 @@ impl Session { keys, appearances: AppearanceCache::default(), text_blocks: TextBlocksCache::default(), + as_opened, }), None, ) @@ -3539,7 +3565,13 @@ impl Session { Err(_) => (None, Some("the document structure could not be read for editing".into())), }; let sig_cache = Arc::new(pdfcraft_sign::DigestCache::default()); - let signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, trust, &sig_cache)).unwrap_or_default(); + let signatures = editor.as_ref().map(|e| signatures_of(e, &bytes, trust, &sig_cache)).unwrap_or_default(); + // Only a signed file needs keeping as it was read. + if !signatures.iter().any(|s| s.signed) + && let Some(e) = editor.as_mut() + { + e.as_opened = None; + } let display = display_bytes(editor.as_mut(), &bytes); let renderer = RenderPool::new(display.clone(), render_threads(), config.clone()); let (form, adopted) = editor @@ -3875,7 +3907,7 @@ impl Session { doc.info.producer = info("Producer"); doc.info.file_size = bytes.len(); if !doc.signatures.is_empty() { - let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache); + let signatures = signatures_of(editor, &bytes, &doc.trust, &doc.sig_cache); doc.signatures = Arc::new(signatures); } doc.bytes = bytes; @@ -3919,7 +3951,7 @@ impl Session { } doc.info.file_size = bytes.len(); doc.form = form; - let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) }; + let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(editor, &bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &bytes); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone()); @@ -3964,7 +3996,7 @@ impl Session { doc.marker_scan = OnceLock::new(); } doc.info.file_size = bytes.len(); - let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) }; + let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(editor, &bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &bytes); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone()); @@ -4039,7 +4071,7 @@ impl Session { if invalidate_links { doc.links = OnceLock::new(); } - let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache); + let signatures = signatures_of(editor, &bytes, &doc.trust, &doc.sig_cache); doc.display = display_bytes(Some(editor), &bytes); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone()); @@ -4108,6 +4140,8 @@ impl Session { pdfcraft_cos::Document::open_with_password(bytes.clone(), keys.reopen.as_deref()).map_err(|e| EditError::Reopen(e.to_string()))?; editor.saved = bytes; editor.saved_keys = keys; + // The saved file holds what opening appended: from now on it is the file. + editor.as_opened = None; } if let Some(p) = path { doc.name = std::path::Path::new(&p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.clone()); @@ -4783,7 +4817,7 @@ impl Session { let Some(editor) = doc.editor.as_mut() else { continue }; // Keep verdict refresh and renderer refresh together. Viewer caches are // invalidated by the UI trust path; trust alone changes no document artwork. - let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache) }; + let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(editor, &doc.bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &doc.bytes); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ec305b1ca5..9cb4181d7f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5801,3 +5801,66 @@ fn cropping_an_existing_image_clips_it_and_moves_with_it() { // No area, or a box off the image, is refused. assert!(s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Crop([10.0, 10.0, 10.0, 50.0]) }).is_err()); } + +/// A certified (DocMDP P=2) form, as a certifying application leaves it: signed over the whole +/// file, with nothing appended. +fn certified_xfa(original: &[u8]) -> Arc> { + let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); + let id = sign::pkcs12::open(&p12, "test").unwrap(); + let cos = pdfcraft_cos::Document::open(Arc::new(original.to_vec())).unwrap(); + let opts = SignOptions { certify: Some(2), date: "D:20270115080000Z".into(), ..SignOptions::default() }; + Arc::new(sign::sign(&cos, &id, &opts).unwrap()) +} + +/// What opening an XFA form writes (its layout, the values from its data, its open scripts) is +/// PdfCraft's own working revision, not a change to the file: a certified government form +/// opened untouched is not "altered since it was signed" (#2759). Once the user changes it, or +/// saves, the file Save writes is what is judged, open-time revisions included. +#[test] +fn certified_xfa_forms_open_unaltered() { + let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); + let signer = sign::pkcs12::open(&p12, "test").unwrap().certificate; + let forms = [ + // Laying the template out adds pages: a change the certification doesn't permit. + ("dynamic", pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::template(3)), "familyName", sign::kind::PAGES), + // Taking the values from the data fills the fields: a permitted change. + ( + "static", + pdfcraft_xfa::fixtures::static_shell("Ada1"), + "form1[0].page1[0].name[0]", + sign::kind::FORM_FILL, + ), + ]; + for (what, form, field, saved_kind) in forms { + let certified = certified_xfa(&form); + let mut s = Session::new().with_clock(|| 1_800_000_000); + let id = s.open("imm.pdf", None, certified.clone(), None).expect("opens"); + let doc = s.get(id).unwrap(); + assert!(doc.bytes.len() > certified.len() && !doc.dirty, "{what}: opening wrote a working revision, not an edit"); + let verdict = |s: &Session| { + let sig = s.get(id).unwrap().signatures[0].clone(); + (sig.status, sig.modification) + }; + assert_eq!(s.get(id).unwrap().signatures[0].certify, Some(2), "{what}"); + assert_eq!(verdict(&s), (SignatureStatus::Unknown, sign::Modification::None), "{what}: {:?}", s.get(id).unwrap().signatures[0].details); + // Trusting the signer revalidates the file as opened too. + s.set_trusted_certificates(vec![signer.clone()]); + assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}"); + // An edit is judged with everything Save would write; undoing it is the file as opened. + s.apply(id, Edit::SetFieldValue { name: field.into(), value: FieldValue::Text("Singh".into()) }).unwrap(); + assert_ne!(verdict(&s).1, sign::Modification::None, "{what}"); + s.undo(id).unwrap(); + assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}"); + s.revert(id).unwrap(); + assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}"); + // Saved, the open-time revision is part of the file. + let saved = s.save_bytes(id).unwrap(); + s.mark_saved(id, saved, None).unwrap(); + let (_, modification) = verdict(&s); + let kinds = match &modification { + sign::Modification::Allowed(k) | sign::Modification::Disallowed(k) => k.clone(), + sign::Modification::None => Vec::new(), + }; + assert!(kinds.contains(&saved_kind), "{what}: {modification:?}"); + } +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c3d319f94f..4eeda60fb0 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6188,8 +6188,8 @@ milestone = "M9" status = "shipped" commands = ["sign.validate"] tools = ["sign_list"] -evidence = ["crates/sign/tests/pdf.rs::signing_then_validating_with_and_without_trust", "crates/automation/tests/automation.rs::digital_ids_signing_and_validation_through_tools", "crates/sign/tests/chain.rs::a_trusted_signer_whose_certificate_may_not_sign_is_not_valid"] -notes = "The signer's key usage, extended key usage and critical extensions are checked; name constraints are not" +evidence = ["crates/sign/tests/pdf.rs::signing_then_validating_with_and_without_trust", "crates/automation/tests/automation.rs::digital_ids_signing_and_validation_through_tools", "crates/sign/tests/chain.rs::a_trusted_signer_whose_certificate_may_not_sign_is_not_valid", "crates/engine/src/tests.rs::certified_xfa_forms_open_unaltered"] +notes = "The signer's key usage, extended key usage and critical extensions are checked; name constraints are not. A signed XFA form is validated as the file was read: the revisions opening appends (dynamic layout, values from the data, open scripts) are not counted as changes until the user edits or saves (#2759). Still missing: saving a certified dynamic XFA form writes PdfCraft's page layout into the file, which the certification does not permit, so an edited or saved one reports pages added; there are no AATL/EUTL trust lists, so publicly issued signers and timestamp authorities stay unknown until their roots are trusted by hand" [[feature]] id = "sign.signatures-panel" From b1109a363fbb1c0769eb9c6b63ef422d817d2c5f Mon Sep 17 00:00:00 2001 From: Braden Herman Date: Fri, 16 Oct 2026 10:36:09 -0500 Subject: [PATCH 006/216] M7: centre new added text on the click The Text tool put the clicked point at the top of the new box, so the first line appeared half a line below where the I-beam pointer was (7.2 pt at 12 pt). The first line is now centred on the click, and a click at the page's top edge keeps the box on the page. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/content_ui.rs | 7 +++++-- crates/ui-egui/tests/content.rs | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/content_ui.rs b/crates/ui-egui/src/content_ui.rs index 5f5ef32f77..f0156c3c10 100644 --- a/crates/ui-egui/src/content_ui.rs +++ b/crates/ui-egui/src/content_ui.rs @@ -372,8 +372,11 @@ pub(crate) fn page_input( let at = to_display(xf, info, page, p); let mut style = style.clone(); style.text.clear(); - let page_width = info.pages.get(page).map_or(f64::INFINITY, |p| p.width as f64); - let rect = [at[0], at[1] - style.size * 1.2, (at[0] + 200.0).min(page_width), at[1]]; + let (page_width, page_height) = info.pages.get(page).map_or((f64::INFINITY, f64::INFINITY), |p| (p.width as f64, p.height as f64)); + // The first line (1.2 em tall) is centred on the click, as the I-beam pointer is; its + // top was at the click, so the text appeared below where it was placed. + let top = (at[1] + style.size * 0.6).min(page_height); + let rect = [at[0], top - style.size * 1.2, (at[0] + 200.0).min(page_width), top]; style.rect = rect; cv.draft = Some(TextDraft { page, index: None, rect, text: String::new(), style, focus: true }); consumed = true; diff --git a/crates/ui-egui/tests/content.rs b/crates/ui-egui/tests/content.rs index dd2c032eff..eafac4a800 100644 --- a/crates/ui-egui/tests/content.rs +++ b/crates/ui-egui/tests/content.rs @@ -183,6 +183,39 @@ fn text_tool_deleting_a_draft_hides_the_old_added_glyphs_and_cancel_restores_the assert!(h.state().views[0].content.draft.is_none()); } +/// The text tool's pointer is an I-beam whose middle is the click: the new box's first line is +/// centred there, not hung below it. A click at the page's top edge keeps the box on the page. +#[test] +fn new_text_is_centred_on_the_click() { + let mut h = harness(); + assert!(h.state_mut().execute("edit.text")); + h.run_steps(2); + let (ph, size) = { + let s = h.state(); + (s.session.get(s.views[0].id).unwrap().info.pages[0].height as f64, s.text_style.size) + }; + // Display space (points, y up from the page's bottom) of a screen point on page 1. + let display = |h: &Harness<'static, PdfCraftApp>, p: Pos2| { + let r = h.state().views[0].page_screen_rect(0).expect("on screen"); + let k = f64::from(r.height()) / ph; + [f64::from(p.x - r.left()) / k, ph - f64::from(p.y - r.top()) / k] + }; + let p = at(&h, 40.0, 300.0); + click(&mut h, p); + let rect = h.state().views[0].content.draft.as_ref().expect("a box opened").rect; + let [x, y] = display(&h, p); + assert!((rect[0] - x).abs() < 0.5, "the box starts at the click ({} vs {x})", rect[0]); + let middle = rect[3] - size * 0.6; + assert!((middle - y).abs() < 0.5, "the first line's middle ({middle}) is at the click ({y})"); + // At the very top of the page the box stays on it. + h.get_by_label("Discard this text (Esc)").click(); + h.run_steps(3); + let p = at(&h, 40.0, 0.5); + click(&mut h, p); + let rect = h.state().views[0].content.draft.as_ref().expect("a box opened").rect; + assert!(rect[3] <= ph, "the box's top ({}) is on the page ({ph})", rect[3]); +} + #[test] fn clicking_elsewhere_keeps_the_text_and_starts_a_new_box() { // #74: a click elsewhere on the page threw away the text being typed and opened a new box. From ed93f17174d32c898fec1d43a746a8f9710364b7 Mon Sep 17 00:00:00 2001 From: rangoDJ Date: Fri, 16 Oct 2026 12:29:51 -0400 Subject: [PATCH 007/216] 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 082502eeb05291413adda890caa6b134c1d36610 Mon Sep 17 00:00:00 2001 From: FerrisEanfar <38483336+FerrisEanfar@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:03:16 -0600 Subject: [PATCH 008/216] fix(organize): keep attachments when inserting pages from a file --- ROADMAP.md | 1 + crates/engine/tests/insert_attachments.rs | 234 ++++++++++++++++++++++ crates/organize/src/import.rs | 44 ++-- docs/roadmap.md | 5 +- parity/acrobat-features.toml | 10 +- 5 files changed, 273 insertions(+), 21 deletions(-) create mode 100644 crates/engine/tests/insert_attachments.rs diff --git a/ROADMAP.md b/ROADMAP.md index 259dbfec04..d001bb99e0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -157,6 +157,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md | 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 | ## Progress log +- **2026-10-16 (M4, Insert from File):** Catalog attachments come along with inserted pages in the same undo step. Existing attachments and destination name trees stay; duplicate UTF-16 keys keep their encoding. Generated engine regressions cover save/undo/redo and failed-batch rollback. Estimates unchanged. - **2026-10-15 (M2, gap 12):** `cargo xtask text-oracle` scores reading order as well as word F1: the longest common subsequence of the two word sequences over the longer one. F1 is a bag of words and cannot see order at all -- measuring #2431, a change that moves text and nothing else, it called 26 of the 29 files whose output changed identical, where the order score separated 18 improvements from 6 regressions. Reports, does not gate; a disagreement with Poppler, not a verdict. Estimates unchanged. - **2026-10-15 (M2, #2305 follow-up):** WinAnsiEncoding 0xA0 and 0xAD and MacRomanEncoding 0xCA extract as the ordinary space and hyphen Annex D.2 names them, in the vendored hayro tables (patch 30) as well as `crates/fonts`, so search, copy and redaction see characters that were hidden behind U+00A0 and U+00AD. Across the pdf.js corpus the soft hyphens we extract fall 117 to 13 and the non-breaking spaces 30 to 26; the rest come from `/ToUnicode`. An explicit `/Differences` name keeps its glyph list value, as pdftotext does. Estimates unchanged. - **2026-10-13 (community, M3, #1569 review):** Pixel-only Wayland wheel, wheel-tilt and continuous input use standalone moved events, so Ctrl zoom does not remain latched after the modifier is released (#991); vendored winit patch (13), with a policy test. Estimates unchanged. diff --git a/crates/engine/tests/insert_attachments.rs b/crates/engine/tests/insert_attachments.rs new file mode 100644 index 0000000000..064ffc6e6e --- /dev/null +++ b/crates/engine/tests/insert_attachments.rs @@ -0,0 +1,234 @@ +use std::{collections::BTreeMap, sync::Arc}; + +use pdfcraft_cos::{Dict, Document, Object, PdfString, SaveOptions, Stream, write_full}; +use pdfcraft_engine::{Edit, Session}; +use pdfcraft_organize::FieldConflicts; + +fn dict(entries: [(&str, Object); N]) -> Dict { + let mut out = Dict::new(); + for (key, value) in entries { + out.set(key.as_bytes().to_vec(), value); + } + out +} + +fn packet(title: &str, attachment_key: Option>, indirect_names: bool) -> Arc> { + let mut doc = Document::new_empty(); + let pages = doc.add(Object::Null); + let font = doc.add(dict([("Type", Object::name("Font")), ("Subtype", Object::name("Type1")), ("BaseFont", Object::name("Helvetica"))])); + let body = format!("BT /F1 12 Tf 72 720 Td ({title}) Tj ET"); + let content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), body.into_bytes()))); + let page = doc.add(dict([ + ("Type", Object::name("Page")), + ("Parent", Object::Ref(pages)), + ("MediaBox", Object::Array([0, 0, 612, 792].map(Object::Int).to_vec())), + ("Contents", Object::Ref(content)), + ("Resources", Object::Dict(dict([("Font", Object::Dict(dict([("F1", Object::Ref(font))])))]))), + ])); + doc.set(pages, dict([("Type", Object::name("Pages")), ("Kids", Object::Array(vec![Object::Ref(page)])), ("Count", Object::Int(1))])); + let destinations = doc.add(dict([( + "Names", + Object::Array(vec![Object::String(PdfString::text("PaymentSchedule")), Object::Array(vec![Object::Ref(page), Object::name("Fit")])]), + )])); + let mut names = dict([("Dests", Object::Ref(destinations))]); + if let Some(key) = attachment_key { + let payload = format!("{title}: vendor insurance verified; review owner Procurement Operations; next review 2027-01-31.\n"); + let file = doc.add(Object::Stream(Stream::from_raw( + dict([ + ("Type", Object::name("EmbeddedFile")), + ("Subtype", Object::name("text/plain")), + ("Params", Object::Dict(dict([("Size", Object::Int(payload.len() as i64))]))), + ]), + payload.into_bytes(), + ))); + let spec = doc.add(dict([ + ("Type", Object::name("Filespec")), + ("F", Object::String(PdfString::text("vendor-compliance.txt"))), + ("EF", Object::Dict(dict([("F", Object::Ref(file))]))), + ])); + let leaf = doc.add(dict([ + ("Names", Object::Array(vec![Object::String(PdfString::literal(key.clone())), Object::Ref(spec)])), + ("Limits", Object::Array(vec![Object::String(PdfString::literal(key.clone())), Object::String(PdfString::literal(key))])), + ])); + let tree = doc.add(dict([("Kids", Object::Array(vec![Object::Ref(leaf)]))])); + names.set(b"EmbeddedFiles".to_vec(), Object::Ref(tree)); + } + let names = if indirect_names { Object::Ref(doc.add(names)) } else { Object::Dict(names) }; + let root = doc.add(dict([("Type", Object::name("Catalog")), ("Pages", Object::Ref(pages)), ("Names", names)])); + doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(root)); + Arc::new(write_full(&doc, &SaveOptions::default()).unwrap()) +} + +fn attachments(doc: &Document) -> Vec<(Vec, Vec)> { + fn visit(doc: &Document, tree: &Object, out: &mut Vec<(Vec, Vec)>) { + let tree = doc.resolve(tree); + let tree = tree.as_dict().unwrap(); + if let Some(names) = tree.get(b"Names") { + for pair in doc.resolve(names).as_array().unwrap().as_chunks::<2>().0 { + let key = pair[0].as_string().unwrap(); + let spec = doc.resolve(&pair[1]); + let ef = doc.resolve(spec.as_dict().unwrap().get(b"EF").unwrap()); + let file = doc.resolve(ef.as_dict().unwrap().get(b"F").unwrap()); + let Object::Stream(file) = file.as_ref() else { panic!("embedded file stream expected") }; + out.push((key.bytes.to_vec(), file.decoded().unwrap())); + } + } + if let Some(kids) = tree.get(b"Kids") { + for kid in doc.resolve(kids).as_array().unwrap() { + visit(doc, kid, out); + } + } + } + let catalog = doc.get(doc.root().unwrap()); + let names = doc.resolve(catalog.as_dict().unwrap().get(b"Names").unwrap()); + let mut out = Vec::new(); + if let Some(tree) = names.as_dict().unwrap().get(b"EmbeddedFiles") { + visit(doc, tree, &mut out); + } + out +} + +fn assert_destination_retained(doc: &Document) { + let catalog = doc.get(doc.root().unwrap()); + let names = doc.resolve(catalog.as_dict().unwrap().get(b"Names").unwrap()); + let dests = doc.resolve(names.as_dict().unwrap().get(b"Dests").expect("target destination tree retained")); + let values = dests.as_dict().unwrap().get(b"Names").unwrap().as_array().unwrap(); + assert_eq!(values[0].as_string().unwrap().to_text(), "PaymentSchedule"); + let page = values[1].as_array().unwrap()[0].as_ref().unwrap(); + assert_eq!(doc.get(page).as_dict().unwrap().name(b"Type"), Some(b"Page".as_slice())); +} + +fn insert(bytes: Arc>) -> Edit { + Edit::InsertPagesFrom { name: "Facilities Compliance Annex.pdf".into(), bytes, pages: None, at: 1, field_conflicts: FieldConflicts::Rename } +} + +#[test] +fn inserted_catalog_attachments_follow_native_undo_redo() { + let unicode = "合规审查.txt"; + let be: Vec = [0xfe, 0xff].into_iter().chain(unicode.encode_utf16().flat_map(u16::to_be_bytes)).collect(); + let le: Vec = [0xff, 0xfe].into_iter().chain(unicode.encode_utf16().flat_map(u16::to_le_bytes)).collect(); + for key in [b"vendor-compliance.txt".to_vec(), be, le] { + // Check raw keys to preserve the incoming encoding, including LE files + // whose labels PdfString::to_text does not currently decode. + let mut renamed = key.clone(); + match key.get(..2) { + Some([0xfe, 0xff]) => renamed.extend(" (2)".encode_utf16().flat_map(u16::to_be_bytes)), + Some([0xff, 0xfe]) => renamed.extend(" (2)".encode_utf16().flat_map(u16::to_le_bytes)), + _ => renamed.extend_from_slice(b" (2)"), + } + for indirect in [false, true] { + let target = packet("Facilities Service Agreement", Some(key.clone()), indirect); + let source = packet("Facilities Compliance Annex", Some(key.clone()), true); + let mut session = Session::new(); + session.set_javascript(false); + let id = session.open("Facilities Contract.pdf", None, target, None).unwrap(); + session.apply(id, Edit::Batch { label: "Merge Annex".into(), edits: vec![insert(source.clone())] }).unwrap(); + let bytes = session.save_bytes(id).unwrap(); + let merged = Document::open(bytes).unwrap(); + let entries = attachments(&merged); + assert_eq!(entries.len(), 2, "target and source attachments must survive"); + assert!(entries.windows(2).all(|p| p[0].0 < p[1].0), "name tree keys sorted and unique"); + let by_key: BTreeMap<_, _> = entries.into_iter().collect(); + assert!(by_key[&key].starts_with(b"Facilities Service Agreement:")); + assert!(by_key[&renamed].starts_with(b"Facilities Compliance Annex:")); + assert_destination_retained(&merged); + assert_eq!(session.get(id).unwrap().info.pages.len(), 2); + assert_eq!(session.get(id).unwrap().can_undo(), Some("Merge Annex")); + session.undo(id).unwrap(); + let undone = Document::open(session.save_bytes(id).unwrap()).unwrap(); + assert_eq!(attachments(&undone).len(), 1); + assert_destination_retained(&undone); + assert_eq!(session.get(id).unwrap().info.pages.len(), 1); + session.redo(id).unwrap(); + let redone = Document::open(session.save_bytes(id).unwrap()).unwrap(); + assert_eq!(attachments(&redone).len(), 2); + assert_destination_retained(&redone); + assert_eq!(session.get(id).unwrap().info.pages.len(), 2); + assert_eq!(attachments(&Document::open(source).unwrap()).len(), 1); + } + } +} + +#[test] +fn inserting_into_a_document_without_attachments_retains_other_names() { + let mut session = Session::new(); + session.set_javascript(false); + let id = session.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", None, true), None).unwrap(); + session.apply(id, insert(packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true))).unwrap(); + let result = Document::open(session.save_bytes(id).unwrap()).unwrap(); + assert_eq!(attachments(&result).len(), 1); + assert_destination_retained(&result); + session.undo(id).unwrap(); + assert!(attachments(&Document::open(session.save_bytes(id).unwrap()).unwrap()).is_empty()); +} + +#[test] +fn inserting_without_source_attachments_does_not_rewrite_target_names() { + let mut session = Session::new(); + session.set_javascript(false); + let id = session + .open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None) + .unwrap(); + let before = Document::open(session.save_bytes(id).unwrap()).unwrap(); + let names = before.get(before.root().unwrap()).as_dict().unwrap().get(b"Names").unwrap().clone(); + assert!(matches!(names, Object::Ref(_))); + session.apply(id, insert(packet("Facilities Payment Schedule", None, false))).unwrap(); + let after = Document::open(session.save_bytes(id).unwrap()).unwrap(); + assert_eq!(after.get(after.root().unwrap()).as_dict().unwrap().get(b"Names"), Some(&names)); + assert_eq!(attachments(&after), attachments(&before)); + assert_destination_retained(&after); +} + +#[test] +fn selecting_no_pages_does_not_import_catalog_attachments() { + let mut session = Session::new(); + session.set_javascript(false); + let id = session + .open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None) + .unwrap(); + let before = Document::open(session.save_bytes(id).unwrap()).unwrap(); + session + .apply( + id, + Edit::InsertPagesFrom { + name: "Facilities Compliance Annex.pdf".into(), + bytes: packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true), + pages: Some(Vec::new()), + at: 1, + field_conflicts: FieldConflicts::Rename, + }, + ) + .unwrap(); + assert_eq!(session.get(id).unwrap().info.pages.len(), 1); + let after = Document::open(session.save_bytes(id).unwrap()).unwrap(); + assert_eq!(attachments(&after), attachments(&before)); + assert_destination_retained(&after); +} + +#[test] +fn failed_insert_batch_rolls_back_pages_and_attachments() { + let mut session = Session::new(); + session.set_javascript(false); + let id = session + .open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None) + .unwrap(); + assert!( + session + .apply( + id, + Edit::Batch { + label: "Merge Annex".into(), + edits: vec![ + insert(packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true)), + Edit::RotatePages { pages: vec![99], degrees: 90 }, + ] + } + ) + .is_err() + ); + assert_eq!(session.get(id).unwrap().info.pages.len(), 1); + assert_eq!(session.get(id).unwrap().can_undo(), None); + let result = Document::open(session.save_bytes(id).unwrap()).unwrap(); + assert_eq!(attachments(&result).len(), 1); + assert_destination_retained(&result); +} diff --git a/crates/organize/src/import.rs b/crates/organize/src/import.rs index 588539866a..18b0df6f94 100644 --- a/crates/organize/src/import.rs +++ b/crates/organize/src/import.rs @@ -261,7 +261,8 @@ pub fn import_pages_with( /// under one new bookmark titled `title` (the file's name) at its first inserted page, as Combine /// Files does for each file. That bookmark goes among the top-level bookmarks where the pages went: /// before the first one that points after them. Bookmarks to pages left out lose their destination; -/// a file without bookmarks adds none. +/// a file without bookmarks adds none. Catalog attachments are merged with the destination's +/// attachments, with duplicate name-tree keys renamed, as in Combine Files. pub fn insert_file_pages( dst: &mut Document, src: &Document, @@ -281,6 +282,15 @@ pub fn insert_file_pages( let after = at.min(crate::page_count(dst)?.saturating_sub(imported.pages.len())).saturating_add(imported.pages.len()); insert_file_bookmark(dst, &Mark { title: title.to_string(), page: *first, outline }, after)?; } + if !imported.pages.is_empty() { + let mut incoming = Vec::new(); + collect_attachments(dst, src, &mut incoming)?; + if !incoming.is_empty() { + let mut attachments = attachment_entries(dst); + attachments.append(&mut incoming); + set_attachments(dst, attachments)?; + } + } Ok(ImportOutcome { pages: imported.pages, renamed_fields: imported.renamed_fields }) } @@ -1125,20 +1135,24 @@ pub fn combine_grouped_with(runs: &[Run<'_>], conflicts: FieldConflicts) -> Resu Ok(CombineOutcome { doc: out, renamed_fields }) } -/// Copy a source's document-level attachments (`/Names /EmbeddedFiles`) into `dst`. -fn collect_attachments(dst: &mut Document, src: &Document, out: &mut Vec<(Vec, Object)>) -> Result<(), OrganizeError> { +fn attachment_entries(src: &Document) -> Vec<(Vec, Object)> { let Some(tree) = src .root() .and_then(|r| src.get(r).as_dict().cloned()) .and_then(|c| c.get(b"Names").map(|n| src.resolve(n))) .and_then(|n| n.as_dict().and_then(|d| d.get(b"EmbeddedFiles").cloned())) else { - return Ok(()); + return Vec::new(); }; let mut entries = Vec::new(); name_tree_entries(src, &tree, 0, &mut entries); + entries +} + +/// Copy a source's document-level attachments (`/Names /EmbeddedFiles`) into `dst`. +fn collect_attachments(dst: &mut Document, src: &Document, out: &mut Vec<(Vec, Object)>) -> Result<(), OrganizeError> { let mut copier = Copier::new(src, HashMap::new(), HashMap::new()); - for (k, v) in entries { + for (k, v) in attachment_entries(src) { let v = copier.copy_value(dst, &v, None)?; out.push((k, v)); } @@ -1155,7 +1169,13 @@ fn set_attachments(dst: &mut Document, mut entries: Vec<(Vec, Object)>) -> R let base = k.clone(); let mut n = 2; while !seen.insert(k.clone()) { - *k = [base.as_slice(), format!(" ({n})").as_bytes()].concat(); + *k = base.clone(); + let suffix = format!(" ({n})"); + match base.get(..2) { + Some([0xfe, 0xff]) => k.extend(suffix.encode_utf16().flat_map(u16::to_be_bytes)), + Some([0xff, 0xfe]) => k.extend(suffix.encode_utf16().flat_map(u16::to_le_bytes)), + _ => k.extend_from_slice(suffix.as_bytes()), + } n += 1; } } @@ -1169,14 +1189,10 @@ fn set_attachments(dst: &mut Document, mut entries: Vec<(Vec, Object)>) -> R tree.set(b"Names".to_vec(), Object::Array(names)); let tree = dst.add(tree); let root = dst.root().ok_or(OrganizeError::NoPageTree)?; - dst.update_dict(root, |c| { - let mut n = match c.get(b"Names") { - Some(Object::Dict(d)) => d.clone(), - _ => Dict::new(), - }; - n.set(b"EmbeddedFiles".to_vec(), Object::Ref(tree)); - c.set(b"Names".to_vec(), Object::Dict(n)); - })?; + let catalog = dst.get(root); + let mut names = catalog.as_dict().and_then(|c| c.get(b"Names")).map(|n| dst.resolve(n)).and_then(|n| n.as_dict().cloned()).unwrap_or_default(); + names.set(b"EmbeddedFiles".to_vec(), Object::Ref(tree)); + dst.update_dict(root, |c| c.set(b"Names".to_vec(), Object::Dict(names)))?; Ok(()) } diff --git a/docs/roadmap.md b/docs/roadmap.md index 3dfea674f4..a548553011 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # PdfCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-14 · **Change:** minor (M14: the Italian catalog has every entry the other catalogs had and the code looks up, 2,528 entries; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS) +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-16 · **Change:** patch (M4: Insert from File retains catalog attachments in its undo step; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS) > **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (M2/M6: spot-colour images convert once per pixel value; widget placement and the Fields panel scale with the field count; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-14 · **Change:** minor (M3 candidate: coordinate control clicks on slow frames and coalesced text selection; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-15 · **Change:** minor (M2: sampled functions index a flat table, one image decode serves every zoom level, patch meshes copy less; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS) @@ -109,7 +109,7 @@ total matches the parity estimate. | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. A custom text match that ends on a reconstructed separator stops before the next glyph (#1315). Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings | | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); Lab Bradford adaptation uses LMS white-point ratios, covered by independent neutral/chromatic and direct/Indexed render oracles; inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Literal page-label prefix whitespace is preserved; nine public-inspection cases cover prefix spaces, encodings and empty-prefix controls | | M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). | -| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Missing: page transitions, recovery on the web | +| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Insert from File retains catalog attachments in the same undo step, preserving existing destination name trees and duplicate-key encoding. Missing: page transitions, recovery on the web | | M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Missing: page transitions, recovery on the web M4: Insert-from-file preserves source bookmarks; integration tests retained with current main. | | M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Renderer-creation errors return to the existing OpenGL startup fallback; a real-GPU regression covers errors and device reuse. The underlying x86 DX12 shader compiler failure remains unresolved; see `windows-renderer-startup.md`. With Windows' Animation effects turned off, the wheel scrolls and zooms without easing and egui's animations take no time (`motion.rs`; macOS, Linux and the browser aren't asked yet); Preferences ▸ Animation effects (Use system setting, On, Off) decides it on every platform. | | M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Missing: page transitions, recovery on the web | @@ -179,6 +179,7 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st | Date | Change | Summary | |---|---|---| +| 2026-10-16 | patch | M4: Insert from File retains catalog attachments with native undo/redo; existing name trees and encoded duplicate keys survive. Estimates unchanged. | | 2026-10-15 | minor | M9 #1895: generic appearance rewriting deferred; separate validation overlays preserve original artwork, exports and printing. Baked captions remain unchanged (#79 open). Estimates unchanged. | | 2026-10-12 | minor | M6: valid AcroForm XML element names with original PDF field names preserved; saved-PDF collision and Unicode regressions. Estimates unchanged. | | 2026-10-12 | minor | M6: preserve carriage returns in exported CSV field names and values; saved-PDF round-trip coverage. Estimates unchanged. | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c3d319f94f..2b97b74e99 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2716,8 +2716,8 @@ milestone = "M4" status = "shipped" commands = ["page.insert"] tools = ["page_insert_file"] -evidence = ["crates/organize/src/tests.rs::inserting_pages_from_another_file_is_an_incremental_edit", "crates/organize/src/tests.rs::inserting_a_file_brings_its_bookmarks_under_one_named_after_it", "crates/automation/tests/automation.rs::inserting_a_file_brings_its_bookmarks", "crates/ui-egui/tests/editing.rs::inserting_a_file_goes_after_the_selection_and_undoes", "crates/ui-egui/tests/editing.rs::plus_between_pages_inserts_picked_files_there_in_order"] -notes = "After the selection (toolbar, File menu) or at any gap of the page grid (a + between pages and at both ends); several files at once, in order; images and .txt files are converted first; the inserted pages end up selected. The file's bookmarks come along, collapsed under one named after the file, placed among the document's bookmarks where the pages went (as Combine does per file). The page_insert_file tool takes PDFs only. Missing: choosing which pages of the file to insert in the app; the file's tags (structure tree) are not merged." +evidence = ["crates/organize/src/tests.rs::inserting_pages_from_another_file_is_an_incremental_edit", "crates/organize/src/tests.rs::inserting_a_file_brings_its_bookmarks_under_one_named_after_it", "crates/automation/tests/automation.rs::inserting_a_file_brings_its_bookmarks", "crates/ui-egui/tests/editing.rs::inserting_a_file_goes_after_the_selection_and_undoes", "crates/ui-egui/tests/editing.rs::plus_between_pages_inserts_picked_files_there_in_order", "crates/engine/tests/insert_attachments.rs::inserted_catalog_attachments_follow_native_undo_redo"] +notes = "After the selection (toolbar, File menu) or at any gap of the page grid (a + between pages and at both ends); several files at once, in order; images and .txt files are converted first; the inserted pages end up selected. The file's bookmarks come along, collapsed under one named after the file, placed among the document's bookmarks where the pages went (as Combine does per file). Catalog attachments are merged with the document's existing attachments in the same undo step; colliding names are suffixed without changing their encoding. The page_insert_file tool takes PDFs only. Missing: choosing which pages of the file to insert in the app; the file's tags (structure tree) are not merged." [[feature]] id = "organize.insert-from-clipboard" @@ -3099,9 +3099,9 @@ tier = "P1" milestone = "M4" status = "shipped" commands = [] -tools = [] -evidence = ["crates/organize/src/tests.rs::combine_nests_source_bookmarks_and_keeps_attachments"] -notes = "" +tools = ["doc_combine", "page_insert_file"] +evidence = ["crates/organize/src/tests.rs::combine_nests_source_bookmarks_and_keeps_attachments", "crates/engine/tests/insert_attachments.rs::inserted_catalog_attachments_follow_native_undo_redo", "crates/engine/tests/insert_attachments.rs::inserting_into_a_document_without_attachments_retains_other_names"] +notes = "Also preserved by Insert from File, including native undo/redo and existing destination name trees. This covers catalog EmbeddedFiles, not PDF 2.0 associated-file relationships (AF)." [[feature]] id = "organize.field-name-conflicts" From 27299b213eba98c38c2c05a60552e6ec8396cab8 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:50:09 +0200 Subject: [PATCH 009/216] Fix blank glyphs inside overprinted numbers and word gaps next to taller glyphs in text extraction (#3172) --- crates/render/src/text.rs | 65 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 5054859961..dec2a77453 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -1257,6 +1257,43 @@ fn collide(glyphs: &[&TextGlyph], height: &dyn Fn(usize) -> f32, h: f32, sc: &mu dense } +/// Removes blank glyphs that are mostly covered by the ink of other glyphs on the line. A run of blanks drawn over +/// the digits of an earlier run (a cover headline that overprints a number with spaces) would otherwise sort between +/// the digits and show as spaces inside the number (#3172). A blank that stands in a gap is kept. +fn drop_covered_blanks(glyphs: &[&TextGlyph], placed: &mut Vec, ink: &mut Vec<[f32; 2]>) { + let blank = |i: usize| glyphs[i].text.trim().is_empty(); + if !placed.iter().any(|&i| blank(i)) { + return; + } + ink.clear(); + ink.extend(placed.iter().filter(|&&i| !blank(i)).map(|&i| [glyphs[i].rect[0], glyphs[i].rect[2]])); + ink.sort_by(|a, b| a[0].total_cmp(&b[0])); + // Merge into disjoint intervals. + ink.dedup_by(|cur, prev| { + let overlaps = cur[0] <= prev[1]; + if overlaps { + prev[1] = prev[1].max(cur[1]); + } + overlaps + }); + placed.retain(|&i| { + if !blank(i) { + return true; + } + let (l, r) = (glyphs[i].rect[0], glyphs[i].rect[2]); + if r - l <= 0.0 { + return true; + } + let mut covered = 0.0; + let mut k = ink.partition_point(|iv| iv[1] <= l); + while let Some(iv) = ink.get(k).filter(|iv| iv[0] < r) { + covered += iv[1].min(r) - iv[0].max(l); + k += 1; + } + covered <= 0.5 * (r - l) + }); +} + /// Simplified bidi class of a glyph or word gap (UAX #9: strong L/R, numbers, neutrals). #[derive(Clone, Copy, PartialEq, Eq)] enum Bidi { @@ -1590,9 +1627,14 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec, Vec, Vec) { // `spaces[w]`: a word gap left of the w-th glyph of the segment, by position on the line, not by drawing order // (#1062). Reused by every segment. let mut spaces: Vec = Vec::new(); + let mut ink: Vec<[f32; 2]> = Vec::new(); for b in block_order { for &si in &blocks[b].0 { place_glyphs(&glyphs, &height, &segs[si], &mut sc); + // Only another run can draw over a run's blanks: a single run is left as it is. + if sc.text.len() > 1 { + drop_covered_blanks(&glyphs, &mut sc.placed, &mut ink); + } let h = segs[si].h; // Word gaps relative to this line's typical letter gap (handles tracking). sc.gaps.clear(); @@ -1605,12 +1647,15 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec, Vec, Vec) { for (w, pair) in sc.placed.windows(2).enumerate() { let &[p, c] = pair else { continue }; let gap = glyphs[c].rect[0] - glyphs[p].rect[2]; + // The word gap follows the two glyphs it lies between, not the tallest glyph of the line (#3172). + let hp = height(p).min(height(c)); + let pair_threshold = (typical + hp * WORD_GAP).max(hp * WORD_GAP).min(threshold); let (pt, ct) = (&glyphs[p].text, &glyphs[c].text); let cjk = pt.chars().any(is_cjk) && ct.chars().any(is_cjk) && gap < h * 0.5; let tight_cluster = (pt.chars().any(is_complex) || ct.chars().any(is_complex)) && gap < h * 0.6; let run_start = sc.breaks.binary_search(&c).is_ok(); if let Some(space) = spaces.get_mut(w + 1) { - *space = (gap > threshold || run_start) && !cjk && !tight_cluster && !pt.trim().is_empty() && !ct.trim().is_empty(); + *space = (gap > pair_threshold || run_start) && !cjk && !tight_cluster && !pt.trim().is_empty() && !ct.trim().is_empty(); } } // Right-to-left spans are reversed (visual → logical) with their gaps, and only then is a second copy made. @@ -2113,6 +2158,24 @@ mod tests { assert_eq!(text.find_opts_limited("o", false, false, 10), vec![0..1, 1..2, 2..3, 3..4]); } + fn tall(t: &str, x0: f32, y0: f32, x1: f32, h: f32) -> TextGlyph { + let rect = [x0, y0, x1, y0 + h]; + TextGlyph { text: t.into(), rect, quad: [[x0, y0], [x1, y0], [x1, rect[3]], [x0, rect[3]]], direction: [1.0, 0.0] } + } + + #[test] + fn blanks_under_a_number_and_a_word_gap_next_to_big_digits() { + // Big dark digits, then a smaller sentence drawn over them with blanks where the digits sit. + let mut v = Vec::new(); + for (t, x) in [("5", 0.0), ("0", 6.0), ("1", 100.0), ("4", 106.0)] { + v.push(tall(t, x, 3.0, x + 6.0, 34.0)); + } + for (t, x) in [("F", 16.5), ("R", 22.5), (" ", 100.0), (" ", 106.0), ("C", 130.0), ("D", 136.0)] { + v.push(tall(t, x, 6.0, x + 6.0, 28.0)); + } + assert_eq!(layout(v).plain_text(), "50 FR 14 CD"); + } + fn word(v: &mut Vec, s: &str, x: f32, y: f32, advance: f32) { for (i, c) in s.chars().enumerate() { let x0 = x + i as f32 * advance; 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 010/216] 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 011/216] 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 f9bf81f8001aa258d9e7b58467c07457375d6e5f Mon Sep 17 00:00:00 2001 From: Ahmad Mujahid Date: Sun, 18 Oct 2026 19:45:06 +0400 Subject: [PATCH 012/216] Guard unsafe a11y tag mutations (#3221) --- ROADMAP.md | 1 + crates/a11y/src/alt.rs | 111 +++++++++-- crates/a11y/tests/stm_refusal.rs | 256 ++++++++++++++++++++++++++ crates/automation/src/tools.rs | 4 +- crates/automation/tests/automation.rs | 95 ++++++++++ docs/roadmap.md | 4 +- parity/acrobat-features.toml | 8 +- 7 files changed, 451 insertions(+), 28 deletions(-) create mode 100644 crates/a11y/tests/stm_refusal.rs diff --git a/ROADMAP.md b/ROADMAP.md index 3eb8e6aaa0..ba4baf3c95 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -168,6 +168,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md | 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 | ## Progress log +- **2026-10-18 (M12, #3221 mutation safety):** Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, references to other pages, invalid references and structure children. Synthetic tests check exact preservation, undo history and save/reopen. Form editing and stream-aware readouts stay outside this fix. Estimates unchanged. - **2026-10-15 (M7, Edit text caret):** In a text region that mixes sizes (a 24 pt title over 12 pt lines), the inline editor's caret on a small row was as tall as the region's first size and reached into the row below: egui draws the caret at least one row of the text field's font tall, and that font had the paragraph's first size. The field's font is now half the region's smallest size, so each row's own height decides. Kittest regression; checked in the app on a real document. Estimates unchanged. - **2026-10-16 (M3, #2781):** The Pages panel follows the current page, as Acrobat's page thumbnails do: going to a page whose thumbnail is out of sight (scrolling, Page Down, Go to page, a bookmark) scrolls the panel just enough to show it. A thumbnail already in view, or clicked, leaves the panel where it is, and a page change while the user scrolls the panel or drags thumbnails does not move it. Estimates unchanged. - **2026-10-16 (M12, #1645):** CLI info, text and render use the engine's dynamic XFA layout rather than placeholder pages. Synthetic two-page and encrypted-form regressions cover counts, text, pixels, copy permissions and unchanged input bytes. Estimates unchanged. diff --git a/crates/a11y/src/alt.rs b/crates/a11y/src/alt.rs index 92a5ae8c20..4a16e2f3b1 100644 --- a/crates/a11y/src/alt.rs +++ b/crates/a11y/src/alt.rs @@ -23,6 +23,10 @@ pub enum AltError { Untagged, #[error("object {0} is not a figure")] NotAFigure(u32), + #[error("the tag has child structure elements; mark a leaf tag instead")] + HasChildren, + #[error("this action does not support form streams, other pages or invalid content references")] + UnsupportedContent, #[error("{0}")] Cos(#[from] pdfcraft_cos::CosError), } @@ -38,6 +42,8 @@ pub enum ArtifactError { HasChildren, #[error("the tag has no direct marked content")] NoMarkedContent, + #[error("this action does not support form streams, other pages or invalid content references")] + UnsupportedContent, #[error("the tag has no page")] NoPage, #[error("the tag's marked content was not found on its page")] @@ -140,6 +146,74 @@ fn mcids(d: &Dict) -> Vec { out } +/// Validation for the page-only destructive actions. Readout keeps its existing MCID reader. +enum MutationContentError { + HasChildren, + Unsupported, +} + +fn mutation_mcids(doc: &Document, tag: &Dict, page: Option) -> Result, MutationContentError> { + fn visit( + doc: &Document, + item: &Object, + page: Option, + depth: usize, + remaining: &mut usize, + ancestors: &mut HashSet, + ids: &mut HashSet, + ) -> Result<(), MutationContentError> { + if depth > 64 || *remaining == 0 { + return Err(MutationContentError::Unsupported); + } + *remaining -= 1; + match item { + Object::Int(id) if *id >= 0 => { + ids.insert(*id); + } + Object::Array(items) => { + for item in items { + visit(doc, item, page, depth + 1, remaining, ancestors, ids)?; + } + } + Object::Ref(reference) => { + if reference.generation != doc.generation(reference.num) || !ancestors.insert(*reference) { + return Err(MutationContentError::Unsupported); + } + let result = visit(doc, &doc.get(*reference), page, depth + 1, remaining, ancestors, ids); + ancestors.remove(reference); + result?; + } + Object::Dict(dict) => { + if dict.contains(b"S") { + // Retiring a parent also removes descendants whose content was not checked. + return Err(MutationContentError::HasChildren); + } + // Presence matters: even a malformed stream qualifier must not become a page ID. + // Never resolve these targets; this action does not support form streams. + if dict.contains(b"Stm") || dict.contains(b"StmOwn") || dict.name(b"Type") != Some(b"MCR") { + return Err(MutationContentError::Unsupported); + } + if let Some(explicit_page) = dict.get(b"Pg") { + let explicit_page = explicit_page.as_ref().ok_or(MutationContentError::Unsupported)?; + if Some(explicit_page) != page { + return Err(MutationContentError::Unsupported); + } + } + let id = dict.get(b"MCID").and_then(Object::as_int).filter(|id| *id >= 0).ok_or(MutationContentError::Unsupported)?; + ids.insert(id); + } + _ => return Err(MutationContentError::Unsupported), + } + Ok(()) + } + + let mut ids = HashSet::new(); + if let Some(kids) = tag.get(b"K") { + visit(doc, kids, page, 0, &mut 4096, &mut HashSet::new(), &mut ids)?; + } + Ok(ids) +} + /// The page's named property lists (`/Resources /Properties`), which a `BDC` can name instead of /// writing its property list inline. fn page_properties(doc: &Document, page: &Dict) -> Dict { @@ -369,13 +443,21 @@ fn artifact_marked_content(doc: &mut Document, page: &pdfcraft_model::Page, ids: } /// Decorative figure: its marked content on the page becomes an artifact, and the element -/// leaves the structure tree (and the parent tree). +/// leaves the structure tree (and the parent tree). Form references and structure children refuse +/// before the document changes. pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError> { let d = check_figure(doc, obj)?; - let ids: HashSet = mcids(&d).into_iter().collect(); let pages = pdfcraft_model::pages(doc); let pg = d.get(b"Pg").and_then(Object::as_ref).or_else(|| elements(doc).into_iter().find(|e| e.object == obj).and_then(|e| e.page)); - if let Some(page) = pg.and_then(|p| pages.iter().find(|x| x.obj == p)).filter(|_| !ids.is_empty()) + let page = pg.and_then(|p| pages.iter().find(|page| page.obj == p)); + let ids = mutation_mcids(doc, &d, page.map(|page| page.obj)).map_err(|error| match error { + MutationContentError::HasChildren => AltError::HasChildren, + MutationContentError::Unsupported => AltError::UnsupportedContent, + })?; + if !ids.is_empty() && page.is_none() { + return Err(AltError::UnsupportedContent); + } + if let Some(page) = page.filter(|_| !ids.is_empty()) && artifact_marked_content(doc, page, &ids)? { // The parent tree no longer points those ids at the figure. @@ -402,16 +484,17 @@ pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError> /// Mark a leaf structure tag's directly owned marked content as an artifact. /// /// This deliberately refuses a tag with child structure elements. Converting a parent would -/// otherwise silently discard semantic descendants. The visible page content is preserved: each +/// otherwise silently discard semantic descendants. Form references and invalid page ownership +/// also refuse before the document changes. The visible page content is preserved: each /// matching marked-content sequence changes from `BDC` with an MCID to `/Artifact BMC`. pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), ArtifactError> { tree_root(doc).ok_or(ArtifactError::Untagged)?; let elements = elements(doc); let Some(element) = elements.iter().find(|e| e.object == obj) else { return Err(ArtifactError::NotATag(obj.num)) }; - if has_child_structure(doc, &element.dict) { - return Err(ArtifactError::HasChildren); - } - let ids: HashSet = mcids(&element.dict).into_iter().collect(); + let ids = mutation_mcids(doc, &element.dict, element.page).map_err(|error| match error { + MutationContentError::HasChildren => ArtifactError::HasChildren, + MutationContentError::Unsupported => ArtifactError::UnsupportedContent, + })?; if ids.is_empty() { return Err(ArtifactError::NoMarkedContent); } @@ -450,18 +533,6 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact Ok(()) } -fn has_child_structure(doc: &Document, tag: &Dict) -> bool { - fn child(doc: &Document, item: &Object) -> bool { - match item { - Object::Array(items) => items.iter().any(|item| child(doc, item)), - Object::Ref(r) => doc.get(*r).as_dict().is_some_and(|d| d.contains(b"S")), - Object::Dict(d) => d.contains(b"S"), - _ => false, - } - } - tag.get(b"K").is_some_and(|items| child(doc, items)) -} - fn remove_from_parent(doc: &mut Document, parent: ObjRef, obj: ObjRef) -> Result<(), ArtifactError> { let kids = doc.get(parent).as_dict().and_then(|p| p.get(b"K").cloned()).ok_or(ArtifactError::NoParent)?; let replacement = match kids { diff --git a/crates/a11y/tests/stm_refusal.rs b/crates/a11y/tests/stm_refusal.rs new file mode 100644 index 0000000000..3b55231f01 --- /dev/null +++ b/crates/a11y/tests/stm_refusal.rs @@ -0,0 +1,256 @@ +//! Contributor-original synthetic stream collision; no external document assets. +use pdfcraft_cos::{Document, ObjRef, Object}; +use std::sync::Arc; + +fn collision_with(kids: &str, extra: &[&str]) -> Document { + let page = "/Figure <> BDC 10 10 20 20 re f EMC\nq /Form Do Q"; + let form = "/Figure <> BDC 0 0 5 5 re f EMC"; + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /StructParents 0 /Resources << /XObject << /Form 10 0 R >> >> >>" + .into(), + format!("<< /Length {} >>\nstream\n{}\nendstream", page.len(), page), + "<< /Type /StructTreeRoot /K 6 0 R /ParentTree 9 0 R >>".into(), + "<< /Type /StructElem /S /Document /P 5 0 R /K [7 0 R 8 0 R] >>".into(), + "<< /Type /StructElem /S /Figure /Pg 3 0 R /P 6 0 R /K 0 /Alt (Page figure) >>".into(), + format!("<< /Type /StructElem /S /Figure /Pg 3 0 R /P 6 0 R /K {kids} /Alt (Form figure) >>"), + "<< /Nums [0 [7 0 R] 1 8 0 R] >>".into(), + format!("<< /Type /XObject /Subtype /Form /BBox [0 0 5 5] /StructParents 1 /Length {} >>\nstream\n{}\nendstream", form.len(), form), + ]; + let extra_pages = extra + .iter() + .enumerate() + .filter(|(_, object)| object.contains("/Type /Page ")) + .map(|(index, _)| format!("{} 0 R", index + 11)) + .collect::>(); + if !extra_pages.is_empty() { + objects[1] = format!("<< /Type /Pages /Kids [3 0 R {}] /Count {} >>", extra_pages.join(" "), extra_pages.len() + 1); + } + objects.extend(extra.iter().map(|s| (*s).to_string())); + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, object) in objects.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", i + 1, object).as_bytes()); + } + let start = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); + for offset in offsets { + bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n", objects.len() + 1, start).as_bytes()); + Document::open(Arc::new(bytes)).unwrap() +} + +fn stream(doc: &Document, number: u32) -> Vec { + let object = doc.get(ObjRef::new(number, 0)); + let Object::Stream(s) = &*object else { panic!("stream required") }; + s.decoded().unwrap() +} + +fn run(decorative: bool) { + let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >>", &[]); + assert!(!doc.is_modified()); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let original_streams = [stream(&doc, 4), stream(&doc, 10)]; + let error = mutate(&mut doc, decorative, 8).unwrap_err(); + assert!(error.contains("form"), "useful error: {error}"); + assert!(!doc.is_modified()); + assert_eq!([stream(&doc, 4), stream(&doc, 10)], original_streams); + assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before); + assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::>(), [6, 7, 8]); +} + +#[test] +fn decorative_refuses_form_collision() { + run(true); +} +#[test] +fn artifact_refuses_form_collision() { + run(false); +} + +fn mutate(doc: &mut Document, decorative: bool, number: u32) -> Result<(), String> { + if decorative { + pdfcraft_a11y::mark_decorative(doc, ObjRef::new(number, 0)).map_err(|e| e.to_string()) + } else { + pdfcraft_a11y::mark_tag_artifact(doc, ObjRef::new(number, 0)).map_err(|e| e.to_string()) + } +} + +fn page_owned(kids: &str, extra: &[&str]) -> Document { + let mut doc = collision_with(kids, extra); + let page_kids = doc.get(ObjRef::new(8, 0)).as_dict().unwrap().get(b"K").unwrap().clone(); + let original = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >>", &[]); + let form_kids = original.get(ObjRef::new(8, 0)).as_dict().unwrap().get(b"K").unwrap().clone(); + doc.update_dict(ObjRef::new(7, 0), |d| d.set(b"K".to_vec(), page_kids)).unwrap(); + doc.update_dict(ObjRef::new(8, 0), |d| d.set(b"K".to_vec(), form_kids)).unwrap(); + // Reopen an incremental save to keep the fixture's object IDs and start from a clean state. + Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap() +} + +#[test] +fn unsupported_owned_references_refuse_without_changing_document_or_saved_data() { + let other_page_content = "/P <> BDC 40 40 5 5 re f EMC"; + let other_page_stream = format!("<< /Length {} >>\nstream\n{other_page_content}\nendstream", other_page_content.len()); + let cases: Vec<(&str, Vec<&str>)> = vec![ + ("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", vec![]), + ("<< /Type /MCR /MCID 2 /Stm 10 0 R >>", vec![]), + ("<< /Type /MCR /MCID 0 /Stm null >>", vec![]), + ("<< /Type /MCR /MCID 0 /Stm 99 0 R >>", vec![]), + ("<< /Type /MCR /MCID 0 /Stm (invalid) >>", vec![]), + ("<< /Type /MCR /MCID 0 /StmOwn 10 0 R >>", vec![]), + ("<< /Type /MCR /MCID 0 /StmOwn null >>", vec![]), + ("11 0 R", vec!["<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]), + ("11 0 R", vec!["12 0 R", "<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]), + ("[0 << /S /Figure /K 0 >>]", vec![]), + ("[0 11 0 R]", vec!["<< /S /Figure /K 0 >>"]), + ("[0 << /Type /MCR /MCID 0 /Stm 10 0 R >>]", vec![]), + ("11 0 R", vec!["[0 12 0 R]", "<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]), + ("[0 [11 0 R]]", vec!["<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]), + ("[0 << /Type /MCR /MCID 0 /Pg 99 0 R >>]", vec![]), + ("<< /Type /MCR /MCID 0 /Pg null >>", vec![]), + ("<< /Type /MCR /MCID 0 /Pg 3 1 R >>", vec![]), + ( + "[0 << /Type /MCR /MCID 0 /Pg 11 0 R >>]", + vec!["<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 12 0 R >>", &other_page_stream], + ), + ("[0 99 0 R]", vec![]), + ("[0 11 1 R]", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ("[0 11 0 R]", vec!["[11 0 R]"]), + ("[0 11 0 R]", vec!["<< /S /Figure /K << /Type /MCR /MCID 0 /Stm 10 0 R >> >>"]), + ("11 0 R", vec!["[12 0 R]", "<< /S /Figure /K << /Type /MCR /MCID 0 /Stm 10 0 R >> >>"]), + ]; + for decorative in [true, false] { + for (kids, extra) in &cases { + let mut doc = collision_with(kids, extra); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let original_streams = [stream(&doc, 4), stream(&doc, 10)]; + let original_objects: Vec<_> = (1..=10).map(|i| doc.get(ObjRef::new(i, 0))).collect(); + let original_alts = pdfcraft_a11y::figures(&doc).into_iter().map(|figure| figure.alt).collect::>(); + let error = match mutate(&mut doc, decorative, 8) { + Ok(()) => panic!("decorative={decorative} K={kids} must refuse"), + Err(error) => error, + }; + assert!( + error.contains("form") || error.contains("unsupported") || error.contains("invalid") || error.contains("child structure elements"), + "ownership refusal needs a useful reason: {error}" + ); + assert!(!doc.is_modified(), "refusal must not create dirty state: {kids}"); + assert_eq!([stream(&doc, 4), stream(&doc, 10)], original_streams, "{kids}"); + assert_eq!( + (1..=10).map(|i| doc.get(ObjRef::new(i, 0))).collect::>(), + original_objects, + "tags, Alt and ParentTree stay unchanged: {kids}" + ); + let saved = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + assert_eq!(saved, before, "saved object graph remains exact: {kids}"); + let reopened = Document::open(Arc::new(saved)).unwrap(); + let page = &pdfcraft_model::pages(&reopened)[0]; + let Object::Stream(page_stream) = &*reopened.resolve(page.dict.get(b"Contents").unwrap()) else { panic!("page stream") }; + assert_eq!(page_stream.decoded().unwrap(), original_streams[0]); + let resources = reopened.dict(page.dict.get(b"Resources").unwrap()).unwrap(); + let xobjects = reopened.dict(resources.get(b"XObject").unwrap()).unwrap(); + let Object::Stream(form_stream) = &*reopened.resolve(xobjects.get(b"Form").unwrap()) else { panic!("form stream") }; + assert_eq!(form_stream.decoded().unwrap(), original_streams[1]); + assert_eq!( + pdfcraft_a11y::figures(&reopened).into_iter().map(|figure| figure.alt).collect::>(), + original_alts, + "all original figures, including children, survive: {kids}" + ); + } + } +} + +#[test] +fn page_only_owned_references_still_become_artifacts() { + let cases: Vec<(&str, Vec<&str>)> = vec![ + ("0", vec![]), + ("<< /Type /MCR /MCID 0 /Pg 3 0 R >>", vec![]), + ("11 0 R", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ("11 0 R", vec!["12 0 R", "<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ("[11 0 R 11 0 R]", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ("11 0 R", vec!["[12 0 R]", "<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ]; + for decorative in [true, false] { + for (kids, extra) in &cases { + let mut doc = page_owned(kids, extra); + let original_form = stream(&doc, 10); + mutate(&mut doc, decorative, 7).unwrap(); + let page = pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").unwrap().as_ref().unwrap(); + let content = String::from_utf8(stream(&doc, page.num)).unwrap(); + assert!(content.contains("/Artifact BMC"), "page content changes for {kids}: {content}"); + assert!(!content.contains("/MCID")); + assert_eq!(stream(&doc, 10), original_form); + assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::>(), [6, 8]); + } + } +} + +#[test] +fn ordinary_alt_edit_remains_available_for_a_stream_figure() { + let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", &[]); + let original = [stream(&doc, 4), stream(&doc, 10)]; + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some(" Blue square ")).unwrap(); + assert_eq!(pdfcraft_a11y::figures(&doc)[1].alt.as_deref(), Some("Blue square")); + assert_eq!([stream(&doc, 4), stream(&doc, 10)], original); +} + +#[test] +fn refusal_preserves_preexisting_document_changes() { + for decorative in [true, false] { + let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", &[]); + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some("Saved later")).unwrap(); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let modified = doc.modified_objects(); + assert!(mutate(&mut doc, decorative, 8).is_err()); + assert!(doc.is_modified()); + assert_eq!(doc.modified_objects(), modified); + assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before); + assert_eq!(pdfcraft_a11y::figures(&doc)[1].alt.as_deref(), Some("Saved later")); + } +} + +#[test] +fn owned_reference_walk_accepts_limits_and_refuses_excess_depth_or_work() { + // The root ownership array counts as one visit. Each nested array adds one depth level. + let cases = [ + (format!("[{}]", "0 ".repeat(4095)), true), + (format!("[{}]", "0 ".repeat(4096)), false), + (format!("{}0{}", "[".repeat(64), "]".repeat(64)), true), + (format!("{}0{}", "[".repeat(65), "]".repeat(65)), false), + ]; + for decorative in [true, false] { + for (kids, supported) in &cases { + let mut doc = page_owned(kids, &[]); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let result = mutate(&mut doc, decorative, 7); + assert_eq!(result.is_ok(), *supported, "decorative={decorative}, result={result:?}"); + if *supported { + let page = pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").unwrap().as_ref().unwrap(); + assert!(String::from_utf8(stream(&doc, page.num)).unwrap().contains("/Artifact BMC")); + assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::>(), [6, 8]); + } else { + assert!(!doc.is_modified()); + assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before); + } + } + } +} + +#[test] +fn decorative_refuses_matching_invalid_element_and_content_pages() { + for page in [ObjRef::new(99, 0), ObjRef::new(3, 1)] { + for kids in [format!("<< /Type /MCR /MCID 0 /Pg {page} >>"), "0".into(), "<< /Type /MCR /MCID 0 >>".into()] { + let mut doc = collision_with(&kids, &[]); + doc.update_dict(ObjRef::new(8, 0), |d| d.set(b"Pg".to_vec(), Object::Ref(page))).unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let error = pdfcraft_a11y::mark_decorative(&mut doc, ObjRef::new(8, 0)).unwrap_err(); + assert!(error.to_string().contains("form")); + assert!(!doc.is_modified()); + assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before); + } + } +} diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 69d1eda217..7d24e304e2 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1000,7 +1000,7 @@ pub fn tools() -> Vec { .ro() .cmd("a11y.alt_text") .with(schema(json!({ "doc": doc() }), &["doc"])), - t("accessibility_set_alt", "Set alternate text", "Set a figure's alternate text (alt; empty or omitted clears it), or mark it decorative (decorative: true: its content becomes an artifact and the figure leaves the tags). figure is a number from accessibility_figures. Returns the figures. Undoable.") + t("accessibility_set_alt", "Set alternate text", "Set a figure's alternate text (alt; empty or omitted clears it), or mark it decorative (decorative: true: its content becomes an artifact and the figure leaves the tags). Decorative actions reject form streams, other-page or invalid content references, and tags with structure children before changing the document. figure is a number from accessibility_figures. Returns the figures. Undoable.") .cmd("a11y.alt_text") .with(schema(json!({ "doc": doc(), "figure": { "type": "integer", "minimum": 1 }, "alt": { "type": "string" }, "decorative": { "type": "boolean" } }), &["doc", "figure"])), t("accessibility_tags", "List structure tags", "List reachable indirect structure tags in document order with PDF object number, generation, nearest indirect parent, depth, page, type, title, actual text, alternate text and language, one page at a time: count is how many tags match, next the offset of the following page (null at the end). types, pages and max_depth keep only some tags. Inline tag dictionaries have no stable object reference and are not listed.") @@ -1028,7 +1028,7 @@ pub fn tools() -> Vec { "property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language"] }, "value": { "type": "string" }, }), &["doc", "object", "generation", "property"])), - t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Tags with child structure elements, no direct marked content, or content not found on its page are rejected. Undoable.") + t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Form streams, other-page or invalid content references, and structure children are rejected before changing the document. Tags with no direct marked content or content not found on its page are also rejected. Undoable.") .with(schema(json!({ "doc": doc(), "object": { "type": "integer", "minimum": 1 }, "generation": { "type": "integer", "minimum": 0, "maximum": 65535 }, diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs index 6a348e0d8c..f1b066430f 100644 --- a/crates/automation/tests/automation.rs +++ b/crates/automation/tests/automation.rs @@ -2435,6 +2435,101 @@ trailer << /Root 1 0 R >> assert!(matches!(a.call("accessibility_mark_tag_artifact", &json!({ "doc": doc, "object": 6, "generation": 0 })), Err(ToolError::Failed(_)))); } +#[test] +fn stream_tag_mutation_refusal_preserves_document_history_and_saved_content() { + use pdfcraft_cos::{Document as CosDocument, Object, SaveOptions}; + use std::sync::Arc; + + let dir = workdir("a11y-stm-refusal"); + // Contributor-original page and form use separate MCID 0 namespaces. + let page = "/Figure <> BDC 10 10 20 20 re f EMC q /Fm Do Q"; + let form = "/Figure <> BDC 0 0 5 5 re f EMC"; + let source = format!( + "%PDF-1.7\n\ +1 0 obj << /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >> endobj\n\ +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\ +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /StructParents 0 /Resources << /XObject << /Fm 10 0 R >> >> >> endobj\n\ +4 0 obj << /Length {} >> stream\n{page}\nendstream endobj\n\ +5 0 obj << /Type /StructTreeRoot /K 6 0 R /ParentTree 9 0 R >> endobj\n\ +6 0 obj << /S /Document /P 5 0 R /K [7 0 R 8 0 R] >> endobj\n\ +7 0 obj << /S /Figure /P 6 0 R /Pg 3 0 R /K 0 /Alt (Page figure) >> endobj\n\ +8 0 obj << /S /Figure /P 6 0 R /Pg 3 0 R /K << /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >> /Alt (Form figure) >> endobj\n\ +9 0 obj << /Nums [0 [7 0 R] 1 8 0 R] >> endobj\n\ +10 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 5 5] /StructParents 1 /Length {} >> stream\n{form}\nendstream endobj\n\ +trailer << /Root 1 0 R >>\n%%EOF", + page.len(), + form.len() + ); + let synthetic = CosDocument::open(Arc::new(source.into_bytes())).unwrap(); + let source = pdfcraft_cos::write_full(&synthetic, &SaveOptions::default()).unwrap(); + std::fs::write(dir.join("stm.pdf"), source).unwrap(); + + for dirty in [false, true] { + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({"path":"stm.pdf"}))["doc"].as_u64().unwrap(); + let figures = ok(&mut a, "accessibility_figures", json!({"doc":doc})); + let figure = figures["figures"].as_array().unwrap().iter().find(|f| f["alt"] == "Form figure").unwrap()["figure"].as_u64().unwrap(); + if dirty { + ok(&mut a, "accessibility_set_alt", json!({"doc":doc,"figure":figure,"alt":"First"})); + ok(&mut a, "accessibility_set_alt", json!({"doc":doc,"figure":figure,"alt":"Second"})); + ok(&mut a, "edit_undo", json!({"doc":doc})); + } + let before = ok(&mut a, "doc_info", json!({"doc":doc}))["document"].clone(); + assert_eq!(before["dirty"], dirty); + assert_eq!(before["undo"].is_string(), dirty); + assert_eq!(before["redo"].is_string(), dirty); + let tags = ok(&mut a, "accessibility_tags", json!({"doc":doc})); + let figures = ok(&mut a, "accessibility_figures", json!({"doc":doc})); + for (tool, args) in [ + ("accessibility_set_alt", json!({"doc":doc,"figure":figure,"decorative":true})), + ("accessibility_mark_tag_artifact", json!({"doc":doc,"object":figure,"generation":0})), + ] { + let Err(ToolError::Failed(message)) = a.call(tool, &args) else { panic!("{tool} must refuse form-owned content") }; + assert!(message.contains("form"), "useful unsupported-content reason: {message}"); + assert_eq!(ok(&mut a, "doc_info", json!({"doc":doc}))["document"], before); + assert_eq!(ok(&mut a, "accessibility_tags", json!({"doc":doc})), tags); + assert_eq!(ok(&mut a, "accessibility_figures", json!({"doc":doc})), figures); + } + if dirty { + ok(&mut a, "edit_redo", json!({"doc":doc})); + let figs = ok(&mut a, "accessibility_figures", json!({"doc":doc})); + assert_eq!(figs["figures"][1]["alt"], "Second"); + ok(&mut a, "edit_undo", json!({"doc":doc})); + assert_eq!(ok(&mut a, "accessibility_figures", json!({"doc":doc})), figures); + } + let name = if dirty { "dirty.pdf" } else { "clean.pdf" }; + ok(&mut a, "doc_save", json!({"doc":doc,"path":name,"full":true})); + let saved = CosDocument::open(Arc::new(std::fs::read(dir.join(name)).unwrap())).unwrap(); + let saved_figures = pdfcraft_engine::a11y::figures(&saved); + assert_eq!(saved_figures.len(), 2); + assert_eq!(saved_figures[0].alt.as_deref(), Some("Page figure")); + assert_eq!(saved_figures[1].alt.as_deref(), Some(if dirty { "First" } else { "Form figure" })); + assert_eq!(pdfcraft_engine::a11y::tags(&saved).len(), 3); + let catalog = saved.get(saved.root().unwrap()); + let root = saved.dict(catalog.as_dict().unwrap().get(b"StructTreeRoot").unwrap()).unwrap(); + let tree = saved.dict(root.get(b"ParentTree").unwrap()).unwrap(); + assert_eq!( + tree.get(b"Nums"), + Some(&Object::Array(vec![ + Object::Int(0), + Object::Array(vec![Object::Ref(saved_figures[0].obj)]), + Object::Int(1), + Object::Ref(saved_figures[1].obj) + ])) + ); + let page_dict = saved.get(saved_figures[0].obj); + let page_ref = page_dict.as_dict().unwrap().get(b"Pg").unwrap(); + let page_dict = saved.dict(page_ref).unwrap(); + let Object::Stream(page_stream) = &*saved.resolve(page_dict.get(b"Contents").unwrap()) else { panic!("page content") }; + assert_eq!(page_stream.decoded().unwrap(), page.as_bytes()); + let resources = saved.dict(page_dict.get(b"Resources").unwrap()).unwrap(); + let xobjects = saved.dict(resources.get(b"XObject").unwrap()).unwrap(); + let Object::Stream(form_stream) = &*saved.resolve(xobjects.get(b"Fm").unwrap()) else { panic!("form content") }; + assert_eq!(form_stream.decoded().unwrap(), form.as_bytes()); + } + std::fs::remove_dir_all(dir).unwrap(); +} + #[test] fn accessibility_review_record_compares_two_versions_without_changing_them() { let dir = workdir("a11y-review-record"); diff --git a/docs/roadmap.md b/docs/roadmap.md index c76936a7ef..c3c200579d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -143,9 +143,9 @@ total matches the parity estimate. | M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.
Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 | | M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).
Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import | | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA | -| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA | +| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, references to other pages, invalid references and structure children. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. | -| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645). | +| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, references to other pages, invalid references and structure children. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645). | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. | | M14 | 1.0 polish: performance, localization, installers | 120–250 | 15% | 80–150 | Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, strict catalog tests); every dialog, panel and notice goes through `tl!`. Catalogs of ≈ 2,000–2,140 entries for Japanese, Simplified and Traditional Chinese, Russian, Bulgarian, German, Spanish, French, Telugu, Hungarian, Ukrainian, Brazilian Portuguese and Arabic (logical-order catalog put into display order; layout not yet mirrored); Czech covers the menus. Italian has 2,528 entries: every key of the other catalogs that the code looks up. Signed and notarized macOS builds, signed Windows installers (x64, x86, ARM64), AppImage, deb, rpm, Flatpak and FreeBSD packages. #307 (bounded large-PDF memory): shared resource indexes and parser metadata, lazy inspection, bounded caches; a 9,156-page file inspects in ≈ 1.8 s at ≈ 500 MiB instead of exceeding 10 GiB. Edits let go of the previous working file before writing the next (a 1 GiB file peaks at two copies while editing, not three; gap 13). Shortcut display uses localized modifier/key names across menus, toolbar, palette, Help and tooltips (#496). Lithuanian adds a 2,578-entry catalog and date names, reviewed by a native-speaking contributor. Validated candidate (macOS raster probe; Windows runtime unverified): the Windows policy changes only embedded JetBrains Mono; horizontal alpha-edge energy per ink improves 2.78%, 3.87% and 1.59% at 100%, 125% and 150%, and is down 0.79% at 200%. Inter is pixel-identical; layout hashes, glyph coverage and the 8 MiB atlas are unchanged. Timing and RSS ranges overlap, with no improvement claimed. Estimates unchanged. Candidate #2383 clamps GPU requests to supported limits while retaining the adapter texture extent; synthetic V3D/downlevel and Windows GPU-required tests pass, but Raspberry Pi startup is unverified. Estimates unchanged. Missing: a right-to-left layout, a Chinese UI face in releases, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation Linux/Unix UI fallback fonts also use Fontconfig directories, including Nix store paths, with bounded discovery and the existing candidate allowlist; relative includes and digit-prefixed config filtering have isolated regressions. | | M14 | 1.0 polish: performance, localization, installers | 120–250 | 15% | 80–150 | Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, strict catalog tests); every dialog, panel and notice goes through `tl!`. Catalogs of ≈ 2,000–2,140 entries for Japanese, Simplified and Traditional Chinese, Russian, Bulgarian, German, Spanish, French, Telugu, Hungarian, Ukrainian, Brazilian Portuguese and Arabic (logical-order catalog put into display order; layout not yet mirrored); Czech covers the menus. Italian has 2,528 entries: every key of the other catalogs that the code looks up. Signed and notarized macOS builds, signed Windows installers (x64, x86, ARM64), AppImage, deb, rpm, Flatpak and FreeBSD packages. #307 (bounded large-PDF memory): shared resource indexes and parser metadata, lazy inspection, bounded caches; a 9,156-page file inspects in ≈ 1.8 s at ≈ 500 MiB instead of exceeding 10 GiB. Edits let go of the previous working file before writing the next (a 1 GiB file peaks at two copies while editing, not three; gap 13). Shortcut display uses localized modifier/key names across menus, toolbar, palette, Help and tooltips (#496). Lithuanian adds a 2,578-entry catalog and date names, reviewed by a native-speaking contributor. Validated candidate (macOS raster probe; Windows runtime unverified): the Windows policy changes only embedded JetBrains Mono; horizontal alpha-edge energy per ink improves 2.78%, 3.87% and 1.59% at 100%, 125% and 150%, and is down 0.79% at 200%. Inter is pixel-identical; layout hashes, glyph coverage and the 8 MiB atlas are unchanged. Timing and RSS ranges overlap, with no improvement claimed. Estimates unchanged. Missing: a right-to-left layout, a Chinese UI face in releases, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation XDG desktops use the configuration base for preferences with non-overwriting migration and original-data preservation (#1395). | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index d8fbe77ddf..8390b06418 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -8972,8 +8972,8 @@ milestone = "M12" status = "partial" commands = ["a11y.tags"] tools = ["accessibility_mark_tag_artifact"] -evidence = ["crates/a11y/src/tests.rs::marking_a_leaf_tag_as_an_artifact_preserves_appearance_and_structure_integrity", "crates/automation/tests/automation.rs::marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved", "crates/ui-egui/tests/accessibility.rs::tags_panel_marks_a_leaf_tag_as_an_artifact"] -notes = "Tags panel and automation can retire a reachable indirect leaf tag that owns direct MCIDs: its visible page content remains but becomes /Artifact and the parent-tree references are cleared. Tags with structural children, non-MCID content, missing pages or ambiguous parents are refused. Arbitrary painted-content selection, direct structure dictionaries and removing whole tagged subtrees remain unsupported." +evidence = ["crates/a11y/src/tests.rs::marking_a_leaf_tag_as_an_artifact_preserves_appearance_and_structure_integrity", "crates/automation/tests/automation.rs::marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved", "crates/ui-egui/tests/accessibility.rs::tags_panel_marks_a_leaf_tag_as_an_artifact", "crates/a11y/tests/stm_refusal.rs::unsupported_owned_references_refuse_without_changing_document_or_saved_data", "crates/automation/tests/automation.rs::stream_tag_mutation_refusal_preserves_document_history_and_saved_content"] +notes = "Tags panel and automation can retire a reachable indirect leaf tag that owns direct MCIDs: its visible page content remains but becomes /Artifact and the parent-tree references are cleared. Tags with structural children, non-MCID content, missing pages or ambiguous parents are refused. Arbitrary painted-content selection, direct structure dictionaries and removing whole tagged subtrees remain unsupported. Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, references to other pages, invalid references and structure children. Figure locations and tag content reads still assume page content." [[feature]] id = "a11y.find-untagged" @@ -9008,8 +9008,8 @@ milestone = "M12" status = "shipped" commands = ["a11y.alt_text"] tools = ["accessibility_figures", "accessibility_set_alt"] -evidence = ["crates/a11y/src/tests.rs::figures_are_listed_with_their_alt_text_and_place", "crates/a11y/src/tests.rs::setting_alt_text_and_marking_decorative", "crates/ui-egui/tests/accessibility.rs::setting_alternate_text_figure_by_figure", "crates/automation/tests/automation.rs::accessibility_check_report_and_fixes_through_tools"] -notes = "Set Alternate Text dialog: each tagged figure (role map honoured) with a preview of where it is drawn, its alternate text, Decorative figure (content becomes /Artifact, element leaves the tags and parent tree), Previous/Next, Save & Close as one undo step" +evidence = ["crates/a11y/src/tests.rs::figures_are_listed_with_their_alt_text_and_place", "crates/a11y/src/tests.rs::setting_alt_text_and_marking_decorative", "crates/ui-egui/tests/accessibility.rs::setting_alternate_text_figure_by_figure", "crates/automation/tests/automation.rs::accessibility_check_report_and_fixes_through_tools", "crates/a11y/tests/stm_refusal.rs::unsupported_owned_references_refuse_without_changing_document_or_saved_data", "crates/automation/tests/automation.rs::stream_tag_mutation_refusal_preserves_document_history_and_saved_content"] +notes = "Set Alternate Text dialog: each tagged figure (role map honoured) with a preview of where it is drawn, its alternate text, Decorative figure (content becomes /Artifact, element leaves the tags and parent tree), Previous/Next, Save & Close as one undo step. Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, references to other pages, invalid references and structure children. Figure locations and tag content reads still assume page content." [[feature]] id = "a11y.alt-text-suggestions" 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 013/216] 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 9092945df14499b6c8a4e6103a20bef0e8d4959c Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Mon, 19 Oct 2026 12:25:17 -0600 Subject: [PATCH 014/216] fix(edit): unlink unused image resources on delete Fixes #3511 by pruning unreferenced resource names after deleting or replacing images, including aliases. Keep resources used by other placements, sibling pages, or nested Forms that inherit page resources. --- crates/edit/src/images.rs | 104 ++++++++++++++++++++++++ crates/edit/src/tests.rs | 164 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 268 insertions(+) diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rs index e90d8e4f15..2b55bd0909 100644 --- a/crates/edit/src/images.rs +++ b/crates/edit/src/images.rs @@ -108,6 +108,67 @@ fn xobjects(doc: &Document, page: &Dict) -> Dict { .unwrap_or_default() } +/// Whether a page resource name is used by the page or by a reachable Form that inherits the +/// page's resources. A Form with its own `/Resources` has an independent namespace; forms without +/// one inherit the caller's. On an unreadable or over-budget Form, preserve the resource. +fn resource_used_by_inheriting_forms(doc: &Document, ops: &[Op], resources: &Dict, name: &[u8], budget: &mut usize) -> bool { + fn walk( + doc: &Document, + ops: &[Op], + resources: &Dict, + name: &[u8], + depth: usize, + budget: &mut usize, + path: &mut std::collections::HashSet, + ) -> bool { + if depth > 32 || *budget == 0 { + return true; + } + let xo = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default(); + for op in ops.iter().filter(|op| op.is("Do")) { + let Some(call_name) = op.name(0) else { + continue; + }; + if call_name == name { + return true; + } + let Some(resource) = xo.get(call_name) else { + continue; + }; + let resolved = doc.resolve(resource); + let Object::Stream(stream) = &*resolved else { + continue; + }; + let Some(reference) = resource.as_ref() else { + if stream.dict.name(b"Subtype") == Some(b"Form") && !stream.dict.contains(b"Resources") { + return true; + } + continue; + }; + if stream.dict.name(b"Subtype") != Some(b"Form") || stream.dict.contains(b"Resources") { + continue; + } + if !path.insert(reference) { + return true; + } + *budget -= 1; + let decoded = match stream.decoded() { + Ok(decoded) => decoded, + Err(_) => return true, + }; + let nested_ops = parse(&decoded).ops; + let used = walk(doc, &nested_ops, resources, name, depth + 1, budget, path); + path.remove(&reference); + if used { + return true; + } + } + false + } + + walk(doc, ops, resources, name, 0, budget, &mut std::collections::HashSet::new()) +} + fn intersection(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> { let r = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]; (r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1]).then_some(r) @@ -461,6 +522,8 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag if !ops.get(img.op).is_some_and(|op| op.is("Do")) { return Err(EditError::Invalid("the image operation is missing".into())); } + let old_name = ops.get(img.op).and_then(|op| op.name(0)).map(<[u8]>::to_vec); + let old_object = img.object; let mut resources = None; let replacement: Vec = match change { ImageChange::Delete => Vec::new(), @@ -486,6 +549,47 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag } }; let changed = crate::text::splice(&pieces, &ops, |index| if index == img.op { (replacement.clone(), false) } else { (Vec::new(), true) }); + if let Some(old_name) = old_name.as_deref() { + let rewritten = Pieces::join(&changed.iter().map(Vec::as_slice).collect::>()); + let rewritten_ops = rewritten.parse().ops; + let current_resources = resources + .as_ref() + .cloned() + .unwrap_or_else(|| p.dict.get(b"Resources").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default()); + let xo = current_resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default(); + let mut aliases = Vec::new(); + for (resource_name, value) in xo.iter() { + let matches_object = old_object.is_some() && value.as_ref() == old_object; + if matches_object || resource_name.as_slice() == old_name { + if aliases.len() >= 256 { + return Err(EditError::Invalid("the image has too many resource aliases to update safely".into())); + } + aliases.push(resource_name.clone()); + } + } + if aliases.is_empty() { + aliases.push(old_name.to_vec()); + } + let mut unused = Vec::new(); + let mut form_scan_budget = 4096; + for resource_name in aliases { + let used_on_page = rewritten_ops.iter().any(|op| op.is("Do") && op.name(0) == Some(resource_name.as_slice())); + let used_in_form = + !used_on_page && resource_used_by_inheriting_forms(doc, &rewritten_ops, ¤t_resources, &resource_name, &mut form_scan_budget); + if !used_on_page && !used_in_form { + unused.push(resource_name); + } + } + if !unused.is_empty() { + let mut res = resources.take().unwrap_or(current_resources); + let mut xo = res.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default(); + for resource_name in &unused { + xo.remove(resource_name); + } + res.set(b"XObject".to_vec(), Object::Dict(xo)); + resources = Some(res); + } + } let contents = crate::text::rewritten_contents(doc, &all, changed); doc.update_dict(p.obj, |d| { d.set(b"Contents".to_vec(), contents); diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 879ebc6c66..4f717c83f4 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -2133,6 +2133,170 @@ fn page_images_move_turn_replace_and_delete() { assert!(images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).is_err()); } +fn identifiable_test_image(bytes: &[u8]) -> Stream { + let mut d = Dict::new(); + for (k, v) in [ + (&b"Type"[..], Object::name("XObject")), + (b"Subtype", Object::name("Image")), + (b"Width", Object::Int(4)), + (b"Height", Object::Int(2)), + (b"ColorSpace", Object::name("DeviceGray")), + (b"BitsPerComponent", Object::Int(8)), + ] { + d.set(k.to_vec(), v); + } + Stream::from_raw(d, bytes.to_vec()) +} + +#[test] +fn deleting_or_replacing_an_image_unlinks_its_unreferenced_resource_on_full_save() { + const OLD: &[u8] = b"PRIVATE_IMAGE_BYTES_3499"; + const NEW: &[u8] = b"PUBLIC_IMAGE_BYTES_3511"; + + let mut deleted = image_page(); + let old = images::page_images(&deleted, 0).unwrap()[0].object.unwrap(); + deleted.set(old, Object::Stream(identifiable_test_image(OLD))); + images::change_image(&mut deleted, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&deleted, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(OLD.len()).any(|w| w == OLD), "deleted image data survived the full save"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert_eq!(xobject(&saved, 0, b"Im0"), None, "deleted resource remains reachable from the page"); + + let mut replaced = image_page(); + let old = images::page_images(&replaced, 0).unwrap()[0].object.unwrap(); + replaced.set(old, Object::Stream(identifiable_test_image(OLD))); + let new = replaced.add(Object::Stream(identifiable_test_image(NEW))); + images::change_image(&mut replaced, 0, 0, &images::ImageChange::Replace(new)).unwrap(); + let bytes = write_full(&replaced, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(OLD.len()).any(|w| w == OLD), "replaced image data survived the full save"); + assert!(bytes.windows(NEW.len()).any(|w| w == NEW), "replacement image data is missing"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + let images = images::page_images(&saved, 0).unwrap(); + assert_eq!(images.len(), 1); + assert_eq!(images[0].name, format!("PCImg{}", new.num)); + assert!(images[0].object.is_some()); +} + +#[test] +fn deleting_one_of_two_placements_keeps_the_resource_still_in_use() { + let mut doc = image_page_with("q 200 0 0 100 100 100 cm /Im0 Do Q q 200 0 0 100 300 100 cm /Im0 Do Q"); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap(); + assert_eq!(images::page_images(&saved, 0).unwrap().len(), 1); + assert!(xobject(&saved, 0, b"Im0").is_some()); +} + +#[test] +fn deleting_a_page_image_keeps_it_when_a_nested_resource_less_form_inherits_it() { + const PRIVATE: &[u8] = b"PRIVATE_NESTED_FORM_IMAGE"; + let mut doc = image_page_with("q 200 0 0 100 100 100 cm /Im0 Do Q /Bare Do"); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(PRIVATE))); + + let mut form = Dict::new(); + form.set(b"Subtype".to_vec(), Object::name("Form")); + form.set(b"BBox".to_vec(), Object::Array([0, 0, 300, 300].map(Object::Int).to_vec())); + let inner = doc.add(Object::Stream(Stream::flate(form.clone(), b"/Im0 Do"))); + let outer = doc.add(Object::Stream(Stream::flate(form, b"/Inner Do"))); + let page = pdfcraft_model::pages(&doc)[0].obj; + let mut resources = doc.get(page).as_dict().unwrap().get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Inner".to_vec(), Object::Ref(inner)); + xobjects.set(b"Bare".to_vec(), Object::Ref(outer)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + let contents = doc.add(Object::Stream(Stream::flate(Dict::new(), b"q 200 0 0 100 100 100 cm /Im0 Do Q /Bare Do"))); + doc.update_dict(page, |d| { + d.set(b"Resources".to_vec(), Object::Dict(resources)); + d.set(b"Contents".to_vec(), Object::Ref(contents)); + }) + .unwrap(); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE), "the nested form's image was lost"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert!(xobject(&saved, 0, b"Im0").is_some(), "the page resource inherited by the Form was removed"); + assert_eq!(images::reading_images(&saved, 0).unwrap().len(), 1); +} + +#[test] +fn deleting_one_page_image_detaches_inherited_resources_without_changing_sibling_pages() { + const SHARED: &[u8] = b"SHARED_INHERITED_IMAGE"; + let mut doc = fixture(); + let image = doc.add(Object::Stream(identifiable_test_image(SHARED))); + doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| { + let mut xobjects = Dict::new(); + xobjects.set(b"Im0".to_vec(), Object::Ref(image)); + d.set(b"XObject".to_vec(), Object::Dict(xobjects)); + }) + .unwrap(); + doc.set(pdfcraft_cos::ObjRef::new(7, 0), Object::Stream(Stream::flate(Dict::new(), b"/Im0 Do"))); + assert_eq!(images::page_images(&doc, 0).unwrap().len(), 1); + assert_eq!(images::page_images(&doc, 1).unwrap().len(), 1); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap(); + assert!(images::page_images(&saved, 0).unwrap().is_empty()); + assert_eq!(images::page_images(&saved, 1).unwrap().len(), 1); + assert!(xobject(&saved, 0, b"Im0").is_none()); + assert!(xobject(&saved, 1, b"Im0").is_some()); +} + +#[test] +fn replacing_an_image_with_the_same_object_keeps_the_replacement_reachable() { + const SAME: &[u8] = b"SAME_IMAGE_OBJECT"; + let mut doc = image_page(); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(SAME))); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Replace(image)).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(SAME.len()).any(|w| w == SAME)); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert_eq!(images::page_images(&saved, 0).unwrap().len(), 1); + assert_eq!(images::page_images(&saved, 0).unwrap()[0].name, format!("PCImg{}", image.num)); +} + +#[test] +fn deleting_an_image_prunes_unused_aliases_but_keeps_aliases_still_drawn() { + const ALIASED: &[u8] = b"ALIASED_IMAGE_BYTES"; + let mut doc = image_page(); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(ALIASED))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"UnusedAlias".to_vec(), Object::Ref(image)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(ALIASED.len()).any(|w| w == ALIASED), "an unused alias kept the deleted image reachable"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert!(xobject(&saved, 0, b"Im0").is_none()); + assert!(xobject(&saved, 0, b"UnusedAlias").is_none()); + + let mut doc = image_page_with("q 200 0 0 100 100 100 cm /Im0 Do Q /Alias Do"); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(ALIASED))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Alias".to_vec(), Object::Ref(image)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap(); + assert_eq!(images::page_images(&saved, 0).unwrap().len(), 1); + assert!(xobject(&saved, 0, b"Im0").is_none()); + assert!(xobject(&saved, 0, b"Alias").is_some()); +} + #[test] fn form_artwork_edits_only_the_selected_placement() { let mut doc = fixture(); // three pages share resources; pages 0 and 1 also share contents 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 015/216] 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 016/216] 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 d7c207bde09e06583e82926b93f6ff9f0fdfec7f Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Mon, 19 Oct 2026 14:07:18 -0600 Subject: [PATCH 017/216] fix(edit): fail closed on malformed image consumers --- crates/automation/tests/automation.rs | 3 +- crates/edit/src/images.rs | 822 +++++++++++++++++++++++--- crates/edit/src/tests.rs | 571 +++++++++++++++++- 3 files changed, 1293 insertions(+), 103 deletions(-) diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs index cbf40f1962..19245b0d9a 100644 --- a/crates/automation/tests/automation.rs +++ b/crates/automation/tests/automation.rs @@ -6213,7 +6213,8 @@ fn a_deleted_image_is_not_kept_by_reduce_or_optimize() { assert_eq!(ok(&mut a, "page_images", json!({ "doc": doc, "page": 1 }))["count"], 0); // The page is blank, so the copies are tiny: the picture's data is not carried along. let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "optimized.pdf" })); - assert_eq!(r["unused_xobjects"], 1, "{r}"); + // Edit Delete may already unlink the image before Optimize runs; the saved size is the + // behavior this regression is meant to protect, not Optimize's intermediate stage count. assert!(r["bytes_after"].as_u64().unwrap() < 4_000, "{r}"); let r = ok(&mut a, "doc_reduce", json!({ "doc": doc, "path": "reduced.pdf" })); assert!(r["bytes_after"].as_u64().unwrap() < 4_000, "{r}"); diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rs index 2b55bd0909..065a5430c3 100644 --- a/crates/edit/src/images.rs +++ b/crates/edit/src/images.rs @@ -108,65 +108,729 @@ fn xobjects(doc: &Document, page: &Dict) -> Dict { .unwrap_or_default() } -/// Whether a page resource name is used by the page or by a reachable Form that inherits the -/// page's resources. A Form with its own `/Resources` has an independent namespace; forms without -/// one inherit the caller's. On an unreadable or over-budget Form, preserve the resource. -fn resource_used_by_inheriting_forms(doc: &Document, ops: &[Op], resources: &Dict, name: &[u8], budget: &mut usize) -> bool { - fn walk( - doc: &Document, - ops: &[Op], - resources: &Dict, - name: &[u8], - depth: usize, - budget: &mut usize, - path: &mut std::collections::HashSet, - ) -> bool { - if depth > 32 || *budget == 0 { - return true; +const IMAGE_CENSUS_MAX_OBJECTS: usize = 100_000; +const IMAGE_CENSUS_MAX_BYTES: usize = 128 * 1024 * 1024; +const IMAGE_CENSUS_MAX_OPERATORS: usize = 5_000_000; +const IMAGE_CENSUS_MAX_VISITS: usize = 50_000; +const IMAGE_CENSUS_MAX_DEPTH: usize = 64; +const IMAGE_CENSUS_MAX_ALIASES: usize = 255; + +/// A full-document, bounded census of executable resource consumers. `incomplete` means a +/// conservative cleanup cannot prove that an image is unused, so callers must leave its bytes. +struct ImageUseCensus<'a> { + doc: &'a Document, + target: ObjRef, + used: bool, + incomplete: bool, + bytes: usize, + operators: usize, + visits: usize, +} + +impl ImageUseCensus<'_> { + fn charge_visit(&mut self) -> bool { + self.visits = self.visits.saturating_add(1); + if self.visits > IMAGE_CENSUS_MAX_VISITS { + self.incomplete = true; + false + } else { + true } - let xo = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default(); - for op in ops.iter().filter(|op| op.is("Do")) { - let Some(call_name) = op.name(0) else { - continue; - }; - if call_name == name { - return true; - } - let Some(resource) = xo.get(call_name) else { - continue; - }; - let resolved = doc.resolve(resource); - let Object::Stream(stream) = &*resolved else { - continue; - }; - let Some(reference) = resource.as_ref() else { - if stream.dict.name(b"Subtype") == Some(b"Form") && !stream.dict.contains(b"Resources") { - return true; - } - continue; - }; - if stream.dict.name(b"Subtype") != Some(b"Form") || stream.dict.contains(b"Resources") { - continue; - } - if !path.insert(reference) { - return true; - } - *budget -= 1; - let decoded = match stream.decoded() { - Ok(decoded) => decoded, - Err(_) => return true, - }; - let nested_ops = parse(&decoded).ops; - let used = walk(doc, &nested_ops, resources, name, depth + 1, budget, path); - path.remove(&reference); - if used { - return true; - } - } - false } - walk(doc, ops, resources, name, 0, budget, &mut std::collections::HashSet::new()) + fn charge_stream(&mut self, stream: &pdfcraft_cos::Stream) -> Option> { + if !self.charge_visit() { + return None; + } + let data = match stream.decoded() { + Ok(data) => data, + Err(_) => { + self.incomplete = true; + return None; + } + }; + self.bytes = self.bytes.saturating_add(data.len()); + if self.bytes > IMAGE_CENSUS_MAX_BYTES { + self.incomplete = true; + return None; + } + Some(data) + } + + fn walk_stream(&mut self, object: &Object, inherited: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if self.used || self.incomplete { + return; + } + if !self.charge_visit() { + return; + } + if depth > IMAGE_CENSUS_MAX_DEPTH { + self.incomplete = true; + return; + } + let reference = object.as_ref(); + if reference == Some(self.target) { + self.used = true; + return; + } + if let Some(reference) = reference + && !path.insert(reference) + { + // A cycle could be rendered differently under an inherited resource scope. + self.incomplete = true; + return; + } + let resolved = self.doc.resolve(object); + let Object::Stream(stream) = &*resolved else { + self.incomplete = true; + return; + }; + + // Image masks and alternates are serialized image consumers even though they are not + // reached by a `Do` of their own. + if stream.dict.name(b"Subtype") == Some(b"Image") { + for key in [b"SMask".as_slice(), b"Mask".as_slice()] { + let Some(dependency) = stream.dict.get(key) else { continue }; + if dependency.as_ref() == Some(self.target) { + self.used = true; + return; + } + match dependency { + Object::Ref(_) => self.walk_stream(dependency, inherited, depth + 1, path), + Object::Null => {} + Object::Name(name) if key == b"SMask" && name == b"None" => {} + Object::Array(values) if key == b"Mask" && values.iter().all(|value| value.as_ref().is_none()) => {} + _ => self.incomplete = true, + } + if self.incomplete || self.used { + return; + } + } + if let Some(alternates) = stream.dict.get(b"Alternates").map(|o| self.doc.resolve(o)) { + let Some(items) = alternates.as_array() else { + self.incomplete = true; + return; + }; + for item in items { + let item = self.doc.resolve(item); + let Some(image) = item.as_dict().and_then(|d| d.get(b"Image")) else { + self.incomplete = true; + return; + }; + if image.as_ref() == Some(self.target) { + self.used = true; + return; + } + self.walk_stream(image, inherited, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + } + if let Some(reference) = reference { + path.remove(&reference); + } + return; + } + + let subtype = stream.dict.name(b"Subtype"); + let pattern = stream.dict.int(b"PatternType") == Some(1); + if subtype != Some(b"Form") && !pattern { + self.incomplete = true; + if let Some(reference) = reference { + path.remove(&reference); + } + return; + } + let resources = + stream.dict.get(b"Resources").map(|r| self.doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_else(|| inherited.clone()); + let Some(data) = self.charge_stream(stream) else { + if let Some(reference) = reference { + path.remove(&reference); + } + return; + }; + self.walk_content(&data, &resources, depth + 1, path); + if let Some(reference) = reference { + path.remove(&reference); + } + } + + fn walk_type3(&mut self, font: &Object, inherited: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if !self.charge_visit() { + return; + } + let resolved = self.doc.resolve(font); + let Some(dict) = resolved.as_dict() else { + self.incomplete = true; + return; + }; + if dict.name(b"Subtype") != Some(b"Type3") { + return; + } + let resources = dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_else(|| inherited.clone()); + let Some(charprocs) = dict.get(b"CharProcs").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + self.incomplete = true; + return; + }; + for (_, charproc) in charprocs.iter() { + self.walk_charproc(charproc, &resources, depth + 1, path); + if self.used || self.incomplete { + return; + } + } + } + + fn walk_charproc(&mut self, object: &Object, inherited: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if self.used || self.incomplete { + return; + } + if !self.charge_visit() { + return; + } + if depth > IMAGE_CENSUS_MAX_DEPTH { + self.incomplete = true; + return; + } + let reference = object.as_ref(); + if reference.is_some_and(|r| !path.insert(r)) { + self.incomplete = true; + return; + } + let resolved = self.doc.resolve(object); + let Object::Stream(stream) = &*resolved else { + self.incomplete = true; + return; + }; + let resources = + stream.dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_else(|| inherited.clone()); + if let Some(data) = self.charge_stream(stream) { + self.walk_content(&data, &resources, depth + 1, path); + } + if let Some(reference) = reference { + path.remove(&reference); + } + } + + fn walk_resources_for_operator(&mut self, op: &Op, resources: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if op.is("Tf") { + let Some(name) = op.name(0) else { + self.incomplete = true; + return; + }; + if let Some(fonts) = resources.get(b"Font").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) + && let Some(font) = fonts.get(name) + { + self.walk_type3(font, resources, depth + 1, path); + } + } else if op.is("gs") { + let Some(name) = op.name(0) else { + self.incomplete = true; + return; + }; + let states = resources.get(b"ExtGState").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()); + let Some(state) = states.as_ref().and_then(|d| d.get(name)).map(|o| self.doc.resolve(o)) else { + self.incomplete = true; + return; + }; + let Some(state_dict) = state.as_dict() else { + self.incomplete = true; + return; + }; + if let Some(font_value) = state_dict.get(b"Font") { + let font = self.doc.resolve(font_value); + let Some(values) = font.as_array() else { + self.incomplete = true; + return; + }; + if values.len() != 2 { + self.incomplete = true; + return; + } + self.walk_type3(&values[0], resources, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + let Some(mask_value) = state_dict.get(b"SMask") else { return }; + let mask = self.doc.resolve(mask_value); + match &*mask { + Object::Name(name) if name == b"None" => {} + Object::Dict(mask_dict) => { + let Some(group) = mask_dict.get(b"G") else { + self.incomplete = true; + return; + }; + let resolved_group = self.doc.resolve(group); + if !matches!(&*resolved_group, Object::Stream(stream) if stream.dict.name(b"Subtype") == Some(b"Form")) { + self.incomplete = true; + return; + } + self.walk_stream(group, resources, depth + 1, path); + } + _ => self.incomplete = true, + } + } else if op.is("scn") || op.is("SCN") { + let Some(name) = op.operands.last().and_then(Object::as_name) else { return }; + let patterns = resources.get(b"Pattern").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()); + if let Some(pattern) = patterns.as_ref().and_then(|d| d.get(name)) { + let resolved = self.doc.resolve(pattern); + if resolved.as_dict().is_some_and(|d| d.int(b"PatternType") == Some(1)) { + self.walk_stream(pattern, resources, depth + 1, path); + } + } + } + } + + fn walk_content(&mut self, data: &[u8], resources: &Dict, depth: usize, path: &mut std::collections::HashSet) { + self.walk_parsed(parse(data), resources, depth, path); + } + + fn walk_parsed(&mut self, parsed: pdfcraft_content::Parsed, resources: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if self.used || self.incomplete { + return; + } + if depth > IMAGE_CENSUS_MAX_DEPTH { + self.incomplete = true; + return; + } + self.operators = self.operators.saturating_add(parsed.ops.len()); + if parsed.skipped != 0 || self.operators > IMAGE_CENSUS_MAX_OPERATORS { + self.incomplete = true; + return; + } + for op in &parsed.ops { + self.walk_resources_for_operator(op, resources, depth, path); + if self.incomplete || self.used { + return; + } + if !op.is("Do") { + continue; + } + let Some(name) = op.name(0) else { + self.incomplete = true; + return; + }; + let Some(xobjects) = resources.get(b"XObject").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + self.incomplete = true; + return; + }; + let Some(xobject) = xobjects.get(name) else { + self.incomplete = true; + return; + }; + if xobject.as_ref() == Some(self.target) { + self.used = true; + return; + } + self.walk_stream(xobject, resources, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + } + + fn walk_appearances(&mut self, object: &Object, resources: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if self.used || self.incomplete { + return; + } + if !self.charge_visit() { + return; + } + if depth > IMAGE_CENSUS_MAX_DEPTH { + self.incomplete = true; + return; + } + let reference = object.as_ref(); + match &*self.doc.resolve(object) { + Object::Stream(_) => self.walk_stream(object, resources, depth + 1, path), + Object::Dict(dict) => { + if let Some(reference) = reference + && !path.insert(reference) + { + self.incomplete = true; + return; + } + if dict.contains(b"Resources") { + self.incomplete = true; + return; + } + for (_, value) in dict.iter() { + self.walk_appearances(value, resources, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + if let Some(reference) = reference { + path.remove(&reference); + } + } + Object::Array(values) => { + if let Some(reference) = reference + && !path.insert(reference) + { + self.incomplete = true; + return; + } + for value in values { + self.walk_appearances(value, resources, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + if let Some(reference) = reference { + path.remove(&reference); + } + } + _ => {} + } + } +} + +/// Remove a deleted/replaced image from every resource dictionary only after a bounded census +/// proves no page, Form, Type3 glyph, soft mask, tiling pattern, or annotation appearance uses it. +/// Any unsupported or malformed consumer preserves the image and still lets the edit succeed. +fn prune_unused_image(doc: &mut Document, target: ObjRef) { + let object_count = doc.scan_objects_checked().take(IMAGE_CENSUS_MAX_OBJECTS + 1).count(); + if object_count > IMAGE_CENSUS_MAX_OBJECTS { + return; + } + let mut census = ImageUseCensus { doc, target, used: false, incomplete: false, bytes: 0, operators: 0, visits: 0 }; + let mut path = std::collections::HashSet::new(); + let pages = pdfcraft_model::pages(doc); + if pages.len() > IMAGE_CENSUS_MAX_OBJECTS { + return; + } + for page in &pages { + let Some(resources) = page.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()) else { + census.incomplete = true; + break; + }; + let contents_object = page.dict.get(b"Contents").map(|value| doc.resolve(value)); + let contents: &[Object] = match contents_object.as_deref() { + None => &[], + Some(Object::Array(items)) => items, + Some(value) => std::slice::from_ref(value), + }; + if contents.len() > IMAGE_CENSUS_MAX_VISITS { + census.incomplete = true; + break; + } + let mut content_data = Vec::with_capacity(contents.len()); + for content in contents { + let resolved = doc.resolve(content); + let Object::Stream(stream) = &*resolved else { + census.incomplete = true; + break; + }; + if let Some(data) = census.charge_stream(stream) { + content_data.push(data); + } + if census.incomplete { + break; + } + } + if !census.incomplete { + census.walk_parsed(Pieces::join(&content_data).parse(), &resources, 0, &mut path); + } + let annots = page.dict.get(b"Annots").map(|o| doc.resolve(o)); + if let Some(annots) = annots { + let Some(items) = annots.as_array() else { + census.incomplete = true; + break; + }; + if items.len() > IMAGE_CENSUS_MAX_OBJECTS { + census.incomplete = true; + break; + } + for item in items { + if !census.charge_visit() { + break; + } + let resolved = doc.resolve(item); + let Some(ap) = resolved.as_dict().and_then(|d| d.get(b"AP")) else { continue }; + census.walk_appearances(ap, &resources, 0, &mut path); + if census.incomplete || census.used { + break; + } + } + } + if census.incomplete || census.used { + break; + } + } + if census.used || census.incomplete { + return; + } + + // Unknown stream types carrying their own resource namespace could also consume XObjects. + let checked: Vec<_> = doc.scan_objects_checked().collect(); + if checked.len() > IMAGE_CENSUS_MAX_OBJECTS || checked.iter().any(|(_, item)| item.is_err()) { + return; + } + if checked.iter().any(|(_, item)| { + item.as_ref().ok().is_some_and(|o| matches!(o.as_ref(), Object::Stream(s) if s.dict.contains(b"Resources") && s.dict.name(b"Subtype") != Some(b"Form") && s.dict.int(b"PatternType") != Some(1))) + }) { + return; + } + + let mut staged = std::collections::HashMap::new(); + let mut indirect_xobject_dicts = std::collections::HashSet::new(); + let mut indirect_alternate_arrays = std::collections::HashSet::new(); + let mut aliases = 0usize; + let mut mapping_visits = 0usize; + let mut dependency_visits = 0usize; + for (reference, item) in checked { + let Ok(object) = item else { return }; + let mut object = (*object).clone(); + let mappings_changed = match prune_xobject_mappings(&mut object, target, &mut indirect_xobject_dicts, &mut aliases, 0, &mut mapping_visits) { + Ok(changed) => changed, + Err(()) => return, + }; + let dependencies_changed = + match prune_image_dependencies(&mut object, doc, target, &mut indirect_alternate_arrays, &mut aliases, 0, &mut dependency_visits) { + Ok(changed) => changed, + Err(()) => return, + }; + if mappings_changed || dependencies_changed { + if aliases > IMAGE_CENSUS_MAX_ALIASES { + return; + } + staged.insert(reference, object); + } + } + for reference in indirect_xobject_dicts { + let was_staged = staged.contains_key(&reference); + let mut object = staged.remove(&reference).unwrap_or_else(|| (*doc.get(reference)).clone()); + let changed = match remove_target_aliases(object.as_dict_mut(), target, &mut aliases) { + Ok(changed) => changed, + Err(()) => return, + }; + if changed || was_staged { + if aliases > IMAGE_CENSUS_MAX_ALIASES { + return; + } + staged.insert(reference, object); + } + } + for reference in indirect_alternate_arrays { + let was_staged = staged.contains_key(&reference); + let mut object = staged.remove(&reference).unwrap_or_else(|| (*doc.get(reference)).clone()); + let changed = match remove_target_alternate_entries(&mut object, doc, target, &mut aliases, &mut dependency_visits) { + Ok(changed) => changed, + Err(()) => return, + }; + if changed { + if aliases > IMAGE_CENSUS_MAX_ALIASES { + return; + } + staged.insert(reference, object); + } else if !matches!(&object, Object::Array(_)) { + // An indirect `/Alternates` value that is not an array is malformed. Since the + // census cannot establish whether it retains the target, preserve the whole edit. + return; + } else if was_staged { + staged.insert(reference, object); + } + } + for (reference, object) in staged { + doc.set(reference, object); + } +} + +fn remove_target_aliases(dict: Option<&mut Dict>, target: ObjRef, aliases: &mut usize) -> Result { + let Some(dict) = dict else { return Ok(false) }; + if dict.iter().take(IMAGE_CENSUS_MAX_VISITS + 1).count() > IMAGE_CENSUS_MAX_VISITS { + return Err(()); + } + let mut names = Vec::new(); + for (name, value) in dict.iter() { + if value.as_ref() == Some(target) { + if aliases.saturating_add(names.len()) >= IMAGE_CENSUS_MAX_ALIASES { + return Err(()); + } + names.push(name.clone()); + } + } + for name in &names { + dict.remove(name); + } + *aliases = aliases.saturating_add(names.len()); + Ok(!names.is_empty()) +} + +fn prune_xobject_mappings( + object: &mut Object, + target: ObjRef, + indirect: &mut std::collections::HashSet, + aliases: &mut usize, + depth: usize, + visits: &mut usize, +) -> Result { + charge_object_walk(depth, visits)?; + let mut changed = false; + match object { + Object::Array(values) => { + for value in values { + changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, visits)?; + } + } + Object::Dict(dict) | Object::Stream(pdfcraft_cos::Stream { dict, .. }) => { + if let Some(xobjects) = dict.get_mut(b"XObject") { + match xobjects { + Object::Ref(reference) => { + indirect.insert(*reference); + } + Object::Dict(mappings) => changed |= remove_target_aliases(Some(mappings), target, aliases)?, + _ => {} + } + } + let mut keys = Vec::new(); + for (key, _) in dict.iter() { + if keys.len() >= IMAGE_CENSUS_MAX_VISITS { + return Err(()); + } + keys.push(key.clone()); + } + for key in keys { + if let Some(value) = dict.get_mut(&key) { + changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, visits)?; + } + } + } + _ => {} + } + Ok(changed) +} + +fn contains_target_ref(object: &Object, target: ObjRef, depth: usize, visits: &mut usize) -> Result { + charge_object_walk(depth, visits)?; + match object { + Object::Ref(reference) => Ok(*reference == target), + Object::Array(values) => { + for value in values { + if contains_target_ref(value, target, depth + 1, visits)? { + return Ok(true); + } + } + Ok(false) + } + _ => Ok(false), + } +} + +fn alternate_uses_target(object: &Object, doc: &Document, target: ObjRef) -> bool { + doc.resolve(object).as_dict().and_then(|dict| dict.get(b"Image")).is_some_and(|image| image.as_ref() == Some(target)) +} + +fn remove_target_alternate_entries(object: &mut Object, doc: &Document, target: ObjRef, aliases: &mut usize, visits: &mut usize) -> Result { + let Object::Array(entries) = object else { return Ok(false) }; + let mut retained = Vec::new(); + let mut removed = 0; + for entry in entries.iter() { + charge_object_walk(1, visits)?; + if alternate_uses_target(entry, doc, target) { + if aliases.saturating_add(removed) >= IMAGE_CENSUS_MAX_ALIASES { + return Err(()); + } + removed += 1; + } else { + retained.push(entry.clone()); + } + } + if removed != 0 { + *entries = retained; + *aliases = aliases.saturating_add(removed); + } + Ok(removed != 0) +} + +/// Remove dependencies on an image only after the document census proves no active consumer +/// uses it. The dependent image is left in place, but its stale optional mask/alternate edge is +/// removed so full-save garbage collection can release the target bytes. +fn prune_image_dependencies( + object: &mut Object, + doc: &Document, + target: ObjRef, + indirect_alternate_arrays: &mut std::collections::HashSet, + aliases: &mut usize, + depth: usize, + visits: &mut usize, +) -> Result { + charge_object_walk(depth, visits)?; + let mut changed = false; + match object { + Object::Array(values) => { + for value in values { + changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, visits)?; + } + } + Object::Dict(dict) | Object::Stream(pdfcraft_cos::Stream { dict, .. }) => { + if dict.name(b"Subtype") == Some(b"Image") { + for key in [b"SMask".as_slice(), b"Mask".as_slice()] { + let contains_target = + if let Some(value) = dict.get(key) { contains_target_ref(value, target, depth + 1, visits)? } else { false }; + if contains_target { + if aliases.saturating_add(1) > IMAGE_CENSUS_MAX_ALIASES { + return Err(()); + } + dict.remove(key); + *aliases = aliases.saturating_add(1); + changed = true; + } + } + match dict.get(b"Alternates") { + Some(Object::Array(_)) => { + let Some(Object::Array(entries)) = dict.get_mut(b"Alternates") else { return Err(()) }; + let mut retained = Vec::new(); + let mut removed = 0; + for entry in entries.iter() { + charge_object_walk(depth + 1, visits)?; + if alternate_uses_target(entry, doc, target) { + if aliases.saturating_add(removed) >= IMAGE_CENSUS_MAX_ALIASES { + return Err(()); + } + removed += 1; + } else { + retained.push(entry.clone()); + } + } + if removed != 0 { + *entries = retained; + *aliases = aliases.saturating_add(removed); + changed = true; + } + } + Some(Object::Ref(reference)) => { + indirect_alternate_arrays.insert(*reference); + } + _ => {} + } + } + let mut keys = Vec::new(); + for (key, _) in dict.iter() { + if keys.len() >= IMAGE_CENSUS_MAX_VISITS { + return Err(()); + } + keys.push(key.clone()); + } + for key in keys { + if let Some(value) = dict.get_mut(&key) { + changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, visits)?; + } + } + } + _ => {} + } + Ok(changed) +} + +fn charge_object_walk(depth: usize, visits: &mut usize) -> Result<(), ()> { + if depth > IMAGE_CENSUS_MAX_DEPTH { + return Err(()); + } + *visits = visits.saturating_add(1); + if *visits > IMAGE_CENSUS_MAX_VISITS { Err(()) } else { Ok(()) } } fn intersection(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> { @@ -522,8 +1186,8 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag if !ops.get(img.op).is_some_and(|op| op.is("Do")) { return Err(EditError::Invalid("the image operation is missing".into())); } - let old_name = ops.get(img.op).and_then(|op| op.name(0)).map(<[u8]>::to_vec); let old_object = img.object; + let prune_target = matches!(change, ImageChange::Delete | ImageChange::Replace(_)).then_some(old_object).flatten(); let mut resources = None; let replacement: Vec = match change { ImageChange::Delete => Vec::new(), @@ -549,47 +1213,6 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag } }; let changed = crate::text::splice(&pieces, &ops, |index| if index == img.op { (replacement.clone(), false) } else { (Vec::new(), true) }); - if let Some(old_name) = old_name.as_deref() { - let rewritten = Pieces::join(&changed.iter().map(Vec::as_slice).collect::>()); - let rewritten_ops = rewritten.parse().ops; - let current_resources = resources - .as_ref() - .cloned() - .unwrap_or_else(|| p.dict.get(b"Resources").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default()); - let xo = current_resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default(); - let mut aliases = Vec::new(); - for (resource_name, value) in xo.iter() { - let matches_object = old_object.is_some() && value.as_ref() == old_object; - if matches_object || resource_name.as_slice() == old_name { - if aliases.len() >= 256 { - return Err(EditError::Invalid("the image has too many resource aliases to update safely".into())); - } - aliases.push(resource_name.clone()); - } - } - if aliases.is_empty() { - aliases.push(old_name.to_vec()); - } - let mut unused = Vec::new(); - let mut form_scan_budget = 4096; - for resource_name in aliases { - let used_on_page = rewritten_ops.iter().any(|op| op.is("Do") && op.name(0) == Some(resource_name.as_slice())); - let used_in_form = - !used_on_page && resource_used_by_inheriting_forms(doc, &rewritten_ops, ¤t_resources, &resource_name, &mut form_scan_budget); - if !used_on_page && !used_in_form { - unused.push(resource_name); - } - } - if !unused.is_empty() { - let mut res = resources.take().unwrap_or(current_resources); - let mut xo = res.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default(); - for resource_name in &unused { - xo.remove(resource_name); - } - res.set(b"XObject".to_vec(), Object::Dict(xo)); - resources = Some(res); - } - } let contents = crate::text::rewritten_contents(doc, &all, changed); doc.update_dict(p.obj, |d| { d.set(b"Contents".to_vec(), contents); @@ -597,6 +1220,9 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag d.set(b"Resources".to_vec(), Object::Dict(res)); } })?; + if let Some(target) = prune_target { + prune_unused_image(doc, target); + } Ok(()) } diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 4f717c83f4..d7a25af3af 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -2196,6 +2196,7 @@ fn deleting_a_page_image_keeps_it_when_a_nested_resource_less_form_inherits_it() let mut form = Dict::new(); form.set(b"Subtype".to_vec(), Object::name("Form")); form.set(b"BBox".to_vec(), Object::Array([0, 0, 300, 300].map(Object::Int).to_vec())); + form.set(b"Resources".to_vec(), Object::Null); let inner = doc.add(Object::Stream(Stream::flate(form.clone(), b"/Im0 Do"))); let outer = doc.add(Object::Stream(Stream::flate(form, b"/Inner Do"))); let page = pdfcraft_model::pages(&doc)[0].obj; @@ -2220,7 +2221,567 @@ fn deleting_a_page_image_keeps_it_when_a_nested_resource_less_form_inherits_it() } #[test] -fn deleting_one_page_image_detaches_inherited_resources_without_changing_sibling_pages() { +fn deleting_an_image_with_too_many_aliases_skips_optional_pruning() { + const PRIVATE: &[u8] = b"PRIVATE_HIGH_ALIAS_COUNT_IMAGE"; + let mut doc = image_page(); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(PRIVATE))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + for i in 0..256 { + xobjects.set(format!("Alias{i}").into_bytes(), Object::Ref(image)); + } + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE), "over-limit optional pruning unexpectedly removed the image"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert!(images::page_images(&saved, 0).unwrap().is_empty()); + assert!(xobject(&saved, 0, b"Alias0").is_some()); +} + +fn set_image_content(doc: &mut Document, page: usize, pieces: &[&[u8]]) { + let page = pdfcraft_model::pages(doc)[page].obj; + let contents = pieces.iter().map(|data| Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), data))))).collect::>(); + doc.update_dict(page, |d| d.set(b"Contents".to_vec(), Object::Array(contents))).unwrap(); +} + +#[test] +fn deleted_image_is_kept_when_reachable_through_each_non_page_consumer() { + const PRIVATE: &[u8] = b"PRIVATE_CONTEXT_IMAGE"; + + // Type 3 CharProc content uses the caller's resource scope when the font has no Resources. + { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let glyph = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/Im0 Do"))); + let mut charprocs = Dict::new(); + charprocs.set(b"A".to_vec(), Object::Ref(glyph)); + let mut font = Dict::new(); + font.set(b"Type".to_vec(), Object::name("Font")); + font.set(b"Subtype".to_vec(), Object::name("Type3")); + font.set(b"CharProcs".to_vec(), Object::Dict(charprocs)); + let font = doc.add(Object::Dict(font)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut fonts = resources.get(b"Font").and_then(Object::as_dict).cloned().unwrap(); + fonts.set(b"T3".to_vec(), Object::Ref(font)); + resources.set(b"Font".to_vec(), Object::Dict(fonts)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q BT /T3 10 Tf (A) Tj ET"]); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); + } + + // A selected soft mask's Form inherits the page's resources. + { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let form = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([(b"Subtype".to_vec(), Object::name("Form")), (b"BBox".to_vec(), Object::Array([0, 0, 1, 1].map(Object::Int).to_vec()))]), + b"/Im0 Do", + ))); + let mut soft_mask = Dict::new(); + soft_mask.set(b"G".to_vec(), Object::Ref(form)); + let mut gs = Dict::new(); + gs.set(b"SMask".to_vec(), Object::Dict(soft_mask)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut states = Dict::new(); + states.set(b"GS".to_vec(), Object::Dict(gs)); + resources.set(b"ExtGState".to_vec(), Object::Dict(states)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs"]); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); + } + + // A used tiling Pattern can draw an image with its caller's resources. + { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut pattern_dict = Dict::new(); + for (key, value) in [ + (&b"PatternType"[..], Object::Int(1)), + (b"PaintType", Object::Int(1)), + (b"TilingType", Object::Int(1)), + (b"BBox", Object::Array([0, 0, 1, 1].map(Object::Int).to_vec())), + (b"XStep", Object::Int(1)), + (b"YStep", Object::Int(1)), + ] { + pattern_dict.set(key.to_vec(), value); + } + let pattern = doc.add(Object::Stream(Stream::flate(pattern_dict, b"/Im0 Do"))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut patterns = Dict::new(); + patterns.set(b"P".to_vec(), Object::Ref(pattern)); + resources.set(b"Pattern".to_vec(), Object::Dict(patterns)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q 0 /P scn 0 0 10 10 re f"]); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); + } + + // Every annotation appearance state is a consumer, even if it is not the normal state. + { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let form = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([ + (b"Subtype".to_vec(), Object::name("Form")), + (b"BBox".to_vec(), Object::Array([0, 0, 10, 10].map(Object::Int).to_vec())), + ]), + b"/Im0 Do", + ))); + let mut states = Dict::new(); + states.set(b"Off".to_vec(), Object::Ref(form)); + let mut ap = Dict::new(); + ap.set(b"D".to_vec(), Object::Dict(states)); + let mut annotation = Dict::new(); + annotation.set(b"AP".to_vec(), Object::Dict(ap)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Dict(annotation)]))).unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); + } +} + +#[test] +fn deleted_image_census_joins_content_pieces_and_checks_each_page_scope() { + const PRIVATE: &[u8] = b"PRIVATE_SCOPED_IMAGE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Im0", b" Do"]); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!( + write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), + "the retained second Do spans content pieces" + ); + + // A shared Form is evaluated in each caller's effective resource scope. The first page maps + // /Im0 to a different image; the second page maps it to the deleted target. + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let other = doc.add(Object::Stream(identifiable_test_image(b"OTHER_SCOPED_IMAGE"))); + let shared = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([ + (b"Subtype".to_vec(), Object::name("Form")), + (b"BBox".to_vec(), Object::Array([0, 0, 1, 1].map(Object::Int).to_vec())), + (b"Resources".to_vec(), Object::Null), + ]), + b"/Im0 Do", + ))); + let page0 = pdfcraft_model::pages(&doc)[0].obj; + let mut res0 = doc.get(page0).as_dict().unwrap().get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xo0 = res0.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xo0.set(b"Target".to_vec(), Object::Ref(target)); + xo0.set(b"Other".to_vec(), Object::Ref(other)); + xo0.set(b"Im0".to_vec(), Object::Ref(other)); + xo0.set(b"Shared".to_vec(), Object::Ref(shared)); + res0.set(b"XObject".to_vec(), Object::Dict(xo0)); + doc.update_dict(page0, |d| { + d.set(b"Resources".to_vec(), Object::Dict(res0)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"/Target Do /Shared Do"]); + let page1_contents = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/Shared Do"))); + let page1 = doc.add(Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::name("Page")), + (b"Parent".to_vec(), Object::Ref(pdfcraft_cos::ObjRef::new(2, 0))), + (b"MediaBox".to_vec(), Object::Array([0, 0, 600, 800].map(Object::Int).to_vec())), + ( + b"Resources".to_vec(), + Object::Dict(Dict::from_iter([( + b"XObject".to_vec(), + Object::Dict(Dict::from_iter([(b"Im0".to_vec(), Object::Ref(target)), (b"Shared".to_vec(), Object::Ref(shared))])), + )])), + ), + (b"Contents".to_vec(), Object::Ref(page1_contents)), + ]))); + doc.update_dict(pdfcraft_cos::ObjRef::new(2, 0), |d| { + let mut kids = d.get(b"Kids").and_then(Object::as_array).cloned().unwrap(); + kids.push(Object::Ref(page1)); + d.set(b"Kids".to_vec(), Object::Array(kids)); + d.set(b"Count".to_vec(), Object::Int(2)); + }) + .unwrap(); + assert_eq!(images::page_images(&doc, 0).unwrap().len(), 2); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!( + write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), + "the same Form must use page one's different inherited scope" + ); +} + +#[test] +fn extgstate_selected_type3_font_keeps_its_glyph_image_after_page_image_delete() { + const PRIVATE: &[u8] = b"PRIVATE_GSTATE_TYPE3_GLYPH_IMAGE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + + let glyph = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/GlyphImg Do"))); + let mut charprocs = Dict::new(); + charprocs.set(b"A".to_vec(), Object::Ref(glyph)); + let glyph_resources = Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"GlyphImg".to_vec(), Object::Ref(target))])))]); + let mut font_dict = Dict::new(); + for (key, value) in [ + (&b"Type"[..], Object::name("Font")), + (b"Subtype", Object::name("Type3")), + (b"FontBBox", Object::Array([0, 0, 1000, 1000].map(Object::Int).to_vec())), + (b"FontMatrix", Object::Array(vec![Object::Int(1), Object::Int(0), Object::Int(0), Object::Int(1), Object::Int(0), Object::Int(0)])), + (b"FirstChar", Object::Int(65)), + (b"LastChar", Object::Int(65)), + (b"Widths", Object::Array(vec![Object::Int(1000)])), + (b"Encoding", Object::Dict(Dict::from_iter([(b"Differences".to_vec(), Object::Array(vec![Object::Int(65), Object::name("A")]))]))), + (b"CharProcs", Object::Dict(charprocs)), + (b"Resources", Object::Dict(glyph_resources)), + ] { + font_dict.set(key.to_vec(), value); + } + let font = doc.add(Object::Dict(font_dict)); + let ext_gstate = Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Array(vec![Object::Ref(font), Object::Int(10)]))])); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"ExtGState".to_vec(), Object::Dict(Dict::from_iter([(b"GS".to_vec(), ext_gstate)]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs BT (A) Tj ET"]); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); + let saved = Document::open(Arc::new(bytes)).unwrap(); + let page = pdfcraft_model::pages(&saved)[0].clone(); + let resources = page.dict.get(b"Resources").map(|o| saved.resolve(o)).unwrap(); + let ext_gstates = resources.as_dict().unwrap().get(b"ExtGState").map(|o| saved.resolve(o)).unwrap(); + let selected = ext_gstates.as_dict().unwrap().get(b"GS").map(|o| saved.resolve(o)).unwrap(); + let font_ref = selected.as_dict().unwrap().get(b"Font").map(|o| saved.resolve(o)).unwrap().as_array().unwrap()[0].as_ref().unwrap(); + let font = saved.get(font_ref); + let charproc_ref = + font.as_dict().unwrap().get(b"CharProcs").map(|o| saved.resolve(o)).unwrap().as_dict().unwrap().get(b"A").unwrap().as_ref().unwrap(); + let charproc = saved.get(charproc_ref); + let glyph_content = match charproc.as_ref() { + Object::Stream(stream) => String::from_utf8_lossy(&stream.decoded().unwrap()).into_owned(), + _ => String::new(), + }; + assert!(glyph_content.contains("/GlyphImg Do")); + let font_resources = font.as_dict().unwrap().get(b"Resources").map(|o| saved.resolve(o)).unwrap(); + let glyph_image = font_resources.as_dict().unwrap().get(b"XObject").map(|o| saved.resolve(o)).unwrap(); + assert_eq!(glyph_image.as_dict().unwrap().get(b"GlyphImg").and_then(Object::as_ref), Some(target)); +} + +#[test] +fn appearance_dictionary_dag_exhaustion_skips_optional_image_pruning() { + const PRIVATE: &[u8] = b"PRIVATE_APPEARANCE_DAG_IMAGE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + + let mut child = doc.add(Object::Dict(Dict::new())); + for _ in 0..30 { + child = doc.add(Object::Dict(Dict::from_iter([(b"Left".to_vec(), Object::Ref(child)), (b"Right".to_vec(), Object::Ref(child))]))); + } + let appearance = Dict::from_iter([(b"N".to_vec(), Object::Ref(child))]); + let annotation = Dict::from_iter([(b"AP".to_vec(), Object::Dict(appearance))]); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Dict(annotation)]))).unwrap(); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); +} + +#[test] +fn unused_image_mask_dependency_is_removed_before_full_save() { + const PRIVATE: &[u8] = b"PRIVATE_UNUSED_IMAGE_MASK_DEPENDENCY"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + + let mut unused_image = identifiable_test_image(b"INACTIVE_IMAGE_OWNER"); + unused_image.dict.set(b"SMask".to_vec(), Object::Ref(target)); + let unused = doc.add(Object::Stream(unused_image)); + let mut mask_owner = identifiable_test_image(b"INACTIVE_MASK_OWNER"); + mask_owner.dict.set(b"Mask".to_vec(), Object::Ref(target)); + let mask_owner = doc.add(Object::Stream(mask_owner)); + let mut alternate = Dict::new(); + alternate.set(b"Image".to_vec(), Object::Ref(target)); + let mut alternate_owner = identifiable_test_image(b"INACTIVE_ALTERNATE_OWNER"); + alternate_owner.dict.set(b"Alternates".to_vec(), Object::Array(vec![Object::Dict(alternate)])); + let alternate_owner = doc.add(Object::Stream(alternate_owner)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Unused".to_vec(), Object::Ref(unused)); + xobjects.set(b"MaskOwner".to_vec(), Object::Ref(mask_owner)); + xobjects.set(b"AlternateOwner".to_vec(), Object::Ref(alternate_owner)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); + let saved = Document::open(Arc::new(bytes)).unwrap(); + let unused = saved.get(xobject(&saved, 0, b"Unused").unwrap()); + assert!(matches!(unused.as_ref(), Object::Stream(stream) if stream.dict.get(b"SMask").is_none())); + let mask_owner = saved.get(xobject(&saved, 0, b"MaskOwner").unwrap()); + assert!(matches!(mask_owner.as_ref(), Object::Stream(stream) if stream.dict.get(b"Mask").is_none())); + let alternate_owner = saved.get(xobject(&saved, 0, b"AlternateOwner").unwrap()); + assert!( + matches!(alternate_owner.as_ref(), Object::Stream(stream) if stream.dict.get(b"Alternates").and_then(Object::as_array).is_some_and(Vec::is_empty)) + ); +} + +#[test] +fn deleting_image_prunes_unused_shared_resources_across_all_pages() { + const PRIVATE: &[u8] = b"PRIVATE_UNUSED_SHARED_IMAGE"; + let mut doc = fixture(); + let target = doc.add(Object::Stream(identifiable_test_image(PRIVATE))); + doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| { + let mut xobjects = Dict::new(); + xobjects.set(b"Im0".to_vec(), Object::Ref(target)); + d.set(b"XObject".to_vec(), Object::Dict(xobjects)); + }) + .unwrap(); + let content = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/Im0 Do"))); + doc.update_dict(pdfcraft_cos::ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Ref(content))).unwrap(); + assert_eq!(images::page_images(&doc, 0).unwrap().len(), 1); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert!(xobject(&saved, 0, b"Im0").is_none()); + assert!(xobject(&saved, 1, b"Im0").is_none()); +} + +#[test] +fn image_mask_dependency_keeps_a_deleted_image_live() { + const PRIVATE: &[u8] = b"PRIVATE_IMAGE_MASK_DEPENDENCY"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut dependent = Dict::new(); + dependent.set(b"Type".to_vec(), Object::name("XObject")); + dependent.set(b"Subtype".to_vec(), Object::name("Image")); + dependent.set(b"Width".to_vec(), Object::Int(1)); + dependent.set(b"Height".to_vec(), Object::Int(1)); + dependent.set(b"ColorSpace".to_vec(), Object::name("DeviceGray")); + dependent.set(b"BitsPerComponent".to_vec(), Object::Int(8)); + dependent.set(b"SMask".to_vec(), Object::Ref(target)); + let dependent = doc.add(Object::Stream(Stream::from_raw(dependent, vec![1]))); + let mut chain_owner = Dict::new(); + chain_owner.set(b"Type".to_vec(), Object::name("XObject")); + chain_owner.set(b"Subtype".to_vec(), Object::name("Image")); + chain_owner.set(b"Width".to_vec(), Object::Int(1)); + chain_owner.set(b"Height".to_vec(), Object::Int(1)); + chain_owner.set(b"ColorSpace".to_vec(), Object::name("DeviceGray")); + chain_owner.set(b"BitsPerComponent".to_vec(), Object::Int(8)); + chain_owner.set(b"SMask".to_vec(), Object::Ref(dependent)); + let chain_owner = doc.add(Object::Stream(Stream::from_raw(chain_owner, vec![1]))); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Source Do"]); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Source".to_vec(), Object::Ref(chain_owner)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); +} + +#[test] +fn malformed_extgstate_soft_masks_skip_optional_image_pruning() { + const PRIVATE: &[u8] = b"PRIVATE_EXTGSTATE_IMAGE"; + let cases = [ + ("unresolved reference", Object::Ref(pdfcraft_cos::ObjRef::new(999_999, 0))), + ("non-dictionary", Object::String(pdfcraft_cos::PdfString::text("bad mask"))), + ("missing group", Object::Dict(Dict::new())), + ("malformed group", Object::Dict(Dict::from_iter([(b"G".to_vec(), Object::Int(7))]))), + ]; + + for (case, mask) in cases { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut gs = Dict::new(); + gs.set(b"SMask".to_vec(), mask); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"ExtGState".to_vec(), Object::Dict(Dict::from_iter([(b"GS".to_vec(), Object::Dict(gs))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs"]); + + assert!( + write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), + "{case} fixture lacked payload before edit" + ); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(saved.windows(PRIVATE.len()).any(|w| w == PRIVATE), "{case} unexpectedly allowed pruning"); + } + + // `/None` is the valid ExtGState spelling for no soft mask and does not block pruning. + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut gs = Dict::new(); + gs.set(b"SMask".to_vec(), Object::name("None")); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"ExtGState".to_vec(), Object::Dict(Dict::from_iter([(b"GS".to_vec(), Object::Dict(gs))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs"]); + assert!( + write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), + "valid /None fixture lacked payload before edit" + ); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!saved.windows(PRIVATE.len()).any(|w| w == PRIVATE), "valid /None prevented pruning"); +} + +#[test] +fn image_typed_soft_mask_group_skips_optional_image_pruning() { + const PRIVATE: &[u8] = b"PRIVATE_IMAGE_TYPED_SOFT_MASK_GROUP"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + + // The renderer decodes `/G` as a Form regardless of its declared subtype. Its content + // inherits the page resources, so the image remains a live consumer despite the bad type. + let group = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([(b"Subtype".to_vec(), Object::name("Image")), (b"BBox".to_vec(), Object::Array([0, 0, 1, 1].map(Object::Int).to_vec()))]), + b"/Im0 Do", + ))); + let mut soft_mask = Dict::new(); + soft_mask.set(b"G".to_vec(), Object::Ref(group)); + let mut gs = Dict::new(); + gs.set(b"SMask".to_vec(), Object::Dict(soft_mask)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"ExtGState".to_vec(), Object::Dict(Dict::from_iter([(b"GS".to_vec(), Object::Dict(gs))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs"]); + + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), "fixture lacked payload before edit"); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(saved.windows(PRIVATE.len()).any(|w| w == PRIVATE), "malformed image-typed SMask group unexpectedly allowed pruning"); +} + +#[test] +fn late_image_prune_staging_failure_does_not_partially_rewrite_resources() { + const PRIVATE: &[u8] = b"PRIVATE_LATE_PRUNE_FAILURE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), "fixture lacked payload before edit"); + + // This valid candidate is staged for removal before the later deeply nested object + // exceeds the rewrite walk budget. Nothing staged may be committed after that failure. + let holder = + doc.add(Object::Dict(Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"Alias".to_vec(), Object::Ref(target))])))]))); + let mut deep = Object::Null; + for _ in 0..=65 { + deep = Object::Array(vec![deep]); + } + doc.add(deep); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let holder = doc.resolve(&Object::Ref(holder)); + assert_eq!( + holder.as_dict().and_then(|d| d.get(b"XObject")).and_then(Object::as_dict).and_then(|d| d.get(b"Alias")).and_then(Object::as_ref), + Some(target) + ); + let saved = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(saved.windows(PRIVATE.len()).any(|w| w == PRIVATE), "failed optional prune partially removed the image payload"); +} + +#[test] +fn image_alternate_dependency_keeps_a_deleted_image_live() { + const PRIVATE: &[u8] = b"PRIVATE_IMAGE_ALTERNATE_DEPENDENCY"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut alternate = Dict::new(); + alternate.set(b"Image".to_vec(), Object::Ref(target)); + let mut primary = identifiable_test_image(b"PRIMARY_IMAGE"); + primary.dict.set(b"Alternates".to_vec(), Object::Array(vec![Object::Dict(alternate)])); + let primary = doc.add(Object::Stream(primary)); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Source Do"]); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Source".to_vec(), Object::Ref(primary)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); +} + +#[test] +fn unsupported_resource_consumer_skips_optional_pruning_but_keeps_edit_successful() { + const PRIVATE: &[u8] = b"PRIVATE_UNSUPPORTED_CONTEXT_IMAGE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut unknown = Dict::new(); + unknown.set(b"Subtype".to_vec(), Object::name("UnknownContent")); + unknown.set( + b"Resources".to_vec(), + Object::Dict(Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"Im0".to_vec(), Object::Ref(target))])))])), + ); + doc.add(Object::Stream(Stream::flate(unknown, b"/Im0 Do"))); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); +} + +#[test] +fn deleting_one_page_image_preserves_shared_inherited_resources_used_by_sibling_pages() { const SHARED: &[u8] = b"SHARED_INHERITED_IMAGE"; let mut doc = fixture(); let image = doc.add(Object::Stream(identifiable_test_image(SHARED))); @@ -2238,7 +2799,9 @@ fn deleting_one_page_image_detaches_inherited_resources_without_changing_sibling let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap(); assert!(images::page_images(&saved, 0).unwrap().is_empty()); assert_eq!(images::page_images(&saved, 1).unwrap().len(), 1); - assert!(xobject(&saved, 0, b"Im0").is_none()); + // Both pages inherit the same resource dictionary. Keep its mapping while the sibling page + // still draws the image; removing it would break that live use. + assert!(xobject(&saved, 0, b"Im0").is_some()); assert!(xobject(&saved, 1, b"Im0").is_some()); } @@ -2257,7 +2820,7 @@ fn replacing_an_image_with_the_same_object_keeps_the_replacement_reachable() { } #[test] -fn deleting_an_image_prunes_unused_aliases_but_keeps_aliases_still_drawn() { +fn deleting_an_image_prunes_unused_aliases_when_no_alias_is_drawn_and_keeps_live_aliases() { const ALIASED: &[u8] = b"ALIASED_IMAGE_BYTES"; let mut doc = image_page(); let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); @@ -2293,7 +2856,7 @@ fn deleting_an_image_prunes_unused_aliases_but_keeps_aliases_still_drawn() { images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap(); assert_eq!(images::page_images(&saved, 0).unwrap().len(), 1); - assert!(xobject(&saved, 0, b"Im0").is_none()); + assert!(xobject(&saved, 0, b"Im0").is_some()); assert!(xobject(&saved, 0, b"Alias").is_some()); } From 526b88d1f7ce7228104bbdf28dbd4e1c5916a277 Mon Sep 17 00:00:00 2001 From: Ahmad Mujahid Date: Tue, 20 Oct 2026 00:44:32 +0400 Subject: [PATCH 018/216] Refuse invalid tag parents before artifact mutation --- ROADMAP.md | 2 +- crates/a11y/src/alt.rs | 13 ++-- crates/a11y/tests/stm_refusal.rs | 107 +++++++++++++++++++++++++++++++ docs/roadmap.md | 4 +- parity/acrobat-features.toml | 4 +- 5 files changed, 119 insertions(+), 11 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 046971160c..7146684cba 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -171,7 +171,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md | 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 | ## Progress log -- **2026-10-18 (M12, #3221 mutation safety):** Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Synthetic tests check exact preservation, undo history and save/reopen. Form editing and stream-aware readouts stay outside this fix. Estimates unchanged. +- **2026-10-18 (M12, #3221 mutation safety):** Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Synthetic tests check exact preservation, undo history and save/reopen. Artifact marking also rejects missing or ambiguous parents before mutation, including indirect MCID ownership. Direct-library tests preserve clean and edited documents. Form editing and stream-aware readouts stay outside this fix. Estimates unchanged. - **2026-10-19 (M14, #3373):** The main menu and its long submenus scroll in short windows, keeping their commands reachable. Estimates unchanged. diff --git a/crates/a11y/src/alt.rs b/crates/a11y/src/alt.rs index 0b49c4b62f..e686a0b2f7 100644 --- a/crates/a11y/src/alt.rs +++ b/crates/a11y/src/alt.rs @@ -485,7 +485,8 @@ pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError> /// /// This deliberately refuses a tag with child structure elements. Converting a parent would /// otherwise silently discard semantic descendants. Form references and invalid page ownership -/// also refuse before the document changes. The visible page content is preserved: each +/// also refuse before the document changes. A missing or ambiguous parent also refuses before +/// mutation. The visible page content is preserved: each /// matching marked-content sequence changes from `BDC` with an MCID to `/Artifact BMC`. pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), ArtifactError> { tree_root(doc).ok_or(ArtifactError::Untagged)?; @@ -519,13 +520,14 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact if found != ids { return Err(ArtifactError::ContentNotFound); } + let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?; + let parent_kids = parent_kids_without_tag(doc, parent, obj)?; let stream = doc.add(Object::Stream(Stream::flate(Dict::new(), &pdfcraft_content::serialize_ops(&ops)))); doc.update_dict(page.obj, |p| p.set(b"Contents".to_vec(), Object::Ref(stream)))?; if let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int) { clear_parent_tree(doc, key, obj).map_err(|e| ArtifactError::ParentTree(e.to_string()))?; } - let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?; - remove_from_parent(doc, parent, obj)?; + doc.update_dict(parent, |p| p.set(b"K".to_vec(), parent_kids))?; // Keep the retired object valid if another object holds an out-of-tree reference to it. doc.update_dict(obj, |d| { d.remove(b"P"); @@ -533,7 +535,7 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact Ok(()) } -fn remove_from_parent(doc: &mut Document, parent: ObjRef, obj: ObjRef) -> Result<(), ArtifactError> { +fn parent_kids_without_tag(doc: &Document, parent: ObjRef, obj: ObjRef) -> Result { let kids = doc.get(parent).as_dict().and_then(|p| p.get(b"K").cloned()).ok_or(ArtifactError::NoParent)?; let replacement = match kids { Object::Array(items) => { @@ -545,8 +547,7 @@ fn remove_from_parent(doc: &mut Document, parent: ObjRef, obj: ObjRef) -> Result Object::Ref(r) if r == obj => Object::Array(Vec::new()), _ => return Err(ArtifactError::NoParent), }; - doc.update_dict(parent, |p| p.set(b"K".to_vec(), replacement))?; - Ok(()) + Ok(replacement) } /// Replace `obj` by null in the page's parent-tree array (`key`), in a flat /Nums tree. diff --git a/crates/a11y/tests/stm_refusal.rs b/crates/a11y/tests/stm_refusal.rs index 166c9927e9..3595c56056 100644 --- a/crates/a11y/tests/stm_refusal.rs +++ b/crates/a11y/tests/stm_refusal.rs @@ -301,3 +301,110 @@ fn annotation_reference_refusal_names_the_unsupported_content_and_preserves_its_ assert_eq!(nums[4], Object::Int(2)); } } + +fn assert_artifact_refusal_preserves(doc: &mut Document, expected: &pdfcraft_a11y::ArtifactError) { + let state = doc.read_state(); + let dirty = doc.is_modified(); + let modified = doc.modified_objects(); + let saved = pdfcraft_cos::write_full(doc, &Default::default()).unwrap(); + let objects: Vec<_> = (1..=12).map(|number| doc.get(ObjRef::new(number, 0))).collect(); + let streams = [stream(doc, 4), stream(doc, 10)]; + let tags = pdfcraft_a11y::tags(doc); + let alts = pdfcraft_a11y::figures(doc).into_iter().map(|figure| figure.alt).collect::>(); + assert!(tags.iter().any(|tag| tag.object == ObjRef::new(7, 0)), "the malformed leaf remains reachable"); + assert_eq!(pdfcraft_a11y::mark_tag_artifact(doc, ObjRef::new(7, 0)).as_ref(), Err(expected)); + assert!(state.matches(doc), "refusal preserves the exact overlay and allocates no stream"); + assert_eq!(doc.is_modified(), dirty); + assert_eq!(doc.modified_objects(), modified); + assert_eq!((1..=12).map(|number| doc.get(ObjRef::new(number, 0))).collect::>(), objects); + assert_eq!([stream(doc, 4), stream(doc, 10)], streams); + let after = pdfcraft_cos::write_full(doc, &Default::default()).unwrap(); + assert_eq!(after, saved); + // Full saves renumber objects; incremental saves retain the fixture IDs checked below. + let reopened = Document::open(Arc::new(pdfcraft_cos::write_incremental(doc, &Default::default()).unwrap())).unwrap(); + assert_eq!(pdfcraft_a11y::tags(&reopened), tags); + assert_eq!(pdfcraft_a11y::figures(&reopened).into_iter().map(|figure| figure.alt).collect::>(), alts); + assert_eq!([stream(&reopened, 4), stream(&reopened, 10)], streams); + assert_eq!(reopened.get(ObjRef::new(3, 0)), objects[2]); + assert_eq!(reopened.get(ObjRef::new(9, 0)), objects[8]); + assert_eq!(reopened.get(ObjRef::new(7, 0)), objects[6]); + assert_eq!( + reopened.get(ObjRef::new(9, 0)).as_dict().unwrap().get(b"Nums").unwrap().as_array().unwrap()[1], + Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]) + ); +} + +#[test] +fn artifact_parent_refusals_preserve_direct_library_state_and_saved_content() { + use pdfcraft_a11y::ArtifactError::{AmbiguousParent, NoParent}; + let cases = [ + (None, "<< >>", NoParent), + (Some(Object::Int(6)), "<< >>", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "null", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< >>", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< /K 3 >>", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< /K 8 0 R >>", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< /K [] >>", AmbiguousParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< /K [7 0 R 7 0 R] >>", AmbiguousParent), + ]; + for dirty in [false, true] { + for (parent, parent_object, expected) in &cases { + let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>", parent_object]); + doc.update_dict(ObjRef::new(7, 0), |dict| { + dict.remove(b"P"); + if let Some(parent) = parent { + dict.set(b"P".to_vec(), parent.clone()); + } + }) + .unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + if dirty { + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some("Saved later")).unwrap(); + } + assert_artifact_refusal_preserves(&mut doc, expected); + } + } +} + +#[test] +fn artifact_missing_page_content_precedes_invalid_parent_without_mutation() { + let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 1 /Pg 3 0 R >>"]); + doc.update_dict(ObjRef::new(7, 0), |dict| { + dict.remove(b"P"); + }) + .unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::ContentNotFound); +} + +#[test] +fn artifact_indirect_content_removes_scalar_or_array_parent_child_and_preserves_drawing() { + for scalar in [false, true] { + let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]); + if scalar { + doc.update_dict(ObjRef::new(6, 0), |dict| dict.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap(); + } + let original_form = stream(&doc, 10); + let other_figure = doc.get(ObjRef::new(8, 0)); + pdfcraft_a11y::mark_tag_artifact(&mut doc, ObjRef::new(7, 0)).unwrap(); + let reopened = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + let contents = reopened.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").unwrap().as_ref().unwrap(); + let ops = pdfcraft_content::parse(&stream(&reopened, contents.num)).ops; + assert!(ops.iter().any(|op| op.op == b"BMC" && op.operands == [Object::name("Artifact")])); + assert!(!ops.iter().any(|op| op.op == b"BDC")); + let rectangle = ops.iter().find(|op| op.op == b"re").unwrap(); + assert_eq!(rectangle.nums::<4>(), Some([10.0, 10.0, 20.0, 20.0])); + assert!(ops.iter().any(|op| op.op == b"f")); + assert!(ops.iter().any(|op| op.op == b"Do" && op.operands == [Object::name("Form")])); + assert_eq!(stream(&reopened, 10), original_form); + assert_eq!(reopened.get(ObjRef::new(8, 0)), other_figure); + let remaining = if scalar { vec![] } else { vec![Object::Ref(ObjRef::new(8, 0))] }; + assert_eq!(reopened.get(ObjRef::new(6, 0)).as_dict().unwrap().get(b"K"), Some(&Object::Array(remaining))); + assert!(!reopened.get(ObjRef::new(7, 0)).as_dict().unwrap().contains(b"P")); + assert_eq!(pdfcraft_a11y::tags(&reopened).iter().map(|tag| tag.object.num).collect::>(), if scalar { vec![6] } else { vec![6, 8] }); + assert_eq!( + reopened.get(ObjRef::new(9, 0)).as_dict().unwrap().get(b"Nums").unwrap().as_array().unwrap()[1], + Object::Array(vec![Object::Null]) + ); + } +} diff --git a/docs/roadmap.md b/docs/roadmap.md index 74ba5e01c1..75550d4ab3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -147,9 +147,9 @@ total matches the parity estimate. | M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.
Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 | | M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).
Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import | | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA | -| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA | +| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing or ambiguous parents before mutation, with exact direct-library preservation tests. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. | -| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645). | +| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing or ambiguous parents before mutation, with exact direct-library preservation tests. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645). | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. | | M14 | 1.0 polish: performance, localization, installers | 120–250 | 15% | 80–150 | Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, strict catalog tests); every dialog, panel and notice goes through `tl!`. Catalogs of ≈ 2,000–2,140 entries for Japanese, Simplified and Traditional Chinese, Russian, Bulgarian, German, Spanish, French, Telugu, Hungarian, Ukrainian, Brazilian Portuguese and Arabic (logical-order catalog put into display order; layout not yet mirrored); Czech covers the menus. Italian has 2,528 entries: every key of the other catalogs that the code looks up. Signed and notarized macOS builds, signed Windows installers (x64, x86, ARM64), AppImage, deb, rpm, Flatpak and FreeBSD packages. #307 (bounded large-PDF memory): shared resource indexes and parser metadata, lazy inspection, bounded caches; a 9,156-page file inspects in ≈ 1.8 s at ≈ 500 MiB instead of exceeding 10 GiB. Edits let go of the previous working file before writing the next (a 1 GiB file peaks at two copies while editing, not three; gap 13). Shortcut display uses localized modifier/key names across menus, toolbar, palette, Help and tooltips (#496). Lithuanian adds a 2,578-entry catalog and date names, reviewed by a native-speaking contributor. Validated candidate (macOS raster probe; Windows runtime unverified): the Windows policy changes only embedded JetBrains Mono; horizontal alpha-edge energy per ink improves 2.78%, 3.87% and 1.59% at 100%, 125% and 150%, and is down 0.79% at 200%. Inter is pixel-identical; layout hashes, glyph coverage and the 8 MiB atlas are unchanged. Timing and RSS ranges overlap, with no improvement claimed. Estimates unchanged. Candidate #2383 clamps GPU requests to supported limits while retaining the adapter texture extent; synthetic V3D/downlevel and Windows GPU-required tests pass, but Raspberry Pi startup is unverified. Estimates unchanged. Missing: a right-to-left layout, a Chinese UI face in releases, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation Linux/Unix UI fallback fonts also use Fontconfig directories, including Nix store paths, with bounded discovery and the existing candidate allowlist; relative includes and digit-prefixed config filtering have isolated regressions. | | M14 | 1.0 polish: performance, localization, installers | 120–250 | 15% | 80–150 | Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, strict catalog tests); every dialog, panel and notice goes through `tl!`. Catalogs of ≈ 2,000–2,140 entries for Japanese, Simplified and Traditional Chinese, Russian, Bulgarian, German, Spanish, French, Telugu, Hungarian, Ukrainian, Brazilian Portuguese and Arabic (logical-order catalog put into display order; layout not yet mirrored); Czech covers the menus. Italian has 2,528 entries: every key of the other catalogs that the code looks up. Signed and notarized macOS builds, signed Windows installers (x64, x86, ARM64), AppImage, deb, rpm, Flatpak and FreeBSD packages. #307 (bounded large-PDF memory): shared resource indexes and parser metadata, lazy inspection, bounded caches; a 9,156-page file inspects in ≈ 1.8 s at ≈ 500 MiB instead of exceeding 10 GiB. Edits let go of the previous working file before writing the next (a 1 GiB file peaks at two copies while editing, not three; gap 13). Shortcut display uses localized modifier/key names across menus, toolbar, palette, Help and tooltips (#496). Lithuanian adds a 2,578-entry catalog and date names, reviewed by a native-speaking contributor. Validated candidate (macOS raster probe; Windows runtime unverified): the Windows policy changes only embedded JetBrains Mono; horizontal alpha-edge energy per ink improves 2.78%, 3.87% and 1.59% at 100%, 125% and 150%, and is down 0.79% at 200%. Inter is pixel-identical; layout hashes, glyph coverage and the 8 MiB atlas are unchanged. Timing and RSS ranges overlap, with no improvement claimed. Estimates unchanged. Missing: a right-to-left layout, a Chinese UI face in releases, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation XDG desktops use the configuration base for preferences with non-overwriting migration and original-data preservation (#1395). | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 7ca78c97d6..a483e53678 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -8972,8 +8972,8 @@ milestone = "M12" status = "partial" commands = ["a11y.tags"] tools = ["accessibility_mark_tag_artifact"] -evidence = ["crates/a11y/src/tests.rs::marking_a_leaf_tag_as_an_artifact_preserves_appearance_and_structure_integrity", "crates/automation/tests/automation.rs::marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved", "crates/ui-egui/tests/accessibility.rs::tags_panel_marks_a_leaf_tag_as_an_artifact", "crates/a11y/tests/stm_refusal.rs::unsupported_owned_references_refuse_without_changing_document_or_saved_data", "crates/automation/tests/automation.rs::stream_tag_mutation_refusal_preserves_document_history_and_saved_content"] -notes = "Tags panel and automation can retire a reachable indirect leaf tag that owns direct MCIDs: its visible page content remains but becomes /Artifact and the parent-tree references are cleared. Tags with structural children, non-MCID content, missing pages or ambiguous parents are refused. Arbitrary painted-content selection, direct structure dictionaries and removing whole tagged subtrees remain unsupported. Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Figure locations and tag content reads still assume page content." +evidence = ["crates/a11y/src/tests.rs::marking_a_leaf_tag_as_an_artifact_preserves_appearance_and_structure_integrity", "crates/automation/tests/automation.rs::marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved", "crates/ui-egui/tests/accessibility.rs::tags_panel_marks_a_leaf_tag_as_an_artifact", "crates/a11y/tests/stm_refusal.rs::unsupported_owned_references_refuse_without_changing_document_or_saved_data", "crates/a11y/tests/stm_refusal.rs::artifact_parent_refusals_preserve_direct_library_state_and_saved_content", "crates/automation/tests/automation.rs::stream_tag_mutation_refusal_preserves_document_history_and_saved_content"] +notes = "Tags panel and automation can retire a reachable indirect leaf tag that owns direct MCIDs: its visible page content remains but becomes /Artifact and the parent-tree references are cleared. Tags with structural children, non-MCID content, missing pages or ambiguous parents are refused. Arbitrary painted-content selection, direct structure dictionaries and removing whole tagged subtrees remain unsupported. Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Missing or ambiguous parents refuse before artifact mutation, including indirect MCID ownership. Direct-library tests preserve clean and edited documents exactly. Figure locations and tag content reads still assume page content." [[feature]] id = "a11y.find-untagged" From 246cc9d5febb25b3f4a6bf042acb2c477b26b197 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Mon, 19 Oct 2026 15:37:17 -0600 Subject: [PATCH 019/216] fix(edit): handle blank pages and bound image cleanup rewrites --- crates/edit/src/images.rs | 148 +++++++++++++++++++++++++------------- crates/edit/src/tests.rs | 129 +++++++++++++++++++++++++++++++++ 2 files changed, 228 insertions(+), 49 deletions(-) diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rs index 065a5430c3..26b2d8e542 100644 --- a/crates/edit/src/images.rs +++ b/crates/edit/src/images.rs @@ -114,6 +114,38 @@ const IMAGE_CENSUS_MAX_OPERATORS: usize = 5_000_000; const IMAGE_CENSUS_MAX_VISITS: usize = 50_000; const IMAGE_CENSUS_MAX_DEPTH: usize = 64; const IMAGE_CENSUS_MAX_ALIASES: usize = 255; +const IMAGE_REWRITE_MAX_ENTRIES: usize = 500_000; +const IMAGE_REWRITE_MAX_CONTAINER_ENTRIES: usize = 100_000; +const IMAGE_REWRITE_MAX_KEY_BYTES: usize = 16 * 1024 * 1024; +const IMAGE_REWRITE_MAX_STAGED_OBJECTS: usize = IMAGE_CENSUS_MAX_ALIASES; + +/// Separate budget for the conservative cleanup rewrite walk. It counts every array item and +/// dictionary entry inspected, including primitive values, without recursively visiting scalar +/// leaves. This work is distinct from the executable-content census budget above. +#[derive(Default)] +struct ImageRewriteBudget { + entries: usize, + key_bytes: usize, +} + +impl ImageRewriteBudget { + fn charge_entries(&mut self, count: usize) -> Result<(), ()> { + if count > IMAGE_REWRITE_MAX_CONTAINER_ENTRIES { + return Err(()); + } + self.entries = self.entries.saturating_add(count); + if self.entries > IMAGE_REWRITE_MAX_ENTRIES { Err(()) } else { Ok(()) } + } + + fn charge_dict(&mut self, dict: &Dict) -> Result<(), ()> { + self.charge_entries(dict.len()) + } + + fn charge_key_bytes(&mut self, count: usize) -> Result<(), ()> { + self.key_bytes = self.key_bytes.saturating_add(count); + if self.key_bytes > IMAGE_REWRITE_MAX_KEY_BYTES { Err(()) } else { Ok(()) } + } +} /// A full-document, bounded census of executable resource consumers. `incomplete` means a /// conservative cleanup cannot prove that an image is unused, so callers must leave its bytes. @@ -502,9 +534,16 @@ fn prune_unused_image(doc: &mut Document, target: ObjRef) { return; } for page in &pages { - let Some(resources) = page.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()) else { - census.incomplete = true; - break; + let resources = match page.dict.get(b"Resources") { + None => Dict::new(), + Some(value) => { + let resolved = doc.resolve(value); + let Some(resources) = resolved.as_dict().cloned() else { + census.incomplete = true; + break; + }; + resources + } }; let contents_object = page.dict.get(b"Contents").map(|value| doc.resolve(value)); let contents: &[Object] = match contents_object.as_deref() { @@ -578,22 +617,21 @@ fn prune_unused_image(doc: &mut Document, target: ObjRef) { let mut indirect_xobject_dicts = std::collections::HashSet::new(); let mut indirect_alternate_arrays = std::collections::HashSet::new(); let mut aliases = 0usize; - let mut mapping_visits = 0usize; - let mut dependency_visits = 0usize; + let mut rewrite_budget = ImageRewriteBudget::default(); for (reference, item) in checked { let Ok(object) = item else { return }; let mut object = (*object).clone(); - let mappings_changed = match prune_xobject_mappings(&mut object, target, &mut indirect_xobject_dicts, &mut aliases, 0, &mut mapping_visits) { + let mappings_changed = match prune_xobject_mappings(&mut object, target, &mut indirect_xobject_dicts, &mut aliases, 0, &mut rewrite_budget) { Ok(changed) => changed, Err(()) => return, }; let dependencies_changed = - match prune_image_dependencies(&mut object, doc, target, &mut indirect_alternate_arrays, &mut aliases, 0, &mut dependency_visits) { + match prune_image_dependencies(&mut object, doc, target, &mut indirect_alternate_arrays, &mut aliases, 0, &mut rewrite_budget) { Ok(changed) => changed, Err(()) => return, }; if mappings_changed || dependencies_changed { - if aliases > IMAGE_CENSUS_MAX_ALIASES { + if aliases > IMAGE_CENSUS_MAX_ALIASES || staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS { return; } staged.insert(reference, object); @@ -602,12 +640,12 @@ fn prune_unused_image(doc: &mut Document, target: ObjRef) { for reference in indirect_xobject_dicts { let was_staged = staged.contains_key(&reference); let mut object = staged.remove(&reference).unwrap_or_else(|| (*doc.get(reference)).clone()); - let changed = match remove_target_aliases(object.as_dict_mut(), target, &mut aliases) { + let changed = match remove_target_aliases(object.as_dict_mut(), target, &mut aliases, &mut rewrite_budget) { Ok(changed) => changed, Err(()) => return, }; if changed || was_staged { - if aliases > IMAGE_CENSUS_MAX_ALIASES { + if aliases > IMAGE_CENSUS_MAX_ALIASES || (!was_staged && staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS) { return; } staged.insert(reference, object); @@ -616,12 +654,12 @@ fn prune_unused_image(doc: &mut Document, target: ObjRef) { for reference in indirect_alternate_arrays { let was_staged = staged.contains_key(&reference); let mut object = staged.remove(&reference).unwrap_or_else(|| (*doc.get(reference)).clone()); - let changed = match remove_target_alternate_entries(&mut object, doc, target, &mut aliases, &mut dependency_visits) { + let changed = match remove_target_alternate_entries(&mut object, doc, target, &mut aliases, &mut rewrite_budget) { Ok(changed) => changed, Err(()) => return, }; if changed { - if aliases > IMAGE_CENSUS_MAX_ALIASES { + if aliases > IMAGE_CENSUS_MAX_ALIASES || (!was_staged && staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS) { return; } staged.insert(reference, object); @@ -638,13 +676,12 @@ fn prune_unused_image(doc: &mut Document, target: ObjRef) { } } -fn remove_target_aliases(dict: Option<&mut Dict>, target: ObjRef, aliases: &mut usize) -> Result { +fn remove_target_aliases(dict: Option<&mut Dict>, target: ObjRef, aliases: &mut usize, budget: &mut ImageRewriteBudget) -> Result { let Some(dict) = dict else { return Ok(false) }; - if dict.iter().take(IMAGE_CENSUS_MAX_VISITS + 1).count() > IMAGE_CENSUS_MAX_VISITS { - return Err(()); - } + budget.charge_dict(dict)?; let mut names = Vec::new(); for (name, value) in dict.iter() { + budget.charge_key_bytes(name.len())?; if value.as_ref() == Some(target) { if aliases.saturating_add(names.len()) >= IMAGE_CENSUS_MAX_ALIASES { return Err(()); @@ -665,14 +702,17 @@ fn prune_xobject_mappings( indirect: &mut std::collections::HashSet, aliases: &mut usize, depth: usize, - visits: &mut usize, + budget: &mut ImageRewriteBudget, ) -> Result { - charge_object_walk(depth, visits)?; + if depth > IMAGE_CENSUS_MAX_DEPTH { + return Err(()); + } let mut changed = false; match object { Object::Array(values) => { - for value in values { - changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, visits)?; + budget.charge_entries(values.len())?; + for value in values.iter_mut().filter(|value| is_container(value)) { + changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, budget)?; } } Object::Dict(dict) | Object::Stream(pdfcraft_cos::Stream { dict, .. }) => { @@ -681,20 +721,21 @@ fn prune_xobject_mappings( Object::Ref(reference) => { indirect.insert(*reference); } - Object::Dict(mappings) => changed |= remove_target_aliases(Some(mappings), target, aliases)?, + Object::Dict(mappings) => changed |= remove_target_aliases(Some(mappings), target, aliases, budget)?, _ => {} } } let mut keys = Vec::new(); - for (key, _) in dict.iter() { - if keys.len() >= IMAGE_CENSUS_MAX_VISITS { - return Err(()); + budget.charge_dict(dict)?; + for (key, value) in dict.iter() { + budget.charge_key_bytes(key.len())?; + if is_container(value) { + keys.push(key.clone()); } - keys.push(key.clone()); } for key in keys { if let Some(value) = dict.get_mut(&key) { - changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, visits)?; + changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, budget)?; } } } @@ -703,13 +744,16 @@ fn prune_xobject_mappings( Ok(changed) } -fn contains_target_ref(object: &Object, target: ObjRef, depth: usize, visits: &mut usize) -> Result { - charge_object_walk(depth, visits)?; +fn contains_target_ref(object: &Object, target: ObjRef, depth: usize, budget: &mut ImageRewriteBudget) -> Result { + if depth > IMAGE_CENSUS_MAX_DEPTH { + return Err(()); + } match object { Object::Ref(reference) => Ok(*reference == target), Object::Array(values) => { - for value in values { - if contains_target_ref(value, target, depth + 1, visits)? { + budget.charge_entries(values.len())?; + for value in values.iter().filter(|value| matches!(value, Object::Array(_))) { + if contains_target_ref(value, target, depth + 1, budget)? { return Ok(true); } } @@ -723,12 +767,18 @@ fn alternate_uses_target(object: &Object, doc: &Document, target: ObjRef) -> boo doc.resolve(object).as_dict().and_then(|dict| dict.get(b"Image")).is_some_and(|image| image.as_ref() == Some(target)) } -fn remove_target_alternate_entries(object: &mut Object, doc: &Document, target: ObjRef, aliases: &mut usize, visits: &mut usize) -> Result { +fn remove_target_alternate_entries( + object: &mut Object, + doc: &Document, + target: ObjRef, + aliases: &mut usize, + budget: &mut ImageRewriteBudget, +) -> Result { let Object::Array(entries) = object else { return Ok(false) }; + budget.charge_entries(entries.len())?; let mut retained = Vec::new(); let mut removed = 0; for entry in entries.iter() { - charge_object_walk(1, visits)?; if alternate_uses_target(entry, doc, target) { if aliases.saturating_add(removed) >= IMAGE_CENSUS_MAX_ALIASES { return Err(()); @@ -755,21 +805,24 @@ fn prune_image_dependencies( indirect_alternate_arrays: &mut std::collections::HashSet, aliases: &mut usize, depth: usize, - visits: &mut usize, + budget: &mut ImageRewriteBudget, ) -> Result { - charge_object_walk(depth, visits)?; + if depth > IMAGE_CENSUS_MAX_DEPTH { + return Err(()); + } let mut changed = false; match object { Object::Array(values) => { - for value in values { - changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, visits)?; + budget.charge_entries(values.len())?; + for value in values.iter_mut().filter(|value| is_container(value)) { + changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, budget)?; } } Object::Dict(dict) | Object::Stream(pdfcraft_cos::Stream { dict, .. }) => { if dict.name(b"Subtype") == Some(b"Image") { for key in [b"SMask".as_slice(), b"Mask".as_slice()] { let contains_target = - if let Some(value) = dict.get(key) { contains_target_ref(value, target, depth + 1, visits)? } else { false }; + if let Some(value) = dict.get(key) { contains_target_ref(value, target, depth + 1, budget)? } else { false }; if contains_target { if aliases.saturating_add(1) > IMAGE_CENSUS_MAX_ALIASES { return Err(()); @@ -782,10 +835,10 @@ fn prune_image_dependencies( match dict.get(b"Alternates") { Some(Object::Array(_)) => { let Some(Object::Array(entries)) = dict.get_mut(b"Alternates") else { return Err(()) }; + budget.charge_entries(entries.len())?; let mut retained = Vec::new(); let mut removed = 0; for entry in entries.iter() { - charge_object_walk(depth + 1, visits)?; if alternate_uses_target(entry, doc, target) { if aliases.saturating_add(removed) >= IMAGE_CENSUS_MAX_ALIASES { return Err(()); @@ -808,15 +861,16 @@ fn prune_image_dependencies( } } let mut keys = Vec::new(); - for (key, _) in dict.iter() { - if keys.len() >= IMAGE_CENSUS_MAX_VISITS { - return Err(()); + budget.charge_dict(dict)?; + for (key, value) in dict.iter() { + budget.charge_key_bytes(key.len())?; + if is_container(value) { + keys.push(key.clone()); } - keys.push(key.clone()); } for key in keys { if let Some(value) = dict.get_mut(&key) { - changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, visits)?; + changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, budget)?; } } } @@ -825,12 +879,8 @@ fn prune_image_dependencies( Ok(changed) } -fn charge_object_walk(depth: usize, visits: &mut usize) -> Result<(), ()> { - if depth > IMAGE_CENSUS_MAX_DEPTH { - return Err(()); - } - *visits = visits.saturating_add(1); - if *visits > IMAGE_CENSUS_MAX_VISITS { Err(()) } else { Ok(()) } +fn is_container(object: &Object) -> bool { + matches!(object, Object::Array(_) | Object::Dict(_) | Object::Stream(_)) } fn intersection(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> { diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index d7a25af3af..1cdc6bccad 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -2252,6 +2252,62 @@ fn set_image_content(doc: &mut Document, page: usize, pieces: &[&[u8]]) { doc.update_dict(page, |d| d.set(b"Contents".to_vec(), Object::Array(contents))).unwrap(); } +fn add_blank_page(doc: &mut Document, resources: Option) { + let mut page = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Page")), + (b"Parent".to_vec(), Object::Ref(pdfcraft_cos::ObjRef::new(2, 0))), + (b"MediaBox".to_vec(), Object::Array([0, 0, 600, 800].map(Object::Int).to_vec())), + ]); + if let Some(resources) = resources { + page.set(b"Resources".to_vec(), resources); + } + let added = doc.add(Object::Dict(page)); + doc.update_dict(pdfcraft_cos::ObjRef::new(2, 0), |d| { + d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(pdfcraft_cos::ObjRef::new(3, 0)), Object::Ref(added)])); + d.set(b"Count".to_vec(), Object::Int(2)); + }) + .unwrap(); +} + +fn image_pruning_fixture(blank_resources: Option>, font_count: usize, private: &[u8]) -> Document { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(private))); + if let Some(resources) = blank_resources { + add_blank_page(&mut doc, resources); + } + if font_count > 0 { + let mut fonts = doc + .get(pdfcraft_model::pages(&doc)[0].obj) + .as_dict() + .and_then(|d| d.get(b"Resources")) + .and_then(Object::as_dict) + .and_then(|d| d.get(b"Font")) + .and_then(Object::as_dict) + .cloned() + .unwrap_or_default(); + for index in 0..font_count { + let font = doc.add(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")), + (b"FirstChar".to_vec(), Object::Int(32)), + (b"LastChar".to_vec(), Object::Int(255)), + (b"Widths".to_vec(), Object::Array(vec![Object::Int(500); 224])), + ]))); + fonts.set(format!("ReviewFont{index}").into_bytes(), Object::Ref(font)); + } + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + resources.set(b"Font".to_vec(), Object::Dict(fonts)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + } + doc +} + #[test] fn deleted_image_is_kept_when_reachable_through_each_non_page_consumer() { const PRIVATE: &[u8] = b"PRIVATE_CONTEXT_IMAGE"; @@ -2582,6 +2638,79 @@ fn deleting_image_prunes_unused_shared_resources_across_all_pages() { assert!(xobject(&saved, 1, b"Im0").is_none()); } +#[test] +fn image_payload_pruning_handles_missing_resources_and_wide_scalar_arrays() { + const PRIVATE: &[u8] = b"PRIVATE_REVIEW_DELETED_IMAGE_PAYLOAD"; + for (resources, font_count) in [(Some(None), 0), (Some(Some(Object::Dict(Dict::new()))), 0), (None, 225)] { + for replace in [false, true] { + let mut source = image_pruning_fixture(resources.clone(), font_count, PRIVATE); + let input = write_full(&source, &SaveOptions::default()).unwrap(); + assert!(input.windows(PRIVATE.len()).any(|window| window == PRIVATE), "fixture lacked payload before editing"); + source = Document::open(Arc::new(input)).unwrap(); + let change = if replace { + images::ImageChange::Replace(source.add(Object::Stream(identifiable_test_image(b"PUBLIC_REPLACEMENT")))) + } else { + images::ImageChange::Delete + }; + images::change_image(&mut source, 0, 0, &change).unwrap(); + + let output = write_full(&source, &SaveOptions::default()).unwrap(); + let reopened = Document::open(Arc::new(output.clone())).unwrap(); + assert!(!output.windows(PRIVATE.len()).any(|window| window == PRIVATE), "replace={replace}, resources={resources:?}, fonts={font_count}"); + assert_eq!(images::page_images(&reopened, 0).unwrap().len(), usize::from(replace)); + } + } +} + +#[test] +fn malformed_present_page_resources_keep_image_payload() { + const PRIVATE: &[u8] = b"PRIVATE_MALFORMED_RESOURCES_IMAGE"; + let mut source = image_pruning_fixture(None, 0, PRIVATE); + add_blank_page(&mut source, Some(Object::Int(7))); + let input = write_full(&source, &SaveOptions::default()).unwrap(); + assert!(input.windows(PRIVATE.len()).any(|window| window == PRIVATE), "fixture lacked payload before editing"); + let mut source = Document::open(Arc::new(input)).unwrap(); + + images::change_image(&mut source, 0, 0, &images::ImageChange::Delete).unwrap(); + let output = write_full(&source, &SaveOptions::default()).unwrap(); + assert!(output.windows(PRIVATE.len()).any(|window| window == PRIVATE), "malformed present Resources unexpectedly allowed pruning"); +} + +#[test] +fn rewrite_entry_budget_failure_keeps_earlier_staged_image_mappings() { + const PRIVATE: &[u8] = b"PRIVATE_REWRITE_BUDGET_IMAGE"; + const OVERSIZED_CONTAINER: usize = 100_001; + let mut source = image_pruning_fixture(None, 0, PRIVATE); + let form = source.add(Object::Stream(Stream::flate( + Dict::from_iter([ + (b"Subtype".to_vec(), Object::name("Form")), + (b"BBox".to_vec(), Object::Array([0, 0, 10, 10].map(Object::Int).to_vec())), + (b"Probe".to_vec(), Object::Array(vec![Object::Int(0); OVERSIZED_CONTAINER])), + ]), + b"", + ))); + let page = pdfcraft_model::pages(&source)[0].obj; + source + .update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"F".to_vec(), Object::Ref(form)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut source, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /F Do"]); + let input = write_full(&source, &SaveOptions::default()).unwrap(); + assert!(input.windows(PRIVATE.len()).any(|window| window == PRIVATE), "fixture lacked payload before editing"); + let mut source = Document::open(Arc::new(input)).unwrap(); + + images::change_image(&mut source, 0, 0, &images::ImageChange::Delete).unwrap(); + let output = write_full(&source, &SaveOptions::default()).unwrap(); + let reopened = Document::open(Arc::new(output.clone())).unwrap(); + assert!(output.windows(PRIVATE.len()).any(|window| window == PRIVATE), "rewrite budget failure pruned image payload"); + assert!(xobject(&reopened, 0, b"Im0").is_some(), "partial staging removed the page's image alias"); +} + #[test] fn image_mask_dependency_keeps_a_deleted_image_live() { const PRIVATE: &[u8] = b"PRIVATE_IMAGE_MASK_DEPENDENCY"; From e5ebbeb607d58054559195436ee3acee5944269c Mon Sep 17 00:00:00 2001 From: Ahmad Mujahid Date: Tue, 20 Oct 2026 11:17:56 +0400 Subject: [PATCH 020/216] Verify reachable parent before artifact conversion --- ROADMAP.md | 2 +- crates/a11y/src/alt.rs | 8 +++- crates/a11y/tests/stm_refusal.rs | 63 ++++++++++++++++++++++++++++++-- docs/roadmap.md | 4 +- parity/acrobat-features.toml | 4 +- 5 files changed, 71 insertions(+), 10 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 7146684cba..6742322947 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -171,7 +171,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md | 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 | ## Progress log -- **2026-10-18 (M12, #3221 mutation safety):** Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Synthetic tests check exact preservation, undo history and save/reopen. Artifact marking also rejects missing or ambiguous parents before mutation, including indirect MCID ownership. Direct-library tests preserve clean and edited documents. Form editing and stream-aware readouts stay outside this fix. Estimates unchanged. +- **2026-10-18 (M12, #3221 mutation safety):** Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Synthetic tests check exact preservation, undo history and save/reopen. Artifact marking also rejects missing, ambiguous or mismatched parents before mutation, including indirect MCID ownership. Direct-library tests preserve clean and edited documents. Form editing and stream-aware readouts stay outside this fix. Estimates unchanged. - **2026-10-19 (M14, #3373):** The main menu and its long submenus scroll in short windows, keeping their commands reachable. Estimates unchanged. diff --git a/crates/a11y/src/alt.rs b/crates/a11y/src/alt.rs index e686a0b2f7..aba534ec14 100644 --- a/crates/a11y/src/alt.rs +++ b/crates/a11y/src/alt.rs @@ -485,7 +485,7 @@ pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError> /// /// This deliberately refuses a tag with child structure elements. Converting a parent would /// otherwise silently discard semantic descendants. Form references and invalid page ownership -/// also refuse before the document changes. A missing or ambiguous parent also refuses before +/// also refuse before the document changes. A missing, ambiguous or mismatched parent also refuses before /// mutation. The visible page content is preserved: each /// matching marked-content sequence changes from `BDC` with an MCID to `/Artifact BMC`. pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), ArtifactError> { @@ -522,6 +522,12 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact } let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?; let parent_kids = parent_kids_without_tag(doc, parent, obj)?; + let reachable_parent = element + .parent + .or_else(|| doc.root().and_then(|catalog| doc.get(catalog).as_dict().and_then(|dict| dict.get(b"StructTreeRoot").and_then(Object::as_ref)))); + if reachable_parent != Some(parent) { + return Err(ArtifactError::NoParent); + } let stream = doc.add(Object::Stream(Stream::flate(Dict::new(), &pdfcraft_content::serialize_ops(&ops)))); doc.update_dict(page.obj, |p| p.set(b"Contents".to_vec(), Object::Ref(stream)))?; if let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int) { diff --git a/crates/a11y/tests/stm_refusal.rs b/crates/a11y/tests/stm_refusal.rs index 3595c56056..459b165690 100644 --- a/crates/a11y/tests/stm_refusal.rs +++ b/crates/a11y/tests/stm_refusal.rs @@ -366,6 +366,47 @@ fn artifact_parent_refusals_preserve_direct_library_state_and_saved_content() { } } +#[test] +fn artifact_mismatched_parent_refuses_before_changing_content_or_saved_state() { + for dirty in [false, true] { + for indirect in [false, true] { + for root in [false, true] { + let kids = if indirect { "11 0 R" } else { "0" }; + let mut doc = page_owned(kids, &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>", "<< /Type /StructElem /S /Document /K [7 0 R] >>"]); + if root { + doc.update_dict(ObjRef::new(5, 0), |dict| dict.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap(); + } + doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(ObjRef::new(12, 0)))).unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + if dirty { + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(7, 0), Some("Saved later")).unwrap(); + } + assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::NoParent); + } + } + } +} + +#[test] +fn artifact_inline_parent_does_not_become_a_removable_indirect_ancestor() { + for dirty in [false, true] { + for root in [false, true] { + let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]); + let parent = ObjRef::new(if root { 5 } else { 6 }, 0); + let mut inline = pdfcraft_cos::Dict::new(); + inline.set(b"S".to_vec(), Object::name("Document")); + inline.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0))); + doc.update_dict(parent, |dict| dict.set(b"K".to_vec(), Object::Dict(inline))).unwrap(); + doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(parent))).unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + if dirty { + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(7, 0), Some("Saved later")).unwrap(); + } + assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::NoParent); + } + } +} + #[test] fn artifact_missing_page_content_precedes_invalid_parent_without_mutation() { let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 1 /Pg 3 0 R >>"]); @@ -379,10 +420,18 @@ fn artifact_missing_page_content_precedes_invalid_parent_without_mutation() { #[test] fn artifact_indirect_content_removes_scalar_or_array_parent_child_and_preserves_drawing() { - for scalar in [false, true] { + for (root, scalar) in [(false, false), (false, true), (true, false), (true, true)] { let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]); + let parent = ObjRef::new(if root { 5 } else { 6 }, 0); + if root { + doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(parent))).unwrap(); + doc.update_dict(parent, |dict| { + dict.set(b"K".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(7, 0)), Object::Ref(ObjRef::new(8, 0))])) + }) + .unwrap(); + } if scalar { - doc.update_dict(ObjRef::new(6, 0), |dict| dict.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap(); + doc.update_dict(parent, |dict| dict.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap(); } let original_form = stream(&doc, 10); let other_figure = doc.get(ObjRef::new(8, 0)); @@ -399,9 +448,15 @@ fn artifact_indirect_content_removes_scalar_or_array_parent_child_and_preserves_ assert_eq!(stream(&reopened, 10), original_form); assert_eq!(reopened.get(ObjRef::new(8, 0)), other_figure); let remaining = if scalar { vec![] } else { vec![Object::Ref(ObjRef::new(8, 0))] }; - assert_eq!(reopened.get(ObjRef::new(6, 0)).as_dict().unwrap().get(b"K"), Some(&Object::Array(remaining))); + assert_eq!(reopened.get(parent).as_dict().unwrap().get(b"K"), Some(&Object::Array(remaining))); assert!(!reopened.get(ObjRef::new(7, 0)).as_dict().unwrap().contains(b"P")); - assert_eq!(pdfcraft_a11y::tags(&reopened).iter().map(|tag| tag.object.num).collect::>(), if scalar { vec![6] } else { vec![6, 8] }); + let expected_tags = match (root, scalar) { + (false, false) => vec![6, 8], + (false, true) => vec![6], + (true, false) => vec![8], + (true, true) => vec![], + }; + assert_eq!(pdfcraft_a11y::tags(&reopened).iter().map(|tag| tag.object.num).collect::>(), expected_tags); assert_eq!( reopened.get(ObjRef::new(9, 0)).as_dict().unwrap().get(b"Nums").unwrap().as_array().unwrap()[1], Object::Array(vec![Object::Null]) diff --git a/docs/roadmap.md b/docs/roadmap.md index 75550d4ab3..6dac75d3f6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -147,9 +147,9 @@ total matches the parity estimate. | M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.
Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 | | M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).
Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import | | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA | -| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing or ambiguous parents before mutation, with exact direct-library preservation tests. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA | +| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing, ambiguous or mismatched parents before mutation, with exact direct-library preservation tests. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. | -| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing or ambiguous parents before mutation, with exact direct-library preservation tests. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645). | +| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing, ambiguous or mismatched parents before mutation, with exact direct-library preservation tests. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645). | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. | | M14 | 1.0 polish: performance, localization, installers | 120–250 | 15% | 80–150 | Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, strict catalog tests); every dialog, panel and notice goes through `tl!`. Catalogs of ≈ 2,000–2,140 entries for Japanese, Simplified and Traditional Chinese, Russian, Bulgarian, German, Spanish, French, Telugu, Hungarian, Ukrainian, Brazilian Portuguese and Arabic (logical-order catalog put into display order; layout not yet mirrored); Czech covers the menus. Italian has 2,528 entries: every key of the other catalogs that the code looks up. Signed and notarized macOS builds, signed Windows installers (x64, x86, ARM64), AppImage, deb, rpm, Flatpak and FreeBSD packages. #307 (bounded large-PDF memory): shared resource indexes and parser metadata, lazy inspection, bounded caches; a 9,156-page file inspects in ≈ 1.8 s at ≈ 500 MiB instead of exceeding 10 GiB. Edits let go of the previous working file before writing the next (a 1 GiB file peaks at two copies while editing, not three; gap 13). Shortcut display uses localized modifier/key names across menus, toolbar, palette, Help and tooltips (#496). Lithuanian adds a 2,578-entry catalog and date names, reviewed by a native-speaking contributor. Validated candidate (macOS raster probe; Windows runtime unverified): the Windows policy changes only embedded JetBrains Mono; horizontal alpha-edge energy per ink improves 2.78%, 3.87% and 1.59% at 100%, 125% and 150%, and is down 0.79% at 200%. Inter is pixel-identical; layout hashes, glyph coverage and the 8 MiB atlas are unchanged. Timing and RSS ranges overlap, with no improvement claimed. Estimates unchanged. Candidate #2383 clamps GPU requests to supported limits while retaining the adapter texture extent; synthetic V3D/downlevel and Windows GPU-required tests pass, but Raspberry Pi startup is unverified. Estimates unchanged. Missing: a right-to-left layout, a Chinese UI face in releases, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation Linux/Unix UI fallback fonts also use Fontconfig directories, including Nix store paths, with bounded discovery and the existing candidate allowlist; relative includes and digit-prefixed config filtering have isolated regressions. | | M14 | 1.0 polish: performance, localization, installers | 120–250 | 15% | 80–150 | Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, strict catalog tests); every dialog, panel and notice goes through `tl!`. Catalogs of ≈ 2,000–2,140 entries for Japanese, Simplified and Traditional Chinese, Russian, Bulgarian, German, Spanish, French, Telugu, Hungarian, Ukrainian, Brazilian Portuguese and Arabic (logical-order catalog put into display order; layout not yet mirrored); Czech covers the menus. Italian has 2,528 entries: every key of the other catalogs that the code looks up. Signed and notarized macOS builds, signed Windows installers (x64, x86, ARM64), AppImage, deb, rpm, Flatpak and FreeBSD packages. #307 (bounded large-PDF memory): shared resource indexes and parser metadata, lazy inspection, bounded caches; a 9,156-page file inspects in ≈ 1.8 s at ≈ 500 MiB instead of exceeding 10 GiB. Edits let go of the previous working file before writing the next (a 1 GiB file peaks at two copies while editing, not three; gap 13). Shortcut display uses localized modifier/key names across menus, toolbar, palette, Help and tooltips (#496). Lithuanian adds a 2,578-entry catalog and date names, reviewed by a native-speaking contributor. Validated candidate (macOS raster probe; Windows runtime unverified): the Windows policy changes only embedded JetBrains Mono; horizontal alpha-edge energy per ink improves 2.78%, 3.87% and 1.59% at 100%, 125% and 150%, and is down 0.79% at 200%. Inter is pixel-identical; layout hashes, glyph coverage and the 8 MiB atlas are unchanged. Timing and RSS ranges overlap, with no improvement claimed. Estimates unchanged. Missing: a right-to-left layout, a Chinese UI face in releases, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation XDG desktops use the configuration base for preferences with non-overwriting migration and original-data preservation (#1395). | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index a483e53678..0f92b62c95 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -8972,8 +8972,8 @@ milestone = "M12" status = "partial" commands = ["a11y.tags"] tools = ["accessibility_mark_tag_artifact"] -evidence = ["crates/a11y/src/tests.rs::marking_a_leaf_tag_as_an_artifact_preserves_appearance_and_structure_integrity", "crates/automation/tests/automation.rs::marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved", "crates/ui-egui/tests/accessibility.rs::tags_panel_marks_a_leaf_tag_as_an_artifact", "crates/a11y/tests/stm_refusal.rs::unsupported_owned_references_refuse_without_changing_document_or_saved_data", "crates/a11y/tests/stm_refusal.rs::artifact_parent_refusals_preserve_direct_library_state_and_saved_content", "crates/automation/tests/automation.rs::stream_tag_mutation_refusal_preserves_document_history_and_saved_content"] -notes = "Tags panel and automation can retire a reachable indirect leaf tag that owns direct MCIDs: its visible page content remains but becomes /Artifact and the parent-tree references are cleared. Tags with structural children, non-MCID content, missing pages or ambiguous parents are refused. Arbitrary painted-content selection, direct structure dictionaries and removing whole tagged subtrees remain unsupported. Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Missing or ambiguous parents refuse before artifact mutation, including indirect MCID ownership. Direct-library tests preserve clean and edited documents exactly. Figure locations and tag content reads still assume page content." +evidence = ["crates/a11y/src/tests.rs::marking_a_leaf_tag_as_an_artifact_preserves_appearance_and_structure_integrity", "crates/automation/tests/automation.rs::marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved", "crates/ui-egui/tests/accessibility.rs::tags_panel_marks_a_leaf_tag_as_an_artifact", "crates/a11y/tests/stm_refusal.rs::unsupported_owned_references_refuse_without_changing_document_or_saved_data", "crates/a11y/tests/stm_refusal.rs::artifact_parent_refusals_preserve_direct_library_state_and_saved_content", "crates/a11y/tests/stm_refusal.rs::artifact_mismatched_parent_refuses_before_changing_content_or_saved_state", "crates/automation/tests/automation.rs::stream_tag_mutation_refusal_preserves_document_history_and_saved_content"] +notes = "Tags panel and automation can retire a reachable indirect leaf tag that owns direct MCIDs: its visible page content remains but becomes /Artifact and the parent-tree references are cleared. Tags with structural children, non-MCID content, missing pages or ambiguous parents are refused. Arbitrary painted-content selection, direct structure dictionaries and removing whole tagged subtrees remain unsupported. Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Missing, ambiguous or mismatched parents refuse before artifact mutation, including indirect MCID ownership. Direct-library tests preserve clean and edited documents exactly. Figure locations and tag content reads still assume page content." [[feature]] id = "a11y.find-untagged" From 97e8209f8771587adac09cc6a97f597684f0395c Mon Sep 17 00:00:00 2001 From: Ahmad Mujahid Date: Tue, 20 Oct 2026 15:16:44 +0400 Subject: [PATCH 021/216] docs(M12): clarify remaining mixed-content tag writing --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 6dac75d3f6..e7df5c7804 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -147,7 +147,7 @@ total matches the parity estimate. | M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.
Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 | | M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).
Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import | | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA | -| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing, ambiguous or mismatched parents before mutation, with exact direct-library preservation tests. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA | +| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing, ambiguous or mismatched parents before mutation, with exact direct-library preservation tests. Missing: mixed-content tag writing, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. | | M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds.
Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Decorative and artifact actions refuse unsupported ownership before any mutation (#3221, mutation safety only). This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Artifact marking also rejects missing, ambiguous or mismatched parents before mutation, with exact direct-library preservation tests. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA
Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645). | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers
Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. | From 08f5fa2734182fe5d35d7ecb9f6c8eb6ba88d8eb Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Wed, 21 Oct 2026 20:47:44 +0800 Subject: [PATCH 022/216] 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 023/216] 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 024/216] 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 025/216] 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 026/216] 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 027/216] 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 028/216] 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 029/216] 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 030/216] 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 031/216] 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 756a7fbff941b74ebe5034daf7845fc2398f89f2 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:02:40 -0400 Subject: [PATCH 032/216] M12: XFA check boxes and radio buttons run their click scripts when a click changes them --- crates/automation/tests/it/automation.rs | 27 ++++++++++++ crates/engine/src/tests.rs | 31 ++++++++++++++ crates/engine/src/xfa.rs | 54 +++++++++++++++++++++--- crates/ui-egui/tests/it/xfa.rs | 29 +++++++++++++ crates/xfa/src/fixtures.rs | 36 ++++++++++++++++ parity/acrobat-features.toml | 4 +- 6 files changed, 173 insertions(+), 8 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 9fd5c4269a..bdf6de9952 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6833,6 +6833,33 @@ fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() { assert_eq!(r["alerts"], json!(["Hello 4"])); } +/// Filling an XFA check box or radio group through form_fill clicks it, as the app does: the +/// field's change scripts, then the click scripts of what was clicked. +#[test] +fn xfa_check_box_and_radio_clicks_run_through_form_fill() { + let dir = workdir("xfa-toggle"); + std::fs::write(dir.join("toggle.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "toggle.pdf" }))["doc"].as_u64().unwrap(); + let log = |a: &mut Automation| { + let f = ok(a, "form_fields", json!({ "doc": doc })); + f["fields"] + .as_array() + .unwrap() + .iter() + .find(|f| f["name"] == "log") + .map(|f| f["value"].as_str().unwrap_or_default().to_string()) + .unwrap_or_default() + }; + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "agree": true } })); + assert_eq!(log(&mut a), "change 1;click 1;"); + let fields = ok(&mut a, "form_fields", json!({ "doc": doc })); + let answer = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "answer").cloned().expect("the radio group"); + let no = answer["options"].as_array().and_then(|o| o.get(1)).and_then(|o| o.as_str().map(str::to_string)).unwrap_or_else(|| panic!("{answer}")); + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "answer": no } })); + assert!(log(&mut a).ends_with("no click;"), "{}", log(&mut a)); +} + #[test] fn doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off() { let dir = workdir("xfa-scripts-off"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ed4e6efa1c..070314e332 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5080,6 +5080,37 @@ fn xfa_data_import_on_a_static_form_replaces_every_value_and_pictures_reach_its_ assert!(xml.contains("Bob") && !xml.contains("1"), "{xml}"); } +/// A click on an XFA check box or radio button runs the field's change scripts, then the click +/// scripts of what was clicked, which read the new value, show messages and may ask for the focus; +/// all as one undo step. A text field's click script doesn't run when its value changes. +#[test] +fn xfa_check_box_and_radio_button_clicks_run_their_click_scripts() { + let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())); + let mut s = Session::new(); + let id = s.open("toggle.pdf", None, bytes, None).expect("opens"); + let log = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "log").and_then(|f| f.value.first().cloned()).unwrap_or_default(); + s.apply(id, Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(true) }).unwrap(); + assert_eq!(log(&s), "change 1;click 1;", "change, then click, each seeing the new value"); + let out = s.take_js_output(id); + assert_eq!(out.alerts, ["Agreed"]); + assert!(out.requests.iter().any(|r| matches!(r, pdfcraft_js::Request::Focus(n) if n == "note")), "a click may move the focus: {out:?}"); + s.apply(id, Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(false) }).unwrap(); + assert_eq!(log(&s), "change 1;click 1;change 0;click 0;", "turning it off is a click too"); + // One undo step takes back the click and what its scripts did. + s.undo(id).unwrap(); + assert_eq!(log(&s), "change 1;click 1;"); + // A radio button runs its own click script, the one now on. + let state = |s: &Session, i: usize| s.get(id).unwrap().form.iter().find(|f| f.name == "answer").and_then(|f| f.widgets.get(i)?.on_state.clone()); + let (yes, no) = (state(&s, 0).expect("yes"), state(&s, 1).expect("no")); + s.apply(id, Edit::SetFieldValue { name: "answer".into(), value: FieldValue::Radio(Some(no)) }).unwrap(); + assert!(log(&s).ends_with("no click;"), "{}", log(&s)); + s.apply(id, Edit::SetFieldValue { name: "answer".into(), value: FieldValue::Radio(Some(yes)) }).unwrap(); + assert!(log(&s).ends_with("no click;yes click;"), "{}", log(&s)); + // A text field's value isn't set by a click. + s.apply(id, Edit::SetFieldValue { name: "note".into(), value: FieldValue::Text("typed".into()) }).unwrap(); + assert!(!log(&s).contains("note click"), "{}", log(&s)); +} + /// Importing data into a dynamic form adds and removes the rows of its repeating subform to /// match, and the calculations over them run again. #[test] diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index 6166426bbf..fa0d2f1fd5 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -212,15 +212,28 @@ struct FieldInfo { on_state: String, /// List boxes that take several values (one per line in the data). multi: bool, + /// Radio groups: each button's on state and SOM path (each button of an XFA radio group is a + /// field of its own, with scripts of its own). + buttons: Vec<(String, String)>, } +/// The generated fields of `doc`, by name, as the runner tracks them. fn field_infos(doc: &pdfcraft_cos::Document) -> HashMap { + let som_of = |obj: pdfcraft_cos::ObjRef| { + let object = doc.get(obj); + object.as_dict()?.get(pdfcraft_xfa::SOM_KEY).map(|s| doc.resolve(s))?.as_string().map(|s| s.to_text()) + }; pdfcraft_forms::fields(doc) .into_iter() .map(|f| { let on_state = f.widgets.first().and_then(|w| w.on_state.clone()).unwrap_or_else(|| "1".into()); let multi = f.kind == pdfcraft_forms::FieldKind::List && f.has(pdfcraft_forms::flags::MULTI_SELECT); - (f.name, FieldInfo { kind: f.kind, value: f.value, on_state, multi }) + let buttons = if f.kind == pdfcraft_forms::FieldKind::Radio { + f.widgets.iter().filter_map(|w| Some((w.on_state.clone()?, som_of(w.obj)?))).collect() + } else { + Vec::new() + }; + (f.name, FieldInfo { kind: f.kind, value: f.value, on_state, multi, buttons }) }) .collect() } @@ -700,6 +713,22 @@ impl<'a, 'b> Runner<'a, 'b> { Ok(()) } + /// The SOM path of what a click on field `name` (at `som`) turned on or off, when it is a + /// check box or a radio group: the check box itself, or the group's radio button now on. + /// `None` for other fields, and for a group left with no button on. + fn clicked(&mut self, name: &str, som: &str) -> Option { + use pdfcraft_forms::FieldKind as K; + let f = self.fields().get(name)?; + match f.kind { + K::CheckBox => Some(som.to_string()), + K::Radio => { + let on = f.value.first()?; + f.buttons.iter().find(|(state, _)| state == on).map(|(_, button)| button.clone()) + } + _ => None, + } + } + fn events_of(&mut self, som: &str, activity: &str) -> Vec { self.live().events.iter().filter(|e| e.som == som && e.activity == activity).cloned().collect() } @@ -823,18 +852,31 @@ pub(crate) fn on_open(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mu r.finish() } +/// What a click on a check box or radio button runs once it has set the value, in order: the +/// field's change scripts (a radio group's, as for any value change), then the click scripts of +/// what was clicked (the check box, or the radio button now on). Their exit scripts follow, as +/// after any change. The order is to be confirmed on a synthetic form in another viewer. +const TOGGLE_ORDER: [&str; 2] = ["change", "click"]; + /// After fields `names` took new values: each one's change, exit and validate scripts, then -/// the calculations once (or only those, after a reset). A validate script that answers false, -/// or fails, shows its message; the value stays, as Acrobat marks the field invalid rather -/// than reverting it. +/// the calculations once (or only those, after a reset). A check box or radio button runs its +/// click scripts too ([`TOGGLE_ORDER`]): it changes only when it is clicked, and a click script +/// reads the new value. A validate script that answers false, or fails, shows its message; the +/// value stays, as Acrobat marks the field invalid rather than reverting it. pub(crate) fn on_changes(doc: &mut pdfcraft_cos::Document, tpl: &Template, names: &[String], run: &mut XfaRun) -> Result<(), String> { let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS); for name in names { let som = r.by_som().iter().find(|(_, f)| *f == name).map(|(s, _)| s.clone()); let Some(som) = som else { continue }; let value = r.fields().get(name).map(|f| f.value.join("\n")).unwrap_or_default(); - for ev in r.events_of(&som, "change").into_iter().chain(r.events_of(&som, "exit")) { - r.run(&ev, &value)?; + let clicked = r.clicked(name, &som); + let steps: &[&str] = if clicked.is_some() { &TOGGLE_ORDER } else { &["change"] }; + for activity in steps.iter().copied().chain(["exit"]) { + // A click's scripts are those of what was clicked; the others are the field's. + let at = if activity == "click" { clicked.as_deref().unwrap_or(&som) } else { som.as_str() }; + for ev in r.events_of(at, activity) { + r.run(&ev, &value)?; + } } for ev in r.events_of(&som, "validate") { let Some(o) = r.run(&ev, &value)? else { continue }; diff --git a/crates/ui-egui/tests/it/xfa.rs b/crates/ui-egui/tests/it/xfa.rs index cf0fc193b1..cbb5e67d88 100644 --- a/crates/ui-egui/tests/it/xfa.rs +++ b/crates/ui-egui/tests/it/xfa.rs @@ -130,6 +130,35 @@ fn click_field(h: &mut Harness<'static, PdfCraftApp>, name: &str) { h.run_steps(4); } +/// Clicking an XFA check box or radio button in the app runs its click script after its change +/// script; the script's message shows. +#[test] +fn xfa_check_box_and_radio_clicks_run_their_click_scripts_in_the_app() { + let mut h = open(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())); + wait_for_pages(&mut h); + let log = |h: &Harness<'static, PdfCraftApp>| { + let s = h.state(); + s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "log").and_then(|f| f.value.first().cloned()).unwrap_or_default() + }; + click_field(&mut h, "agree"); + assert_eq!(log(&h), "change 1;click 1;", "console: {:?}", h.state().js_console.log); + assert!(h.query_by_label_contains("Agreed").is_some(), "the click script's message shows"); + // The second radio button of the group. + let p = { + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + let f = doc.form.iter().find(|f| f.name == "answer").expect("the radio group"); + pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 1).expect("on screen").center() + }; + h.hover_at(p); + h.run_steps(1); + h.drag_at(p); + h.run_steps(1); + h.drop_at(p); + h.run_steps(4); + assert!(log(&h).ends_with("no click;"), "{}", log(&h)); +} + #[test] fn xfa_buttons_run_their_scripts_in_the_app() { let mut h = open(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::scripted_template())); diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index a0307a6944..be48040a3c 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -234,6 +234,42 @@ pub fn scripted_template() -> String { .to_string() } +/// A form whose check box `agree` logs its change and click scripts (with the value each sees) +/// into `log`, and whose click also shows "Agreed" and asks for the focus in `note` when it turns +/// the box on; whose radio group `answer` has buttons `yes` and `no` that log their own clicks; +/// and whose text field `note` has a click script, which a change of its value doesn't run. +pub fn toggle_template() -> String { + let js = "application/x-javascript"; + let add = |what: &str| format!(r#"log.rawValue = (log.rawValue || "") + {what} + ";";"#); + format!( + r##" + + + +"##, + add(r#""change " + this.rawValue"#), + add(r#""click " + this.rawValue"#), + add(r#""yes click""#), + add(r#""no click""#), + add(r#""note click""#), + ) +} + /// [`scripted_template`] with every script in FormCalc (no `contentType`, as Designer writes /// the default language): the same fields, plus `words`, the total in English words. pub fn formcalc_template() -> String { diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 4ec39848c5..abdf561212 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5249,8 +5249,8 @@ milestone = "M12" status = "partial" commands = ["file.open"] tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"] -evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn"] -notes = "Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, captions, rich text, JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes, radio groups, drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; metrics are approximate and Acrobat fidelity is eyeballed on real forms, not measured (#60)" +evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::xfa_check_box_and_radio_button_clicks_run_their_click_scripts", "crates/automation/tests/it/automation.rs::xfa_check_box_and_radio_clicks_run_through_form_fill", "crates/ui-egui/tests/it/xfa.rs::xfa_check_box_and_radio_clicks_run_their_click_scripts_in_the_app"] +notes = "Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, captions, rich text, JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes, radio groups, drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app) and for check boxes and radio buttons each time a click changes them, after their change scripts, a radio button running its own (in the app and through form_fill), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; metrics are approximate and Acrobat fidelity is eyeballed on real forms, not measured (#60)" [[feature]] id = "form.xfa-formcalc" From e550622877d18f2cee9143a189d5ce7756344d2c Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:14:52 -0400 Subject: [PATCH 033/216] M12: a check box or radio button set to the value it had runs no click scripts --- crates/engine/src/lib.rs | 6 ++++-- crates/engine/src/tests.rs | 9 +++++++++ crates/engine/src/xfa.rs | 22 +++++++++++++++++----- 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 86fc9dce4f..a76efe7688 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3912,8 +3912,10 @@ impl Session { if !changed.is_empty() || reset { let mut run = xfa::XfaRun { page_count: cx.pages, out: &mut cx.xfa_out, datasets: cx.xfa_datasets, ran_away: false }; // Every changed field's scripts, then the calculations once (after a reset, - // only those). - let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &mut run)) + // only those). The values before the edit tell a click from a value set again. + let before: std::collections::HashMap> = + doc.form.iter().filter(|f| changed.contains(&f.name)).map(|f| (f.name.clone(), f.value.clone())).collect(); + let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &before, &mut run)) .unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})"))); cx.xfa_datasets = run.datasets; cx.xfa_ran_away |= run.ran_away; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 070314e332..9636c7b816 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5109,6 +5109,15 @@ fn xfa_check_box_and_radio_button_clicks_run_their_click_scripts() { // A text field's value isn't set by a click. s.apply(id, Edit::SetFieldValue { name: "note".into(), value: FieldValue::Text("typed".into()) }).unwrap(); assert!(!log(&s).contains("note click"), "{}", log(&s)); + // A value set again, unchanged, isn't a click: no click script, no message or request. + let _ = s.take_js_output(id); + let seen = log(&s); + s.apply(id, Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(true) }).unwrap(); + s.apply(id, Edit::SetFieldValue { name: "answer".into(), value: FieldValue::Radio(Some(state(&s, 0).unwrap())) }).unwrap(); + let after = log(&s); + assert!(!after.get(seen.len()..).unwrap_or_default().contains("click"), "{after}"); + let out = s.take_js_output(id); + assert!(out.alerts.is_empty() && out.requests.is_empty(), "{out:?}"); } /// Importing data into a dynamic form adds and removes the rows of its repeating subform to diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index fa0d2f1fd5..7762674f3e 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -715,10 +715,14 @@ impl<'a, 'b> Runner<'a, 'b> { /// The SOM path of what a click on field `name` (at `som`) turned on or off, when it is a /// check box or a radio group: the check box itself, or the group's radio button now on. - /// `None` for other fields, and for a group left with no button on. - fn clicked(&mut self, name: &str, som: &str) -> Option { + /// `None` for other fields, for a group left with no button on, and when the value is still + /// `before` (set again, not clicked). + fn clicked(&mut self, name: &str, som: &str, before: Option<&Vec>) -> Option { use pdfcraft_forms::FieldKind as K; let f = self.fields().get(name)?; + if before.is_some_and(|b| *b == f.value) { + return None; + } match f.kind { K::CheckBox => Some(som.to_string()), K::Radio => { @@ -862,14 +866,22 @@ const TOGGLE_ORDER: [&str; 2] = ["change", "click"]; /// the calculations once (or only those, after a reset). A check box or radio button runs its /// click scripts too ([`TOGGLE_ORDER`]): it changes only when it is clicked, and a click script /// reads the new value. A validate script that answers false, or fails, shows its message; the -/// value stays, as Acrobat marks the field invalid rather than reverting it. -pub(crate) fn on_changes(doc: &mut pdfcraft_cos::Document, tpl: &Template, names: &[String], run: &mut XfaRun) -> Result<(), String> { +/// value stays, as Acrobat marks the field invalid rather than reverting it. `before` holds each +/// field's value before the edit: a check box or radio group set to the value it had runs no +/// click scripts, since nothing was clicked. +pub(crate) fn on_changes( + doc: &mut pdfcraft_cos::Document, + tpl: &Template, + names: &[String], + before: &HashMap>, + run: &mut XfaRun, +) -> Result<(), String> { let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS); for name in names { let som = r.by_som().iter().find(|(_, f)| *f == name).map(|(s, _)| s.clone()); let Some(som) = som else { continue }; let value = r.fields().get(name).map(|f| f.value.join("\n")).unwrap_or_default(); - let clicked = r.clicked(name, &som); + let clicked = r.clicked(name, &som, before.get(name)); let steps: &[&str] = if clicked.is_some() { &TOGGLE_ORDER } else { &["change"] }; for activity in steps.iter().copied().chain(["exit"]) { // A click's scripts are those of what was clicked; the others are the field's. From 629ba855c485e0e6d298c573a626bc72d1eead6c Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:16:33 -0400 Subject: [PATCH 034/216] M12: docstrings for the functions next to the click-script change --- crates/automation/tests/it/automation.rs | 3 +++ crates/engine/src/xfa.rs | 1 + crates/ui-egui/tests/it/xfa.rs | 2 ++ 3 files changed, 6 insertions(+) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index bdf6de9952..b07255a467 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6803,6 +6803,8 @@ fn repeated_xfa_print_buttons_work_through_tools_and_after_reopen() { check(&mut a, doc); } +/// XFA scripts run through the tools: initialize and calculate on opening, calculations after +/// form_fill, and a button's click script through js_run, adding a row that undo takes away. #[test] fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() { let dir = workdir("xfa-scripts"); @@ -6860,6 +6862,7 @@ fn xfa_check_box_and_radio_clicks_run_through_form_fill() { assert!(log(&mut a).ends_with("no click;"), "{}", log(&mut a)); } +/// A form whose opening script runs away has its scripts turned off, and doc_info says so. #[test] fn doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off() { let dir = workdir("xfa-scripts-off"); diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index 7762674f3e..dbe4f02371 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -733,6 +733,7 @@ impl<'a, 'b> Runner<'a, 'b> { } } + /// The `activity` scripts of the object at `som` in the live form. fn events_of(&mut self, som: &str, activity: &str) -> Vec { self.live().events.iter().filter(|e| e.som == som && e.activity == activity).cloned().collect() } diff --git a/crates/ui-egui/tests/it/xfa.rs b/crates/ui-egui/tests/it/xfa.rs index cbb5e67d88..e114ea8296 100644 --- a/crates/ui-egui/tests/it/xfa.rs +++ b/crates/ui-egui/tests/it/xfa.rs @@ -159,6 +159,8 @@ fn xfa_check_box_and_radio_clicks_run_their_click_scripts_in_the_app() { assert!(log(&h).ends_with("no click;"), "{}", log(&h)); } +/// Clicking an XFA button in the app runs its click script: one adds a row, another shows its +/// message as a notice. #[test] fn xfa_buttons_run_their_scripts_in_the_app() { let mut h = open(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::scripted_template())); From 8e52d9ec76db0fe95f16c38f806bf2af3ebd0bd5 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:20:44 -0400 Subject: [PATCH 035/216] M12: comments for the closures the click-script change adds --- crates/automation/tests/it/automation.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/xfa.rs | 1 + crates/ui-egui/tests/it/xfa.rs | 1 + crates/xfa/src/fixtures.rs | 1 + 5 files changed, 5 insertions(+) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index b07255a467..3a192d38fc 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6843,6 +6843,7 @@ fn xfa_check_box_and_radio_clicks_run_through_form_fill() { std::fs::write(dir.join("toggle.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())).unwrap(); let mut a = auto(&dir); let doc = ok(&mut a, "doc_open", json!({ "path": "toggle.pdf" }))["doc"].as_u64().unwrap(); + // What the scripts have written to the form's log field so far. let log = |a: &mut Automation| { let f = ok(a, "form_fields", json!({ "doc": doc })); f["fields"] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9636c7b816..dfcae9fd62 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5088,6 +5088,7 @@ fn xfa_check_box_and_radio_button_clicks_run_their_click_scripts() { let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())); let mut s = Session::new(); let id = s.open("toggle.pdf", None, bytes, None).expect("opens"); + // What the scripts have written to the form's log field so far. let log = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "log").and_then(|f| f.value.first().cloned()).unwrap_or_default(); s.apply(id, Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(true) }).unwrap(); assert_eq!(log(&s), "change 1;click 1;", "change, then click, each seeing the new value"); diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index dbe4f02371..857a8a02ad 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -219,6 +219,7 @@ struct FieldInfo { /// The generated fields of `doc`, by name, as the runner tracks them. fn field_infos(doc: &pdfcraft_cos::Document) -> HashMap { + // The SOM path a widget or field records for its XFA object. let som_of = |obj: pdfcraft_cos::ObjRef| { let object = doc.get(obj); object.as_dict()?.get(pdfcraft_xfa::SOM_KEY).map(|s| doc.resolve(s))?.as_string().map(|s| s.to_text()) diff --git a/crates/ui-egui/tests/it/xfa.rs b/crates/ui-egui/tests/it/xfa.rs index e114ea8296..3fff06651c 100644 --- a/crates/ui-egui/tests/it/xfa.rs +++ b/crates/ui-egui/tests/it/xfa.rs @@ -136,6 +136,7 @@ fn click_field(h: &mut Harness<'static, PdfCraftApp>, name: &str) { fn xfa_check_box_and_radio_clicks_run_their_click_scripts_in_the_app() { let mut h = open(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())); wait_for_pages(&mut h); + // What the scripts have written to the form's log field so far. let log = |h: &Harness<'static, PdfCraftApp>| { let s = h.state(); s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "log").and_then(|f| f.value.first().cloned()).unwrap_or_default() diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index be48040a3c..4530485cfa 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -240,6 +240,7 @@ pub fn scripted_template() -> String { /// and whose text field `note` has a click script, which a change of its value doesn't run. pub fn toggle_template() -> String { let js = "application/x-javascript"; + // A script line that adds `what` (JavaScript), then ";", to the log field. let add = |what: &str| format!(r#"log.rawValue = (log.rawValue || "") + {what} + ";";"#); format!( r##" From a64fb1b2c972f7878d849f54508b50aff6ee6d25 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 036/216] ci: deny yanked crates cargo deny only warned about a yanked crate in Cargo.lock. With yanked = "deny" the dependency check now fails on one instead. This commit used to also add --locked to the Clippy, test and CLI steps of ci.yml. Those steps now run in the shared gate workflow, and the git-sources job already fails CI when Cargo.lock is out of date with the manifests (cargo metadata --locked), so that part is dropped. --- deny.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deny.toml b/deny.toml index ed9c26c206..9265c1db31 100644 --- a/deny.toml +++ b/deny.toml @@ -37,7 +37,7 @@ unknown-git = "deny" allow-git = ["https://github.com/storytold/craft-libs", "https://github.com/storytold/winprint.rs"] [advisories] -yanked = "warn" +yanked = "deny" ignore = [ # Marvin (RSA private-key timing side channel, no fixed `rsa` release). pdfcraft-sign uses # `rsa` only for public-key signature verification, which the advisory does not affect; RSA From 258a76c2b17962ee421db0905e1c6617a780ee57 Mon Sep 17 00:00:00 2001 From: oracola91 <118899664+oracola91@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:26:08 +0300 Subject: [PATCH 037/216] Cargo.lock: clipboard-win 5.4.3 5.4.1 is yanked (5.4.2 and 5.4.3 came out on 2026-10-23), so with yanked = "deny" the dependency check failed on it. cargo update -p clipboard-win changes only this package. It comes in through arboard and egui-winit, on Windows. --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 93c047eef3..b53399b3d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -953,9 +953,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] From 0c88cc9c0350c3d8ae1a875aea2f41644cc8de6f Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 08:49:37 -0400 Subject: [PATCH 038/216] M12: the click-script UI test waits for the form as main's tests now do --- crates/ui-egui/tests/it/xfa.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/xfa.rs b/crates/ui-egui/tests/it/xfa.rs index f9a20984a3..9fb1422139 100644 --- a/crates/ui-egui/tests/it/xfa.rs +++ b/crates/ui-egui/tests/it/xfa.rs @@ -132,7 +132,7 @@ fn click_field(h: &mut Harness<'static, PdfCraftApp>, name: &str) { #[test] fn xfa_check_box_and_radio_clicks_run_their_click_scripts_in_the_app() { let mut h = open(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())); - wait_for_pages(&mut h); + crate::support::settle(&mut h); // What the scripts have written to the form's log field so far. let log = |h: &Harness<'static, PdfCraftApp>| { let s = h.state(); From ec429fdd90e8a75ed1eba4905913878156173eff Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Sat, 24 Oct 2026 16:50:45 +0200 Subject: [PATCH 039/216] fix(forms, xfdf): importing a value into same-named check boxes turns on the box it names --- crates/forms/src/lib.rs | 9 ++++++-- crates/xfdf/src/lib.rs | 3 +++ crates/xfdf/src/tests.rs | 50 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 75c3dbee00..977525d512 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -1068,13 +1068,18 @@ fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scripts: &mut redraw(doc, f, std::slice::from_ref(t), scripts) } (FieldKind::CheckBox, v) => { - let state = f.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into()); + let mut state = f.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into()); let on = match v { FieldValue::Check(on) => *on, // The on-state name or a yes/no word also work (agents, FDF-style data). FieldValue::Text(t) | FieldValue::Radio(Some(t)) => { let t = t.trim(); - if t == state || f.state_for(t).is_some() || ["yes", "true", "on", "1", "x", "checked"].contains(&t.to_lowercase().as_str()) { + // Same-named check boxes with different on states (/A, /B) are one field: a + // value naming another box's state turns that box on, not the first one. + if let Some(named) = f.state_for(t) { + state = named.to_string(); + true + } else if t == state || ["yes", "true", "on", "1", "x", "checked"].contains(&t.to_lowercase().as_str()) { true } else if t.is_empty() || ["no", "false", "off", "0", "unchecked"].contains(&t.to_lowercase().as_str()) { false diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index 6131c9c96b..e0d5b7d639 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -892,6 +892,9 @@ fn apply_values(doc: &mut Document, values: &[(String, Vec)], report: &m let first = vals.first().cloned().unwrap_or_default(); let v = match f.kind { FieldKind::Text => FieldValue::Text(first), + // A value that names one of the boxes' on states picks that box (same-named check + // boxes with different on states); anything else is just on or off. + FieldKind::CheckBox if f.state_for(&first).is_some() => FieldValue::Text(first), FieldKind::CheckBox => FieldValue::Check(!first.is_empty() && first != "Off"), FieldKind::Radio => FieldValue::Radio((!first.is_empty() && first != "Off").then_some(first)), // XML, CSV and text hold a multi-select list's values in one cell, joined by ", " diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs index 17c48c281b..a1bc0dfc23 100644 --- a/crates/xfdf/src/tests.rs +++ b/crates/xfdf/src/tests.rs @@ -1933,3 +1933,53 @@ fn annots_of(doc: &Document) -> Vec { .filter(|d| d.get(b"Subtype") != Some(&Object::name("Widget"))) .collect() } + +/// Check boxes sharing one name with different on states (`/A`, `/B`) are one field whose value +/// picks the box. Importing `B` turned on the first box's state instead, whatever the data said. +fn check_box_pair(value: &str) -> Document { + let objs = [ + "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".to_string(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".to_string(), + "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>".to_string(), + "<< /Fields [5 0 R] >>".to_string(), + format!("<< /FT /Btn /T (choice) /V /{value} /Kids [6 0 R 7 0 R] >>"), + format!( + "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /P 3 0 R /Rect [50 700 64 714] /AS /{} /AP << /N << /A 8 0 R /Off 8 0 R >> >> >>", + if value == "A" { "A" } else { "Off" } + ), + format!( + "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /P 3 0 R /Rect [80 700 94 714] /AS /{} /AP << /N << /B 8 0 R /Off 8 0 R >> >> >>", + if value == "B" { "B" } else { "Off" } + ), + "<< /Length 0 >>\nstream\n\nendstream".to_string(), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + Document::open(Arc::new(out)).unwrap() +} + +#[test] +fn a_check_box_group_value_selects_its_own_box_on_import() { + let src = check_box_pair("B"); + assert_eq!(values(&src), vec![("choice".to_string(), vec!["B".to_string()])]); + let exports = [ + ("xfdf", export_xfdf(&src, false, true, "form.pdf").into_bytes()), + ("fdf", export_fdf(&src, false, true, "form.pdf").unwrap()), + ("xml", export_data(&src, Format::Xml).into_bytes()), + ]; + for (format, data) in exports { + let mut dst = check_box_pair("Off"); + let report = import(&mut dst, &data); + assert_eq!(values(&dst), values(&src), "{format}: {report:?}: {}", String::from_utf8_lossy(&data)); + } +} From 8e9b734ed067866daf32b6abaaf3341dae9b1ec8 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:34:36 -0400 Subject: [PATCH 040/216] M6: a check box a batch sets twice is clicked once --- crates/engine/src/tests.rs | 6 ++++++ crates/engine/src/xfa.rs | 10 ++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f7a443c061..a91debba49 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5648,6 +5648,12 @@ fn xfa_check_box_and_radio_button_clicks_run_their_click_scripts() { assert!(!after.get(seen.len()..).unwrap_or_default().contains("click"), "{after}"); let out = s.take_js_output(id); assert!(out.alerts.is_empty() && out.requests.is_empty(), "{out:?}"); + // A batch that turns the check box off twice clicks it once: the second set changes nothing. + let off = || Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(false) }; + let seen = log(&s); + s.apply(id, Edit::Batch { label: "twice".into(), edits: vec![off(), off()] }).unwrap(); + let after = log(&s); + assert_eq!(after.get(seen.len()..).unwrap_or_default().matches("click 0;").count(), 1, "{after}"); } /// Importing data into a dynamic form adds and removes the rows of its repeating subform to diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index 2e4edc8fef..b1bb5d9c83 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -872,7 +872,8 @@ const TOGGLE_ORDER: [&str; 2] = ["change", "click"]; /// reads the new value. A validate script that answers false, or fails, shows its message; the /// value stays, as Acrobat marks the field invalid rather than reverting it. `before` holds each /// field's value before the edit: a check box or radio group set to the value it had runs no -/// click scripts, since nothing was clicked. +/// click scripts, since nothing was clicked. A field named twice (a batch that sets it twice) +/// is compared the second time with what the first left, so it is clicked once at most. pub(crate) fn on_changes( doc: &mut pdfcraft_cos::Document, tpl: &Template, @@ -881,11 +882,13 @@ pub(crate) fn on_changes( run: &mut XfaRun, ) -> Result<(), String> { let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS); + // Each field's value once its scripts have run, for a later mention of the same field. + let mut done: HashMap> = HashMap::new(); for name in names { let som = r.by_som().iter().find(|(_, f)| *f == name).map(|(s, _)| s.clone()); let Some(som) = som else { continue }; let value = r.fields().get(name).map(|f| f.value.join("\n")).unwrap_or_default(); - let clicked = r.clicked(name, &som, before.get(name)); + let clicked = r.clicked(name, &som, done.get(name).or_else(|| before.get(name))); let steps: &[&str] = if clicked.is_some() { &TOGGLE_ORDER } else { &["change"] }; for activity in steps.iter().copied().chain(["exit"]) { // A click's scripts are those of what was clicked; the others are the field's. @@ -900,6 +903,9 @@ pub(crate) fn on_changes( r.alert(ev.message.clone().unwrap_or_else(|| format!("{name}: the value is not valid"))); } } + if let Some(f) = r.fields().get(name) { + done.insert(name.clone(), f.value.clone()); + } } r.calculates()?; r.finish().map(|_| ()) From 3f6471e6648f6811298758804d2e5e02da3346cb Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:51:59 -0400 Subject: [PATCH 041/216] M6: a radio group's change and click scripts run before its button's, as another viewer runs them --- crates/automation/tests/it/automation.rs | 4 ++-- crates/engine/src/tests.rs | 14 ++++++++------ crates/engine/src/xfa.rs | 19 ++++++++++++------- crates/ui-egui/tests/it/xfa.rs | 2 +- crates/xfa/src/fixtures.rs | 14 ++++++++++++-- parity/acrobat-features.toml | 2 +- 6 files changed, 36 insertions(+), 19 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 3b9806d665..39f7fa801d 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -7253,7 +7253,7 @@ fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() { } /// Filling an XFA check box or radio group through form_fill clicks it, as the app does: the -/// field's change scripts, then the click scripts of what was clicked. +/// change scripts, then the click scripts, a radio group's before those of the button now on. #[test] fn xfa_check_box_and_radio_clicks_run_through_form_fill() { let dir = workdir("xfa-toggle"); @@ -7277,7 +7277,7 @@ fn xfa_check_box_and_radio_clicks_run_through_form_fill() { let answer = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "answer").cloned().expect("the radio group"); let no = answer["options"].as_array().and_then(|o| o.get(1)).and_then(|o| o.as_str().map(str::to_string)).unwrap_or_else(|| panic!("{answer}")); ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "answer": no } })); - assert!(log(&mut a).ends_with("no click;"), "{}", log(&mut a)); + assert!(log(&mut a).ends_with("group click;no click;no exit;group exit;"), "{}", log(&mut a)); } /// A form whose opening script runs away has its scripts turned off, and doc_info says so. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a91debba49..03eedb55a8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5609,9 +5609,10 @@ fn xfa_data_import_on_a_static_form_replaces_every_value_and_pictures_reach_its_ assert!(xml.contains("Bob") && !xml.contains("1"), "{xml}"); } -/// A click on an XFA check box or radio button runs the field's change scripts, then the click -/// scripts of what was clicked, which read the new value, show messages and may ask for the focus; -/// all as one undo step. A text field's click script doesn't run when its value changes. +/// A click on an XFA check box or radio button runs its change scripts, then its click scripts, +/// which read the new value, show messages and may ask for the focus; a radio group's run before +/// those of the button now on. All as one undo step. A text field's click script doesn't run when +/// its value changes. #[test] fn xfa_check_box_and_radio_button_clicks_run_their_click_scripts() { let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())); @@ -5629,13 +5630,14 @@ fn xfa_check_box_and_radio_button_clicks_run_their_click_scripts() { // One undo step takes back the click and what its scripts did. s.undo(id).unwrap(); assert_eq!(log(&s), "change 1;click 1;"); - // A radio button runs its own click script, the one now on. + // A radio group runs each activity's scripts, then the button now on runs its own; the + // button turned off runs none. Exit scripts follow, the button's first. let state = |s: &Session, i: usize| s.get(id).unwrap().form.iter().find(|f| f.name == "answer").and_then(|f| f.widgets.get(i)?.on_state.clone()); let (yes, no) = (state(&s, 0).expect("yes"), state(&s, 1).expect("no")); s.apply(id, Edit::SetFieldValue { name: "answer".into(), value: FieldValue::Radio(Some(no)) }).unwrap(); - assert!(log(&s).ends_with("no click;"), "{}", log(&s)); + assert!(log(&s).ends_with("group change N;no change;group click;no click;no exit;group exit;"), "{}", log(&s)); s.apply(id, Edit::SetFieldValue { name: "answer".into(), value: FieldValue::Radio(Some(yes)) }).unwrap(); - assert!(log(&s).ends_with("no click;yes click;"), "{}", log(&s)); + assert!(log(&s).ends_with("no exit;group exit;group change Y;yes change;group click;yes click;yes exit;group exit;"), "{}", log(&s)); // A text field's value isn't set by a click. s.apply(id, Edit::SetFieldValue { name: "note".into(), value: FieldValue::Text("typed".into()) }).unwrap(); assert!(!log(&s).contains("note click"), "{}", log(&s)); diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index b1bb5d9c83..6fcd9db35a 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -861,9 +861,10 @@ pub(crate) fn on_open(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mu } /// What a click on a check box or radio button runs once it has set the value, in order: the -/// field's change scripts (a radio group's, as for any value change), then the click scripts of -/// what was clicked (the check box, or the radio button now on). Their exit scripts follow, as -/// after any change. The order is to be confirmed on a synthetic form in another viewer. +/// change scripts, then the click scripts, each reading the new value. A radio group runs each +/// activity's scripts, then the radio button now on runs its own; the button it turned off runs +/// none. Exit scripts follow, as after any change: the button's, then the group's. This is the +/// order another viewer showed on a synthetic form. const TOGGLE_ORDER: [&str; 2] = ["change", "click"]; /// After fields `names` took new values: each one's change, exit and validate scripts, then @@ -890,11 +891,15 @@ pub(crate) fn on_changes( let value = r.fields().get(name).map(|f| f.value.join("\n")).unwrap_or_default(); let clicked = r.clicked(name, &som, done.get(name).or_else(|| before.get(name))); let steps: &[&str] = if clicked.is_some() { &TOGGLE_ORDER } else { &["change"] }; + // A radio group's button now on runs each activity's scripts after the group's, and + // its exit scripts before the group's, as when leaving it. + let button = clicked.as_deref().filter(|b| *b != som); for activity in steps.iter().copied().chain(["exit"]) { - // A click's scripts are those of what was clicked; the others are the field's. - let at = if activity == "click" { clicked.as_deref().unwrap_or(&som) } else { som.as_str() }; - for ev in r.events_of(at, activity) { - r.run(&ev, &value)?; + let order = if activity == "exit" { [button, Some(som.as_str())] } else { [Some(som.as_str()), button] }; + for at in order.into_iter().flatten() { + for ev in r.events_of(at, activity) { + r.run(&ev, &value)?; + } } } for ev in r.events_of(&som, "validate") { diff --git a/crates/ui-egui/tests/it/xfa.rs b/crates/ui-egui/tests/it/xfa.rs index 9fb1422139..7e0b0e945d 100644 --- a/crates/ui-egui/tests/it/xfa.rs +++ b/crates/ui-egui/tests/it/xfa.rs @@ -154,7 +154,7 @@ fn xfa_check_box_and_radio_clicks_run_their_click_scripts_in_the_app() { h.run_steps(1); h.drop_at(p); h.run_steps(4); - assert!(log(&h).ends_with("no click;"), "{}", log(&h)); + assert!(log(&h).ends_with("group click;no click;no exit;group exit;"), "{}", log(&h)); } /// Clicking an XFA button in the app runs its click script: one adds a row, another shows its diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index f082defb7c..b1d2f79826 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -253,8 +253,11 @@ pub fn toggle_template() -> String { - Y - N + Y + N + + + @@ -265,8 +268,15 @@ pub fn toggle_template() -> String { "##, add(r#""change " + this.rawValue"#), add(r#""click " + this.rawValue"#), + add(r#""yes change""#), add(r#""yes click""#), + add(r#""yes exit""#), + add(r#""no change""#), add(r#""no click""#), + add(r#""no exit""#), + add(r#""group change " + this.rawValue"#), + add(r#""group click""#), + add(r#""group exit""#), add(r#""note click""#), ) } diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 6aaec66d69..28ca3cb4c2 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5297,7 +5297,7 @@ status = "partial" commands = ["file.open"] tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"] evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn", "crates/engine/src/tests.rs::xfa_check_box_and_radio_button_clicks_run_their_click_scripts", "crates/automation/tests/it/automation.rs::xfa_check_box_and_radio_clicks_run_through_form_fill", "crates/ui-egui/tests/it/xfa.rs::xfa_check_box_and_radio_clicks_run_their_click_scripts_in_the_app"] -notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app) and for check boxes and radio buttons each time a click changes them, after their change scripts, a radio button running its own (in the app and through form_fill), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" +notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app) and for check boxes and radio buttons each time a click changes them, after their change scripts, a radio group's change and click scripts running before those of the button now on, in the order another viewer runs them on a synthetic form (in the app and through form_fill), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; a check box's or radio button's exit scripts run after each click, where another viewer runs them once, when it loses the focus; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" [[feature]] id = "form.xfa-formcalc" From aafcc8261fba215d3ef798bed84e76096aedb0b8 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:49:33 -0400 Subject: [PATCH 042/216] M12: an XFA date field keeps what its patterns don't read as typed, and reads its own patterns first --- crates/automation/tests/it/automation.rs | 31 +++++++++++ crates/engine/src/lib.rs | 17 +++--- crates/engine/src/tests.rs | 26 +++++---- crates/forms/src/af.rs | 68 ++++++++++++++++++++++++ crates/forms/src/appearance.rs | 2 +- crates/forms/src/lib.rs | 10 +++- crates/xfa/README.md | 1 + crates/xfa/src/fixtures.rs | 19 +++++++ crates/xfa/src/lib.rs | 2 +- crates/xfa/src/pdf.rs | 6 ++- parity/acrobat-features.toml | 4 +- 11 files changed, 157 insertions(+), 29 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 9049299702..9ac75c3e6d 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6917,6 +6917,37 @@ fn links_in_xfa_rich_text_are_listed_through_tools() { assert_eq!(urls(&mut a, doc), ["mailto:forms@example.com"], "one link after a save and a fresh open, not two"); } +/// What a date typed into an XFA date field leaves in the form's data, for each kind of picture: +/// what another viewer kept for the same typing on a synthetic form. A date one of the edit +/// picture's patterns reads is kept as an ISO date; anything else, ISO text included, as typed, +/// and nothing is refused. +#[test] +fn xfa_date_fields_keep_typed_dates_as_another_viewer_does() { + let dir = workdir("xfa-typed-dates"); + std::fs::write(dir.join("dates.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_pictures_template())).unwrap(); + let mut a = auto(&dir); + // typed, then the data for display, edit, either and bare. + let seen = [ + ("2016-10-18", ["2016-10-18", "2016-10-18", "2016-10-18", "2016-10-18"]), + ("10/18/2016", ["10/18/2016", "2016-10-18", "10/18/2016", "10/18/2016"]), + ("20161018", ["20161018", "20161018", "2016-10-18", "20161018"]), + ("18OCT16", ["18OCT16", "18OCT16", "2016-10-18", "18OCT16"]), + ("26 10 18", ["26 10 18", "26 10 18", "26 10 18", "26 10 18"]), + ("xyz", ["xyz", "xyz", "xyz", "xyz"]), + ]; + for (typed, kept) in seen { + for (field, want) in ["display", "edit", "either", "bare"].into_iter().zip(kept) { + let doc = ok(&mut a, "doc_open", json!({ "path": "dates.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { field: typed } })); + ok(&mut a, "doc_export_data", json!({ "doc": doc, "path": "data.xml", "what": "fields" })); + let xml = std::fs::read_to_string(dir.join("data.xml")).unwrap(); + assert!(xml.contains(&format!("<{field}>{want}")), "{typed} in {field}: want {want}, got {xml}"); + ok(&mut a, "doc_close", json!({ "doc": doc, "discard_changes": true })); + } + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn dynamic_xfa_forms_open_render_fill_and_save_through_tools() { let dir = workdir("xfa"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index aa71d82fef..8ae02e201f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2659,17 +2659,12 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Some(js) => pdfcraft_forms::set_value_with(doc, name, value, js), None => pdfcraft_forms::set_value(doc, name, value), }; - match set(doc, value) { - Ok(()) => {} - // A date the field's format doesn't read may be typed by another of an XFA date - // field's patterns: it is kept in the first. Only a format refusal is tried - // again: it comes before any of the field's scripts run, so they run once. - Err(refused @ pdfcraft_forms::FormError::Format(_)) => match xfa::typed_date(doc, cx.xfa.as_deref(), name, value) { - Some(typed) => set(doc, &typed)?, - None => return Err(refused.into()), - }, - Err(refused) => return Err(refused.into()), - } + // A date typed by another of an XFA date field's patterns is kept in the first, before + // the field's format reads it more loosely (`18OCT16` in a `YYYYMMDD|DDMMMYY` field is + // the 18th of October 2016, not a day of 2018). + let laid_out = pdfcraft_xfa::xfa_shape(doc).is_some_and(|s| s.laid_out); + let typed = if laid_out { xfa::typed_date(doc, cx.xfa.as_deref(), name, value) } else { None }; + set(doc, typed.as_ref().unwrap_or(value))?; } Edit::ApplyScriptChanges { changes } => match cx.js.as_mut() { Some(js) => pdfcraft_forms::apply_script_changes(doc, changes, js)?, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index dc76159d14..648f5479d7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8080,7 +8080,8 @@ fn exporting_office_keeps_dotted_leader_entries_as_paragraphs() { } /// A date typed in another of an XFA date field's edit patterns is kept in its first: yymmdd and -/// yyyymd are rewritten as yyyymmdd, a date none of them reads is refused, and the data holds the date. +/// yyyymd are rewritten as yyyymmdd, and the data holds the date. Text none of them reads is kept +/// as typed, in the field and the data, as another viewer keeps it. #[test] fn a_date_typed_by_another_of_an_xfa_fields_edit_patterns_is_kept_in_its_first() { let mut s = Session::new(); @@ -8092,18 +8093,21 @@ fn a_date_typed_by_another_of_an_xfa_fields_edit_patterns_is_kept_in_its_first() assert_eq!(value(&s), ["20261018"]); s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("2026118".into()) }).expect("so is yyyymd"); assert_eq!(value(&s), ["20261108"]); - let refused = s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("2618".into()) }); - assert!(refused.is_err_and(|e| e.to_string().contains("yyyymmdd")), "none of its patterns reads it"); - assert_eq!(value(&s), ["20261108"]); // The data holds the date. - let cos = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap(); - let data = pdfcraft_xfa::parse_datasets(&pdfcraft_xfa::read_packets(&cos).unwrap().unwrap().xdp).expect("a datasets packet"); - assert_eq!(data.text_at(&pdfcraft_xfa::som_to_path("form[0].leave[0]")), Some("2026-11-08")); + let data_of = |s: &Session| { + let cos = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap(); + let data = pdfcraft_xfa::parse_datasets(&pdfcraft_xfa::read_packets(&cos).unwrap().unwrap().xdp).expect("a datasets packet"); + data.text_at(&pdfcraft_xfa::som_to_path("form[0].leave[0]")).map(str::to_string) + }; + assert_eq!(data_of(&s).as_deref(), Some("2026-11-08")); + s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("2618".into()) }).expect("kept as typed"); + assert_eq!(value(&s), ["2618"]); + assert_eq!(data_of(&s).as_deref(), Some("2618")); } -/// A date the field's own scripts refuse is not tried again in another of an XFA date field's -/// patterns: only a date its format refuses is, which happens before any script runs, so the -/// scripts run once. This validate script counts its runs in `name` and accepts on its second. +/// A date typed in another of an XFA date field's patterns is rewritten before any of the field's +/// scripts run, so they run once, and a date they refuse stays refused. This validate script counts +/// its runs in `name` and accepts on its second. #[test] fn a_date_its_validate_script_refuses_is_not_tried_again() { let mut s = Session::new(); @@ -8113,7 +8117,7 @@ fn a_date_its_validate_script_refuses_is_not_tried_again() { let script = Some("var n = Number(getField('name').value || 0) + 1; getField('name').value = String(n); event.rc = n >= 2;".to_string()); s.apply(id, Edit::SetFieldScript { name: "leave".into(), event: "validate".into(), script }).unwrap(); let value = |s: &Session, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).unwrap().value.clone(); - // Its format reads 18OCT26, and so does its DDMMMYY pattern. + // Its DDMMMYY pattern reads 18OCT26, which its format would read more loosely too. let refused = s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("18OCT26".into()) }); assert!(refused.is_err(), "the validate script refused it, once"); assert!(value(&s, "name").is_empty(), "nothing the refused run changed is kept: {:?}", value(&s, "name")); diff --git a/crates/forms/src/af.rs b/crates/forms/src/af.rs index 7b706e9ae9..90a0ac6f09 100644 --- a/crates/forms/src/af.rs +++ b/crates/forms/src/af.rs @@ -95,6 +95,9 @@ pub struct Actions { pub unsupported: Vec<&'static str>, /// Those scripts' JavaScript, run through [`crate::Scripts`]. pub scripts: Scripts, + /// A date field PdfCraft laid out for an XFA form (`/PCXfaDate true`): text its format doesn't + /// read is kept and shown as typed rather than refused, as an XFA form keeps it. + pub xfa_date: bool, } /// Field scripts that aren't AF calls, by event. @@ -110,6 +113,43 @@ impl Actions { pub fn is_empty(&self) -> bool { self.format == Format::None && self.validate == Validate::None && self.calculate == Calculate::None } + + /// The Keystroke event on commit ([`keystroke`]); an XFA date field keeps text its format + /// doesn't read, as typed. + pub fn keystroke(&self, field: &str, value: &str) -> Result { + match keystroke(&self.format, field, value) { + Err(_) if self.xfa_date => Ok(value.trim().to_string()), + checked => checked, + } + } + + /// What the Format event shows for `value` ([`format_value`]). An XFA date field shows a date + /// only for a value that is one, in its format already or as an ISO date (`2026-10-18` or + /// `20261018`); anything else, which its format would read loosely, shows as typed. + pub fn format_value(&self, value: &str) -> String { + match &self.format { + Format::Date(fmt) if self.xfa_date => { + let t = value.trim(); + let in_format = parse_date(t, fmt).is_some_and(|dt| format_date(dt, fmt).eq_ignore_ascii_case(t)); + match iso_date(t) { + Some(dt) if !in_format => format_date(dt, fmt), + _ => value.to_string(), + } + } + f => format_value(f, value), + } + } +} + +/// `text` as an ISO 8601 calendar date, `yyyy-mm-dd` or `yyyymmdd` (digits only, a real day). +fn iso_date(text: &str) -> Option { + let b = text.as_bytes(); + let fmt = match b.len() { + 10 if b.iter().enumerate().all(|(i, c)| if i == 4 || i == 7 { *c == b'-' } else { c.is_ascii_digit() }) => "yyyy-mm-dd", + 8 if b.iter().all(u8::is_ascii_digit) => "yyyymmdd", + _ => return None, + }; + parse_date(text, fmt).filter(|dt| format_date(*dt, fmt) == text) } // ── parsing scripts ───────────────────────────────────────────────────────────────────────── @@ -1753,6 +1793,34 @@ mod tests { assert_eq!(keystroke(&Format::None, "Name", " \t"), Ok(" \t".into())); } + /// A date field laid out for an XFA form keeps text its pattern doesn't read, as typed, and + /// shows a date only for a value that is one: in the pattern already, or an ISO date. Another + /// viewer keeps and shows such text the same way on a synthetic form; an ordinary date field + /// still refuses it. + #[test] + fn xfa_date_fields_keep_and_show_what_their_pattern_does_not_read() { + let xfa = |fmt: &str| Actions { format: Format::Date(fmt.into()), xfa_date: true, ..Actions::default() }; + let plain = |fmt: &str| Actions { format: Format::Date(fmt.into()), ..Actions::default() }; + for (fmt, typed) in [("yyyy-mm-dd", "10/18/2016"), ("mm/dd/yyyy", "xyz"), ("yyyymmdd", "10/18/2016")] { + assert_eq!(xfa(fmt).keystroke("Date", typed), Ok(typed.to_string()), "{typed} in {fmt}"); + assert!(plain(fmt).keystroke("Date", typed).is_err(), "an ordinary date field refuses {typed}"); + } + // Shown: in the pattern, as it is; an ISO date, in the pattern; anything else as typed, + // where an ordinary field's looser reading would show a date the value doesn't hold. + let ymd = xfa("yyyymmdd"); + assert_eq!(ymd.format_value("20161018"), "20161018"); + assert_eq!(ymd.format_value("2016-10-18"), "20161018"); + assert_eq!(ymd.format_value("26 10 18"), "26 10 18"); + assert_ne!(plain("yyyymmdd").format_value("26 10 18"), "26 10 18", "read loosely as a date"); + let mdy = xfa("mm/dd/yyyy"); + assert_eq!(mdy.format_value("2016-10-18"), "10/18/2016"); + assert_eq!(mdy.format_value("20161018"), "10/18/2016"); + assert_eq!(mdy.format_value("10/18/2016"), "10/18/2016"); + assert_eq!(mdy.format_value("xyz"), "xyz"); + assert_eq!(mdy.format_value("2016-02-30"), "2016-02-30", "not a real day: as typed"); + assert_eq!(xfa("ddmmmyy").format_value("18OCT16"), "18OCT16", "in the pattern, its case kept"); + } + #[test] fn dates_times_and_masks() { let d = Format::Date("mm/dd/yyyy".into()); diff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rs index da25c211c0..d6b1d46c6b 100644 --- a/crates/forms/src/appearance.rs +++ b/crates/forms/src/appearance.rs @@ -735,7 +735,7 @@ fn field_appearance_fit(doc: &Document, f: &Field, w: &Widget, values: &[String] && values.len() == 1 && f.actions.format != crate::af::Format::None { - formatted = vec![crate::af::format_value(&f.actions.format, &values[0])]; + formatted = vec![f.actions.format_value(&values[0])]; &formatted[..] } else { values diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 75c3dbee00..281200df09 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -405,7 +405,11 @@ fn actions_of(doc: &Document, d: &Dict, widgets: &[ObjRef], scripts: &mut Decode .and_then(|w| w.as_dict().and_then(|wd| wd.get(b"AA").map(|a| doc.resolve(a)))) .and_then(|a| a.as_dict().cloned()) }); - let mut out = af::Actions::default(); + let mut out = af::Actions { + // A date field the XFA layout generated: what its format doesn't read is kept as typed. + xfa_date: matches!(d.get(b"PCXfaDate").map(|o| doc.resolve(o)).as_deref(), Some(Object::Bool(true))), + ..af::Actions::default() + }; let Some(aa) = aa else { return out }; let mut js = |k: &[u8]| aa.get(k).and_then(|a| script(doc, a, scripts)); if let Some(f) = js(b"F") { @@ -1045,6 +1049,8 @@ fn invalid(m: impl Into) -> Result { Err(FormError::Invalid(m.into())) } +/// Put `value` into field `f` as its kind takes one (a text value through the field's Keystroke +/// and Validate events and its scripts first), and redraw the field. fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scripts: &mut dyn Scripts) -> Result<(), FormError> { match (f.kind, value) { (FieldKind::Text, FieldValue::Text(t)) => { @@ -1054,7 +1060,7 @@ fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scripts: &mut return invalid(format!("{:?} takes at most {max} characters", f.name)); } // Keystroke (on commit) and Validate, as Acrobat runs them before accepting a value. - let t = &af::keystroke(&f.actions.format, &f.name, t).map_err(FormError::Format)?; + let t = &f.actions.keystroke(&f.name, t).map_err(FormError::Format)?; af::validate(&f.actions.validate, t).map_err(FormError::Invalid)?; let t = &scripting::accept(doc, f, t, scripts)?; doc.update_dict(f.obj, |d| { diff --git a/crates/xfa/README.md b/crates/xfa/README.md index 23a6ef0d0e..ecdb1d90fe 100644 --- a/crates/xfa/README.md +++ b/crates/xfa/README.md @@ -82,6 +82,7 @@ be measured exponentially often in their nesting. A measurement budget backs thi | `/PCSom` | generated fields | the field's SOM path, so values go back to the data | | `/PCXfaLayout` | AcroForm | what laying out produced, so a saved form is not laid out again | | `/PCXfaOverrides` | AcroForm | `<< /Presence << /som (hidden) … >> /Access << /som (readOnly) … >> >>`: presence and access scripts set, by SOM path (instance 0 of a repeating subform stands for all); applied to the template before every layout, so undo, save and reopen keep them. Adobe's viewers draw from the XFA packets and don't read it; at most 10 000 entries are read or written | + | `/PCXfaDate` | generated date fields | `true`: text the field's date pattern doesn't read is kept, and shown, as typed rather than refused, as an XFA form keeps it; the forms layer reads it | | `/PCXfaClick` | generated push buttons | `true`: the template has a click script for this button. Such buttons carry no `/A`: XFA JavaScript is not Acrobat JavaScript, so it is never written as a `/S /JavaScript` action other viewers would run. PdfCraft finds the script by the field's `/PCSom` | ## API sketch diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index b76b3efa1a..03de74ff43 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -528,6 +528,25 @@ pub fn date_alternatives_template() -> String { .to_string() } +/// Date fields with each kind of picture: `display` a display picture only, `edit` an edit and a +/// display picture, `either` an edit picture of two alternatives, `bare` none. +pub fn date_pictures_template() -> String { + r##" + + + +"## + .to_string() +} + /// A form of `sections` sections of `rows` rows, each row with a calculated total (half in /// JavaScript, half in FormCalc) and a section sum over its rows: 2 × sections × rows + sections /// calculate scripts, every one reading values the earlier ones settled. diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs index 7fe372d53a..4631510fe4 100644 --- a/crates/xfa/src/lib.rs +++ b/crates/xfa/src/lib.rs @@ -99,7 +99,7 @@ pub use data::{ pub use layout::{Action, BorderShape, Form, Item, MAX_PAGES, Page, Widget, WidgetKind, formatted_value, layout}; pub use packets::{Encoding, Packets, decode as decode_packet, encode as encode_packet, read_packets}; pub use parse::{measure, parse}; -pub use pdf::{CLICK_KEY, LAYOUT_KEY, SOM_KEY, Stripped, XfaShape, existing_layout, strip, xfa_shape}; +pub use pdf::{CLICK_KEY, DATE_KEY, LAYOUT_KEY, SOM_KEY, Stripped, XfaShape, existing_layout, strip, xfa_shape}; pub use picture::typed_date; pub use script::{ FormNode, LiveForm, MAX_FORM_NODES, NodeKind, OVERRIDES_KEY, Overrides, ScriptEvent, apply_overrides, data_of, field_grows_with_text, diff --git a/crates/xfa/src/pdf.rs b/crates/xfa/src/pdf.rs index 8e930c8f46..b467d04dc3 100644 --- a/crates/xfa/src/pdf.rs +++ b/crates/xfa/src/pdf.rs @@ -21,6 +21,9 @@ pub const LAYOUT_KEY: &[u8] = b"PCXfaLayout"; /// PDF action (the script is XFA's, not Acrobat JavaScript); PdfCraft runs the script by the /// field's SOM path. pub const CLICK_KEY: &[u8] = b"PCXfaClick"; +/// Private key on generated date fields: text the date pattern doesn't read is kept, and shown, +/// as typed, as an XFA form keeps it (the forms layer reads this key). +pub const DATE_KEY: &[u8] = b"PCXfaDate"; /// Width and height of a JPEG from its first frame header (SOF0–SOF15, not the DNL/JPG/DAC/DHT /// markers). `None` for anything else. @@ -394,6 +397,7 @@ impl Emitter<'_> { d.set(b"DV".to_vec(), Object::String(PdfString::text(v))); } if let WidgetKind::Date(pattern) = &w.kind { + d.set(DATE_KEY.to_vec(), Object::Bool(true)); let mut aa = Dict::new(); aa.set(b"F".to_vec(), js_action(&format!("AFDate_FormatEx(\"{pattern}\");"))); aa.set(b"K".to_vec(), js_action(&format!("AFDate_KeystrokeEx(\"{pattern}\");"))); @@ -1174,7 +1178,7 @@ pub fn strip(doc: &mut Document) -> Result { out.image_fields += 1; } let private: Vec> = - [SOM_KEY, CLICK_KEY, IMAGE_FIELD_KEY, b"PCItems".as_slice()].iter().filter(|k| d.contains(k)).map(|k| k.to_vec()).collect(); + [SOM_KEY, CLICK_KEY, IMAGE_FIELD_KEY, DATE_KEY, b"PCItems".as_slice()].iter().filter(|k| d.contains(k)).map(|k| k.to_vec()).collect(); if !private.is_empty() { out.field_keys += private.len(); doc.update_dict(r, |d| { diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 2c9cf17197..26517a8dae 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5296,8 +5296,8 @@ milestone = "M12" status = "partial" commands = ["file.open"] tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"] -evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn"] -notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" +evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn", "crates/forms/src/af.rs::xfa_date_fields_keep_and_show_what_their_pattern_does_not_read", "crates/automation/tests/it/automation.rs::xfa_date_fields_keep_typed_dates_as_another_viewer_does"] +notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats (a date one of the edit picture's patterns reads is kept in its first, and in the data as an ISO date; text none of them reads, ISO text included, is kept and shown as typed rather than refused, as another viewer keeps it on a synthetic form; a display picture that differs from the edit picture isn't used to show the date yet), check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" [[feature]] id = "form.xfa-formcalc" From 725f27107f25287cbae7dbd91c0565c7c00d87b0 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:07:06 -0400 Subject: [PATCH 043/216] M12: an XFA date field keeps unread text with its spaces, as typed --- crates/forms/src/af.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/forms/src/af.rs b/crates/forms/src/af.rs index 90a0ac6f09..f9819844ae 100644 --- a/crates/forms/src/af.rs +++ b/crates/forms/src/af.rs @@ -118,7 +118,7 @@ impl Actions { /// doesn't read, as typed. pub fn keystroke(&self, field: &str, value: &str) -> Result { match keystroke(&self.format, field, value) { - Err(_) if self.xfa_date => Ok(value.trim().to_string()), + Err(_) if self.xfa_date => Ok(value.to_string()), checked => checked, } } @@ -1805,6 +1805,7 @@ mod tests { assert_eq!(xfa(fmt).keystroke("Date", typed), Ok(typed.to_string()), "{typed} in {fmt}"); assert!(plain(fmt).keystroke("Date", typed).is_err(), "an ordinary date field refuses {typed}"); } + assert_eq!(xfa("mm/dd/yyyy").keystroke("Date", " pending "), Ok(" pending ".to_string()), "spaces and all"); // Shown: in the pattern, as it is; an ISO date, in the pattern; anything else as typed, // where an ordinary field's looser reading would show a date the value doesn't hold. let ymd = xfa("yyyymmdd"); From 0afb79075e4b5bab74dbb5161b88e4dd1ae1c6ea Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:14:59 -0400 Subject: [PATCH 044/216] M12: doc comments on the functions the typed-dates change touches --- crates/automation/tests/it/automation.rs | 2 ++ crates/engine/src/tests.rs | 2 ++ crates/forms/src/af.rs | 5 +++++ crates/forms/src/lib.rs | 1 + crates/xfa/src/lib.rs | 1 + 5 files changed, 11 insertions(+) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 9ac75c3e6d..e47ee9bdbc 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6948,6 +6948,8 @@ fn xfa_date_fields_keep_typed_dates_as_another_viewer_does() { let _ = std::fs::remove_dir_all(&dir); } +/// A dynamic XFA form opens laid out from its template through the tools, renders, takes values +/// and saves them. #[test] fn dynamic_xfa_forms_open_render_fill_and_save_through_tools() { let dir = workdir("xfa"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 648f5479d7..afb7ac6aad 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8058,6 +8058,8 @@ fn exporting_to_word_keeps_the_page_background() { assert!(docx.windows(b"word/settings.xml".len()).any(|w| w == b"word/settings.xml"), "Word is told to show the page colour"); } +/// A table of contents' entries with dotted leaders export to an office document as paragraphs, in +/// reading order, not as a table. #[test] fn exporting_office_keeps_dotted_leader_entries_as_paragraphs() { let mut content = String::new(); diff --git a/crates/forms/src/af.rs b/crates/forms/src/af.rs index f9819844ae..3be1f96152 100644 --- a/crates/forms/src/af.rs +++ b/crates/forms/src/af.rs @@ -61,6 +61,7 @@ impl CalcOp { } } + /// How the operation is named in a list of them (`sum (+)`, `average`). pub fn label(self) -> &'static str { match self { CalcOp::Sum => "sum (+)", @@ -110,6 +111,7 @@ pub struct Scripts { } impl Actions { + /// Whether the field has no format, validation or calculation PdfCraft recognises. pub fn is_empty(&self) -> bool { self.format == Format::None && self.validate == Validate::None && self.calculate == Calculate::None } @@ -1770,6 +1772,8 @@ mod tests { assert_eq!(calculation_reads("AFSimple_Calculate(\"SUM\", \"a, b\");"), ["a", "b"]); } + /// Number formats show separators, decimals, currency and negatives as AFNumber_Format does, + /// and the keystroke check stores the number. #[test] fn numbers_format_like_acrobat() { let n = |d, s, ng, c: &str, p| Format::Number { decimals: d, sep: s, neg: ng, currency: c.into(), prepend: p }; @@ -1822,6 +1826,7 @@ mod tests { assert_eq!(xfa("ddmmmyy").format_value("18OCT16"), "18OCT16", "in the pattern, its case kept"); } + /// Date, time and mask formats show values in their pattern and refuse what doesn't fit. #[test] fn dates_times_and_masks() { let d = Format::Date("mm/dd/yyyy".into()); diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 281200df09..b2101ef4df 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -1045,6 +1045,7 @@ pub fn calculations_changed(before: &[Field], after: &[Field]) -> Vec { .collect() } +/// A [`FormError::Invalid`] with message `m`. fn invalid(m: impl Into) -> Result { Err(FormError::Invalid(m.into())) } diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs index 4631510fe4..a60892f72a 100644 --- a/crates/xfa/src/lib.rs +++ b/crates/xfa/src/lib.rs @@ -38,6 +38,7 @@ pub(crate) const MAX_XML_DEPTH: usize = 1_024; /// cannot under-count a real element; a stray `<` in text is invalid XML and only makes it /// over-count, which errs towards refusing the document. pub(crate) fn xml_nesting_depth(text: &str) -> usize { + /// Where `needle` next starts in `hay` at or after `from`. fn find(hay: &[u8], from: usize, needle: &[u8]) -> Option { (from..hay.len()).find(|&p| hay[p..].starts_with(needle)) } From 872e3a654fb332af7d071a45286579e505bae653 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:59:43 -0400 Subject: [PATCH 045/216] M12: an XFA date field is shown through its display picture and typed in its edit picture's pattern --- crates/automation/tests/it/automation.rs | 30 ++++++++++++++++ crates/xfa/README.md | 2 +- crates/xfa/src/data.rs | 20 ++++++----- crates/xfa/src/layout.rs | 4 +++ crates/xfa/src/pdf.rs | 4 ++- crates/xfa/src/tests.rs | 44 ++++++++++++++++++++++++ parity/acrobat-features.toml | 4 +-- 7 files changed, 96 insertions(+), 12 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index e47ee9bdbc..b4b0a479f8 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6949,6 +6949,36 @@ fn xfa_date_fields_keep_typed_dates_as_another_viewer_does() { } /// A dynamic XFA form opens laid out from its template through the tools, renders, takes values +/// What an XFA date field shows once a date is typed into it: through its display picture, as +/// another viewer showed the same typing on a synthetic form (the field's `formattedValue`). A +/// date is shown in the picture; text that isn't one, as typed. +#[test] +fn xfa_date_fields_show_typed_dates_through_their_display_picture() { + let dir = workdir("xfa-shown-dates"); + std::fs::write(dir.join("dates.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_pictures_template())).unwrap(); + let mut a = auto(&dir); + // typed, then what display, edit and either show (the field without pictures is left out: + // the other viewer shows it in its locale's default, which isn't followed yet). + let seen = [ + ("2016-10-18", ["10/18/2016", "10/18/2016", "20161018"]), + ("10/18/2016", ["10/18/2016", "10/18/2016", "10/18/2016"]), + ("20161018", ["10/18/2016", "10/18/2016", "20161018"]), + ("18OCT16", ["18OCT16", "18OCT16", "20161018"]), + ("26 10 18", ["26 10 18", "26 10 18", "26 10 18"]), + ("xyz", ["xyz", "xyz", "xyz"]), + ]; + for (typed, shown) in seen { + for (field, want) in ["display", "edit", "either"].into_iter().zip(shown) { + let doc = ok(&mut a, "doc_open", json!({ "path": "dates.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { field: typed } })); + let text = page_text(&mut a, doc).join("\n"); + assert_eq!(text, want, "{typed} in {field}"); + ok(&mut a, "doc_close", json!({ "doc": doc, "discard_changes": true })); + } + } + let _ = std::fs::remove_dir_all(&dir); +} + /// and saves them. #[test] fn dynamic_xfa_forms_open_render_fill_and_save_through_tools() { diff --git a/crates/xfa/README.md b/crates/xfa/README.md index ecdb1d90fe..ed5a370947 100644 --- a/crates/xfa/README.md +++ b/crates/xfa/README.md @@ -36,7 +36,7 @@ that warning and keeps the existing layout and accepted widget values. - **PDF** (`pdf::write_form`): pages with content streams in the standard 14 fonts (Arial and friends → Helvetica, Courier New → Courier, serif faces → Times; nothing is embedded), JPEG XObjects, and widgets: text (multi-line, max length, alignment), date (Acrobat's `AFDate` - format and keystroke actions from the picture clause), check boxes and radio groups (from + format action from the display picture, keystroke action from the edit picture), check boxes and radio groups (from `exclGroup`), push buttons with Reset / Print / Save As / URI actions recognised from their scripts. Appearance streams are left empty for the forms layer to generate. Each field keeps its SOM path in `/PCSom`; the AcroForm gets `/PCXfaLayout` so a saved form is not laid out diff --git a/crates/xfa/src/data.rs b/crates/xfa/src/data.rs index 95f59a44b9..2f3b84ff3d 100644 --- a/crates/xfa/src/data.rs +++ b/crates/xfa/src/data.rs @@ -332,17 +332,21 @@ fn items_of(doc: &Document, f: &FieldDatum) -> (String, String) { (on, off) } -/// The Acrobat date pattern a field's format action names (`AFDate_FormatEx("yyyy-mm-dd")`). +/// The Acrobat date pattern a field's value is kept in: what its keystroke action names +/// (`AFDate_KeystrokeEx("yyyy-mm-dd")`, the edit picture's), else its format action (a field laid +/// out before the format action took the display picture names the same pattern in both). fn date_pattern_of(doc: &Document, f: &FieldDatum) -> Option { let d = doc.get(f.obj); let aa = doc.resolve(d.as_dict()?.get(b"AA")?); - let fa = doc.resolve(aa.as_dict()?.get(b"F")?); - let js = text_of(doc, fa.as_dict()?, b"JS")?; - let i = js.find("AFDate_FormatEx(")?; - let rest = &js[i + "AFDate_FormatEx(".len()..]; - let q = rest.find('"')?; - let body = &rest[q + 1..]; - Some(body[..body.find('"')?].to_string()) + let aa = aa.as_dict()?; + let named = |key: &[u8], call: &str| -> Option { + let action = doc.resolve(aa.get(key)?); + let js = text_of(doc, action.as_dict()?, b"JS")?; + let rest = js.get(js.find(call)? + call.len()..)?; + let body = rest.get(rest.find('"')? + 1..)?; + Some(body.get(..body.find('"')?)?.to_string()) + }; + named(b"K", "AFDate_KeystrokeEx(").or_else(|| named(b"F", "AFDate_FormatEx(")) } const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs index 670d43791a..6e2f0b5321 100644 --- a/crates/xfa/src/layout.rs +++ b/crates/xfa/src/layout.rs @@ -168,6 +168,9 @@ pub struct Widget { pub items: Vec, /// A text field that doesn't scroll: it takes no more text than it shows (`DoNotScroll`). pub no_scroll: bool, + /// Date fields: the date letters of the display picture (``), how the value + /// shows when it isn't being typed in. `None`: as the edit pattern writes it. + pub display_date: Option, } #[derive(Clone, Debug, Default, PartialEq)] @@ -2087,6 +2090,7 @@ impl Layouter<'_> { action, items, no_scroll: f.no_scroll, + display_date: (f.ui == Ui::DateTimeEdit).then(|| f.display_picture.as_deref().and_then(crate::data::date_letters)).flatten(), }))) } } diff --git a/crates/xfa/src/pdf.rs b/crates/xfa/src/pdf.rs index b467d04dc3..d8326bfc01 100644 --- a/crates/xfa/src/pdf.rs +++ b/crates/xfa/src/pdf.rs @@ -399,7 +399,9 @@ impl Emitter<'_> { if let WidgetKind::Date(pattern) = &w.kind { d.set(DATE_KEY.to_vec(), Object::Bool(true)); let mut aa = Dict::new(); - aa.set(b"F".to_vec(), js_action(&format!("AFDate_FormatEx(\"{pattern}\");"))); + // Shown through the display picture, typed in the edit picture's pattern. + let shown = w.display_date.as_deref().unwrap_or(pattern); + aa.set(b"F".to_vec(), js_action(&format!("AFDate_FormatEx(\"{shown}\");"))); aa.set(b"K".to_vec(), js_action(&format!("AFDate_KeystrokeEx(\"{pattern}\");"))); d.set(b"AA".to_vec(), Object::Dict(aa)); } diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 3175882f89..2aae953c59 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -3009,6 +3009,50 @@ fn a_zero_caption_reserve_sizes_the_caption_as_none_does() { assert!((x_of("withZero") - x_of("without")).abs() < 0.01, "as without a reserve: {} {}", x_of("withZero"), x_of("without")); } +/// A date field is shown through its display picture and typed in its edit picture's pattern: its +/// format action takes the display picture's letters (weekday and month names included), its +/// keystroke action the edit picture's; without a display picture both take the edit pattern. +#[test] +fn date_fields_are_shown_through_their_display_picture() { + let xdp = r##" + + + +"##; + let form = layout_xml(xdp).unwrap(); + let w = widgets(&form.pages[0]); + let shown = |n: &str| w.iter().find(|w| w.name == n).unwrap().display_date.clone(); + assert_eq!(shown("plain").as_deref(), Some("yyyymmdd")); + assert_eq!(shown("long").as_deref(), Some("dddd, mmmm d, yyyy")); + assert_eq!(shown("both").as_deref(), Some("yyyymmmdd")); + assert_eq!(shown("none"), None); + let mut doc = Document::open(Arc::new(shell(xdp))).unwrap(); + render_into(&mut doc).unwrap(); + let fields = pdfcraft_forms_free_fields(&doc); + let action = |n: &str, k: &[u8]| { + let d = fields.iter().find(|(name, _)| name == n).map(|(_, d)| d.clone()).unwrap(); + let aa = doc.resolve(d.get(b"AA").unwrap()).as_dict().unwrap().clone(); + let a = doc.resolve(aa.get(k).unwrap()).as_dict().unwrap().clone(); + doc.resolve(a.get(b"JS").unwrap()).as_string().unwrap().to_text() + }; + assert_eq!(action("plain", b"F"), r#"AFDate_FormatEx("yyyymmdd");"#); + assert_eq!(action("plain", b"K"), r#"AFDate_KeystrokeEx("yyyy-mm-dd");"#, "typed in the default edit pattern"); + assert_eq!(action("long", b"F"), r#"AFDate_FormatEx("dddd, mmmm d, yyyy");"#); + assert_eq!( + (action("both", b"F"), action("both", b"K")), + (r#"AFDate_FormatEx("yyyymmmdd");"#.to_string(), r#"AFDate_KeystrokeEx("yyyymmdd");"#.to_string()) + ); + assert_eq!(action("none", b"F"), r#"AFDate_FormatEx("dd/mm/yyyy");"#); +} + #[test] fn a_signed_signature_box_shows_the_signature_the_file_holds() { let mut doc = Document::open(Arc::new(crate::fixtures::signed_shell())).unwrap(); diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 26517a8dae..03c923bce7 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5296,8 +5296,8 @@ milestone = "M12" status = "partial" commands = ["file.open"] tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"] -evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn", "crates/forms/src/af.rs::xfa_date_fields_keep_and_show_what_their_pattern_does_not_read", "crates/automation/tests/it/automation.rs::xfa_date_fields_keep_typed_dates_as_another_viewer_does"] -notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats (a date one of the edit picture's patterns reads is kept in its first, and in the data as an ISO date; text none of them reads, ISO text included, is kept and shown as typed rather than refused, as another viewer keeps it on a synthetic form; a display picture that differs from the edit picture isn't used to show the date yet), check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" +evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn", "crates/forms/src/af.rs::xfa_date_fields_keep_and_show_what_their_pattern_does_not_read", "crates/automation/tests/it/automation.rs::xfa_date_fields_keep_typed_dates_as_another_viewer_does", "crates/xfa/src/tests.rs::date_fields_are_shown_through_their_display_picture", "crates/automation/tests/it/automation.rs::xfa_date_fields_show_typed_dates_through_their_display_picture"] +notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats (a date one of the edit picture's patterns reads is kept in its first, and in the data as an ISO date; text none of them reads, ISO text included, is kept and shown as typed rather than refused, as another viewer keeps it on a synthetic form; shown through the field's display picture (weekday and month names included) and typed in its edit picture's pattern, as another viewer shows a date on a synthetic form; a field with no picture at all shows yyyy-mm-dd, where that viewer uses its locale's default), check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" [[feature]] id = "form.xfa-formcalc" From 2832d3cc23348ec048235849461332b9746c73c9 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:17:53 -0400 Subject: [PATCH 046/216] M12: an XFA date field reads typed dates with its edit picture before showing them through its display picture --- crates/automation/tests/it/automation.rs | 30 +++++++++++++- crates/forms/src/af.rs | 52 ++++++++++++++++++------ crates/forms/src/lib.rs | 9 +++- crates/xfa/src/fixtures.rs | 4 +- 4 files changed, 80 insertions(+), 15 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index b4b0a479f8..95fe8fb245 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6948,7 +6948,6 @@ fn xfa_date_fields_keep_typed_dates_as_another_viewer_does() { let _ = std::fs::remove_dir_all(&dir); } -/// A dynamic XFA form opens laid out from its template through the tools, renders, takes values /// What an XFA date field shows once a date is typed into it: through its display picture, as /// another viewer showed the same typing on a synthetic form (the field's `formattedValue`). A /// date is shown in the picture; text that isn't one, as typed. @@ -6979,6 +6978,35 @@ fn xfa_date_fields_show_typed_dates_through_their_display_picture() { let _ = std::fs::remove_dir_all(&dir); } +/// An XFA date field whose edit picture differs from its display picture reads a typed date with +/// the edit picture and shows it with the display picture, as another viewer did for the same +/// typing on a synthetic form: day first in, month first out. What the edit picture can't read is +/// kept and shown as typed. +#[test] +fn xfa_date_fields_read_typed_dates_through_their_edit_picture() { + let dir = workdir("xfa-edit-dates"); + std::fs::write(dir.join("dates.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_pictures_template())).unwrap(); + let mut a = auto(&dir); + // typed, then what the field shows and what the data keeps. + let seen = [ + ("18/10/2016", "10/18/2016", "2016-10-18"), + ("10/11/2016", "11/10/2016", "2016-11-10"), + ("10/18/2016", "10/18/2016", "10/18/2016"), + ("2016-10-18", "10/18/2016", "2016-10-18"), + ]; + for (typed, shown, kept) in seen { + let doc = ok(&mut a, "doc_open", json!({ "path": "dates.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "swapped": typed } })); + assert_eq!(page_text(&mut a, doc).join("\n"), shown, "{typed} shown"); + ok(&mut a, "doc_export_data", json!({ "doc": doc, "path": "data.xml", "what": "fields" })); + let xml = std::fs::read_to_string(dir.join("data.xml")).unwrap(); + assert!(xml.contains(&format!("{kept}")), "{typed} kept: want {kept}, got {xml}"); + ok(&mut a, "doc_close", json!({ "doc": doc, "discard_changes": true })); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// A dynamic XFA form opens laid out from its template through the tools, renders, takes values /// and saves them. #[test] fn dynamic_xfa_forms_open_render_fill_and_save_through_tools() { diff --git a/crates/forms/src/af.rs b/crates/forms/src/af.rs index 3be1f96152..48e54d3ce4 100644 --- a/crates/forms/src/af.rs +++ b/crates/forms/src/af.rs @@ -99,6 +99,10 @@ pub struct Actions { /// A date field PdfCraft laid out for an XFA form (`/PCXfaDate true`): text its format doesn't /// read is kept and shown as typed rather than refused, as an XFA form keeps it. pub xfa_date: bool, + /// Such a field's edit pattern (its `AFDate_KeystrokeEx`) when it differs from the display + /// pattern [`Actions::format`] names: the value is typed and kept in this one, and shown in + /// that one. + pub edit_date: Option, } /// Field scripts that aren't AF calls, by event. @@ -116,31 +120,47 @@ impl Actions { self.format == Format::None && self.validate == Validate::None && self.calculate == Calculate::None } - /// The Keystroke event on commit ([`keystroke`]); an XFA date field keeps text its format - /// doesn't read, as typed. + /// The Keystroke event on commit ([`keystroke`]); an XFA date field checks the text against its + /// edit pattern and keeps what that doesn't read, as typed. pub fn keystroke(&self, field: &str, value: &str) -> Result { - match keystroke(&self.format, field, value) { + let edit = self.edit_pattern().map(|p| Format::Date(p.to_string())); + match keystroke(edit.as_ref().unwrap_or(&self.format), field, value) { Err(_) if self.xfa_date => Ok(value.to_string()), checked => checked, } } /// What the Format event shows for `value` ([`format_value`]). An XFA date field shows a date - /// only for a value that is one, in its format already or as an ISO date (`2026-10-18` or - /// `20261018`); anything else, which its format would read loosely, shows as typed. + /// only for a value that is one, in its edit pattern (written in the display pattern) or as an + /// ISO date (`2026-10-18` or `20261018`); anything else, which its format would read loosely, + /// shows as typed. pub fn format_value(&self, value: &str) -> String { - match &self.format { - Format::Date(fmt) if self.xfa_date => { + match (&self.format, self.edit_pattern()) { + (Format::Date(fmt), Some(edit)) => { let t = value.trim(); - let in_format = parse_date(t, fmt).is_some_and(|dt| format_date(dt, fmt).eq_ignore_ascii_case(t)); - match iso_date(t) { - Some(dt) if !in_format => format_date(dt, fmt), - _ => value.to_string(), + match parse_date(t, edit).filter(|dt| format_date(*dt, edit).eq_ignore_ascii_case(t)) { + // Typed as it shows: kept as it is, its case too. + Some(_) if edit == fmt => value.to_string(), + Some(dt) => format_date(dt, fmt), + None => iso_date(t).map_or_else(|| value.to_string(), |dt| format_date(dt, fmt)), } } - f => format_value(f, value), + (f, _) => format_value(f, value), } } + + /// An XFA date field's edit pattern: [`Actions::edit_date`], else its display pattern. + fn edit_pattern(&self) -> Option<&str> { + match &self.format { + Format::Date(fmt) if self.xfa_date => Some(self.edit_date.as_deref().unwrap_or(fmt)), + _ => None, + } + } +} + +/// The pattern an `AFDate_KeystrokeEx("…")` keystroke script checks dates against. +pub fn parse_date_keystroke(js: &str) -> Option { + call(js, "AFDate_KeystrokeEx")?.first().and_then(Arg::string) } /// `text` as an ISO 8601 calendar date, `yyyy-mm-dd` or `yyyymmdd` (digits only, a real day). @@ -1824,6 +1844,14 @@ mod tests { assert_eq!(mdy.format_value("xyz"), "xyz"); assert_eq!(mdy.format_value("2016-02-30"), "2016-02-30", "not a real day: as typed"); assert_eq!(xfa("ddmmmyy").format_value("18OCT16"), "18OCT16", "in the pattern, its case kept"); + // Typed in an edit pattern unlike the display pattern: read with the one, shown in the other. + let swapped = Actions { edit_date: Some("dd/mm/yyyy".into()), ..xfa("mm/dd/yyyy") }; + assert_eq!(swapped.format_value("18/10/2016"), "10/18/2016"); + assert_eq!(swapped.format_value("10/11/2016"), "11/10/2016", "10 November"); + assert_eq!(swapped.format_value("10/18/2016"), "10/18/2016", "not a day-first date: as typed"); + assert_eq!(swapped.format_value("2016-10-18"), "10/18/2016"); + assert_eq!(swapped.keystroke("Date", " 18/10/2016 "), Ok("18/10/2016".to_string()), "checked against the edit pattern"); + assert_eq!(swapped.keystroke("Date", "10/18/2016"), Ok("10/18/2016".to_string())); } /// Date, time and mask formats show values in their pattern and refuse what doesn't fit. diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index b2101ef4df..5440498af4 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -422,7 +422,14 @@ fn actions_of(doc: &Document, d: &Dict, widgets: &[ObjRef], scripts: &mut Decode None => {} } } - if let Some(k) = js(b"K") + let k = js(b"K"); + // An XFA date field typed in another pattern than it shows. + if out.xfa_date + && let af::Format::Date(shown) = &out.format + { + out.edit_date = k.as_deref().and_then(af::parse_date_keystroke).filter(|edit| edit != shown); + } + if let Some(k) = k && out.format == af::Format::None { // A mask has only a keystroke script. diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index 03de74ff43..2a501881a8 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -529,7 +529,8 @@ pub fn date_alternatives_template() -> String { } /// Date fields with each kind of picture: `display` a display picture only, `edit` an edit and a -/// display picture, `either` an edit picture of two alternatives, `bare` none. +/// display picture, `either` an edit picture of two alternatives, `bare` none, `swapped` an edit +/// picture (day first) unlike its display picture (month first). pub fn date_pictures_template() -> String { r##" @@ -540,6 +541,7 @@ pub fn date_pictures_template() -> String { date{MM/DD/YYYY}date{MM/DD/YYYY} date{YYYYMMDD}|date{DDMMMYY}date{YYYYMMDD} + date{DD/MM/YYYY}date{MM/DD/YYYY} From 36deeb666755a6b74f4c62904636dc0bb7875aa3 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:35:03 -0400 Subject: [PATCH 047/216] M12: XFA ready events run in the other viewer's order, and layout:ready again after a new layout --- crates/engine/src/tests.rs | 22 ++++++- crates/engine/src/xfa.rs | 114 ++++++++++++++++++++++++++++------- crates/xfa/src/fixtures.rs | 46 ++++++++++++++ parity/acrobat-features.toml | 6 +- 4 files changed, 160 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 16278390cc..21be08467d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8083,7 +8083,7 @@ fn exporting_office_keeps_dotted_leader_entries_as_paragraphs() { /// layout:ready scripts run once on opening: the root's turns field highlighting on (only when it /// is off), a field's sets a value and a later script reads the new highlight, while page -/// numbering is left to the layout and form:ready is another event. +/// numbering is left to the layout. form:ready is another event, and runs too. #[test] fn a_forms_layout_ready_scripts_run_once_it_is_laid_out() { let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::layout_ready_template())); @@ -8095,13 +8095,31 @@ fn a_forms_layout_ready_scripts_run_once_it_is_laid_out() { assert_eq!(value(&s, "stamp"), vec!["laid out".to_string()]); assert_eq!(value(&s, "seen"), vec!["true".to_string()], "a later script reads the highlight the root's turned on"); assert!(value(&s, "pageNo").iter().all(|v| v.is_empty()), "page numbers are the layout's: {:?}", value(&s, "pageNo")); - assert!(value(&s, "note").iter().all(|v| v.is_empty()), "form:ready is another event"); + assert_eq!(value(&s, "note"), vec!["form ready".to_string()], "form:ready runs on opening too"); // With highlighting already on, the form has nothing to ask for. s.set_field_highlight(true); let id = s.open("ready.pdf", None, bytes, None).expect("opens"); assert!(s.take_js_output(id).requests.is_empty()); } +/// The ready events run on opening in the order another viewer ran them on a synthetic form: +/// initialize children first, form:ready and layout:ready parents first, docReady after the first +/// layout:ready. A click that lays the form out again (showing a tall section: a second page) +/// runs every layout:ready script again, once each, and they read the new page count. +#[test] +fn ready_events_run_in_order_and_layout_ready_runs_again_after_a_new_layout() { + let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::ready_events_template())); + let mut s = Session::new(); + let id = s.open("ready.pdf", None, bytes, None).expect("opens"); + let log = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "log").map(|f| f.value.join("")).unwrap_or_default(); + let opened = "title initialize|root initialize|root form:ready|title form:ready|root layout:ready pages=1|title layout:ready|root docReady"; + assert_eq!(log(&s), opened); + assert_eq!(s.get(id).unwrap().info.pages.len(), 1); + s.apply(id, Edit::XfaEvent { som: "form[0].grow[0]".into(), activity: "click".into() }).expect("clicks"); + assert_eq!(s.get(id).unwrap().info.pages.len(), 2, "the tall section takes a second page"); + assert_eq!(log(&s), format!("{opened}|root layout:ready pages=2|title layout:ready")); +} + /// Field scripts of one edit read the field highlight an earlier one set: `on`'s calculation turns /// it on, and `seen`'s, which runs after it, records what it reads. #[test] diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index d0e2153181..e17c9efb97 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -264,6 +264,9 @@ struct Runner<'a, 'b> { skipped: usize, relayouts: usize, relayouts_skipped: bool, + /// The form was laid out again since its layout:ready scripts last ran: they run once more + /// when the event ends. + laid_out: bool, dropped_output: usize, truncated_warned: bool, data: Option, @@ -303,6 +306,7 @@ impl<'a, 'b> Runner<'a, 'b> { skipped: 0, relayouts: 0, relayouts_skipped: false, + laid_out: false, dropped_output: 0, truncated_warned: false, data, @@ -530,8 +534,14 @@ impl<'a, 'b> Runner<'a, 'b> { return Ok(()); } self.relayouts += 1; + self.laid_out = true; self.flush()?; let report = pdfcraft_xfa::rerender(self.doc, self.tpl).map_err(|e| e.to_string())?; + if report.pages != self.run.page_count { + // Later scripts read the new page count (`xfa.layout.pageCount()`) from a new session. + self.run.page_count = report.pages; + self.session = None; + } self.console(report.warnings); crate::xfa_redraw(self.doc)?; self.console(crate::undrawn_field_warnings(self.doc)); @@ -733,16 +743,52 @@ impl<'a, 'b> Runner<'a, 'b> { self.live().events.iter().filter(|e| e.som == som && e.activity == activity).cloned().collect() } - /// End the event: write what is left, lay the form out if a capped relayout is owed, and - /// report what the limits cut. - fn finish(mut self) -> Result { - #[cfg(test)] - self.check_live(); + /// Every script of `activity`, in document order (parents before their children). + fn events_named(&mut self, activity: &str) -> Vec { + self.live().events.iter().filter(|e| e.activity == activity).cloned().collect() + } + + /// Every layout:ready script, parents first. A field that numbers pages keeps the number the + /// layout gave each page: the value a script writes to it is dropped (one value would put the + /// same number on every page). + fn layout_ready(&mut self) -> Result<(), String> { + self.laid_out = false; + let (ready, numbered) = { + let live = self.live(); + let ready: Vec = live.events.iter().filter(|e| e.activity == "layoutReady").cloned().collect(); + let numbered: HashSet = + ready.iter().filter(|e| pdfcraft_xfa::numbers_pages(&e.script) && is_field(&live.root, &e.som, 0)).map(|e| e.som.clone()).collect(); + (ready, numbered) + }; + self.numbered = numbered; + for ev in &ready { + self.run(ev, "")?; + } + self.numbered.clear(); + Ok(()) + } + + /// Lay the form out once more if a capped relayout is owed. + fn owed_relayout(&mut self) -> Result<(), String> { if self.relayouts_skipped { self.relayouts = 0; self.relayouts_skipped = false; self.relayout()?; } + Ok(()) + } + + /// End the event: lay the form out if a capped relayout is owed, run the layout:ready scripts + /// again if the form was laid out again (once: what they lay out doesn't run them a third + /// time), write what is left, and report what the limits cut. + fn finish(mut self) -> Result { + #[cfg(test)] + self.check_live(); + self.owed_relayout()?; + if self.laid_out { + self.layout_ready()?; + self.owed_relayout()?; + } self.flush()?; self.session = None; if self.skipped > 0 { @@ -841,35 +887,57 @@ pub(crate) fn relayout_changed_text( Ok(Some(report.warnings)) } -/// On open: initialize scripts, then layout:ready scripts (the form is laid out by now), then -/// calculations. Returns what they changed. +/// On open, in the order another viewer runs them: initialize scripts (children before their +/// parent), form:ready (parents first), layout:ready (parents first; the form is laid out by +/// now), docReady, then the calculations. Returns what they changed. /// -/// layout:ready runs once here, where forms set themselves up (turning field highlighting on, -/// say); a viewer runs it after every layout. Every layout:ready script runs, but a field that -/// numbers pages keeps the number the layout gave each page: the value a script writes to it is -/// dropped (one value would put the same number on every page). +/// layout:ready runs here, where forms set themselves up (turning field highlighting on, say), +/// and again whenever a later script lays the form out again ([`Runner::finish`]). pub(crate) fn on_open(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mut XfaRun) -> Result { let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS); - let events: Vec = r.live().events.iter().filter(|e| e.activity == "initialize" || e.activity == "docReady").cloned().collect(); - for ev in &events { + let initialize = r.events_named("initialize"); + for ev in &children_first(initialize) { r.run(ev, "")?; } - let (ready, numbered) = { - let live = r.live(); - let ready: Vec = live.events.iter().filter(|e| e.activity == "layoutReady").cloned().collect(); - let numbered: HashSet = - ready.iter().filter(|e| pdfcraft_xfa::numbers_pages(&e.script) && is_field(&live.root, &e.som, 0)).map(|e| e.som.clone()).collect(); - (ready, numbered) - }; - r.numbered = numbered; - for ev in &ready { + // `ready` without `ref="$layout"` is form:ready. + for ev in &r.events_named("ready") { + r.run(ev, "")?; + } + r.layout_ready()?; + for ev in &r.events_named("docReady") { r.run(ev, "")?; } - r.numbered.clear(); r.calculates()?; r.finish() } +/// `events` (in document order) reordered so that each object's come after those of the objects +/// inside it, siblings keeping their order; an object's own events keep theirs. +fn children_first(events: Vec) -> Vec { + let mut out = Vec::with_capacity(events.len()); + // The objects whose events wait for their children's, outermost first. + let mut open: Vec> = Vec::new(); + for ev in events { + while let Some(top) = open.last() { + let parent = top.first().map_or("", |e| e.som.as_str()); + // The same object, or one inside it (the root may have an empty path). + let inside = parent.is_empty() || ev.som == parent || ev.som.strip_prefix(parent).is_some_and(|rest| rest.starts_with('.')); + if inside { + break; + } + out.extend(open.pop().unwrap_or_default()); + } + match open.last_mut() { + Some(top) if top.first().is_some_and(|e| e.som == ev.som) => top.push(ev), + _ => open.push(vec![ev]), + } + } + while let Some(top) = open.pop() { + out.extend(top); + } + out +} + /// After fields `names` took new values: each one's change, exit and validate scripts, then /// the calculations once (or only those, after a reset). A validate script that answers false, /// or fails, shows its message; the value stays, as Acrobat marks the field invalid rather diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index 9328b854c9..9d69d18822 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -188,6 +188,52 @@ pub fn layout_ready_template() -> String { .to_string() } +/// A form whose scripts log the ready events they run, in `log`: the root subform's initialize, +/// form:ready, layout:ready (with the page count) and docReady, and the same but docReady for the +/// field `title` inside it. The button `grow` shows the hidden subform `tall`, which takes the form +/// to a second page. +pub fn ready_events_template() -> String { + let log = |what: &str| { + format!( + r#""# + ) + }; + format!( + r##" + + + +"##, + root_init = log(r#""root initialize""#), + root_form = log(r#""root form:ready""#), + root_layout = log(r#""root layout:ready pages=" + xfa.layout.pageCount()"#), + root_doc = log(r#""root docReady""#), + title_init = log(r#""title initialize""#), + title_form = log(r#""title form:ready""#), + title_layout = log(r#""title layout:ready""#), + ) +} + /// A hidden subform `details` a script may show, holding a named field and three unnamed /// objects: a caption, an old caption the form keeps hidden, and a hidden subform. Unnamed /// objects have no SOM name of their own, so showing `details` must leave the hidden ones hidden. diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 18e2a77a7e..5eb7da8158 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4464,7 +4464,7 @@ status = "shipped" commands = [] tools = [] evidence = ["crates/ui-egui/tests/it/view.rs::highlight_fields_tints_the_field_area", "crates/ui-egui/tests/it/view.rs::required_radio_buttons_get_a_round_red_border", "crates/ui-egui/tests/it/view.rs::field_highlighting_is_on_by_default_and_remembered", "crates/ui-egui/tests/it/view.rs::stored_field_highlight_choice_wins_over_the_default", "crates/ui-egui/tests/it/view.rs::highlight_fields_leaves_read_only_fields_alone", "crates/ui-egui/tests/it/editing.rs::a_secured_form_shows_its_form_notice_and_its_security", "crates/ui-egui/tests/it/xfa.rs::a_form_that_turns_field_highlighting_on_gets_it", "crates/engine/src/tests.rs::a_forms_layout_ready_scripts_run_once_it_is_laid_out"] -notes = "a form's scripts read and set it as app.runtimeHighlight (XFA forms usually in layout:ready, which runs once on opening), and a setting they make carries over as the button's does; only fields that can be filled are marked (a read-only field is left as drawn, so a form's locked boxes don't look fillable); offered on secured forms too; on by default for new settings (a stored choice is kept) and remembered for the next document and session; toggled from the form bar and from Preferences > Appearance, where it sets the default for documents opened afterwards; required fields get a red border (round for radio buttons); the tint is drawn over the field, where Acrobat paints the highlight colour behind it" +notes = "a form's scripts read and set it as app.runtimeHighlight (XFA forms usually in layout:ready, which runs on opening and again after each new layout), and a setting they make carries over as the button's does; only fields that can be filled are marked (a read-only field is left as drawn, so a form's locked boxes don't look fillable); offered on secured forms too; on by default for new settings (a stored choice is kept) and remembered for the next document and session; toggled from the form bar and from Preferences > Appearance, where it sets the default for documents opened afterwards; required fields get a red border (round for radio buttons); the tint is drawn over the field, where Acrobat paints the highlight colour behind it" [[feature]] id = "form.field-appearance-display" @@ -5296,8 +5296,8 @@ milestone = "M12" status = "partial" commands = ["file.open"] tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"] -evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn"] -notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" +evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::ready_events_run_in_order_and_layout_ready_runs_again_after_a_new_layout", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn"] +notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): on open initialize (children before their parent), form:ready, layout:ready and docReady, in the order another viewer runs them on a synthetic form, then calculate; layout:ready again, once each, after a script lays the form out again (with the new page count); exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" [[feature]] id = "form.xfa-formcalc" From 364ba61bebc66ca324749de018fb1b745137db26 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:50:24 -0400 Subject: [PATCH 048/216] M12: the parity notes say layout:ready reruns after scripted re-layouts only --- parity/acrobat-features.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 5eb7da8158..06cce6d0c3 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4464,7 +4464,7 @@ status = "shipped" commands = [] tools = [] evidence = ["crates/ui-egui/tests/it/view.rs::highlight_fields_tints_the_field_area", "crates/ui-egui/tests/it/view.rs::required_radio_buttons_get_a_round_red_border", "crates/ui-egui/tests/it/view.rs::field_highlighting_is_on_by_default_and_remembered", "crates/ui-egui/tests/it/view.rs::stored_field_highlight_choice_wins_over_the_default", "crates/ui-egui/tests/it/view.rs::highlight_fields_leaves_read_only_fields_alone", "crates/ui-egui/tests/it/editing.rs::a_secured_form_shows_its_form_notice_and_its_security", "crates/ui-egui/tests/it/xfa.rs::a_form_that_turns_field_highlighting_on_gets_it", "crates/engine/src/tests.rs::a_forms_layout_ready_scripts_run_once_it_is_laid_out"] -notes = "a form's scripts read and set it as app.runtimeHighlight (XFA forms usually in layout:ready, which runs on opening and again after each new layout), and a setting they make carries over as the button's does; only fields that can be filled are marked (a read-only field is left as drawn, so a form's locked boxes don't look fillable); offered on secured forms too; on by default for new settings (a stored choice is kept) and remembered for the next document and session; toggled from the form bar and from Preferences > Appearance, where it sets the default for documents opened afterwards; required fields get a red border (round for radio buttons); the tint is drawn over the field, where Acrobat paints the highlight colour behind it" +notes = "a form's scripts read and set it as app.runtimeHighlight (XFA forms usually in layout:ready, which runs on opening and again after a script lays the form out again, but not yet after typing into a growable field lays it out again), and a setting they make carries over as the button's does; only fields that can be filled are marked (a read-only field is left as drawn, so a form's locked boxes don't look fillable); offered on secured forms too; on by default for new settings (a stored choice is kept) and remembered for the next document and session; toggled from the form bar and from Preferences > Appearance, where it sets the default for documents opened afterwards; required fields get a red border (round for radio buttons); the tint is drawn over the field, where Acrobat paints the highlight colour behind it" [[feature]] id = "form.field-appearance-display" @@ -5297,7 +5297,7 @@ status = "partial" commands = ["file.open"] tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"] evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::ready_events_run_in_order_and_layout_ready_runs_again_after_a_new_layout", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn"] -notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): on open initialize (children before their parent), form:ready, layout:ready and docReady, in the order another viewer runs them on a synthetic form, then calculate; layout:ready again, once each, after a script lays the form out again (with the new page count); exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" +notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): on open initialize (children before their parent), form:ready, layout:ready and docReady, in the order another viewer runs them on a synthetic form, then calculate; layout:ready again, once each, after a script lays the form out again (with the new page count); exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: layout:ready after typing into a growable field lays the form out again (only re-layouts scripts cause run it again), and the extra layout:ready another viewer runs on opening after scripts change only field text; a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" [[feature]] id = "form.xfa-formcalc" From 127536c42727da1387600972ece59ece7bcdf331 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:33:01 -0400 Subject: [PATCH 049/216] M12: a form saved with its pages is laid out from its template when it requires dynamic rendering, unless signed Co-authored-by: EULA <90616501+EULArule@users.noreply.github.com> --- crates/engine/src/tests.rs | 23 ++++++++++++++ crates/render/src/inspect.rs | 11 +++++-- crates/xfa/README.md | 4 +++ crates/xfa/src/fixtures.rs | 40 +++++++++++++++++++++++++ crates/xfa/src/lib.rs | 11 +++++-- crates/xfa/src/packets.rs | 58 ++++++++++++++++++++++++++++++++++++ crates/xfa/src/tests.rs | 35 ++++++++++++++++++++++ parity/acrobat-features.toml | 4 +-- 8 files changed, 180 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index dc76159d14..202f3a3190 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5288,6 +5288,29 @@ fn dynamic_xfa_forms_open_with_the_values_and_rows_of_their_data() { assert!(!doc.dirty); } +/// A dynamic form a viewer saved with its pages drawn holds only its signature box, so it opened as +/// a picture with nothing to fill in. When its configuration says it must be rendered dynamically +/// it is laid out from its template on opening, and its text field can be filled; once signed, it +/// opens as saved, its pages and signature untouched. +#[test] +fn a_form_saved_with_its_pages_that_requires_dynamic_rendering_is_laid_out_unless_signed() { + let mut s = Session::new().with_clock(|| 1_700_000_000); + let unsigned = Arc::new(pdfcraft_xfa::fixtures::saved_with_pages_shell("required", false)); + let id = s.open("saved.pdf", None, unsigned, None).expect("opens"); + let doc = s.get(id).unwrap(); + assert_eq!(doc.info.xfa, Some(pdfcraft_render::Xfa::Dynamic)); + assert!(doc.xfa.is_some(), "laid out from the template"); + let name = doc.form.iter().find(|f| f.name.contains("name")).map(|f| f.name.clone()).expect("the template's text field"); + s.apply(id, Edit::SetFieldValue { name: name.clone(), value: FieldValue::Text("Ada".into()) }).expect("fills"); + assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == name).map(|f| f.value.clone()), Some(vec!["Ada".to_string()])); + let signed = Arc::new(pdfcraft_xfa::fixtures::saved_with_pages_shell("required", true)); + let id = s.open("signed.pdf", None, signed.clone(), None).expect("opens"); + let doc = s.get(id).unwrap(); + assert_eq!(doc.info.xfa, Some(pdfcraft_render::Xfa::Static), "signed: as saved"); + assert!(doc.xfa.is_none(), "nothing was laid out"); + assert_eq!(doc.bytes[..], signed[..], "no revision was appended on open"); +} + /// #3180: an XFA form with no fields whose configuration says `dynamicRender` is `forbidden` is a /// static form: its pages are the form. Opening it used to lay the template out into new pages /// and write them as a revision, so even a save with no change replaced the pages. diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs index 827e678567..4290c3c48a 100644 --- a/crates/render/src/inspect.rs +++ b/crates/render/src/inspect.rs @@ -809,8 +809,15 @@ impl<'a> Inspector<'a> { // A form with no fields is taken to be laid out from its template, unless its // configuration says it is a static form (#3180): Designer writes // `forbidden` for one, whose pages are the form. - let static_form = self.xfa_dynamic_render(xfa).as_deref() == Some("forbidden"); - info.xfa = Some(if needs_rendering || (info.fields.is_empty() && !static_form) { Xfa::Dynamic } else { Xfa::Static }); + let render = self.xfa_dynamic_render(xfa); + let static_form = render.as_deref() == Some("forbidden"); + // A form a viewer saved with its pages drawn, whose configuration says it must be + // rendered dynamically, is laid out from its template too: its fields live there. + // Not once it is signed: the signature covers the pages as saved (the xfa crate's + // `is_dynamic` keeps the same rule). + let signed = info.fields.iter().any(|f| f.kind == FieldKind::Signature && f.value.is_some()); + let required = render.as_deref() == Some("required") && !signed; + info.xfa = Some(if needs_rendering || required || (info.fields.is_empty() && !static_form) { Xfa::Dynamic } else { Xfa::Static }); } self.layers(catalog, &mut info.layers); info.layer_groups = self.layer_groups(catalog); diff --git a/crates/xfa/README.md b/crates/xfa/README.md index 23a6ef0d0e..a48b43c6ec 100644 --- a/crates/xfa/README.md +++ b/crates/xfa/README.md @@ -134,6 +134,10 @@ let form = pdfcraft_xfa::layout_xml(template_xml)?; // pages of items, for only their data is read and written. A form with no fields is also static when its `config` packet says `forbidden` (Designer's static PDF form): its pages are the form and are not laid out again (#3180). Without that, no fields means dynamic. + The other way round, a form with fields is dynamic when its `config` packet says + `required`: a viewer saved it with its pages drawn and only its + signature boxes as fields, so its other fields live in the template. Once one of those boxes + is signed it stays as saved, since laying it out would change the pages the signature covers. - **Flattening and converting.** `strip` takes the XFA out of a document: the packets, `/NeedsRendering`, the layout mark, the overrides and the private keys on the fields. The engine calls it after flattening an XFA form's fields (so Adobe's viewers show the baked diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index b76b3efa1a..f563ad7988 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -674,6 +674,46 @@ pub fn signed_shell() -> Vec { assemble(objs) } +/// A dynamic form as a viewer saves it with its pages drawn: no `/NeedsRendering`, a page with +/// the form's picture, and only its signature box `sign` among the AcroForm's fields (the text +/// field `name` lives in the template), signed when `signed`. Its configuration packet says +/// `{render}` (none when `render` is empty). +pub fn saved_with_pages_shell(render: &str, signed: bool) -> Vec { + let config = if render.is_empty() { + String::new() + } else { + format!( + r#"1.7{render}"# + ) + }; + let xdp = format!( + r##" + +{config} + + +"## + ); + let value = if signed { " /V 7 0 R" } else { "" }; + let picture = "BT /F1 12 Tf 72 700 Td (Name: ______) Tj ET"; + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /XFA 5 0 R /Fields [6 0 R] /SigFlags 3 >> >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Annots [6 0 R] >>".to_vec(), + format!("<< /Length {} >>\nstream\n{picture}\nendstream", picture.len()).into_bytes(), + format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len()).into_bytes(), + format!("<< /T (form[0].sign[0]) /FT /Sig{value} /Type /Annot /Subtype /Widget /Rect [72 500 288 572] /P 3 0 R >>").into_bytes(), + b"<< /Type /Sig /Name (A Signer) >>".to_vec(), + ]; + assemble(objs) +} + /// A check box `kind` whose change script, once it is checked, opens the protected check box /// `leave` and shows the invisible field `details`, then fails on an object the form doesn't /// have (as scripts written for an earlier version of a form do). diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs index 7fe372d53a..a90c335231 100644 --- a/crates/xfa/src/lib.rs +++ b/crates/xfa/src/lib.rs @@ -130,9 +130,16 @@ pub struct Report { } /// Is this a dynamic XFA form still showing its placeholder pages (one PdfCraft has not laid -/// out yet)? +/// out yet)? That is a form that asks to be laid out (`/NeedsRendering`), one with no fields of +/// its own, or one a viewer saved with its pages drawn whose configuration says it must be +/// rendered dynamically (`required`): its fields live in the +/// template. A signature on such a form covers the pages as saved, so a signed one is left as it +/// is: laying it out would change what was signed. pub fn is_dynamic(doc: &Document) -> bool { - existing_layout(doc).is_none() && matches!(read_packets(doc), Ok(Some(p)) if p.needs_rendering || !p.has_fields) + existing_layout(doc).is_none() + && matches!(read_packets(doc), Ok(Some(p)) if p.needs_rendering + || !p.has_fields + || (packets::requires_dynamic_render(&p.xdp) && !packets::has_signature(doc))) } /// Lay a template packet (or whole XDP, whose datasets then fill the fields) out. diff --git a/crates/xfa/src/packets.rs b/crates/xfa/src/packets.rs index f79b071c0e..d1ac1831e3 100644 --- a/crates/xfa/src/packets.rs +++ b/crates/xfa/src/packets.rs @@ -97,6 +97,64 @@ fn to_text(bytes: &[u8]) -> String { } } +/// Whether the XDP's configuration packet asks for dynamic rendering: `required` at +/// `config/acrobat/acrobat7/dynamicRender` (Designer writes it for a dynamic form). The same +/// names in the template or the data are not the configuration. +pub(crate) fn requires_dynamic_render(xdp: &str) -> bool { + // The configuration packet: from `' || c.is_whitespace())) + else { + return false; + }; + let Some(packet) = xdp.get(start..).and_then(|r| r.find("").and_then(|end| r.get(..end + "".len()))) else { + return false; + }; + let Ok(config) = roxmltree::Document::parse(packet) else { return false }; + let mut node = config.root_element(); + for name in ["acrobat", "acrobat7", "dynamicRender"] { + match node.children().find(|c| c.is_element() && c.tag_name().name() == name) { + Some(c) => node = c, + None => return false, + } + } + node.text().is_some_and(|t| t.trim() == "required") +} + +/// Whether the AcroForm holds a signed signature field (`/FT /Sig` with a value), looked for at +/// most 32 levels deep and among at most 10 000 fields. +pub(crate) fn has_signature(doc: &Document) -> bool { + let Some(root) = doc.root() else { return false }; + let catalog = doc.get(root); + let Some(acro) = catalog.as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)) else { return false }; + let Some(fields) = acro.as_dict().and_then(|a| a.get(b"Fields")).map(|f| doc.resolve(f)) else { return false }; + let Some(fields) = fields.as_array() else { return false }; + // (field, inherited field type, depth) + let mut todo: Vec<(Object, bool, usize)> = fields.iter().map(|f| (f.clone(), false, 0)).collect(); + let mut seen = std::collections::HashSet::new(); + let mut budget = 10_000usize; + while let Some((f, sig_above, depth)) = todo.pop() { + if budget == 0 || depth > 32 || f.as_ref().is_some_and(|r| !seen.insert(r)) { + continue; + } + budget -= 1; + let f = doc.resolve(&f); + let Some(d) = f.as_dict() else { continue }; + let sig = d.name(b"FT").map_or(sig_above, |t| t == b"Sig"); + if sig && d.get(b"V").is_some_and(|v| !matches!(&*doc.resolve(v), Object::Null)) { + return true; + } + if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)) + && let Some(kids) = kids.as_array() + { + todo.extend(kids.iter().map(|k| (k.clone(), sig, depth + 1))); + } + } + false +} + /// Read the XFA packets, if the document has any. pub fn read_packets(doc: &Document) -> Result, XfaError> { let Some(root) = doc.root() else { return Ok(None) }; diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 3175882f89..7bb0b7d4ca 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -299,6 +299,41 @@ fn tables_break_across_pages_and_repeat_their_header_row() { assert_eq!(all.len(), all.iter().collect::>().len(), "field names are unique"); } +/// A form a viewer saved with its pages drawn, holding only its signature box, is laid out from +/// its template when its configuration says it must be rendered dynamically: its other fields +/// live there. Signed, it is left as saved (laying it out would change what was signed), as it is +/// without that configuration or with `forbidden`. +#[test] +fn a_form_saved_with_its_pages_is_laid_out_when_it_requires_dynamic_rendering() { + let open = |render: &str, signed: bool| Document::open(Arc::new(crate::fixtures::saved_with_pages_shell(render, signed))).unwrap(); + let mut doc = open("required", false); + assert!(is_dynamic(&doc)); + let report = render_into(&mut doc).unwrap(); + assert_eq!(report.fields, 2, "the text field from the template, and the signature box"); + assert!(!is_dynamic(&open("required", true)), "signed: left as saved"); + assert!(!is_dynamic(&open("", false)), "no configuration: the fields it has are the form's"); + assert!(!is_dynamic(&open("forbidden", false))); +} + +/// Only the configuration packet's `acrobat/acrobat7/dynamicRender` asks for dynamic rendering: +/// not the same element elsewhere, another element that starts with `config`, or another value. +#[test] +fn dynamic_rendering_is_read_from_the_configuration_only() { + let required = crate::packets::requires_dynamic_render; + let config = |inner: &str| { + format!( + r#"{inner}