mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-01 02:36:02 +01:00
Merge main into #4369
This commit is contained in:
commit
1e05eefeae
23 files changed
+1240
-104
No files matched your search
Generated
+2
-2
@@ -1136,9 +1136,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",
|
||||
]
|
||||
|
||||
@@ -412,6 +412,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
|
||||
- **2026-10-23 (M2, #234, continuation of #1567):** Reconciled installed CJK viewer fallback with current rendering changes; Windows preserves installed Song/Hei/Kai families and bounds font reads. GBK-EUC-H CIDFontType2 regression coverage includes text extraction; viewer fallback also survives reload with retained preferences. System fonts remain display-only. No overall readiness estimate changed.
|
||||
- **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. 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-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.
|
||||
|
||||
- **2026-10-20 (M9 #79 review, M2, M8):** text extraction reads a marked-content /ActualText that marks no glyph where it paints (paths and images, cut to what is visible, along the direction they are drawn), so words drawn as outlines can be found, copied and exported; OCR and scan field detection still count such a page as having no text of its own. Redaction strips /ActualText, /Alt, /E and /T from inline marked content around paint it clips, as it already did around paint it removed, so a partly redacted outlined word leaves no name in the file. Named-layer recognition also needs the layer form to draw n1 and n3. Estimates unchanged.
|
||||
|
||||
+100
-20
@@ -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, annotation or object references, other pages or invalid content references")]
|
||||
UnsupportedContent,
|
||||
#[error("the page has more content than can be edited")]
|
||||
TooLarge,
|
||||
#[error("the figure's content may be in a damaged or unreadable content stream, or after the damage, so nothing was changed")]
|
||||
@@ -42,6 +46,8 @@ pub enum ArtifactError {
|
||||
HasChildren,
|
||||
#[error("the tag has no direct marked content")]
|
||||
NoMarkedContent,
|
||||
#[error("this action does not support form streams, annotation or object references, 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")]
|
||||
@@ -154,6 +160,74 @@ fn mcids(doc: &Document, d: &Dict) -> Vec<i64> {
|
||||
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<ObjRef>) -> Result<HashSet<i64>, MutationContentError> {
|
||||
fn visit(
|
||||
doc: &Document,
|
||||
item: &Object,
|
||||
page: Option<ObjRef>,
|
||||
depth: usize,
|
||||
remaining: &mut usize,
|
||||
ancestors: &mut HashSet<ObjRef>,
|
||||
ids: &mut HashSet<i64>,
|
||||
) -> 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 {
|
||||
@@ -514,13 +588,21 @@ fn artifact_marked_content(
|
||||
}
|
||||
|
||||
/// 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<i64> = mcids(doc, &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()) {
|
||||
let streams = decode_page_streams(doc, &page.dict).ok_or(AltError::TooLarge)?;
|
||||
match artifact_marked_content(doc, page, streams, &ids, false)? {
|
||||
// The parent tree no longer points those ids at the figure.
|
||||
@@ -552,16 +634,18 @@ 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. 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> {
|
||||
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<i64> = mcids(doc, &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);
|
||||
}
|
||||
@@ -570,6 +654,14 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact
|
||||
let page = pages.iter().find(|page| page.obj == page_ref).ok_or(ArtifactError::NoPage)?;
|
||||
let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?;
|
||||
let replacement = replacement_kids(doc, parent, obj)?;
|
||||
// The `/P` the tag names must be the parent it was reached from (or the structure root),
|
||||
// checked before the page changes.
|
||||
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 streams = decode_page_streams(doc, &page.dict).ok_or(ArtifactError::TooLarge)?;
|
||||
match artifact_marked_content(doc, page, streams, &ids, true)? {
|
||||
Marked::Done => {}
|
||||
@@ -587,18 +679,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 replacement_kids(doc: &Document, parent: ObjRef, obj: ObjRef) -> Result<Object, ArtifactError> {
|
||||
let kids = doc.get(parent).as_dict().and_then(|p| p.get(b"K").cloned()).ok_or(ArtifactError::NoParent)?;
|
||||
match kids {
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
//! 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 <</MCID 0>> BDC 10 10 20 20 re f EMC\nq /Form Do Q";
|
||||
let form = "/Figure <</MCID 0>> 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::<Vec<_>>();
|
||||
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<u8> {
|
||||
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::<Vec<_>>(), [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 <</MCID 0>> 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 << /MCID 0 /Pg 3 0 R >>]", vec![]),
|
||||
("[0 << /Type /MCR /Pg 3 0 R >>]", vec![]),
|
||||
("[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::<Vec<_>>();
|
||||
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::<Vec<_>>(),
|
||||
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::<Vec<_>>(),
|
||||
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::<Vec<_>>(), [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::<Vec<_>>(), [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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn annotation_reference_refusal_names_the_unsupported_content_and_preserves_its_links() {
|
||||
for decorative in [true, false] {
|
||||
let mut doc = collision_with(
|
||||
"[0 << /Type /OBJR /Obj 11 0 R /Pg 3 0 R >>]",
|
||||
&["<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /P 3 0 R /StructParent 2 >>"],
|
||||
);
|
||||
doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(11, 0))]))).unwrap();
|
||||
doc.update_dict(ObjRef::new(9, 0), |d| {
|
||||
d.set(
|
||||
b"Nums".to_vec(),
|
||||
Object::Array(vec![
|
||||
Object::Int(0),
|
||||
Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]),
|
||||
Object::Int(1),
|
||||
Object::Ref(ObjRef::new(8, 0)),
|
||||
Object::Int(2),
|
||||
Object::Ref(ObjRef::new(8, 0)),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.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 original_objects: Vec<_> = (1..=11).map(|i| doc.get(ObjRef::new(i, 0))).collect();
|
||||
let error = mutate(&mut doc, decorative, 8).unwrap_err();
|
||||
assert!(error.contains("annotation or object references"), "useful OBJR refusal: {error}");
|
||||
assert!(!doc.is_modified());
|
||||
assert_eq!((1..=11).map(|i| doc.get(ObjRef::new(i, 0))).collect::<Vec<_>>(), original_objects);
|
||||
let saved = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
assert_eq!(saved, before);
|
||||
let reopened = Document::open(Arc::new(saved)).unwrap();
|
||||
let page = &pdfcraft_model::pages(&reopened)[0];
|
||||
let annotation = reopened.resolve(&page.dict.get(b"Annots").unwrap().as_array().unwrap()[0]);
|
||||
assert_eq!(annotation.as_dict().unwrap().get(b"StructParent"), Some(&Object::Int(2)));
|
||||
let catalog = reopened.get(reopened.root().unwrap());
|
||||
let root = reopened.dict(catalog.as_dict().unwrap().get(b"StructTreeRoot").unwrap()).unwrap();
|
||||
let tree = reopened.dict(root.get(b"ParentTree").unwrap()).unwrap();
|
||||
let nums = tree.get(b"Nums").unwrap().as_array().unwrap();
|
||||
let tag = reopened.resolve(&nums[5]);
|
||||
assert_eq!(tag.as_dict().unwrap().get(b"K").unwrap().as_array().unwrap()[0], Object::Int(0));
|
||||
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::<Vec<_>>();
|
||||
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::<Vec<_>>(), 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::<Vec<_>>(), 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_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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Main checks the parent before it reads the page, so a tag with both a missing `/P` and
|
||||
/// content missing from its page is refused for its parent, with nothing changed.
|
||||
#[test]
|
||||
fn artifact_invalid_parent_precedes_missing_page_content_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::NoParent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artifact_indirect_content_removes_scalar_or_array_parent_child_and_preserves_drawing() {
|
||||
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(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));
|
||||
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(parent).as_dict().unwrap().get(b"K"), Some(&Object::Array(remaining)));
|
||||
assert!(!reopened.get(ObjRef::new(7, 0)).as_dict().unwrap().contains(b"P"));
|
||||
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::<Vec<_>>(), 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])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1399,7 +1399,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.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, annotation or object references, 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, language, a table's summary and a header cell's scope, 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.")
|
||||
@@ -1427,7 +1427,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language", "summary", "scope"] },
|
||||
"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, content not found on its page, or content that a damaged or undecodable content stream may hide or change 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, annotation or object references, other-page or invalid content references, and structure children are rejected before changing the document. Tags with no direct marked content, content not found on its page, or content that a damaged or undecodable content stream may hide or change are also rejected. Undoable.")
|
||||
.with(schema(json!({
|
||||
"doc": doc(), "object": { "type": "integer", "minimum": 1 },
|
||||
"generation": { "type": "integer", "minimum": 0, "maximum": 65535 },
|
||||
|
||||
@@ -4454,6 +4454,145 @@ 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 <</MCID 0>> BDC 10 10 20 20 re f EMC q /Fm Do Q";
|
||||
let form = "/Figure <</MCID 0>> 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()
|
||||
);
|
||||
for annotation_owned in [false, true] {
|
||||
let mut synthetic = CosDocument::open(Arc::new(source.clone().into_bytes())).unwrap();
|
||||
if annotation_owned {
|
||||
use pdfcraft_cos::{Dict, ObjRef};
|
||||
let annotation = synthetic.add(Object::Dict(Dict::from_iter([
|
||||
(b"Type".to_vec(), Object::Name(b"Annot".to_vec())),
|
||||
(b"Subtype".to_vec(), Object::Name(b"Link".to_vec())),
|
||||
(b"Rect".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(10), Object::Int(10)])),
|
||||
(b"P".to_vec(), Object::Ref(ObjRef::new(3, 0))),
|
||||
(b"StructParent".to_vec(), Object::Int(2)),
|
||||
])));
|
||||
synthetic.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(annotation)]))).unwrap();
|
||||
synthetic
|
||||
.update_dict(ObjRef::new(8, 0), |d| {
|
||||
d.set(
|
||||
b"K".to_vec(),
|
||||
Object::Array(vec![
|
||||
Object::Int(0),
|
||||
Object::Dict(Dict::from_iter([
|
||||
(b"Type".to_vec(), Object::Name(b"OBJR".to_vec())),
|
||||
(b"Obj".to_vec(), Object::Ref(annotation)),
|
||||
])),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
synthetic
|
||||
.update_dict(ObjRef::new(9, 0), |d| {
|
||||
d.set(
|
||||
b"Nums".to_vec(),
|
||||
Object::Array(vec![
|
||||
Object::Int(0),
|
||||
Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]),
|
||||
Object::Int(1),
|
||||
Object::Ref(ObjRef::new(8, 0)),
|
||||
Object::Int(2),
|
||||
Object::Ref(ObjRef::new(8, 0)),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.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 unsupported ownership") };
|
||||
let reason = if annotation_owned { "annotation or object references" } else { "form streams" };
|
||||
assert!(message.contains(reason), "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();
|
||||
let mut expected_nums =
|
||||
vec![Object::Int(0), Object::Array(vec![Object::Ref(saved_figures[0].obj)]), Object::Int(1), Object::Ref(saved_figures[1].obj)];
|
||||
if annotation_owned {
|
||||
expected_nums.extend([Object::Int(2), Object::Ref(saved_figures[1].obj)]);
|
||||
}
|
||||
assert_eq!(tree.get(b"Nums"), Some(&Object::Array(expected_nums)));
|
||||
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();
|
||||
if annotation_owned {
|
||||
let annotation = saved.resolve(&page_dict.get(b"Annots").unwrap().as_array().unwrap()[0]);
|
||||
assert_eq!(annotation.as_dict().unwrap().get(b"StructParent"), Some(&Object::Int(2)));
|
||||
}
|
||||
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");
|
||||
|
||||
@@ -116,6 +116,21 @@ pub(crate) fn signatures_of(
|
||||
pdfcraft_sign::pdf::list_cached(cos, bytes, trust, cache)
|
||||
}
|
||||
|
||||
/// Validate the signature fields of `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.
|
||||
pub(crate) fn editor_signatures(
|
||||
editor: &crate::history::Editor,
|
||||
bytes: &[u8],
|
||||
trust: &TrustStore,
|
||||
cache: &pdfcraft_sign::DigestCache,
|
||||
) -> Vec<SignatureInfo> {
|
||||
match &editor.as_opened {
|
||||
Some(o) if !editor.cos.is_modified() && Arc::ptr_eq(editor.cos.bytes(), &editor.saved) => signatures_of(&o.cos, &o.bytes, trust, cache),
|
||||
_ => signatures_of(&editor.cos, bytes, trust, cache),
|
||||
}
|
||||
}
|
||||
|
||||
/// What Optimize PDF did.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct OptimizeReport {
|
||||
|
||||
@@ -803,6 +803,8 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
};
|
||||
cx.xfa_datasets = run.datasets;
|
||||
cx.xfa_ran_away |= run.ran_away;
|
||||
// The next XFA run of a batch starts from the page count this one left.
|
||||
cx.pages = run.page_count;
|
||||
cx.xfa_relaid |= run.relaid;
|
||||
// The next edit of a batch reads the highlight this one's scripts set.
|
||||
let on = run.highlight;
|
||||
|
||||
@@ -150,6 +150,17 @@ pub(crate) struct Editor {
|
||||
pub(crate) field_appearances: pdfcraft_forms::FieldAppearanceCache,
|
||||
/// The text blocks last computed for one page, reused while the document is unchanged.
|
||||
pub(crate) 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).
|
||||
pub(crate) as_opened: Option<AsOpened>,
|
||||
}
|
||||
|
||||
/// The file as read, before opening appended PdfCraft's own revisions to it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AsOpened {
|
||||
pub(crate) cos: pdfcraft_cos::Document,
|
||||
pub(crate) bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// One page's text blocks ([`pdfcraft_edit::text_blocks`]) and the document state they were read
|
||||
|
||||
@@ -192,7 +192,7 @@ pub use pdfcraft_edit::ArrangeOrder;
|
||||
|
||||
use clock::{local_utc_offset, parse_ymd};
|
||||
pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files};
|
||||
use doc_state::{LOW_RESOLUTION_PRINT_DPI, render_threads, renderer_password, signatures_of, writable};
|
||||
use doc_state::{LOW_RESOLUTION_PRINT_DPI, editor_signatures, render_threads, renderer_password, signatures_of, writable};
|
||||
|
||||
/// The configuration of the pool that draws the viewer: the document's own, plus installed CJK
|
||||
/// fonts for fonts a PDF does not embed (`pdfcraft_render::RenderConfig::system_fonts`). Exports,
|
||||
|
||||
@@ -5,11 +5,11 @@ use std::sync::{Arc, OnceLock};
|
||||
use pdfcraft_cos::{SaveOptions, write_incremental};
|
||||
use pdfcraft_render::{DocInfo, OpenError, RenderConfig, RenderPool, inspect};
|
||||
|
||||
use crate::history::{Editor, Keys, TextBlocksCache};
|
||||
use crate::history::{AsOpened, Editor, Keys, TextBlocksCache};
|
||||
use crate::{
|
||||
AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard,
|
||||
info_fields, js, note_warnings, print_preview_layers, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout,
|
||||
xfa_values_from_datasets,
|
||||
AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config,
|
||||
editor_signatures, guard, info_fields, js, note_warnings, print_preview_layers, recovered_render_password, render_threads, same_pages, xfa,
|
||||
xfa_layout, xfa_values_from_datasets,
|
||||
};
|
||||
|
||||
/// Immutable session state needed while a document is prepared away from its owning thread.
|
||||
@@ -37,6 +37,8 @@ struct DocumentOpenData<'a> {
|
||||
render_password: Option<String>,
|
||||
password: Option<&'a str>,
|
||||
xfa: Option<XfaLayout>,
|
||||
/// The file as read, when opening appended revisions to it ([`crate::history::AsOpened`]).
|
||||
as_opened: Option<AsOpened>,
|
||||
}
|
||||
|
||||
impl OpenContext {
|
||||
@@ -152,6 +154,11 @@ impl Session {
|
||||
}
|
||||
Ok((new_bytes, new_info, new_cos))
|
||||
};
|
||||
// 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,
|
||||
};
|
||||
let (bytes, info, cos, xfa) = match (info.xfa, cos) {
|
||||
(Some(pdfcraft_render::Xfa::Dynamic), Ok(Ok(cos))) if pdfcraft_xfa::existing_layout(&cos).is_none() => {
|
||||
let mut work = cos.clone();
|
||||
@@ -286,8 +293,9 @@ impl Session {
|
||||
};
|
||||
// XFA notes survive the document being re-read after edits.
|
||||
let xfa_warnings: Vec<String> = if info.xfa.is_some() { info.warnings.clone() } else { Vec::new() };
|
||||
let as_opened = as_read.filter(|o| !Arc::ptr_eq(&o.bytes, &bytes));
|
||||
let mut document =
|
||||
Self::build_document(context, DocumentOpenData { name, path, bytes, info, structure: cos, render_password, password, xfa });
|
||||
Self::build_document(context, DocumentOpenData { name, path, bytes, info, structure: 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);
|
||||
@@ -301,7 +309,7 @@ impl Session {
|
||||
|
||||
/// The last step of opening: build the document record and register it.
|
||||
fn build_document(context: &OpenContext, data: DocumentOpenData<'_>) -> Document {
|
||||
let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa } = data;
|
||||
let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa, as_opened } = data;
|
||||
let mut config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() };
|
||||
let (mut editor, read_only_reason) = match cos {
|
||||
Ok(Ok(cos)) => {
|
||||
@@ -319,6 +327,7 @@ impl Session {
|
||||
appearances: AppearanceCache::default(),
|
||||
field_appearances: pdfcraft_forms::FieldAppearanceCache::default(),
|
||||
text_blocks: TextBlocksCache::default(),
|
||||
as_opened,
|
||||
}),
|
||||
None,
|
||||
)
|
||||
@@ -327,7 +336,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 mut signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, &context.trust, &sig_cache)).unwrap_or_default();
|
||||
let mut signatures = editor.as_ref().map(|e| editor_signatures(e, &bytes, &context.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;
|
||||
}
|
||||
// The inspection reads only `/Info`; a file stating its title or author only in XMP still
|
||||
// shows them (#2373).
|
||||
if let Some(e) = &editor {
|
||||
|
||||
@@ -13,9 +13,9 @@ use crate::{
|
||||
BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden,
|
||||
ImageResolution, LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart,
|
||||
StatusCaptions, SummarySort, TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, carry_verdict_marks, comment_list,
|
||||
comment_summary, decode_text, display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, office_to_pdf, open_source,
|
||||
open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, print_raster, render_threads, scan_colours,
|
||||
set_default_layer_state, shown_under_redactions, signatures_of, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa,
|
||||
comment_summary, decode_text, display_bytes, display_config, editor_signatures, guard, info_fields, js, local_utc_offset, note_warnings,
|
||||
office_to_pdf, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, print_raster, render_threads,
|
||||
scan_colours, set_default_layer_state, shown_under_redactions, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa,
|
||||
xfa_sync_datasets,
|
||||
};
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
use super::check_refresh_panic;
|
||||
use super::{
|
||||
Arc, DocId, Document, Edit, EditCtx, EditError, Label, MAX_UNDO, ObjectKind, OnceLock, RenderPool, SaveOptions, Scope, Session,
|
||||
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, guard, info_fields,
|
||||
inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state,
|
||||
undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets,
|
||||
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, editor_signatures,
|
||||
guard, info_fields, inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions,
|
||||
sync_xfa_state, undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets,
|
||||
};
|
||||
use crate::{EditNotice, MarkKind, print_preview_layers};
|
||||
|
||||
@@ -290,6 +290,8 @@ impl Session {
|
||||
cx.xfa_ran_away |= run.ran_away;
|
||||
cx.xfa_relaid |= run.relaid;
|
||||
// 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 {
|
||||
@@ -323,6 +325,7 @@ impl Session {
|
||||
// Layout replaces pages and widgets, even if the page count is unchanged.
|
||||
// Undo/redo must rebuild these too instead of refreshing only field values.
|
||||
scope = Scope::Full;
|
||||
rerun_layout_ready(&mut next, &mut cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -535,7 +538,7 @@ impl Session {
|
||||
#[cfg(test)]
|
||||
check_refresh_panic();
|
||||
if !doc.signatures.is_empty() {
|
||||
let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
|
||||
let mut signatures = editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache);
|
||||
// The display copy is kept for a metadata edit, and so are its marks, unless the
|
||||
// edit changed a verdict (a certification can forbid it): the page then draws the
|
||||
// new one.
|
||||
@@ -586,7 +589,7 @@ impl Session {
|
||||
}
|
||||
doc.info.file_size = bytes.len();
|
||||
doc.form = form;
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
@@ -651,7 +654,7 @@ impl Session {
|
||||
doc.marker_scan = OnceLock::new();
|
||||
}
|
||||
doc.info.file_size = bytes.len();
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
@@ -759,7 +762,7 @@ impl Session {
|
||||
if invalidate_links {
|
||||
doc.links = OnceLock::new();
|
||||
}
|
||||
let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
|
||||
let mut signatures = editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache);
|
||||
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
@@ -768,6 +771,37 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// After a new layout: the form's `layout:ready` scripts run again, reading its page count, as
|
||||
/// after a layout its scripts asked for. Not after a script of this edit ran away: the form's
|
||||
/// scripts turn off once it is done.
|
||||
fn rerun_layout_ready(next: &mut pdfcraft_cos::Document, cx: &mut EditCtx) {
|
||||
if cx.xfa_ran_away {
|
||||
return;
|
||||
}
|
||||
let Some(tpl) = cx.xfa.clone() else { return };
|
||||
let highlight = cx.highlight();
|
||||
let page_count = pdfcraft_organize::page_count(next).unwrap_or(cx.pages);
|
||||
let mut run = xfa::XfaRun {
|
||||
page_count,
|
||||
out: &mut cx.xfa_out,
|
||||
datasets: cx.xfa_datasets,
|
||||
ran_away: false,
|
||||
highlight,
|
||||
time_scale: cx.xfa_time_scale,
|
||||
relaid: false,
|
||||
};
|
||||
let ran = guard(|| xfa::on_layout(next, &tpl, &mut run)).unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})")));
|
||||
cx.xfa_datasets = run.datasets;
|
||||
cx.xfa_ran_away |= run.ran_away;
|
||||
cx.xfa_relaid |= run.relaid;
|
||||
cx.pages = run.page_count;
|
||||
let on = run.highlight;
|
||||
cx.set_highlight(on);
|
||||
if let Err(e) = ran {
|
||||
cx.xfa_out.errors.push(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// The optional content groups `cos` lists as layers, in order (what the inspection reads: a group
|
||||
/// listed twice is one layer, and one that is not a dictionary is none).
|
||||
fn layer_ids(cos: &pdfcraft_cos::Document) -> Vec<(u32, u16)> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Arc, DocId, Document, EditError, Keys, OpenError, RecoverySnapshot, RenderPool, SaveOptions, Session, SignOptions, StatusCaptions, TrustStore,
|
||||
display_bytes, display_config, guard, render_threads, signatures_of, writable, write_full, write_incremental, xfa_sync_datasets,
|
||||
display_bytes, display_config, editor_signatures, guard, render_threads, writable, write_full, write_incremental, xfa_sync_datasets,
|
||||
};
|
||||
|
||||
impl Session {
|
||||
@@ -90,6 +90,8 @@ impl Session {
|
||||
editor.saved = bytes;
|
||||
editor.saved_keys = keys;
|
||||
editor.unsaved_file = false;
|
||||
// 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());
|
||||
@@ -269,7 +271,7 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let Some(editor) = doc.editor.as_mut() else { return };
|
||||
let mut signatures = signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache);
|
||||
let mut signatures = editor_signatures(editor, &doc.bytes, &doc.trust, &doc.sig_cache);
|
||||
doc.display = display_bytes(Some(editor), &doc.bytes, &mut signatures, &doc.captions);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
|
||||
+213
-12
@@ -9478,6 +9478,57 @@ fn filling_growable_xfa_text_reflows_and_undo_restores_the_layout() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Typing text that makes a growable field take another page lays the form out again, and its
|
||||
/// layout:ready scripts run again, reading the new page count.
|
||||
#[test]
|
||||
fn layout_ready_scripts_run_again_after_text_grows_the_form() {
|
||||
let template = pdfcraft_xfa::fixtures::growable_text_template(false).replacen(
|
||||
"<pageSet>",
|
||||
r#"<event activity="ready" ref="$layout"><script contentType="application/x-javascript">xfa.form.form.pages.rawValue = String(xfa.layout.pageCount());</script></event><field name="pages" w="1in" h="0.3in"><ui><textEdit/></ui></field><pageSet>"#,
|
||||
1,
|
||||
);
|
||||
let text: String = (0..150).map(|i| format!("Row{i:03} {}sample\n", "sample ".repeat(8))).collect();
|
||||
let mut s = Session::new();
|
||||
let id = s.open("growing.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
let pages = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "pages").map(|f| f.value.clone()).unwrap_or_default();
|
||||
let before = s.get(id).unwrap().info.pages.len();
|
||||
assert_eq!(pages(&s), vec![before.to_string()]);
|
||||
s.apply(id, Edit::SetFieldValue { name: "ACTIVIDADES".into(), value: FieldValue::Text(text) }).unwrap();
|
||||
let after = s.get(id).unwrap().info.pages.len();
|
||||
assert_eq!(after, before + 1, "the text takes another page");
|
||||
assert_eq!(pages(&s), vec![after.to_string()], "layout:ready read the new page count");
|
||||
}
|
||||
|
||||
/// An edit whose change script runs away runs no more of the form's scripts, even when its text
|
||||
/// lays the form out again: the layout:ready scripts that a new layout runs wait, and the scripts
|
||||
/// turn off once the edit is done.
|
||||
#[test]
|
||||
fn a_new_layout_after_a_runaway_change_script_runs_no_layout_ready_scripts() {
|
||||
let template = pdfcraft_xfa::fixtures::growable_text_template(false)
|
||||
.replacen(
|
||||
"<pageSet>",
|
||||
r#"<event activity="ready" ref="$layout"><script contentType="application/x-javascript">xfa.form.form.log.rawValue = (xfa.form.form.log.rawValue || "") + "L";</script></event><field name="log" w="1in" h="0.3in"><ui><textEdit/></ui></field><pageSet>"#,
|
||||
1,
|
||||
)
|
||||
.replacen(
|
||||
r#"<field name="ACTIVIDADES" w="540pt" minH="207.017mm">"#,
|
||||
r#"<field name="ACTIVIDADES" w="540pt" minH="207.017mm"><event activity="exit"><script contentType="application/x-javascript">function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();</script></event>"#,
|
||||
1,
|
||||
);
|
||||
let text: String = (0..150).map(|i| format!("Row{i:03} {}sample\n", "sample ".repeat(8))).collect();
|
||||
let mut s = Session::new();
|
||||
let id = s.open("growing.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
let log = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "log").map(|f| f.value.clone()).unwrap_or_default();
|
||||
assert_eq!(log(&s), vec!["L".to_string()], "layout:ready ran once on opening");
|
||||
let before = s.get(id).unwrap().info.pages.len();
|
||||
s.apply(id, Edit::SetFieldValue { name: "ACTIVIDADES".into(), value: FieldValue::Text(text) }).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), before + 1, "the text still takes another page");
|
||||
let out = s.take_js_output(id);
|
||||
assert!(out.errors.iter().any(|e| e.contains("abandoned")), "{:?}", out.errors);
|
||||
assert!(s.get(id).unwrap().xfa_scripts_off());
|
||||
assert_eq!(log(&s), vec!["L".to_string()], "no layout:ready run after the runaway");
|
||||
}
|
||||
|
||||
/// What the last edit (the top of the undo stack) said it changed.
|
||||
fn last_scope(s: &Session, id: DocId) -> crate::history::Scope {
|
||||
s.get(id).unwrap().editor.as_ref().unwrap().undo.last().unwrap().3
|
||||
@@ -11995,6 +12046,71 @@ fn cropping_an_existing_image_clips_it_and_moves_with_it() {
|
||||
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<Vec<u8>> {
|
||||
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, SignatureStatus::Invalid),
|
||||
// Taking the values from the data fills the fields: a permitted change.
|
||||
(
|
||||
"static",
|
||||
pdfcraft_xfa::fixtures::static_shell("<form1><page1><name>Ada</name><agree>1</agree></page1></form1>"),
|
||||
"form1[0].page1[0].name[0]",
|
||||
sign::kind::FORM_FILL,
|
||||
SignatureStatus::Valid,
|
||||
),
|
||||
];
|
||||
for (what, form, field, saved_kind, saved_status) 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 (status, modification) = verdict(&s);
|
||||
assert_eq!(status, saved_status, "{what}: {modification:?}");
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert colours re-encodes pictures too (RGB → gray, the JPEG staying JPEG) and is one undo
|
||||
/// step; a document with nothing to convert refuses rather than leaving an empty step.
|
||||
#[test]
|
||||
@@ -12664,7 +12780,7 @@ fn a_field_that_only_reads_the_page_count_keeps_its_scripts_value() {
|
||||
|
||||
/// 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()));
|
||||
@@ -12676,13 +12792,78 @@ 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"));
|
||||
}
|
||||
|
||||
/// On opening, the calculations run once the initialize scripts have, before form:ready (XFA
|
||||
/// 3.3 fires the form ready event after them), and form:ready runs in the reverse of
|
||||
/// initialize's order (the root, then its fields last to first), while layout:ready keeps
|
||||
/// document order, as another viewer logged on a synthetic form. Since the ready scripts wrote a
|
||||
/// value (the log), the calculations run once more after them: which ones read it isn't known
|
||||
/// here. A form whose ready scripts write nothing runs them once.
|
||||
#[test]
|
||||
fn calculations_run_before_form_ready_which_runs_in_reverse() {
|
||||
let js = |what: &str| {
|
||||
format!(r#"var l = xfa.form.form.log; l.rawValue = (l.rawValue == null || l.rawValue == "" ? "" : l.rawValue + "|") + "{what}";"#)
|
||||
};
|
||||
let event = |activity: &str, reference: &str, what: &str| {
|
||||
format!(r#"<event activity="{activity}"{reference}><script contentType="application/x-javascript">{}</script></event>"#, js(what))
|
||||
};
|
||||
let field = |name: &str, extra: &str| {
|
||||
format!(
|
||||
r#"<field name="{name}" w="2in" h="0.3in"><ui><textEdit/></ui>{}{}{extra}</field>"#,
|
||||
event("initialize", "", &format!("{name} initialize")),
|
||||
event("ready", r#" ref="$form""#, &format!("{name} form:ready")),
|
||||
)
|
||||
};
|
||||
let calc = format!(r#"<calculate><script contentType="application/x-javascript">{} 42;</script></calculate>"#, js("calc calculate"));
|
||||
let layout = |name: &str| event("ready", r#" ref="$layout""#, &format!("{name} layout:ready"));
|
||||
let fields = [field("calc", &calc), field("a", &layout("a")), field("b", &layout("b"))].concat();
|
||||
let xdp = pdfcraft_xfa::fixtures::ready_events_template().replace(r#" <field name="grow""#, &format!(" {fields}\n <field name=\"grow\""));
|
||||
let mut s = Session::new();
|
||||
let id = s.open("ready.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&xdp)), None).expect("opens");
|
||||
let value = |s: &Session, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).map(|f| f.value.join("")).unwrap_or_default();
|
||||
let initialize = "title initialize|calc initialize|a initialize|b initialize|root initialize";
|
||||
let ready = "root form:ready|b form:ready|a form:ready|calc form:ready|title form:ready";
|
||||
let layout = "root layout:ready pages=1|title layout:ready|a layout:ready|b layout:ready";
|
||||
assert_eq!(value(&s, "log"), format!("{initialize}|calc calculate|{ready}|{layout}|root docReady|calc calculate"));
|
||||
assert_eq!(value(&s, "calc"), "42");
|
||||
// Ready scripts that write nothing: the calculations run once, before form:ready.
|
||||
let mut quiet = xdp.clone();
|
||||
for start in
|
||||
[r#"<event activity="ready" ref="$form">"#, r#"<event activity="ready" ref="$layout">"#, r#"<event activity="docReady" ref="$host">"#]
|
||||
{
|
||||
// Each ready script writes nothing; its logging moves to an event that never fires.
|
||||
quiet =
|
||||
quiet.replace(start, &format!(r#"{start}<script contentType="application/x-javascript">1;</script></event><event activity="never">"#));
|
||||
}
|
||||
let id = s.open("quiet.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&quiet)), None).expect("opens");
|
||||
let log = s.get(id).unwrap().form.iter().find(|f| f.name == "log").map(|f| f.value.join("")).unwrap_or_default();
|
||||
assert_eq!(log.matches("calc calculate").count(), 1, "{log}");
|
||||
}
|
||||
|
||||
/// An edit's two script runtimes share one field highlight: a change an XFA script makes reaches
|
||||
/// the field scripts' runner, and one the field scripts make is what the next XFA script reads.
|
||||
#[test]
|
||||
@@ -12698,6 +12879,31 @@ 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 value edits, a later field's change script reads the page count an earlier one's
|
||||
/// layout left: `bump`'s change shows a tall section (a second page), and `count`'s change, in the
|
||||
/// same batch, records `xfa.layout.pageCount()`.
|
||||
#[test]
|
||||
fn a_later_xfa_edit_in_a_batch_reads_the_page_count_an_earlier_one_left() {
|
||||
let script = |js: &str| format!(r#"<event activity="change"><script contentType="application/x-javascript">{js}</script></event>"#);
|
||||
let xdp = pdfcraft_xfa::fixtures::ready_events_template().replace(
|
||||
"<field name=\"log\"",
|
||||
&format!(
|
||||
r#"<field name="bump" w="1in" h="0.3in"><ui><textEdit/></ui>{bump}</field>
|
||||
<field name="count" w="1in" h="0.3in"><ui><textEdit/></ui>{count}</field>
|
||||
<field name="seen" w="1in" h="0.3in"><ui><textEdit/></ui></field>
|
||||
<field name="log""#,
|
||||
bump = script(r#"xfa.form.form.tall.presence = "visible";"#),
|
||||
count = script("xfa.form.form.seen.rawValue = String(xfa.layout.pageCount());"),
|
||||
),
|
||||
);
|
||||
let mut s = Session::new();
|
||||
let id = s.open("batch.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&xdp)), None).expect("opens");
|
||||
let type_in = |name: &str| Edit::SetFieldValue { name: name.into(), value: FieldValue::Text("x".into()) };
|
||||
s.apply(id, Edit::Batch { edits: vec![type_in("bump"), type_in("count")], label: "Type".into() }).expect("types");
|
||||
let seen = s.get(id).unwrap().form.iter().find(|f| f.name == "seen").map(|f| f.value.clone()).unwrap_or_default();
|
||||
assert_eq!(seen, vec!["2".to_string()]);
|
||||
}
|
||||
|
||||
/// In a batch of value edits, a later field's change script reads the field highlight an earlier
|
||||
/// one's set: `on`'s change turns it on, and `look`'s, in the same batch, records what it reads.
|
||||
/// (A form-script event itself can't be batched.)
|
||||
@@ -14320,13 +14526,12 @@ fn a_batch_that_applies_redactions_and_copies_a_page_is_refused() {
|
||||
/// so when the form is saved.
|
||||
#[test]
|
||||
fn an_opening_reset_reaches_a_row_added_while_opening() {
|
||||
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
|
||||
"if (qty.rawValue === null) qty.rawValue = 2;",
|
||||
r#"if (qty.rawValue === null) qty.rawValue = 2; table._row.addInstance(1);"#,
|
||||
)
|
||||
// The row is added by a script of a field before `grand`: the initialize scripts run children
|
||||
// before their parents, so a script of `page1` would come after `grand`'s.
|
||||
let tpl = pdfcraft_xfa::fixtures::scripted_template()
|
||||
.replace(
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly">"#,
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly"><event activity="initialize"><script contentType="application/x-javascript">xfa.resolveNode("form.page1.table.row[1].item").rawValue = "X"; xfa.host.resetData("form.page1.table.row[1].item");</script></event>"#,
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly"><event activity="initialize"><script contentType="application/x-javascript">table._row.addInstance(1);</script></event><event activity="initialize"><script contentType="application/x-javascript">xfa.resolveNode("form.page1.table.row[1].item").rawValue = "X"; xfa.host.resetData("form.page1.table.row[1].item");</script></event>"#,
|
||||
);
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("rows.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).unwrap();
|
||||
@@ -14345,14 +14550,10 @@ fn an_opening_reset_reaches_a_row_added_while_opening() {
|
||||
fn an_opening_reset_reaches_an_exclusion_group_of_a_row_added_while_opening() {
|
||||
let group = r#"<exclGroup name="pick" w="1in" h="0.3in"><field name="a" w="0.5in" h="0.3in"><ui><checkButton/></ui><items><text>A</text></items><value><text>A</text></value></field><field name="b" w="0.5in" h="0.3in"><ui><checkButton/></ui><items><text>B</text></items></field></exclGroup>"#;
|
||||
let tpl = pdfcraft_xfa::fixtures::scripted_template()
|
||||
.replace(
|
||||
"if (qty.rawValue === null) qty.rawValue = 2;",
|
||||
r#"if (qty.rawValue === null) qty.rawValue = 2; table._row.addInstance(1);"#,
|
||||
)
|
||||
.replace(r#"<field name="amount" h="0.3in"><ui><numericEdit/></ui></field>"#, &format!(r#"<field name="amount" h="0.3in"><ui><numericEdit/></ui></field>{group}"#))
|
||||
.replace(
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly">"#,
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly"><event activity="initialize"><script contentType="application/x-javascript">xfa.resolveNode("form.page1.table.row[1].pick").rawValue = "B"; xfa.host.resetData("form.page1.table.row[1].pick");</script></event>"#,
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly"><event activity="initialize"><script contentType="application/x-javascript">table._row.addInstance(1);</script></event><event activity="initialize"><script contentType="application/x-javascript">xfa.resolveNode("form.page1.table.row[1].pick").rawValue = "B"; xfa.host.resetData("form.page1.table.row[1].pick");</script></event>"#,
|
||||
);
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("rows.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).unwrap();
|
||||
|
||||
+136
-32
@@ -476,6 +476,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,
|
||||
/// Lay the form out once, when the event ends, rather than after every script that changed
|
||||
/// its structure (opening: see [`on_open`]).
|
||||
defer_relayout: bool,
|
||||
@@ -529,6 +532,7 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
skipped: 0,
|
||||
relayouts: 0,
|
||||
relayouts_skipped: false,
|
||||
laid_out: false,
|
||||
defer_relayout: false,
|
||||
relayout_owed: false,
|
||||
dropped_output: 0,
|
||||
@@ -778,11 +782,17 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
return Ok(());
|
||||
}
|
||||
self.relayouts += 1;
|
||||
self.laid_out = true;
|
||||
self.flush()?;
|
||||
// Set before the layout: one that fails part way may already have replaced fields.
|
||||
self.run.relaid = true;
|
||||
self.embedded_changed = false;
|
||||
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));
|
||||
@@ -1091,17 +1101,59 @@ 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<Changes, String> {
|
||||
#[cfg(test)]
|
||||
self.check_live();
|
||||
/// Every script of `activity`, in document order (parents before their children).
|
||||
fn events_named(&mut self, activity: &str) -> Vec<ScriptEvent> {
|
||||
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<ScriptEvent> = live.events.iter().filter(|e| e.activity == "layoutReady").cloned().collect();
|
||||
// The fields, gathered in one walk rather than one per script.
|
||||
let mut fields = HashSet::new();
|
||||
field_soms(&live.root, &mut fields, 0);
|
||||
let numbered: HashSet<String> = ready
|
||||
.iter()
|
||||
.filter(|e| fields.contains(&e.som) && pdfcraft_xfa::numbers_pages(&e.script, e.formcalc))
|
||||
.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.relayout_owed || self.embedded_changed {
|
||||
self.relayouts = 0;
|
||||
self.relayouts_skipped = false;
|
||||
self.relayout_owed = 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<Changes, String> {
|
||||
#[cfg(test)]
|
||||
self.check_live();
|
||||
self.owed_relayout()?;
|
||||
if self.laid_out {
|
||||
self.layout_ready()?;
|
||||
self.owed_relayout()?;
|
||||
}
|
||||
self.flush()?;
|
||||
if !self.focus_requests.is_empty() {
|
||||
self.by_som();
|
||||
@@ -1269,41 +1321,46 @@ fn value_unchanged(doc: &pdfcraft_cos::Document, f: &pdfcraft_forms::Field, v: O
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<Changes, String> {
|
||||
let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS);
|
||||
// The scripts read the live form (template, data and overrides), not the pages, so the
|
||||
// pages are laid out once, after the last of them. Laying a large form out after every
|
||||
// script that hides a subform spent the time limit on the first few, and the form was kept
|
||||
// half initialized: a page its initialize scripts hide stayed open to typing until the
|
||||
// next opening hid it and reset its data.
|
||||
// pages are laid out once, after the last of the initialize scripts. Laying a large form out
|
||||
// after every script that hides a subform spent the time limit on the first few, and the
|
||||
// form was kept half initialized: a page its initialize scripts hide stayed open to typing
|
||||
// until the next opening hid it and reset its data.
|
||||
r.defer_relayout = true;
|
||||
let events: Vec<ScriptEvent> = r.live().events.iter().filter(|e| e.activity == "initialize" || e.activity == "docReady").cloned().collect();
|
||||
for ev in &events {
|
||||
let initialize = children_first(r.events_named("initialize"));
|
||||
for ev in &initialize {
|
||||
r.run(ev, "")?;
|
||||
}
|
||||
let (ready, numbered) = {
|
||||
let live = r.live();
|
||||
let ready: Vec<ScriptEvent> = live.events.iter().filter(|e| e.activity == "layoutReady").cloned().collect();
|
||||
// The fields, gathered in one walk rather than one per script.
|
||||
let mut fields = HashSet::new();
|
||||
field_soms(&live.root, &mut fields, 0);
|
||||
let numbered: HashSet<String> =
|
||||
ready.iter().filter(|e| fields.contains(&e.som) && pdfcraft_xfa::numbers_pages(&e.script, e.formcalc)).map(|e| e.som.clone()).collect();
|
||||
(ready, numbered)
|
||||
};
|
||||
r.numbered = numbered;
|
||||
for ev in &ready {
|
||||
r.run(ev, "")?;
|
||||
}
|
||||
r.numbered.clear();
|
||||
// The calculations, before form:ready (XFA 3.3 fires the form ready event once they have run;
|
||||
// another viewer runs them there too).
|
||||
r.calculates()?;
|
||||
let calculated = r.field_changes.clone();
|
||||
// `ready` without `ref="$layout"` is form:ready: in the reverse of initialize's order, the
|
||||
// root first and the objects inside it last to first, as another viewer runs it.
|
||||
for ev in &objects_reversed(children_first(r.events_named("ready"))) {
|
||||
r.run(ev, "")?;
|
||||
}
|
||||
// Lay the form out once for what the scripts so far changed, then the layout:ready scripts
|
||||
// see the new pages.
|
||||
r.defer_relayout = false;
|
||||
r.owed_relayout()?;
|
||||
r.layout_ready()?;
|
||||
for ev in &r.events_named("docReady") {
|
||||
r.run(ev, "")?;
|
||||
}
|
||||
// A ready script wrote a value: the calculations run again, as after any change (which of
|
||||
// them read it isn't known here, so all of them).
|
||||
if r.field_changes != calculated {
|
||||
r.calculates()?;
|
||||
}
|
||||
r.finish()
|
||||
}
|
||||
|
||||
@@ -1314,6 +1371,45 @@ pub(crate) fn on_open(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mu
|
||||
/// order another viewer showed on a synthetic form.
|
||||
const TOGGLE_ORDER: [&str; 2] = ["change", "click"];
|
||||
|
||||
/// `events` with their objects in the reverse order, each object's own events keeping theirs.
|
||||
fn objects_reversed(events: Vec<ScriptEvent>) -> Vec<ScriptEvent> {
|
||||
let mut objects: Vec<Vec<ScriptEvent>> = Vec::new();
|
||||
for ev in events {
|
||||
match objects.last_mut() {
|
||||
Some(last) if last.first().is_some_and(|e| e.som == ev.som) => last.push(ev),
|
||||
_ => objects.push(vec![ev]),
|
||||
}
|
||||
}
|
||||
objects.into_iter().rev().flatten().collect()
|
||||
}
|
||||
|
||||
/// `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<ScriptEvent>) -> Vec<ScriptEvent> {
|
||||
let mut out = Vec::with_capacity(events.len());
|
||||
// The objects whose events wait for their children's, outermost first.
|
||||
let mut open: Vec<Vec<ScriptEvent>> = 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 check box or radio button runs its
|
||||
/// click scripts too ([`TOGGLE_ORDER`]): it changes only when it is clicked, and a click script
|
||||
@@ -1385,6 +1481,14 @@ pub(crate) fn on_changes(
|
||||
r.finish().map(|_| ())
|
||||
}
|
||||
|
||||
/// The form was laid out again outside its scripts (a field's text grew or shrank): its
|
||||
/// layout:ready scripts run, as after any new layout, and what they change is written.
|
||||
pub(crate) fn on_layout(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mut XfaRun) -> Result<(), String> {
|
||||
let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS);
|
||||
r.layout_ready()?;
|
||||
r.finish().map(|_| ())
|
||||
}
|
||||
|
||||
/// The form's data changed outside its scripts (a data file imported, a picture chosen): lay
|
||||
/// the form out again from the data, then, when `calculate`, run every calculation.
|
||||
pub(crate) fn on_data_replaced(doc: &mut pdfcraft_cos::Document, tpl: &Template, calculate: bool, run: &mut XfaRun) -> Result<(), String> {
|
||||
|
||||
@@ -249,6 +249,8 @@ pub(crate) fn xfa_after_data_change(doc: &mut pdfcraft_cos::Document, cx: &mut E
|
||||
.unwrap_or_else(|m| Err(format!("laying the form out again failed unexpectedly ({m})")));
|
||||
cx.xfa_datasets = run.datasets;
|
||||
cx.xfa_ran_away |= run.ran_away;
|
||||
// The next XFA run of a batch starts from the page count this one left.
|
||||
cx.pages = run.page_count;
|
||||
cx.xfa_relaid |= run.relaid;
|
||||
// The next edit of a batch reads the highlight this one's scripts set.
|
||||
let on = run.highlight;
|
||||
|
||||
@@ -845,10 +845,10 @@ impl PdfCraftApp {
|
||||
view.session.pending_pick = None;
|
||||
}
|
||||
}
|
||||
panes::frame(self, &ctx);
|
||||
// Forms' scripts read Highlight fields as `app.runtimeHighlight`.
|
||||
let highlight = self.active.and_then(|i| self.views.get(i)).map_or(self.highlight_fields, |v| v.session.highlight_fields);
|
||||
self.session.set_field_highlight(highlight);
|
||||
panes::frame(self, &ctx);
|
||||
self.sync_titles(&ctx);
|
||||
// The accessible window takes the same name, so a screen reader (AT-SPI on Linux, UIA on
|
||||
// Windows) can tell it apart (#4614). egui builds the root node afresh every pass.
|
||||
|
||||
@@ -300,6 +300,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#"<script contentType="application/x-javascript">var l = xfa.form.form.log; l.rawValue = (l.rawValue == null || l.rawValue == "" ? "" : l.rawValue + "|") + {what};</script>"#
|
||||
)
|
||||
};
|
||||
format!(
|
||||
r##"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
|
||||
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
|
||||
<subform name="form" layout="tb">
|
||||
<event activity="initialize">{root_init}</event>
|
||||
<event activity="ready" ref="$form">{root_form}</event>
|
||||
<event activity="ready" ref="$layout">{root_layout}</event>
|
||||
<event activity="docReady" ref="$host">{root_doc}</event>
|
||||
<pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
|
||||
<field name="title" w="7.5in" h="0.3in"><ui><textEdit/></ui>
|
||||
<event activity="initialize">{title_init}</event>
|
||||
<event activity="ready" ref="$form">{title_form}</event>
|
||||
<event activity="ready" ref="$layout">{title_layout}</event>
|
||||
</field>
|
||||
<field name="grow" w="1.5in" h="0.35in"><ui><button/></ui><caption><value><text>Grow</text></value></caption>
|
||||
<event activity="click"><script contentType="application/x-javascript">xfa.form.form.tall.presence = "visible";</script></event>
|
||||
</field>
|
||||
<field name="log" w="7.5in" h="0.3in"><ui><textEdit/></ui></field>
|
||||
<subform name="tall" layout="tb" w="7.5in" presence="hidden">
|
||||
<draw w="7.5in" h="9.5in"><value><text>A tall section.</text></value></draw>
|
||||
</subform>
|
||||
</subform>
|
||||
</template>
|
||||
</xdp:xdp>
|
||||
"##,
|
||||
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.
|
||||
|
||||
@@ -237,11 +237,12 @@ struct Layouter<'t> {
|
||||
}
|
||||
|
||||
/// How many instances of a repeating subform to lay out: what the data holds once it holds
|
||||
/// any (rows added or removed), else the template's initial count; never below one, never
|
||||
/// above the maximum.
|
||||
/// any (rows added or removed), else the template's initial count; at least the minimum
|
||||
/// whatever the data holds (XFA 3.3, "Repeating Elements using Occurrence Limits", #4744);
|
||||
/// never below one, never above the maximum.
|
||||
pub fn instance_count(occur: &Occur, from_data: usize) -> usize {
|
||||
let n = if from_data > 0 { from_data } else { occur.initial };
|
||||
n.min(occur.max.unwrap_or(usize::MAX)).clamp(1, MAX_INSTANCES)
|
||||
n.max(occur.min).min(occur.max.unwrap_or(usize::MAX)).clamp(1, MAX_INSTANCES)
|
||||
}
|
||||
|
||||
/// How many instances of `sf` the layout makes under the container at `parent_som`: its `occur`
|
||||
@@ -354,6 +355,22 @@ thread_local! {
|
||||
pub(crate) static EMBED_COPIED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod instance_count_tests {
|
||||
use super::instance_count;
|
||||
use crate::model::Occur;
|
||||
|
||||
/// #4744: `min` is honoured whatever the data holds. A repeating subform with
|
||||
/// `occur min="2" max="2"` keeps two instances even when the data has one.
|
||||
#[test]
|
||||
fn min_is_kept_whatever_the_data_holds() {
|
||||
let occur = Occur { min: 2, max: Some(2), initial: 2 };
|
||||
assert_eq!(instance_count(&occur, 0), 2, "no data: the initial count, at least the minimum");
|
||||
assert_eq!(instance_count(&occur, 1), 2, "one data instance: the minimum still applies");
|
||||
assert_eq!(instance_count(&occur, 3), 2, "more than the maximum: the maximum wins");
|
||||
}
|
||||
}
|
||||
|
||||
// The item count the last layout on this thread ended with, against `MAX_ITEMS`.
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
|
||||
@@ -44,7 +44,7 @@ allow-git = [
|
||||
]
|
||||
|
||||
[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
|
||||
|
||||
+2
-2
@@ -301,9 +301,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.<br>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).<br>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. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #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`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Vector printing keeps field and comment artwork whose rectangle coordinates or appearance-state names are indirect, requiring exactly four finite resolved rectangle values and a usable state name for state dictionaries. Rectangle arrays, coordinates and state names follow up to 64 indirect references with cycle detection. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. |
|
||||
| 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). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178). 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. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>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). Done since: #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Done since: #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Done since: #2570: Dynamic XFA rich-text fields carry exData/maxLength into AcroForm MaxLen for reported and enforced Unicode character limits, retained after save/reopen. Done since: #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |
|
||||
| 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. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>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). Done since: #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Done since: #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Done since: #2570: Dynamic XFA rich-text fields carry exData/maxLength into AcroForm MaxLen for reported and enforced Unicode character limits, retained after save/reopen. Done since: #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. 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<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |
|
||||
| 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<br>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. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>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, heading and paragraph tags and a parent tree, marks running headers and footers as pagination artifacts, then opens the Tags panel for review. Missing: mixed-content and field autotag, list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645).<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |
|
||||
| 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. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>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, heading and paragraph tags and a parent tree, marks running headers and footers as pagination artifacts, 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, list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645).<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |
|
||||
| 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<br>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 | Local customization: adjustable, floating or side-docked hotbar with optional full-side strip and persistent tool picker; freehand highlighting is grouped with Highlight. Estimates unchanged. 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 and Arabic (logical catalog; explicit right-to-left labels and mirrored stock chrome; end-to-end RTL workflows unqualified); the 2,674-entry Brazilian Portuguese catalog covers the current key union; 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. Norwegian Bokmål adds a catalog and date names (terminology reviewed by a native speaker). 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. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, 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. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, 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). Traditional Chinese accessibility statuses, rule semantics and Taiwan form/table terms have catalog regressions. Long main-menu lists scroll in short windows (#3373). Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, file-backed input and global memory budgets, performance budgets, keyboard-only operation. Candidate #3558: bounded-worker macOS per-file PDFCraft association recovery after desktop open/save/sign; metadata-only watcher handling and upstream #3042 shared-writer preservation; recovery parser limits do not narrow save limits. Native workflow qualified on macOS 27.0.1; other versions and physical SMB/FUSE volumes remain unqualified. Estimates unchanged. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation. |
|
||||
| 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 |
|
||||
|
||||
@@ -4621,7 +4621,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", "crates/ui-egui/tests/it/view.rs::round_check_boxes_get_a_round_highlight"]
|
||||
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 (the tint and border round for radio buttons and for check boxes laid out for a round XFA check button); 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, whether a script or typing into a growable field caused it), 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 (the tint and border round for radio buttons and for check boxes laid out for a round XFA check button); the tint is drawn over the field, where Acrobat paints the highlight colour behind it"
|
||||
|
||||
[[feature]]
|
||||
id = "form.field-appearance-display"
|
||||
@@ -5453,8 +5453,8 @@ milestone = "M12"
|
||||
status = "partial"
|
||||
commands = ["file.open"]
|
||||
tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run", "form_focus"]
|
||||
evidence = ["crates/xfa/src/tests.rs::a_draw_turns_counter_clockwise_about_its_anchor", "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/testsLine truncated
|
||||
notes = "A draw placed by position turns about its anchor (rotate); fields, subforms and draws in a flow don't. 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. A field change, reset or picture whose scripts or data lay the form out again (a section shown that needs another page, or hidden again) rebuilds the pages and fields the same way, whether or not the page count changed, so the view, undo/redo and save see the new pages. 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 (prototypes first: use/usehref references to #id or #som(...) in the same template, as Designer style sheets write them, are merged in by the XFA 3.3 chapter 6 rules, the element's own attributes and children winning, with loops cut and chain length, nesting, look-up and merge work and growth capped, each with a warning; prototypes in other documents are not followed, and SOM references cover names, #class and [n] only; 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 (in their field's font unless they name their own), objects shown only on screen or only in print (relevant -print and +print, inside containers too: fields by their annotation flags, draws in optional content groups whose view and print usage say so; PdfCraft's own printing doesn't yet apply a layer's print usage, so a screen-only or print-only draw prints as it shows on screen, and a hidden object relevant prints isn't laid out), rounded and inverted border corners (XFA 3.3 p. 38 gives the order of edges and corners and says the last one listed is reused for the sides not listed; readers draw an unlisted edge or corner from the one on the same side instead, one serving all four, two alternating, three reusing the second for the bottom-left; edges already followed the readers, and corners now do too), rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats (a date one of the edit picture's patterns reads is kept in its first, and in the data as an ISO date; text none of them reads, ISO text included, is kept and shown as typed rather than refused, as another viewer keeps it on a synthetic form; a display picture that differs from the edit picture isn't used to show the date yet), check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields (each named by its SOM path, under a generated field for each step above it, so that another viewer, which lays the form out again, finds a signature made here, as seen on a synthetic form, and a box signed here keeps its signature, and that name, when a script lays the form out again; a box whose path, or a part of it, the file already gives another field keeps its own name, and its signature isn't found there yet), 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;Line truncated
|
||||
evidence = ["crates/xfa/src/tests.rs::a_draw_turns_counter_clockwise_about_its_anchor", "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/testsLine truncated
|
||||
notes = "A draw placed by position turns about its anchor (rotate); fields, subforms and draws in a flow don't. 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. A field change, reset or picture whose scripts or data lay the form out again (a section shown that needs another page, or hidden again) rebuilds the pages and fields the same way, whether or not the page count changed, so the view, undo/redo and save see the new pages. 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 (prototypes first: use/usehref references to #id or #som(...) in the same template, as Designer style sheets write them, are merged in by the XFA 3.3 chapter 6 rules, the element's own attributes and children winning, with loops cut and chain length, nesting, look-up and merge work and growth capped, each with a warning; prototypes in other documents are not followed, and SOM references cover names, #class and [n] only; 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 (in their field's font unless they name their own), objects shown only on screen or only in print (relevant -print and +print, inside containers too: fields by their annotation flags, draws in optional content groups whose view and print usage say so; PdfCraft's own printing doesn't yet apply a layer's print usage, so a screen-only or print-only draw prints as it shows on screen, and a hidden object relevant prints isn't laid out), rounded and inverted border corners (XFA 3.3 p. 38 gives the order of edges and corners and says the last one listed is reused for the sides not listed; readers draw an unlisted edge or corner from the one on the same side instead, one serving all four, two alternating, three reusing the second for the bottom-left; edges already followed the readers, and corners now do too), rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats (a date one of the edit picture's patterns reads is kept in its first, and in the data as an ISO date; text none of them reads, ISO text included, is kept and shown as typed rather than refused, as another viewer keeps it on a synthetic form; a display picture that differs from the edit picture isn't used to show the date yet), check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields (each named by its SOM path, under a generated field for each step above it, so that another viewer, which lays the form out again, finds a signature made here, as seen on a synthetic form, and a box signed here keeps its signature, and that name, when a script lays the form out again; a box whose path, or a part of it, the file already gives another field keeps its own name, and its signature isn't found there yet), 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;Line truncated
|
||||
|
||||
[[feature]]
|
||||
id = "form.xfa-formcalc"
|
||||
@@ -6433,8 +6433,8 @@ milestone = "M9"
|
||||
status = "shipped"
|
||||
commands = ["sign.validate"]
|
||||
tools = ["sign_list"]
|
||||
evidence = ["crates/sign/tests/it/pdf.rs::signing_then_validating_with_and_without_trust", "crates/automation/tests/it/automation.rs::digital_ids_signing_and_validation_through_tools", "crates/sign/tests/it/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/it/pdf.rs::signing_then_validating_with_and_without_trust", "crates/automation/tests/it/automation.rs::digital_ids_signing_and_validation_through_tools", "crates/sign/tests/it/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"
|
||||
@@ -9283,8 +9283,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/it/automation.rs::marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved", "crates/ui-egui/tests/it/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/it/automation.rs::marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved", "crates/ui-egui/tests/it/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/it/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"
|
||||
@@ -9319,8 +9319,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/it/accessibility.rs::setting_alternate_text_figure_by_figure", "crates/automation/tests/it/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/it/accessibility.rs::setting_alternate_text_figure_by_figure", "crates/automation/tests/it/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/it/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, annotation or object references, 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"
|
||||
|
||||
Reference in new issue
Block a user