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 01/18] 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 f9bf81f8001aa258d9e7b58467c07457375d6e5f Mon Sep 17 00:00:00 2001 From: Ahmad Mujahid Date: Sun, 18 Oct 2026 19:45:06 +0400 Subject: [PATCH 02/18] 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 526b88d1f7ce7228104bbdf28dbd4e1c5916a277 Mon Sep 17 00:00:00 2001 From: Ahmad Mujahid Date: Tue, 20 Oct 2026 00:44:32 +0400 Subject: [PATCH 03/18] 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 e5ebbeb607d58054559195436ee3acee5944269c Mon Sep 17 00:00:00 2001 From: Ahmad Mujahid Date: Tue, 20 Oct 2026 11:17:56 +0400 Subject: [PATCH 04/18] 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 05/18] 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 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 06/18] 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 07/18] 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 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 08/18] 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 09/18] 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 0cb25e6036bff76f9000d36abd1e6998bcb24b1a Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:37:32 -0400 Subject: [PATCH 10/18] M12: a later XFA event of a batch reads the page count an earlier one's layout left --- crates/engine/src/lib.rs | 6 ++++++ crates/engine/src/tests.rs | 20 ++++++++++++++++++++ crates/engine/src/xfa.rs | 7 +++++-- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ae369c700f..9f61fff1d7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2703,6 +2703,8 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> cx.xfa_datasets = run.datasets; cx.xfa_ran_away |= run.ran_away; // The next edit of a batch reads the highlight this one's scripts set. + // The next XFA run of a batch starts from the page count this one left. + cx.pages = run.page_count; let on = run.highlight; cx.set_highlight(on); ran.map_err(EditError::Invalid)?; @@ -3504,6 +3506,8 @@ fn xfa_after_data_change(doc: &mut pdfcraft_cos::Document, cx: &mut EditCtx, cal cx.xfa_datasets = run.datasets; cx.xfa_ran_away |= run.ran_away; // The next edit of a batch reads the highlight this one's scripts set. + // The next XFA run of a batch starts from the page count this one left. + cx.pages = run.page_count; let on = run.highlight; cx.set_highlight(on); if let Err(e) = r { @@ -4094,6 +4098,8 @@ impl Session { cx.xfa_datasets = run.datasets; cx.xfa_ran_away |= run.ran_away; // The next edit of a batch reads the highlight this one's scripts set. + // The next XFA run of a batch starts from the page count this one left. + cx.pages = run.page_count; let on = run.highlight; cx.set_highlight(on); if let Err(e) = ran { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c5dbf7fb26..a245b41f84 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8135,6 +8135,26 @@ fn an_edits_xfa_and_field_scripts_share_the_field_highlight() { assert!(!cx.highlight(), "the next XFA script reads the field scripts' change"); } +/// In a batch of XFA events, a later event's scripts read the page count an earlier one's layout +/// left: `grow`'s click shows a tall section (a second page), and `count`'s click, in the same +/// batch, records `xfa.layout.pageCount()`. +#[test] +fn a_later_xfa_event_in_a_batch_reads_the_page_count_an_earlier_one_left() { + let xdp = pdfcraft_xfa::fixtures::ready_events_template().replace( + "